diff --git a/.gitattributes b/.gitattributes
index 4f2411f67347b9a1f0f962254de390d96ecfc9a9..f6bcd7d7635607455ec33f7f7e0504d69ab46b3e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3156,3 +3156,9 @@ platform/dbops/binaries/go/go/src/cmd/compile/default.pgo filter=lfs diff=lfs me
platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/go/go/src/debug/pe/testdata/gcc-amd64-mingw-exec filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good filter=lfs diff=lfs merge=lfs -text
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/export_test.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7f1ac70e8fa01cf1b18e36edda1afde3ce61ca6f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/export_test.go
@@ -0,0 +1,11 @@
+// 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.
+
+//go:build windows
+
+package registry
+
+func (k Key) SetValue(name string, valtype uint32, data []byte) error {
+ return k.setValue(name, valtype, data)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/key.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/key.go
new file mode 100644
index 0000000000000000000000000000000000000000..b95fa8d3326e39bff771415f94084ae250096d54
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/key.go
@@ -0,0 +1,168 @@
+// 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.
+
+//go:build windows
+
+// Package registry provides access to the Windows registry.
+//
+// Here is a simple example, opening a registry key and reading a string value from it.
+//
+// k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
+// if err != nil {
+// log.Fatal(err)
+// }
+// defer k.Close()
+//
+// s, _, err := k.GetStringValue("SystemRoot")
+// if err != nil {
+// log.Fatal(err)
+// }
+// fmt.Printf("Windows system root is %q\n", s)
+//
+// NOTE: This package is a copy of golang.org/x/sys/windows/registry
+// with KeyInfo.ModTime removed to prevent dependency cycles.
+package registry
+
+import (
+ "runtime"
+ "syscall"
+)
+
+const (
+ // Registry key security and access rights.
+ // See https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-key-security-and-access-rights
+ // for details.
+ ALL_ACCESS = 0xf003f
+ CREATE_LINK = 0x00020
+ CREATE_SUB_KEY = 0x00004
+ ENUMERATE_SUB_KEYS = 0x00008
+ EXECUTE = 0x20019
+ NOTIFY = 0x00010
+ QUERY_VALUE = 0x00001
+ READ = 0x20019
+ SET_VALUE = 0x00002
+ WOW64_32KEY = 0x00200
+ WOW64_64KEY = 0x00100
+ WRITE = 0x20006
+)
+
+// Key is a handle to an open Windows registry key.
+// Keys can be obtained by calling OpenKey; there are
+// also some predefined root keys such as CURRENT_USER.
+// Keys can be used directly in the Windows API.
+type Key syscall.Handle
+
+const (
+ // Windows defines some predefined root keys that are always open.
+ // An application can use these keys as entry points to the registry.
+ // Normally these keys are used in OpenKey to open new keys,
+ // but they can also be used anywhere a Key is required.
+ CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT)
+ CURRENT_USER = Key(syscall.HKEY_CURRENT_USER)
+ LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE)
+ USERS = Key(syscall.HKEY_USERS)
+ CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG)
+)
+
+// Close closes open key k.
+func (k Key) Close() error {
+ return syscall.RegCloseKey(syscall.Handle(k))
+}
+
+// OpenKey opens a new key with path name relative to key k.
+// It accepts any open key, including CURRENT_USER and others,
+// and returns the new key and an error.
+// The access parameter specifies desired access rights to the
+// key to be opened.
+func OpenKey(k Key, path string, access uint32) (Key, error) {
+ p, err := syscall.UTF16PtrFromString(path)
+ if err != nil {
+ return 0, err
+ }
+ var subkey syscall.Handle
+ err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
+ if err != nil {
+ return 0, err
+ }
+ return Key(subkey), nil
+}
+
+// ReadSubKeyNames returns the names of subkeys of key k.
+func (k Key) ReadSubKeyNames() ([]string, error) {
+ // RegEnumKeyEx must be called repeatedly and to completion.
+ // During this time, this goroutine cannot migrate away from
+ // its current thread. See #49320.
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ names := make([]string, 0)
+ // Registry key size limit is 255 bytes and described there:
+ // https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
+ buf := make([]uint16, 256) //plus extra room for terminating zero byte
+loopItems:
+ for i := uint32(0); ; i++ {
+ l := uint32(len(buf))
+ for {
+ err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
+ if err == nil {
+ break
+ }
+ if err == syscall.ERROR_MORE_DATA {
+ // Double buffer size and try again.
+ l = uint32(2 * len(buf))
+ buf = make([]uint16, l)
+ continue
+ }
+ if err == _ERROR_NO_MORE_ITEMS {
+ break loopItems
+ }
+ return names, err
+ }
+ names = append(names, syscall.UTF16ToString(buf[:l]))
+ }
+ return names, nil
+}
+
+// CreateKey creates a key named path under open key k.
+// CreateKey returns the new key and a boolean flag that reports
+// whether the key already existed.
+// The access parameter specifies the access rights for the key
+// to be created.
+func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
+ var h syscall.Handle
+ var d uint32
+ err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path),
+ 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
+ if err != nil {
+ return 0, false, err
+ }
+ return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
+}
+
+// DeleteKey deletes the subkey path of key k and its values.
+func DeleteKey(k Key, path string) error {
+ return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path))
+}
+
+// A KeyInfo describes the statistics of a key. It is returned by Stat.
+type KeyInfo struct {
+ SubKeyCount uint32
+ MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
+ ValueCount uint32
+ MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
+ MaxValueLen uint32 // longest data component among the key's values, in bytes
+ lastWriteTime syscall.Filetime
+}
+
+// Stat retrieves information about the open key k.
+func (k Key) Stat() (*KeyInfo, error) {
+ var ki KeyInfo
+ err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
+ &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
+ &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
+ if err != nil {
+ return nil, err
+ }
+ return &ki, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/mksyscall.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/mksyscall.go
new file mode 100644
index 0000000000000000000000000000000000000000..0e0b4210d58a0d25f3a093d28c0f7c2df1be08ad
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/mksyscall.go
@@ -0,0 +1,9 @@
+// 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 generate
+
+package registry
+
+//go:generate go run ../../../../syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/registry_test.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/registry_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..afe7a5d1c3ffa44591dd9c722389153c835ec4c3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/registry_test.go
@@ -0,0 +1,666 @@
+// 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.
+
+//go:build windows
+
+package registry_test
+
+import (
+ "bytes"
+ "crypto/rand"
+ "os"
+ "syscall"
+ "testing"
+ "unsafe"
+
+ "internal/syscall/windows/registry"
+)
+
+func randKeyName(prefix string) string {
+ const numbers = "0123456789"
+ buf := make([]byte, 10)
+ rand.Read(buf)
+ for i, b := range buf {
+ buf[i] = numbers[b%byte(len(numbers))]
+ }
+ return prefix + string(buf)
+}
+
+func TestReadSubKeyNames(t *testing.T) {
+ k, err := registry.OpenKey(registry.CLASSES_ROOT, "TypeLib", registry.ENUMERATE_SUB_KEYS)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer k.Close()
+
+ names, err := k.ReadSubKeyNames()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var foundStdOle bool
+ for _, name := range names {
+ // Every PC has "stdole 2.0 OLE Automation" library installed.
+ if name == "{00020430-0000-0000-C000-000000000046}" {
+ foundStdOle = true
+ }
+ }
+ if !foundStdOle {
+ t.Fatal("could not find stdole 2.0 OLE Automation")
+ }
+}
+
+func TestCreateOpenDeleteKey(t *testing.T) {
+ k, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer k.Close()
+
+ testKName := randKeyName("TestCreateOpenDeleteKey_")
+
+ testK, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer testK.Close()
+
+ if exist {
+ t.Fatalf("key %q already exists", testKName)
+ }
+
+ testKAgain, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer testKAgain.Close()
+
+ if !exist {
+ t.Fatalf("key %q should already exist", testKName)
+ }
+
+ testKOpened, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer testKOpened.Close()
+
+ err = registry.DeleteKey(k, testKName)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ testKOpenedAgain, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS)
+ if err == nil {
+ defer testKOpenedAgain.Close()
+ t.Fatalf("key %q should already been deleted", testKName)
+ }
+ if err != registry.ErrNotExist {
+ t.Fatalf(`unexpected error ("not exist" expected): %v`, err)
+ }
+}
+
+func equalStringSlice(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ if a == nil {
+ return true
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+type ValueTest struct {
+ Type uint32
+ Name string
+ Value any
+ WillFail bool
+}
+
+var ValueTests = []ValueTest{
+ {Type: registry.SZ, Name: "String1", Value: ""},
+ {Type: registry.SZ, Name: "String2", Value: "\000", WillFail: true},
+ {Type: registry.SZ, Name: "String3", Value: "Hello World"},
+ {Type: registry.SZ, Name: "String4", Value: "Hello World\000", WillFail: true},
+ {Type: registry.EXPAND_SZ, Name: "ExpString1", Value: ""},
+ {Type: registry.EXPAND_SZ, Name: "ExpString2", Value: "\000", WillFail: true},
+ {Type: registry.EXPAND_SZ, Name: "ExpString3", Value: "Hello World"},
+ {Type: registry.EXPAND_SZ, Name: "ExpString4", Value: "Hello\000World", WillFail: true},
+ {Type: registry.EXPAND_SZ, Name: "ExpString5", Value: "%PATH%"},
+ {Type: registry.EXPAND_SZ, Name: "ExpString6", Value: "%NO_SUCH_VARIABLE%"},
+ {Type: registry.EXPAND_SZ, Name: "ExpString7", Value: "%PATH%;."},
+ {Type: registry.BINARY, Name: "Binary1", Value: []byte{}},
+ {Type: registry.BINARY, Name: "Binary2", Value: []byte{1, 2, 3}},
+ {Type: registry.BINARY, Name: "Binary3", Value: []byte{3, 2, 1, 0, 1, 2, 3}},
+ {Type: registry.DWORD, Name: "Dword1", Value: uint64(0)},
+ {Type: registry.DWORD, Name: "Dword2", Value: uint64(1)},
+ {Type: registry.DWORD, Name: "Dword3", Value: uint64(0xff)},
+ {Type: registry.DWORD, Name: "Dword4", Value: uint64(0xffff)},
+ {Type: registry.QWORD, Name: "Qword1", Value: uint64(0)},
+ {Type: registry.QWORD, Name: "Qword2", Value: uint64(1)},
+ {Type: registry.QWORD, Name: "Qword3", Value: uint64(0xff)},
+ {Type: registry.QWORD, Name: "Qword4", Value: uint64(0xffff)},
+ {Type: registry.QWORD, Name: "Qword5", Value: uint64(0xffffff)},
+ {Type: registry.QWORD, Name: "Qword6", Value: uint64(0xffffffff)},
+ {Type: registry.MULTI_SZ, Name: "MultiString1", Value: []string{"a", "b", "c"}},
+ {Type: registry.MULTI_SZ, Name: "MultiString2", Value: []string{"abc", "", "cba"}},
+ {Type: registry.MULTI_SZ, Name: "MultiString3", Value: []string{""}},
+ {Type: registry.MULTI_SZ, Name: "MultiString4", Value: []string{"abcdef"}},
+ {Type: registry.MULTI_SZ, Name: "MultiString5", Value: []string{"\000"}, WillFail: true},
+ {Type: registry.MULTI_SZ, Name: "MultiString6", Value: []string{"a\000b"}, WillFail: true},
+ {Type: registry.MULTI_SZ, Name: "MultiString7", Value: []string{"ab", "\000", "cd"}, WillFail: true},
+ {Type: registry.MULTI_SZ, Name: "MultiString8", Value: []string{"\000", "cd"}, WillFail: true},
+ {Type: registry.MULTI_SZ, Name: "MultiString9", Value: []string{"ab", "\000"}, WillFail: true},
+}
+
+func setValues(t *testing.T, k registry.Key) {
+ for _, test := range ValueTests {
+ var err error
+ switch test.Type {
+ case registry.SZ:
+ err = k.SetStringValue(test.Name, test.Value.(string))
+ case registry.EXPAND_SZ:
+ err = k.SetExpandStringValue(test.Name, test.Value.(string))
+ case registry.MULTI_SZ:
+ err = k.SetStringsValue(test.Name, test.Value.([]string))
+ case registry.BINARY:
+ err = k.SetBinaryValue(test.Name, test.Value.([]byte))
+ case registry.DWORD:
+ err = k.SetDWordValue(test.Name, uint32(test.Value.(uint64)))
+ case registry.QWORD:
+ err = k.SetQWordValue(test.Name, test.Value.(uint64))
+ default:
+ t.Fatalf("unsupported type %d for %s value", test.Type, test.Name)
+ }
+ if test.WillFail {
+ if err == nil {
+ t.Fatalf("setting %s value %q should fail, but succeeded", test.Name, test.Value)
+ }
+ } else {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+}
+
+func enumerateValues(t *testing.T, k registry.Key) {
+ names, err := k.ReadValueNames()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ haveNames := make(map[string]bool)
+ for _, n := range names {
+ haveNames[n] = false
+ }
+ for _, test := range ValueTests {
+ wantFound := !test.WillFail
+ _, haveFound := haveNames[test.Name]
+ if wantFound && !haveFound {
+ t.Errorf("value %s is not found while enumerating", test.Name)
+ }
+ if haveFound && !wantFound {
+ t.Errorf("value %s is found while enumerating, but expected to fail", test.Name)
+ }
+ if haveFound {
+ delete(haveNames, test.Name)
+ }
+ }
+ for n, v := range haveNames {
+ t.Errorf("value %s (%v) is found while enumerating, but has not been created", n, v)
+ }
+}
+
+func testErrNotExist(t *testing.T, name string, err error) {
+ if err == nil {
+ t.Errorf("%s value should not exist", name)
+ return
+ }
+ if err != registry.ErrNotExist {
+ t.Errorf("reading %s value should return 'not exist' error, but got: %s", name, err)
+ return
+ }
+}
+
+func testErrUnexpectedType(t *testing.T, test ValueTest, gottype uint32, err error) {
+ if err == nil {
+ t.Errorf("GetXValue(%q) should not succeed", test.Name)
+ return
+ }
+ if err != registry.ErrUnexpectedType {
+ t.Errorf("reading %s value should return 'unexpected key value type' error, but got: %s", test.Name, err)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+}
+
+func testGetStringValue(t *testing.T, k registry.Key, test ValueTest) {
+ got, gottype, err := k.GetStringValue(test.Name)
+ if err != nil {
+ t.Errorf("GetStringValue(%s) failed: %v", test.Name, err)
+ return
+ }
+ if got != test.Value {
+ t.Errorf("want %s value %q, got %q", test.Name, test.Value, got)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+ if gottype == registry.EXPAND_SZ {
+ _, err = registry.ExpandString(got)
+ if err != nil {
+ t.Errorf("ExpandString(%s) failed: %v", got, err)
+ return
+ }
+ }
+}
+
+func testGetIntegerValue(t *testing.T, k registry.Key, test ValueTest) {
+ got, gottype, err := k.GetIntegerValue(test.Name)
+ if err != nil {
+ t.Errorf("GetIntegerValue(%s) failed: %v", test.Name, err)
+ return
+ }
+ if got != test.Value.(uint64) {
+ t.Errorf("want %s value %v, got %v", test.Name, test.Value, got)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+}
+
+func testGetBinaryValue(t *testing.T, k registry.Key, test ValueTest) {
+ got, gottype, err := k.GetBinaryValue(test.Name)
+ if err != nil {
+ t.Errorf("GetBinaryValue(%s) failed: %v", test.Name, err)
+ return
+ }
+ if !bytes.Equal(got, test.Value.([]byte)) {
+ t.Errorf("want %s value %v, got %v", test.Name, test.Value, got)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+}
+
+func testGetStringsValue(t *testing.T, k registry.Key, test ValueTest) {
+ got, gottype, err := k.GetStringsValue(test.Name)
+ if err != nil {
+ t.Errorf("GetStringsValue(%s) failed: %v", test.Name, err)
+ return
+ }
+ if !equalStringSlice(got, test.Value.([]string)) {
+ t.Errorf("want %s value %#v, got %#v", test.Name, test.Value, got)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+}
+
+func testGetValue(t *testing.T, k registry.Key, test ValueTest, size int) {
+ if size <= 0 {
+ return
+ }
+ // read data with no buffer
+ gotsize, gottype, err := k.GetValue(test.Name, nil)
+ if err != nil {
+ t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err)
+ return
+ }
+ if gotsize != size {
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+ // read data with short buffer
+ gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size-1))
+ if err == nil {
+ t.Errorf("GetValue(%s, [%d]byte) should fail, but succeeded", test.Name, size-1)
+ return
+ }
+ if err != registry.ErrShortBuffer {
+ t.Errorf("reading %s value should return 'short buffer' error, but got: %s", test.Name, err)
+ return
+ }
+ if gotsize != size {
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+ // read full data
+ gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size))
+ if err != nil {
+ t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err)
+ return
+ }
+ if gotsize != size {
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
+ return
+ }
+ if gottype != test.Type {
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
+ return
+ }
+ // check GetValue returns ErrNotExist as required
+ _, _, err = k.GetValue(test.Name+"_not_there", make([]byte, size))
+ if err == nil {
+ t.Errorf("GetValue(%q) should not succeed", test.Name)
+ return
+ }
+ if err != registry.ErrNotExist {
+ t.Errorf("GetValue(%q) should return 'not exist' error, but got: %s", test.Name, err)
+ return
+ }
+}
+
+func testValues(t *testing.T, k registry.Key) {
+ for _, test := range ValueTests {
+ switch test.Type {
+ case registry.SZ, registry.EXPAND_SZ:
+ if test.WillFail {
+ _, _, err := k.GetStringValue(test.Name)
+ testErrNotExist(t, test.Name, err)
+ } else {
+ testGetStringValue(t, k, test)
+ _, gottype, err := k.GetIntegerValue(test.Name)
+ testErrUnexpectedType(t, test, gottype, err)
+ // Size of utf16 string in bytes is not perfect,
+ // but correct for current test values.
+ // Size also includes terminating 0.
+ testGetValue(t, k, test, (len(test.Value.(string))+1)*2)
+ }
+ _, _, err := k.GetStringValue(test.Name + "_string_not_created")
+ testErrNotExist(t, test.Name+"_string_not_created", err)
+ case registry.DWORD, registry.QWORD:
+ testGetIntegerValue(t, k, test)
+ _, gottype, err := k.GetBinaryValue(test.Name)
+ testErrUnexpectedType(t, test, gottype, err)
+ _, _, err = k.GetIntegerValue(test.Name + "_int_not_created")
+ testErrNotExist(t, test.Name+"_int_not_created", err)
+ size := 8
+ if test.Type == registry.DWORD {
+ size = 4
+ }
+ testGetValue(t, k, test, size)
+ case registry.BINARY:
+ testGetBinaryValue(t, k, test)
+ _, gottype, err := k.GetStringsValue(test.Name)
+ testErrUnexpectedType(t, test, gottype, err)
+ _, _, err = k.GetBinaryValue(test.Name + "_byte_not_created")
+ testErrNotExist(t, test.Name+"_byte_not_created", err)
+ testGetValue(t, k, test, len(test.Value.([]byte)))
+ case registry.MULTI_SZ:
+ if test.WillFail {
+ _, _, err := k.GetStringsValue(test.Name)
+ testErrNotExist(t, test.Name, err)
+ } else {
+ testGetStringsValue(t, k, test)
+ _, gottype, err := k.GetStringValue(test.Name)
+ testErrUnexpectedType(t, test, gottype, err)
+ size := 0
+ for _, s := range test.Value.([]string) {
+ size += len(s) + 1 // nil terminated
+ }
+ size += 1 // extra nil at the end
+ size *= 2 // count bytes, not uint16
+ testGetValue(t, k, test, size)
+ }
+ _, _, err := k.GetStringsValue(test.Name + "_strings_not_created")
+ testErrNotExist(t, test.Name+"_strings_not_created", err)
+ default:
+ t.Errorf("unsupported type %d for %s value", test.Type, test.Name)
+ continue
+ }
+ }
+}
+
+func testStat(t *testing.T, k registry.Key) {
+ subk, _, err := registry.CreateKey(k, "subkey", registry.CREATE_SUB_KEY)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer subk.Close()
+
+ defer registry.DeleteKey(k, "subkey")
+
+ ki, err := k.Stat()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if ki.SubKeyCount != 1 {
+ t.Error("key must have 1 subkey")
+ }
+ if ki.MaxSubKeyLen != 6 {
+ t.Error("key max subkey name length must be 6")
+ }
+ if ki.ValueCount != 24 {
+ t.Errorf("key must have 24 values, but is %d", ki.ValueCount)
+ }
+ if ki.MaxValueNameLen != 12 {
+ t.Errorf("key max value name length must be 10, but is %d", ki.MaxValueNameLen)
+ }
+ if ki.MaxValueLen != 38 {
+ t.Errorf("key max value length must be 38, but is %d", ki.MaxValueLen)
+ }
+}
+
+func deleteValues(t *testing.T, k registry.Key) {
+ for _, test := range ValueTests {
+ if test.WillFail {
+ continue
+ }
+ err := k.DeleteValue(test.Name)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ }
+ names, err := k.ReadValueNames()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if len(names) != 0 {
+ t.Errorf("some values remain after deletion: %v", names)
+ }
+}
+
+func TestValues(t *testing.T) {
+ softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer softwareK.Close()
+
+ testKName := randKeyName("TestValues_")
+
+ k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer k.Close()
+
+ if exist {
+ t.Fatalf("key %q already exists", testKName)
+ }
+
+ defer registry.DeleteKey(softwareK, testKName)
+
+ setValues(t, k)
+
+ enumerateValues(t, k)
+
+ testValues(t, k)
+
+ testStat(t, k)
+
+ deleteValues(t, k)
+}
+
+func TestExpandString(t *testing.T) {
+ got, err := registry.ExpandString("%PATH%")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := os.Getenv("PATH")
+ if got != want {
+ t.Errorf("want %q string expanded, got %q", want, got)
+ }
+}
+
+func TestInvalidValues(t *testing.T) {
+ softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer softwareK.Close()
+
+ testKName := randKeyName("TestInvalidValues_")
+
+ k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer k.Close()
+
+ if exist {
+ t.Fatalf("key %q already exists", testKName)
+ }
+
+ defer registry.DeleteKey(softwareK, testKName)
+
+ var tests = []struct {
+ Type uint32
+ Name string
+ Data []byte
+ }{
+ {registry.DWORD, "Dword1", nil},
+ {registry.DWORD, "Dword2", []byte{1, 2, 3}},
+ {registry.QWORD, "Qword1", nil},
+ {registry.QWORD, "Qword2", []byte{1, 2, 3}},
+ {registry.QWORD, "Qword3", []byte{1, 2, 3, 4, 5, 6, 7}},
+ {registry.MULTI_SZ, "MultiString1", nil},
+ {registry.MULTI_SZ, "MultiString2", []byte{0}},
+ {registry.MULTI_SZ, "MultiString3", []byte{'a', 'b', 0}},
+ {registry.MULTI_SZ, "MultiString4", []byte{'a', 0, 0, 'b', 0}},
+ {registry.MULTI_SZ, "MultiString5", []byte{'a', 0, 0}},
+ }
+
+ for _, test := range tests {
+ err := k.SetValue(test.Name, test.Type, test.Data)
+ if err != nil {
+ t.Fatalf("SetValue for %q failed: %v", test.Name, err)
+ }
+ }
+
+ for _, test := range tests {
+ switch test.Type {
+ case registry.DWORD, registry.QWORD:
+ value, valType, err := k.GetIntegerValue(test.Name)
+ if err == nil {
+ t.Errorf("GetIntegerValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value)
+ }
+ case registry.MULTI_SZ:
+ value, valType, err := k.GetStringsValue(test.Name)
+ if err == nil {
+ if len(value) != 0 {
+ t.Errorf("GetStringsValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value)
+ }
+ }
+ default:
+ t.Errorf("unsupported type %d for %s value", test.Type, test.Name)
+ }
+ }
+}
+
+func TestGetMUIStringValue(t *testing.T) {
+ var dtzi DynamicTimezoneinformation
+ if _, err := GetDynamicTimeZoneInformation(&dtzi); err != nil {
+ t.Fatal(err)
+ }
+ tzKeyName := syscall.UTF16ToString(dtzi.TimeZoneKeyName[:])
+ timezoneK, err := registry.OpenKey(registry.LOCAL_MACHINE,
+ `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\`+tzKeyName, registry.READ)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer timezoneK.Close()
+
+ type testType struct {
+ name string
+ want string
+ }
+ var tests = []testType{
+ {"MUI_Std", syscall.UTF16ToString(dtzi.StandardName[:])},
+ }
+ if dtzi.DynamicDaylightTimeDisabled == 0 {
+ tests = append(tests, testType{"MUI_Dlt", syscall.UTF16ToString(dtzi.DaylightName[:])})
+ }
+
+ for _, test := range tests {
+ got, err := timezoneK.GetMUIStringValue(test.name)
+ if err != nil {
+ t.Error("GetMUIStringValue:", err)
+ }
+
+ if got != test.want {
+ t.Errorf("GetMUIStringValue: %s: Got %q, want %q", test.name, got, test.want)
+ }
+ }
+}
+
+type DynamicTimezoneinformation struct {
+ Bias int32
+ StandardName [32]uint16
+ StandardDate syscall.Systemtime
+ StandardBias int32
+ DaylightName [32]uint16
+ DaylightDate syscall.Systemtime
+ DaylightBias int32
+ TimeZoneKeyName [128]uint16
+ DynamicDaylightTimeDisabled uint8
+}
+
+var (
+ kernel32DLL = syscall.NewLazyDLL("kernel32")
+
+ procGetDynamicTimeZoneInformation = kernel32DLL.NewProc("GetDynamicTimeZoneInformation")
+)
+
+func GetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (rc uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(dtzi)), 0, 0)
+ rc = uint32(r0)
+ if rc == 0xffffffff {
+ if e1 != 0 {
+ err = error(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/syscall.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/syscall.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e730916a969734d80f26868eb018ec87aa21276
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/syscall.go
@@ -0,0 +1,27 @@
+// 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.
+
+//go:build windows
+
+package registry
+
+import "syscall"
+
+const (
+ _REG_OPTION_NON_VOLATILE = 0
+
+ _REG_CREATED_NEW_KEY = 1
+ _REG_OPENED_EXISTING_KEY = 2
+
+ _ERROR_NO_MORE_ITEMS syscall.Errno = 259
+)
+
+//sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW
+//sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW
+//sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW
+//sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW
+//sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW
+//sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW
+
+//sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/value.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/value.go
new file mode 100644
index 0000000000000000000000000000000000000000..67b1144eae586f3ceb9bb5bfea3fa71563078604
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/value.go
@@ -0,0 +1,369 @@
+// 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.
+
+//go:build windows
+
+package registry
+
+import (
+ "errors"
+ "syscall"
+ "unicode/utf16"
+ "unsafe"
+)
+
+const (
+ // Registry value types.
+ NONE = 0
+ SZ = 1
+ EXPAND_SZ = 2
+ BINARY = 3
+ DWORD = 4
+ DWORD_BIG_ENDIAN = 5
+ LINK = 6
+ MULTI_SZ = 7
+ RESOURCE_LIST = 8
+ FULL_RESOURCE_DESCRIPTOR = 9
+ RESOURCE_REQUIREMENTS_LIST = 10
+ QWORD = 11
+)
+
+var (
+ // ErrShortBuffer is returned when the buffer was too short for the operation.
+ ErrShortBuffer = syscall.ERROR_MORE_DATA
+
+ // ErrNotExist is returned when a registry key or value does not exist.
+ ErrNotExist = syscall.ERROR_FILE_NOT_FOUND
+
+ // ErrUnexpectedType is returned by Get*Value when the value's type was unexpected.
+ ErrUnexpectedType = errors.New("unexpected key value type")
+)
+
+// GetValue retrieves the type and data for the specified value associated
+// with an open key k. It fills up buffer buf and returns the retrieved
+// byte count n. If buf is too small to fit the stored value it returns
+// ErrShortBuffer error along with the required buffer size n.
+// If no buffer is provided, it returns true and actual buffer size n.
+// If no buffer is provided, GetValue returns the value's type only.
+// If the value does not exist, the error returned is ErrNotExist.
+//
+// GetValue is a low level function. If value's type is known, use the appropriate
+// Get*Value function instead.
+func (k Key) GetValue(name string, buf []byte) (n int, valtype uint32, err error) {
+ pname, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return 0, 0, err
+ }
+ var pbuf *byte
+ if len(buf) > 0 {
+ pbuf = (*byte)(unsafe.Pointer(&buf[0]))
+ }
+ l := uint32(len(buf))
+ err = syscall.RegQueryValueEx(syscall.Handle(k), pname, nil, &valtype, pbuf, &l)
+ if err != nil {
+ return int(l), valtype, err
+ }
+ return int(l), valtype, nil
+}
+
+func (k Key) getValue(name string, buf []byte) (date []byte, valtype uint32, err error) {
+ p, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return nil, 0, err
+ }
+ var t uint32
+ n := uint32(len(buf))
+ for {
+ err = syscall.RegQueryValueEx(syscall.Handle(k), p, nil, &t, (*byte)(unsafe.Pointer(&buf[0])), &n)
+ if err == nil {
+ return buf[:n], t, nil
+ }
+ if err != syscall.ERROR_MORE_DATA {
+ return nil, 0, err
+ }
+ if n <= uint32(len(buf)) {
+ return nil, 0, err
+ }
+ buf = make([]byte, n)
+ }
+}
+
+// GetStringValue retrieves the string value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetStringValue returns ErrNotExist.
+// If value is not SZ or EXPAND_SZ, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetStringValue(name string) (val string, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return "", typ, err2
+ }
+ switch typ {
+ case SZ, EXPAND_SZ:
+ default:
+ return "", typ, ErrUnexpectedType
+ }
+ if len(data) == 0 {
+ return "", typ, nil
+ }
+ u := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[: len(data)/2 : len(data)/2]
+ return syscall.UTF16ToString(u), typ, nil
+}
+
+// GetMUIStringValue retrieves the localized string value for
+// the specified value name associated with an open key k.
+// If the value name doesn't exist or the localized string value
+// can't be resolved, GetMUIStringValue returns ErrNotExist.
+func (k Key) GetMUIStringValue(name string) (string, error) {
+ pname, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return "", err
+ }
+
+ buf := make([]uint16, 1024)
+ var buflen uint32
+ var pdir *uint16
+
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ if err == syscall.ERROR_FILE_NOT_FOUND { // Try fallback path
+
+ // Try to resolve the string value using the system directory as
+ // a DLL search path; this assumes the string value is of the form
+ // @[path]\dllname,-strID but with no path given, e.g. @tzres.dll,-320.
+
+ // This approach works with tzres.dll but may have to be revised
+ // in the future to allow callers to provide custom search paths.
+
+ var s string
+ s, err = ExpandString("%SystemRoot%\\system32\\")
+ if err != nil {
+ return "", err
+ }
+ pdir, err = syscall.UTF16PtrFromString(s)
+ if err != nil {
+ return "", err
+ }
+
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ }
+
+ for err == syscall.ERROR_MORE_DATA { // Grow buffer if needed
+ if buflen <= uint32(len(buf)) {
+ break // Buffer not growing, assume race; break
+ }
+ buf = make([]uint16, buflen)
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ }
+
+ if err != nil {
+ return "", err
+ }
+
+ return syscall.UTF16ToString(buf), nil
+}
+
+// ExpandString expands environment-variable strings and replaces
+// them with the values defined for the current user.
+// Use ExpandString to expand EXPAND_SZ strings.
+func ExpandString(value string) (string, error) {
+ if value == "" {
+ return "", nil
+ }
+ p, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return "", err
+ }
+ r := make([]uint16, 100)
+ for {
+ n, err := expandEnvironmentStrings(p, &r[0], uint32(len(r)))
+ if err != nil {
+ return "", err
+ }
+ if n <= uint32(len(r)) {
+ return syscall.UTF16ToString(r[:n]), nil
+ }
+ r = make([]uint16, n)
+ }
+}
+
+// GetStringsValue retrieves the []string value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetStringsValue returns ErrNotExist.
+// If value is not MULTI_SZ, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetStringsValue(name string) (val []string, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return nil, typ, err2
+ }
+ if typ != MULTI_SZ {
+ return nil, typ, ErrUnexpectedType
+ }
+ if len(data) == 0 {
+ return nil, typ, nil
+ }
+ p := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[: len(data)/2 : len(data)/2]
+ if len(p) == 0 {
+ return nil, typ, nil
+ }
+ if p[len(p)-1] == 0 {
+ p = p[:len(p)-1] // remove terminating null
+ }
+ val = make([]string, 0, 5)
+ from := 0
+ for i, c := range p {
+ if c == 0 {
+ val = append(val, syscall.UTF16ToString(p[from:i]))
+ from = i + 1
+ }
+ }
+ return val, typ, nil
+}
+
+// GetIntegerValue retrieves the integer value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetIntegerValue returns ErrNotExist.
+// If value is not DWORD or QWORD, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetIntegerValue(name string) (val uint64, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 8))
+ if err2 != nil {
+ return 0, typ, err2
+ }
+ switch typ {
+ case DWORD:
+ if len(data) != 4 {
+ return 0, typ, errors.New("DWORD value is not 4 bytes long")
+ }
+ return uint64(*(*uint32)(unsafe.Pointer(&data[0]))), DWORD, nil
+ case QWORD:
+ if len(data) != 8 {
+ return 0, typ, errors.New("QWORD value is not 8 bytes long")
+ }
+ return *(*uint64)(unsafe.Pointer(&data[0])), QWORD, nil
+ default:
+ return 0, typ, ErrUnexpectedType
+ }
+}
+
+// GetBinaryValue retrieves the binary value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetBinaryValue returns ErrNotExist.
+// If value is not BINARY, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetBinaryValue(name string) (val []byte, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return nil, typ, err2
+ }
+ if typ != BINARY {
+ return nil, typ, ErrUnexpectedType
+ }
+ return data, typ, nil
+}
+
+func (k Key) setValue(name string, valtype uint32, data []byte) error {
+ p, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return err
+ }
+ if len(data) == 0 {
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0)
+ }
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data)))
+}
+
+// SetDWordValue sets the data and type of a name value
+// under key k to value and DWORD.
+func (k Key) SetDWordValue(name string, value uint32) error {
+ return k.setValue(name, DWORD, (*[4]byte)(unsafe.Pointer(&value))[:])
+}
+
+// SetQWordValue sets the data and type of a name value
+// under key k to value and QWORD.
+func (k Key) SetQWordValue(name string, value uint64) error {
+ return k.setValue(name, QWORD, (*[8]byte)(unsafe.Pointer(&value))[:])
+}
+
+func (k Key) setStringValue(name string, valtype uint32, value string) error {
+ v, err := syscall.UTF16FromString(value)
+ if err != nil {
+ return err
+ }
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[: len(v)*2 : len(v)*2]
+ return k.setValue(name, valtype, buf)
+}
+
+// SetStringValue sets the data and type of a name value
+// under key k to value and SZ. The value must not contain a zero byte.
+func (k Key) SetStringValue(name, value string) error {
+ return k.setStringValue(name, SZ, value)
+}
+
+// SetExpandStringValue sets the data and type of a name value
+// under key k to value and EXPAND_SZ. The value must not contain a zero byte.
+func (k Key) SetExpandStringValue(name, value string) error {
+ return k.setStringValue(name, EXPAND_SZ, value)
+}
+
+// SetStringsValue sets the data and type of a name value
+// under key k to value and MULTI_SZ. The value strings
+// must not contain a zero byte.
+func (k Key) SetStringsValue(name string, value []string) error {
+ ss := ""
+ for _, s := range value {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 0 {
+ return errors.New("string cannot have 0 inside")
+ }
+ }
+ ss += s + "\x00"
+ }
+ v := utf16.Encode([]rune(ss + "\x00"))
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[: len(v)*2 : len(v)*2]
+ return k.setValue(name, MULTI_SZ, buf)
+}
+
+// SetBinaryValue sets the data and type of a name value
+// under key k to value and BINARY.
+func (k Key) SetBinaryValue(name string, value []byte) error {
+ return k.setValue(name, BINARY, value)
+}
+
+// DeleteValue removes a named value from the key k.
+func (k Key) DeleteValue(name string) error {
+ return regDeleteValue(syscall.Handle(k), syscall.StringToUTF16Ptr(name))
+}
+
+// ReadValueNames returns the value names of key k.
+func (k Key) ReadValueNames() ([]string, error) {
+ ki, err := k.Stat()
+ if err != nil {
+ return nil, err
+ }
+ names := make([]string, 0, ki.ValueCount)
+ buf := make([]uint16, ki.MaxValueNameLen+1) // extra room for terminating null character
+loopItems:
+ for i := uint32(0); ; i++ {
+ l := uint32(len(buf))
+ for {
+ err := regEnumValue(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
+ if err == nil {
+ break
+ }
+ if err == syscall.ERROR_MORE_DATA {
+ // Double buffer size and try again.
+ l = uint32(2 * len(buf))
+ buf = make([]uint16, l)
+ continue
+ }
+ if err == _ERROR_NO_MORE_ITEMS {
+ break loopItems
+ }
+ return names, err
+ }
+ names = append(names, syscall.UTF16ToString(buf[:l]))
+ }
+ return names, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/zsyscall_windows.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/zsyscall_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..cab13193749c1b446d15f3155bb3c6937329e8e5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/zsyscall_windows.go
@@ -0,0 +1,107 @@
+// Code generated by 'go generate'; DO NOT EDIT.
+
+package registry
+
+import (
+ "internal/syscall/windows/sysdll"
+ "syscall"
+ "unsafe"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+ errERROR_EINVAL error = syscall.EINVAL
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return errERROR_EINVAL
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
+
+ procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW")
+ procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW")
+ procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW")
+ procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW")
+ procRegLoadMUIStringW = modadvapi32.NewProc("RegLoadMUIStringW")
+ procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW")
+ procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW")
+)
+
+func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegLoadMUIStringW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir)), 0, 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size))
+ n = uint32(r0)
+ if n == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/syscall_windows.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/syscall_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..d10e30cb6825fb9d29d47f40cb0e6f1a1ae33046
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/syscall_windows.go
@@ -0,0 +1,445 @@
+// Copyright 2014 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 (
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+// UTF16PtrToString is like UTF16ToString, but takes *uint16
+// as a parameter instead of []uint16.
+func UTF16PtrToString(p *uint16) string {
+ if p == nil {
+ return ""
+ }
+ end := unsafe.Pointer(p)
+ n := 0
+ for *(*uint16)(end) != 0 {
+ end = unsafe.Pointer(uintptr(end) + unsafe.Sizeof(*p))
+ n++
+ }
+ return syscall.UTF16ToString(unsafe.Slice(p, n))
+}
+
+const (
+ ERROR_BAD_LENGTH syscall.Errno = 24
+ ERROR_SHARING_VIOLATION syscall.Errno = 32
+ ERROR_LOCK_VIOLATION syscall.Errno = 33
+ ERROR_NOT_SUPPORTED syscall.Errno = 50
+ ERROR_CALL_NOT_IMPLEMENTED syscall.Errno = 120
+ ERROR_INVALID_NAME syscall.Errno = 123
+ ERROR_LOCK_FAILED syscall.Errno = 167
+ ERROR_NO_UNICODE_TRANSLATION syscall.Errno = 1113
+)
+
+const GAA_FLAG_INCLUDE_PREFIX = 0x00000010
+
+const (
+ IF_TYPE_OTHER = 1
+ IF_TYPE_ETHERNET_CSMACD = 6
+ IF_TYPE_ISO88025_TOKENRING = 9
+ IF_TYPE_PPP = 23
+ IF_TYPE_SOFTWARE_LOOPBACK = 24
+ IF_TYPE_ATM = 37
+ IF_TYPE_IEEE80211 = 71
+ IF_TYPE_TUNNEL = 131
+ IF_TYPE_IEEE1394 = 144
+)
+
+type SocketAddress struct {
+ Sockaddr *syscall.RawSockaddrAny
+ SockaddrLength int32
+}
+
+type IpAdapterUnicastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterUnicastAddress
+ Address SocketAddress
+ PrefixOrigin int32
+ SuffixOrigin int32
+ DadState int32
+ ValidLifetime uint32
+ PreferredLifetime uint32
+ LeaseLifetime uint32
+ OnLinkPrefixLength uint8
+}
+
+type IpAdapterAnycastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterAnycastAddress
+ Address SocketAddress
+}
+
+type IpAdapterMulticastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterMulticastAddress
+ Address SocketAddress
+}
+
+type IpAdapterDnsServerAdapter struct {
+ Length uint32
+ Reserved uint32
+ Next *IpAdapterDnsServerAdapter
+ Address SocketAddress
+}
+
+type IpAdapterPrefix struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterPrefix
+ Address SocketAddress
+ PrefixLength uint32
+}
+
+type IpAdapterAddresses struct {
+ Length uint32
+ IfIndex uint32
+ Next *IpAdapterAddresses
+ AdapterName *byte
+ FirstUnicastAddress *IpAdapterUnicastAddress
+ FirstAnycastAddress *IpAdapterAnycastAddress
+ FirstMulticastAddress *IpAdapterMulticastAddress
+ FirstDnsServerAddress *IpAdapterDnsServerAdapter
+ DnsSuffix *uint16
+ Description *uint16
+ FriendlyName *uint16
+ PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte
+ PhysicalAddressLength uint32
+ Flags uint32
+ Mtu uint32
+ IfType uint32
+ OperStatus uint32
+ Ipv6IfIndex uint32
+ ZoneIndices [16]uint32
+ FirstPrefix *IpAdapterPrefix
+ /* more fields might be present here. */
+}
+
+type SecurityAttributes struct {
+ Length uint16
+ SecurityDescriptor uintptr
+ InheritHandle bool
+}
+
+type FILE_BASIC_INFO struct {
+ CreationTime int64
+ LastAccessTime int64
+ LastWriteTime int64
+ ChangedTime int64
+ FileAttributes uint32
+
+ // Pad out to 8-byte alignment.
+ //
+ // Without this padding, TestChmod fails due to an argument validation error
+ // in SetFileInformationByHandle on windows/386.
+ //
+ // https://learn.microsoft.com/en-us/cpp/build/reference/zp-struct-member-alignment?view=msvc-170
+ // says that “The C/C++ headers in the Windows SDK assume the platform's
+ // default alignment is used.” What we see here is padding rather than
+ // alignment, but maybe it is related.
+ _ uint32
+}
+
+const (
+ IfOperStatusUp = 1
+ IfOperStatusDown = 2
+ IfOperStatusTesting = 3
+ IfOperStatusUnknown = 4
+ IfOperStatusDormant = 5
+ IfOperStatusNotPresent = 6
+ IfOperStatusLowerLayerDown = 7
+)
+
+//sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
+//sys GetComputerNameEx(nameformat uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
+//sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
+//sys GetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
+//sys SetFileInformationByHandle(handle syscall.Handle, fileInformationClass uint32, buf unsafe.Pointer, bufsize uint32) (err error) = kernel32.SetFileInformationByHandle
+//sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery
+//sys GetTempPath2(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPath2W
+
+const (
+ // flags for CreateToolhelp32Snapshot
+ TH32CS_SNAPMODULE = 0x08
+ TH32CS_SNAPMODULE32 = 0x10
+)
+
+const MAX_MODULE_NAME32 = 255
+
+type ModuleEntry32 struct {
+ Size uint32
+ ModuleID uint32
+ ProcessID uint32
+ GlblcntUsage uint32
+ ProccntUsage uint32
+ ModBaseAddr uintptr
+ ModBaseSize uint32
+ ModuleHandle syscall.Handle
+ Module [MAX_MODULE_NAME32 + 1]uint16
+ ExePath [syscall.MAX_PATH]uint16
+}
+
+const SizeofModuleEntry32 = unsafe.Sizeof(ModuleEntry32{})
+
+//sys Module32First(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW
+//sys Module32Next(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW
+
+const (
+ WSA_FLAG_OVERLAPPED = 0x01
+ WSA_FLAG_NO_HANDLE_INHERIT = 0x80
+
+ WSAEMSGSIZE syscall.Errno = 10040
+
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x0100
+ MSG_CTRUNC = 0x0200
+
+ socket_error = uintptr(^uint32(0))
+)
+
+var WSAID_WSASENDMSG = syscall.GUID{
+ Data1: 0xa441e712,
+ Data2: 0x754f,
+ Data3: 0x43ca,
+ Data4: [8]byte{0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d},
+}
+
+var WSAID_WSARECVMSG = syscall.GUID{
+ Data1: 0xf689d7c8,
+ Data2: 0x6f1f,
+ Data3: 0x436b,
+ Data4: [8]byte{0x8a, 0x53, 0xe5, 0x4f, 0xe3, 0x51, 0xc3, 0x22},
+}
+
+var sendRecvMsgFunc struct {
+ once sync.Once
+ sendAddr uintptr
+ recvAddr uintptr
+ err error
+}
+
+type WSAMsg struct {
+ Name syscall.Pointer
+ Namelen int32
+ Buffers *syscall.WSABuf
+ BufferCount uint32
+ Control syscall.WSABuf
+ Flags uint32
+}
+
+//sys WSASocket(af int32, typ int32, protocol int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = ws2_32.WSASocketW
+
+func loadWSASendRecvMsg() error {
+ sendRecvMsgFunc.once.Do(func() {
+ var s syscall.Handle
+ s, sendRecvMsgFunc.err = syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
+ if sendRecvMsgFunc.err != nil {
+ return
+ }
+ defer syscall.CloseHandle(s)
+ var n uint32
+ sendRecvMsgFunc.err = syscall.WSAIoctl(s,
+ syscall.SIO_GET_EXTENSION_FUNCTION_POINTER,
+ (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),
+ uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),
+ (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),
+ uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),
+ &n, nil, 0)
+ if sendRecvMsgFunc.err != nil {
+ return
+ }
+ sendRecvMsgFunc.err = syscall.WSAIoctl(s,
+ syscall.SIO_GET_EXTENSION_FUNCTION_POINTER,
+ (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),
+ uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),
+ (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),
+ uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),
+ &n, nil, 0)
+ })
+ return sendRecvMsgFunc.err
+}
+
+func WSASendMsg(fd syscall.Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *syscall.Overlapped, croutine *byte) error {
+ err := loadWSASendRecvMsg()
+ if err != nil {
+ return err
+ }
+ r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return err
+}
+
+func WSARecvMsg(fd syscall.Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *syscall.Overlapped, croutine *byte) error {
+ err := loadWSASendRecvMsg()
+ if err != nil {
+ return err
+ }
+ r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return err
+}
+
+const (
+ ComputerNameNetBIOS = 0
+ ComputerNameDnsHostname = 1
+ ComputerNameDnsDomain = 2
+ ComputerNameDnsFullyQualified = 3
+ ComputerNamePhysicalNetBIOS = 4
+ ComputerNamePhysicalDnsHostname = 5
+ ComputerNamePhysicalDnsDomain = 6
+ ComputerNamePhysicalDnsFullyQualified = 7
+ ComputerNameMax = 8
+
+ MOVEFILE_REPLACE_EXISTING = 0x1
+ MOVEFILE_COPY_ALLOWED = 0x2
+ MOVEFILE_DELAY_UNTIL_REBOOT = 0x4
+ MOVEFILE_WRITE_THROUGH = 0x8
+ MOVEFILE_CREATE_HARDLINK = 0x10
+ MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
+)
+
+func Rename(oldpath, newpath string) error {
+ from, err := syscall.UTF16PtrFromString(oldpath)
+ if err != nil {
+ return err
+ }
+ to, err := syscall.UTF16PtrFromString(newpath)
+ if err != nil {
+ return err
+ }
+ return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
+}
+
+//sys LockFileEx(file syscall.Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) = kernel32.LockFileEx
+//sys UnlockFileEx(file syscall.Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) = kernel32.UnlockFileEx
+
+const (
+ LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
+ LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
+)
+
+const MB_ERR_INVALID_CHARS = 8
+
+//sys GetACP() (acp uint32) = kernel32.GetACP
+//sys GetConsoleCP() (ccp uint32) = kernel32.GetConsoleCP
+//sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
+//sys GetCurrentThread() (pseudoHandle syscall.Handle, err error) = kernel32.GetCurrentThread
+
+// Constants from lmshare.h
+const (
+ STYPE_DISKTREE = 0x00
+ STYPE_TEMPORARY = 0x40000000
+)
+
+type SHARE_INFO_2 struct {
+ Netname *uint16
+ Type uint32
+ Remark *uint16
+ Permissions uint32
+ MaxUses uint32
+ CurrentUses uint32
+ Path *uint16
+ Passwd *uint16
+}
+
+//sys NetShareAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint16) (neterr error) = netapi32.NetShareAdd
+//sys NetShareDel(serverName *uint16, netName *uint16, reserved uint32) (neterr error) = netapi32.NetShareDel
+
+const (
+ FILE_NAME_NORMALIZED = 0x0
+ FILE_NAME_OPENED = 0x8
+
+ VOLUME_NAME_DOS = 0x0
+ VOLUME_NAME_GUID = 0x1
+ VOLUME_NAME_NONE = 0x4
+ VOLUME_NAME_NT = 0x2
+)
+
+//sys GetFinalPathNameByHandle(file syscall.Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW
+
+func ErrorLoadingGetTempPath2() error {
+ return procGetTempPath2W.Find()
+}
+
+//sys CreateEnvironmentBlock(block **uint16, token syscall.Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
+//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
+//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
+
+//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
+
+type FILE_ID_BOTH_DIR_INFO struct {
+ NextEntryOffset uint32
+ FileIndex uint32
+ CreationTime syscall.Filetime
+ LastAccessTime syscall.Filetime
+ LastWriteTime syscall.Filetime
+ ChangeTime syscall.Filetime
+ EndOfFile uint64
+ AllocationSize uint64
+ FileAttributes uint32
+ FileNameLength uint32
+ EaSize uint32
+ ShortNameLength uint32
+ ShortName [12]uint16
+ FileID uint64
+ FileName [1]uint16
+}
+
+type FILE_FULL_DIR_INFO struct {
+ NextEntryOffset uint32
+ FileIndex uint32
+ CreationTime syscall.Filetime
+ LastAccessTime syscall.Filetime
+ LastWriteTime syscall.Filetime
+ ChangeTime syscall.Filetime
+ EndOfFile uint64
+ AllocationSize uint64
+ FileAttributes uint32
+ FileNameLength uint32
+ EaSize uint32
+ FileName [1]uint16
+}
+
+//sys GetVolumeInformationByHandle(file syscall.Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW
+//sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW
+
+//sys RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) = kernel32.RtlLookupFunctionEntry
+//sys RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) = kernel32.RtlVirtualUnwind
+
+type SERVICE_STATUS struct {
+ ServiceType uint32
+ CurrentState uint32
+ ControlsAccepted uint32
+ Win32ExitCode uint32
+ ServiceSpecificExitCode uint32
+ CheckPoint uint32
+ WaitHint uint32
+}
+
+const (
+ SERVICE_RUNNING = 4
+ SERVICE_QUERY_STATUS = 4
+)
+
+//sys OpenService(mgr syscall.Handle, serviceName *uint16, access uint32) (handle syscall.Handle, err error) = advapi32.OpenServiceW
+//sys QueryServiceStatus(hService syscall.Handle, lpServiceStatus *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus
+//sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle syscall.Handle, err error) [failretval==0] = advapi32.OpenSCManagerW
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/sysdll/sysdll.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/sysdll/sysdll.go
new file mode 100644
index 0000000000000000000000000000000000000000..e79fd19edc0ebb3a3907d4302575e17a550264b7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/sysdll/sysdll.go
@@ -0,0 +1,30 @@
+// 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 windows
+
+// Package sysdll is an internal leaf package that records and reports
+// which Windows DLL names are used by Go itself. These DLLs are then
+// only loaded from the System32 directory. See Issue 14959.
+package sysdll
+
+// IsSystemDLL reports whether the named dll key (a base name, like
+// "foo.dll") is a system DLL which should only be loaded from the
+// Windows SYSTEM32 directory.
+//
+// Filenames are case sensitive, but that doesn't matter because
+// the case registered with Add is also the same case used with
+// LoadDLL later.
+//
+// It has no associated mutex and should only be mutated serially
+// (currently: during init), and not concurrent with DLL loading.
+var IsSystemDLL = map[string]bool{}
+
+// Add notes that dll is a system32 DLL which should only be loaded
+// from the Windows SYSTEM32 directory. It returns its argument back,
+// for ease of use in generated code.
+func Add(dll string) string {
+ IsSystemDLL[dll] = true
+ return dll
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/syscall/windows/zsyscall_windows.go b/platform/dbops/binaries/go/go/src/internal/syscall/windows/zsyscall_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..931f157cf166c267573aa8834bbcc72157da7352
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/syscall/windows/zsyscall_windows.go
@@ -0,0 +1,436 @@
+// Code generated by 'go generate'; DO NOT EDIT.
+
+package windows
+
+import (
+ "internal/syscall/windows/sysdll"
+ "syscall"
+ "unsafe"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+ errERROR_EINVAL error = syscall.EINVAL
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return errERROR_EINVAL
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
+ modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
+
+ procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
+ procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
+ procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf")
+ procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
+ procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW")
+ procOpenServiceW = modadvapi32.NewProc("OpenServiceW")
+ procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
+ procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
+ procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
+ procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
+ procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
+ procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
+ procCreateEventW = modkernel32.NewProc("CreateEventW")
+ procGetACP = modkernel32.NewProc("GetACP")
+ procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW")
+ procGetConsoleCP = modkernel32.NewProc("GetConsoleCP")
+ procGetCurrentThread = modkernel32.NewProc("GetCurrentThread")
+ procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx")
+ procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW")
+ procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW")
+ procGetTempPath2W = modkernel32.NewProc("GetTempPath2W")
+ procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW")
+ procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW")
+ procLockFileEx = modkernel32.NewProc("LockFileEx")
+ procModule32FirstW = modkernel32.NewProc("Module32FirstW")
+ procModule32NextW = modkernel32.NewProc("Module32NextW")
+ procMoveFileExW = modkernel32.NewProc("MoveFileExW")
+ procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar")
+ procRtlLookupFunctionEntry = modkernel32.NewProc("RtlLookupFunctionEntry")
+ procRtlVirtualUnwind = modkernel32.NewProc("RtlVirtualUnwind")
+ procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle")
+ procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
+ procVirtualQuery = modkernel32.NewProc("VirtualQuery")
+ procNetShareAdd = modnetapi32.NewProc("NetShareAdd")
+ procNetShareDel = modnetapi32.NewProc("NetShareDel")
+ procNetUserGetLocalGroups = modnetapi32.NewProc("NetUserGetLocalGroups")
+ procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
+ procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock")
+ procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock")
+ procGetProfilesDirectoryW = moduserenv.NewProc("GetProfilesDirectoryW")
+ procWSASocketW = modws2_32.NewProc("WSASocketW")
+)
+
+func adjustTokenPrivileges(token syscall.Token, disableAllPrivileges bool, newstate *TOKEN_PRIVILEGES, buflen uint32, prevstate *TOKEN_PRIVILEGES, returnlen *uint32) (ret uint32, err error) {
+ var _p0 uint32
+ if disableAllPrivileges {
+ _p0 = 1
+ }
+ r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen)))
+ ret = uint32(r0)
+ if true {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func DuplicateTokenEx(hExistingToken syscall.Token, dwDesiredAccess uint32, lpTokenAttributes *syscall.SecurityAttributes, impersonationLevel uint32, tokenType TokenType, phNewToken *syscall.Token) (err error) {
+ r1, _, e1 := syscall.Syscall6(procDuplicateTokenEx.Addr(), 6, uintptr(hExistingToken), uintptr(dwDesiredAccess), uintptr(unsafe.Pointer(lpTokenAttributes)), uintptr(impersonationLevel), uintptr(tokenType), uintptr(unsafe.Pointer(phNewToken)))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func ImpersonateSelf(impersonationlevel uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(impersonationlevel), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) {
+ r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemname)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid)))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access))
+ handle = syscall.Handle(r0)
+ if handle == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func OpenService(mgr syscall.Handle, serviceName *uint16, access uint32) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access))
+ handle = syscall.Handle(r0)
+ if handle == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func OpenThreadToken(h syscall.Handle, access uint32, openasself bool, token *syscall.Token) (err error) {
+ var _p0 uint32
+ if openasself {
+ _p0 = 1
+ }
+ r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(h), uintptr(access), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func QueryServiceStatus(hService syscall.Handle, lpServiceStatus *SERVICE_STATUS) (err error) {
+ r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(hService), uintptr(unsafe.Pointer(lpServiceStatus)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func RevertToSelf() (err error) {
+ r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func SetTokenInformation(tokenHandle syscall.Token, tokenInformationClass uint32, tokenInformation uintptr, tokenInformationLength uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procSetTokenInformation.Addr(), 4, uintptr(tokenHandle), uintptr(tokenInformationClass), uintptr(tokenInformation), uintptr(tokenInformationLength), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func ProcessPrng(buf []byte) (err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) {
+ r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0)
+ if r0 != 0 {
+ errcode = syscall.Errno(r0)
+ }
+ return
+}
+
+func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0)
+ handle = syscall.Handle(r0)
+ if handle == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetACP() (acp uint32) {
+ r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0)
+ acp = uint32(r0)
+ return
+}
+
+func GetComputerNameEx(nameformat uint32, buf *uint16, n *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nameformat), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetConsoleCP() (ccp uint32) {
+ r0, _, _ := syscall.Syscall(procGetConsoleCP.Addr(), 0, 0, 0, 0)
+ ccp = uint32(r0)
+ return
+}
+
+func GetCurrentThread() (pseudoHandle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0)
+ pseudoHandle = syscall.Handle(r0)
+ if pseudoHandle == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetFileInformationByHandleEx(handle syscall.Handle, class uint32, info *byte, bufsize uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(info)), uintptr(bufsize), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetFinalPathNameByHandle(file syscall.Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall6(procGetFinalPathNameByHandleW.Addr(), 4, uintptr(file), uintptr(unsafe.Pointer(filePath)), uintptr(filePathSize), uintptr(flags), 0, 0)
+ n = uint32(r0)
+ if n == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, uintptr(module), uintptr(unsafe.Pointer(fn)), uintptr(len))
+ n = uint32(r0)
+ if n == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetTempPath2(buflen uint32, buf *uint16) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetTempPath2W.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0)
+ n = uint32(r0)
+ if n == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetVolumeInformationByHandle(file syscall.Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procGetVolumeInformationByHandleW.Addr(), 8, uintptr(file), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetVolumeNameForVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferlength))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func LockFileEx(file syscall.Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall6(procLockFileEx.Addr(), 6, uintptr(file), uintptr(flags), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped)))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func Module32First(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) {
+ r1, _, e1 := syscall.Syscall(procModule32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func Module32Next(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) {
+ r1, _, e1 := syscall.Syscall(procModule32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) {
+ r0, _, e1 := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6, uintptr(codePage), uintptr(dwFlags), uintptr(unsafe.Pointer(str)), uintptr(nstr), uintptr(unsafe.Pointer(wchar)), uintptr(nwchar))
+ nwrite = int32(r0)
+ if nwrite == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) {
+ r0, _, _ := syscall.Syscall(procRtlLookupFunctionEntry.Addr(), 3, uintptr(pc), uintptr(unsafe.Pointer(baseAddress)), uintptr(unsafe.Pointer(table)))
+ ret = uintptr(r0)
+ return
+}
+
+func RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) {
+ r0, _, _ := syscall.Syscall9(procRtlVirtualUnwind.Addr(), 8, uintptr(handlerType), uintptr(baseAddress), uintptr(pc), uintptr(entry), uintptr(ctxt), uintptr(unsafe.Pointer(data)), uintptr(unsafe.Pointer(frame)), uintptr(unsafe.Pointer(ctxptrs)), 0)
+ ret = uintptr(r0)
+ return
+}
+
+func SetFileInformationByHandle(handle syscall.Handle, fileInformationClass uint32, buf unsafe.Pointer, bufsize uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(handle), uintptr(fileInformationClass), uintptr(buf), uintptr(bufsize), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func UnlockFileEx(file syscall.Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall6(procUnlockFileEx.Addr(), 5, uintptr(file), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procVirtualQuery.Addr(), 3, uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func NetShareAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint16) (neterr error) {
+ r0, _, _ := syscall.Syscall6(procNetShareAdd.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(level), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(parmErr)), 0, 0)
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func NetShareDel(serverName *uint16, netName *uint16, reserved uint32) (neterr error) {
+ r0, _, _ := syscall.Syscall(procNetShareDel.Addr(), 3, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(netName)), uintptr(reserved))
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func NetUserGetLocalGroups(serverName *uint16, userName *uint16, level uint32, flags uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32) (neterr error) {
+ r0, _, _ := syscall.Syscall9(procNetUserGetLocalGroups.Addr(), 8, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(flags), uintptr(unsafe.Pointer(buf)), uintptr(prefMaxLen), uintptr(unsafe.Pointer(entriesRead)), uintptr(unsafe.Pointer(totalEntries)), 0)
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func GetProcessMemoryInfo(handle syscall.Handle, memCounters *PROCESS_MEMORY_COUNTERS, cb uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(memCounters)), uintptr(cb))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func CreateEnvironmentBlock(block **uint16, token syscall.Token, inheritExisting bool) (err error) {
+ var _p0 uint32
+ if inheritExisting {
+ _p0 = 1
+ }
+ r1, _, e1 := syscall.Syscall(procCreateEnvironmentBlock.Addr(), 3, uintptr(unsafe.Pointer(block)), uintptr(token), uintptr(_p0))
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func DestroyEnvironmentBlock(block *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procDestroyEnvironmentBlock.Addr(), 1, uintptr(unsafe.Pointer(block)), 0, 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func GetProfilesDirectory(dir *uint16, dirLen *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetProfilesDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen)), 0)
+ if r1 == 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+func WSASocket(af int32, typ int32, protocol int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procWSASocketW.Addr(), 6, uintptr(af), uintptr(typ), uintptr(protocol), uintptr(unsafe.Pointer(protinfo)), uintptr(group), uintptr(flags))
+ handle = syscall.Handle(r0)
+ if handle == syscall.InvalidHandle {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_10_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_10_good
new file mode 100644
index 0000000000000000000000000000000000000000..a4f2ed83d84d2a5d8bf65f7b5a65bd7e178c41fd
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_10_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_11_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_11_good
new file mode 100644
index 0000000000000000000000000000000000000000..0efcc6fba19a32c47c9b67a4d3847a6462f8cdc3
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_11_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_19_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_19_good
new file mode 100644
index 0000000000000000000000000000000000000000..c1d519e7d5da8d3b32eac715a32871c78bd619db
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_19_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_21_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_21_good
new file mode 100644
index 0000000000000000000000000000000000000000..b3295f9e5d760cb78cd0f574a764f5c207a489ed
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_21_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_5_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_5_good
new file mode 100644
index 0000000000000000000000000000000000000000..0736cae674186cfcc6fa31508fec410242936f20
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_5_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_7_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_7_good
new file mode 100644
index 0000000000000000000000000000000000000000..b0e318e9a44aec862b9151664fee01e4d581a7c2
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_7_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_9_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_9_good
new file mode 100644
index 0000000000000000000000000000000000000000..ca892788383bbfe4c2585ff480a20780557c325f
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_9_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good
new file mode 100644
index 0000000000000000000000000000000000000000..df152a73c320350a183f27c5e2fdfd817aa67796
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0608236a31dadbff8a3f91dcc3c94399a3429ceeb30d7007fd9dbd0e85a85614
+size 370999
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good
new file mode 100644
index 0000000000000000000000000000000000000000..805ff03e764eb4e7aa7f8355efbc3cf89b0aae98
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9878383c755505fbd034e542490c7b9ce49e6d9c33432a725968a2df067a4f28
+size 370129
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good
new file mode 100644
index 0000000000000000000000000000000000000000..dd3c414bf245a5c2c483e751096651e15d9c5efc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f2706ed5beddd2be37cca3c48108aaf683fc9d9ea2778329653b9518fc460268
+size 322338
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good
new file mode 100644
index 0000000000000000000000000000000000000000..cca139df876e24b17ce6e81268c454270e4ac2a8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0c9077aadea706ca77a0044b5b350917db94cf7ed2da777f17e6cd7b2ca64f09
+size 353725
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_good
new file mode 100644
index 0000000000000000000000000000000000000000..c5055ebd19ffca30e2905abd29cb1306a0ce98a0
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_unordered b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_unordered
new file mode 100644
index 0000000000000000000000000000000000000000..11f7d745ca95f3ed2fa0e0ece4e7895608bdc39d
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_unordered differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good
new file mode 100644
index 0000000000000000000000000000000000000000..c1aa07a98f7b9164e7d3171eb4e4066fd61dde31
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:50fb7e557d495520d95a97539716638ca74af88e1ed361d0e9823b2d5e34db54
+size 396526
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good
new file mode 100644
index 0000000000000000000000000000000000000000..193ccea29164ae93faa9263c63754cf56ebbf60d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:439de9dc3b154052f4d6b8d2c1c9fbde8b8964a8242342e99c224f461b91bf43
+size 365129
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_10_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_10_good
new file mode 100644
index 0000000000000000000000000000000000000000..b908e10f2567d64df0feb9dea43c216ee694c76c
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_10_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_11_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_11_good
new file mode 100644
index 0000000000000000000000000000000000000000..457f01a6cdec08a1ab02e3fb486ee0534140d467
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_11_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_19_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_19_good
new file mode 100644
index 0000000000000000000000000000000000000000..92d92789c4f2562ecf94b816af5a0232bc88c5b6
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_19_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_21_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_21_good
new file mode 100644
index 0000000000000000000000000000000000000000..fff46a9a071b7727a0f2585c776b13d2e290c3da
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_21_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_5_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_5_good
new file mode 100644
index 0000000000000000000000000000000000000000..72a887b8444ff9cb3f9b9711b4ae382d177a6676
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_5_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_7_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_7_good
new file mode 100644
index 0000000000000000000000000000000000000000..c23ed7dc0871ce0e3ebafe0c1bdacdec93b7158d
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_7_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_9_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_9_good
new file mode 100644
index 0000000000000000000000000000000000000000..f00f190f32644058936da39850fe58acef0a149d
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_9_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_11_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_11_good
new file mode 100644
index 0000000000000000000000000000000000000000..f4edb67e6565dc62f6d9ab8968f0aa1124255132
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_11_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_19_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_19_good
new file mode 100644
index 0000000000000000000000000000000000000000..1daa3b25a6c64d8620c85fedb1fb46d287e72882
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_19_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_21_good b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_21_good
new file mode 100644
index 0000000000000000000000000000000000000000..5c01a6405d8da87275b38ff777523fd56a66fc5c
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_21_good differ
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/emitter.go b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/emitter.go
new file mode 100644
index 0000000000000000000000000000000000000000..c91c743a7bfb6c83141a576fe74724a61ef51b1c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/emitter.go
@@ -0,0 +1,813 @@
+// 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 traceviewer
+
+import (
+ "encoding/json"
+ "fmt"
+ "internal/trace"
+ "internal/trace/traceviewer/format"
+ "io"
+ "strconv"
+ "time"
+)
+
+type TraceConsumer struct {
+ ConsumeTimeUnit func(unit string)
+ ConsumeViewerEvent func(v *format.Event, required bool)
+ ConsumeViewerFrame func(key string, f format.Frame)
+ Flush func()
+}
+
+// ViewerDataTraceConsumer returns a TraceConsumer that writes to w. The
+// startIdx and endIdx are used for splitting large traces. They refer to
+// indexes in the traceEvents output array, not the events in the trace input.
+func ViewerDataTraceConsumer(w io.Writer, startIdx, endIdx int64) TraceConsumer {
+ allFrames := make(map[string]format.Frame)
+ requiredFrames := make(map[string]format.Frame)
+ enc := json.NewEncoder(w)
+ written := 0
+ index := int64(-1)
+
+ io.WriteString(w, "{")
+ return TraceConsumer{
+ ConsumeTimeUnit: func(unit string) {
+ io.WriteString(w, `"displayTimeUnit":`)
+ enc.Encode(unit)
+ io.WriteString(w, ",")
+ },
+ ConsumeViewerEvent: func(v *format.Event, required bool) {
+ index++
+ if !required && (index < startIdx || index > endIdx) {
+ // not in the range. Skip!
+ return
+ }
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
+ s := strconv.Itoa(id)
+ requiredFrames[s] = allFrames[s]
+ })
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
+ s := strconv.Itoa(id)
+ requiredFrames[s] = allFrames[s]
+ })
+ if written == 0 {
+ io.WriteString(w, `"traceEvents": [`)
+ }
+ if written > 0 {
+ io.WriteString(w, ",")
+ }
+ enc.Encode(v)
+ // TODO(mknyszek): get rid of the extra \n inserted by enc.Encode.
+ // Same should be applied to splittingTraceConsumer.
+ written++
+ },
+ ConsumeViewerFrame: func(k string, v format.Frame) {
+ allFrames[k] = v
+ },
+ Flush: func() {
+ io.WriteString(w, `], "stackFrames":`)
+ enc.Encode(requiredFrames)
+ io.WriteString(w, `}`)
+ },
+ }
+}
+
+func SplittingTraceConsumer(max int) (*splitter, TraceConsumer) {
+ type eventSz struct {
+ Time float64
+ Sz int
+ Frames []int
+ }
+
+ var (
+ // data.Frames contains only the frames for required events.
+ data = format.Data{Frames: make(map[string]format.Frame)}
+
+ allFrames = make(map[string]format.Frame)
+
+ sizes []eventSz
+ cw countingWriter
+ )
+
+ s := new(splitter)
+
+ return s, TraceConsumer{
+ ConsumeTimeUnit: func(unit string) {
+ data.TimeUnit = unit
+ },
+ ConsumeViewerEvent: func(v *format.Event, required bool) {
+ if required {
+ // Store required events inside data so flush
+ // can include them in the required part of the
+ // trace.
+ data.Events = append(data.Events, v)
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
+ s := strconv.Itoa(id)
+ data.Frames[s] = allFrames[s]
+ })
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
+ s := strconv.Itoa(id)
+ data.Frames[s] = allFrames[s]
+ })
+ return
+ }
+ enc := json.NewEncoder(&cw)
+ enc.Encode(v)
+ size := eventSz{Time: v.Time, Sz: cw.size + 1} // +1 for ",".
+ // Add referenced stack frames. Their size is computed
+ // in flush, where we can dedup across events.
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
+ size.Frames = append(size.Frames, id)
+ })
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
+ size.Frames = append(size.Frames, id) // This may add duplicates. We'll dedup later.
+ })
+ sizes = append(sizes, size)
+ cw.size = 0
+ },
+ ConsumeViewerFrame: func(k string, v format.Frame) {
+ allFrames[k] = v
+ },
+ Flush: func() {
+ // Calculate size of the mandatory part of the trace.
+ // This includes thread names and stack frames for
+ // required events.
+ cw.size = 0
+ enc := json.NewEncoder(&cw)
+ enc.Encode(data)
+ requiredSize := cw.size
+
+ // Then calculate size of each individual event and
+ // their stack frames, grouping them into ranges. We
+ // only include stack frames relevant to the events in
+ // the range to reduce overhead.
+
+ var (
+ start = 0
+
+ eventsSize = 0
+
+ frames = make(map[string]format.Frame)
+ framesSize = 0
+ )
+ for i, ev := range sizes {
+ eventsSize += ev.Sz
+
+ // Add required stack frames. Note that they
+ // may already be in the map.
+ for _, id := range ev.Frames {
+ s := strconv.Itoa(id)
+ _, ok := frames[s]
+ if ok {
+ continue
+ }
+ f := allFrames[s]
+ frames[s] = f
+ framesSize += stackFrameEncodedSize(uint(id), f)
+ }
+
+ total := requiredSize + framesSize + eventsSize
+ if total < max {
+ continue
+ }
+
+ // Reached max size, commit this range and
+ // start a new range.
+ startTime := time.Duration(sizes[start].Time * 1000)
+ endTime := time.Duration(ev.Time * 1000)
+ s.Ranges = append(s.Ranges, Range{
+ Name: fmt.Sprintf("%v-%v", startTime, endTime),
+ Start: start,
+ End: i + 1,
+ StartTime: int64(startTime),
+ EndTime: int64(endTime),
+ })
+ start = i + 1
+ frames = make(map[string]format.Frame)
+ framesSize = 0
+ eventsSize = 0
+ }
+ if len(s.Ranges) <= 1 {
+ s.Ranges = nil
+ return
+ }
+
+ if end := len(sizes) - 1; start < end {
+ s.Ranges = append(s.Ranges, Range{
+ Name: fmt.Sprintf("%v-%v", time.Duration(sizes[start].Time*1000), time.Duration(sizes[end].Time*1000)),
+ Start: start,
+ End: end,
+ StartTime: int64(sizes[start].Time * 1000),
+ EndTime: int64(sizes[end].Time * 1000),
+ })
+ }
+ },
+ }
+}
+
+type splitter struct {
+ Ranges []Range
+}
+
+type countingWriter struct {
+ size int
+}
+
+func (cw *countingWriter) Write(data []byte) (int, error) {
+ cw.size += len(data)
+ return len(data), nil
+}
+
+func stackFrameEncodedSize(id uint, f format.Frame) int {
+ // We want to know the marginal size of traceviewer.Data.Frames for
+ // each event. Running full JSON encoding of the map for each event is
+ // far too slow.
+ //
+ // Since the format is fixed, we can easily compute the size without
+ // encoding.
+ //
+ // A single entry looks like one of the following:
+ //
+ // "1":{"name":"main.main:30"},
+ // "10":{"name":"pkg.NewSession:173","parent":9},
+ //
+ // The parent is omitted if 0. The trailing comma is omitted from the
+ // last entry, but we don't need that much precision.
+ const (
+ baseSize = len(`"`) + len(`":{"name":"`) + len(`"},`)
+
+ // Don't count the trailing quote on the name, as that is
+ // counted in baseSize.
+ parentBaseSize = len(`,"parent":`)
+ )
+
+ size := baseSize
+
+ size += len(f.Name)
+
+ // Bytes for id (always positive).
+ for id > 0 {
+ size += 1
+ id /= 10
+ }
+
+ if f.Parent > 0 {
+ size += parentBaseSize
+ // Bytes for parent (always positive).
+ for f.Parent > 0 {
+ size += 1
+ f.Parent /= 10
+ }
+ }
+
+ return size
+}
+
+// WalkStackFrames calls fn for id and all of its parent frames from allFrames.
+func WalkStackFrames(allFrames map[string]format.Frame, id int, fn func(id int)) {
+ for id != 0 {
+ f, ok := allFrames[strconv.Itoa(id)]
+ if !ok {
+ break
+ }
+ fn(id)
+ id = f.Parent
+ }
+}
+
+type Mode int
+
+const (
+ ModeGoroutineOriented Mode = 1 << iota
+ ModeTaskOriented
+ ModeThreadOriented // Mutually exclusive with ModeGoroutineOriented.
+)
+
+// NewEmitter returns a new Emitter that writes to c. The rangeStart and
+// rangeEnd args are used for splitting large traces.
+func NewEmitter(c TraceConsumer, rangeStart, rangeEnd time.Duration) *Emitter {
+ c.ConsumeTimeUnit("ns")
+
+ return &Emitter{
+ c: c,
+ rangeStart: rangeStart,
+ rangeEnd: rangeEnd,
+ frameTree: frameNode{children: make(map[uint64]frameNode)},
+ resources: make(map[uint64]string),
+ tasks: make(map[uint64]task),
+ }
+}
+
+type Emitter struct {
+ c TraceConsumer
+ rangeStart time.Duration
+ rangeEnd time.Duration
+
+ heapStats, prevHeapStats heapStats
+ gstates, prevGstates [gStateCount]int64
+ threadStats, prevThreadStats [threadStateCount]int64
+ gomaxprocs uint64
+ frameTree frameNode
+ frameSeq int
+ arrowSeq uint64
+ filter func(uint64) bool
+ resourceType string
+ resources map[uint64]string
+ focusResource uint64
+ tasks map[uint64]task
+ asyncSliceSeq uint64
+}
+
+type task struct {
+ name string
+ sortIndex int
+}
+
+func (e *Emitter) Gomaxprocs(v uint64) {
+ if v > e.gomaxprocs {
+ e.gomaxprocs = v
+ }
+}
+
+func (e *Emitter) Resource(id uint64, name string) {
+ if e.filter != nil && !e.filter(id) {
+ return
+ }
+ e.resources[id] = name
+}
+
+func (e *Emitter) SetResourceType(name string) {
+ e.resourceType = name
+}
+
+func (e *Emitter) SetResourceFilter(filter func(uint64) bool) {
+ e.filter = filter
+}
+
+func (e *Emitter) Task(id uint64, name string, sortIndex int) {
+ e.tasks[id] = task{name, sortIndex}
+}
+
+func (e *Emitter) Slice(s SliceEvent) {
+ if e.filter != nil && !e.filter(s.Resource) {
+ return
+ }
+ e.slice(s, format.ProcsSection, "")
+}
+
+func (e *Emitter) TaskSlice(s SliceEvent) {
+ e.slice(s, format.TasksSection, pickTaskColor(s.Resource))
+}
+
+func (e *Emitter) slice(s SliceEvent, sectionID uint64, cname string) {
+ if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) {
+ return
+ }
+ e.OptionalEvent(&format.Event{
+ Name: s.Name,
+ Phase: "X",
+ Time: viewerTime(s.Ts),
+ Dur: viewerTime(s.Dur),
+ PID: sectionID,
+ TID: s.Resource,
+ Stack: s.Stack,
+ EndStack: s.EndStack,
+ Arg: s.Arg,
+ Cname: cname,
+ })
+}
+
+type SliceEvent struct {
+ Name string
+ Ts time.Duration
+ Dur time.Duration
+ Resource uint64
+ Stack int
+ EndStack int
+ Arg any
+}
+
+func (e *Emitter) AsyncSlice(s AsyncSliceEvent) {
+ if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) {
+ return
+ }
+ if e.filter != nil && !e.filter(s.Resource) {
+ return
+ }
+ cname := ""
+ if s.TaskColorIndex != 0 {
+ cname = pickTaskColor(s.TaskColorIndex)
+ }
+ e.asyncSliceSeq++
+ e.OptionalEvent(&format.Event{
+ Category: s.Category,
+ Name: s.Name,
+ Phase: "b",
+ Time: viewerTime(s.Ts),
+ TID: s.Resource,
+ ID: e.asyncSliceSeq,
+ Scope: s.Scope,
+ Stack: s.Stack,
+ Cname: cname,
+ })
+ e.OptionalEvent(&format.Event{
+ Category: s.Category,
+ Name: s.Name,
+ Phase: "e",
+ Time: viewerTime(s.Ts + s.Dur),
+ TID: s.Resource,
+ ID: e.asyncSliceSeq,
+ Scope: s.Scope,
+ Stack: s.EndStack,
+ Arg: s.Arg,
+ Cname: cname,
+ })
+}
+
+type AsyncSliceEvent struct {
+ SliceEvent
+ Category string
+ Scope string
+ TaskColorIndex uint64 // Take on the same color as the task with this ID.
+}
+
+func (e *Emitter) Instant(i InstantEvent) {
+ if !e.tsWithinRange(i.Ts) {
+ return
+ }
+ if e.filter != nil && !e.filter(i.Resource) {
+ return
+ }
+ cname := ""
+ e.OptionalEvent(&format.Event{
+ Name: i.Name,
+ Category: i.Category,
+ Phase: "I",
+ Scope: "t",
+ Time: viewerTime(i.Ts),
+ PID: format.ProcsSection,
+ TID: i.Resource,
+ Stack: i.Stack,
+ Cname: cname,
+ Arg: i.Arg,
+ })
+}
+
+type InstantEvent struct {
+ Ts time.Duration
+ Name string
+ Category string
+ Resource uint64
+ Stack int
+ Arg any
+}
+
+func (e *Emitter) Arrow(a ArrowEvent) {
+ if e.filter != nil && (!e.filter(a.FromResource) || !e.filter(a.ToResource)) {
+ return
+ }
+ e.arrow(a, format.ProcsSection)
+}
+
+func (e *Emitter) TaskArrow(a ArrowEvent) {
+ e.arrow(a, format.TasksSection)
+}
+
+func (e *Emitter) arrow(a ArrowEvent, sectionID uint64) {
+ if !e.tsWithinRange(a.Start) || !e.tsWithinRange(a.End) {
+ return
+ }
+ e.arrowSeq++
+ e.OptionalEvent(&format.Event{
+ Name: a.Name,
+ Phase: "s",
+ TID: a.FromResource,
+ PID: sectionID,
+ ID: e.arrowSeq,
+ Time: viewerTime(a.Start),
+ Stack: a.FromStack,
+ })
+ e.OptionalEvent(&format.Event{
+ Name: a.Name,
+ Phase: "t",
+ TID: a.ToResource,
+ PID: sectionID,
+ ID: e.arrowSeq,
+ Time: viewerTime(a.End),
+ })
+}
+
+type ArrowEvent struct {
+ Name string
+ Start time.Duration
+ End time.Duration
+ FromResource uint64
+ FromStack int
+ ToResource uint64
+}
+
+func (e *Emitter) Event(ev *format.Event) {
+ e.c.ConsumeViewerEvent(ev, true)
+}
+
+func (e *Emitter) HeapAlloc(ts time.Duration, v uint64) {
+ e.heapStats.heapAlloc = v
+ e.emitHeapCounters(ts)
+}
+
+func (e *Emitter) Focus(id uint64) {
+ e.focusResource = id
+}
+
+func (e *Emitter) GoroutineTransition(ts time.Duration, from, to GState) {
+ e.gstates[from]--
+ e.gstates[to]++
+ if e.prevGstates == e.gstates {
+ return
+ }
+ if e.tsWithinRange(ts) {
+ e.OptionalEvent(&format.Event{
+ Name: "Goroutines",
+ Phase: "C",
+ Time: viewerTime(ts),
+ PID: 1,
+ Arg: &format.GoroutineCountersArg{
+ Running: uint64(e.gstates[GRunning]),
+ Runnable: uint64(e.gstates[GRunnable]),
+ GCWaiting: uint64(e.gstates[GWaitingGC]),
+ },
+ })
+ }
+ e.prevGstates = e.gstates
+}
+
+func (e *Emitter) IncThreadStateCount(ts time.Duration, state ThreadState, delta int64) {
+ e.threadStats[state] += delta
+ if e.prevThreadStats == e.threadStats {
+ return
+ }
+ if e.tsWithinRange(ts) {
+ e.OptionalEvent(&format.Event{
+ Name: "Threads",
+ Phase: "C",
+ Time: viewerTime(ts),
+ PID: 1,
+ Arg: &format.ThreadCountersArg{
+ Running: int64(e.threadStats[ThreadStateRunning]),
+ InSyscall: int64(e.threadStats[ThreadStateInSyscall]),
+ // TODO(mknyszek): Why is InSyscallRuntime not included here?
+ },
+ })
+ }
+ e.prevThreadStats = e.threadStats
+}
+
+func (e *Emitter) HeapGoal(ts time.Duration, v uint64) {
+ // This cutoff at 1 PiB is a Workaround for https://github.com/golang/go/issues/63864.
+ //
+ // TODO(mknyszek): Remove this once the problem has been fixed.
+ const PB = 1 << 50
+ if v > PB {
+ v = 0
+ }
+ e.heapStats.nextGC = v
+ e.emitHeapCounters(ts)
+}
+
+func (e *Emitter) emitHeapCounters(ts time.Duration) {
+ if e.prevHeapStats == e.heapStats {
+ return
+ }
+ diff := uint64(0)
+ if e.heapStats.nextGC > e.heapStats.heapAlloc {
+ diff = e.heapStats.nextGC - e.heapStats.heapAlloc
+ }
+ if e.tsWithinRange(ts) {
+ e.OptionalEvent(&format.Event{
+ Name: "Heap",
+ Phase: "C",
+ Time: viewerTime(ts),
+ PID: 1,
+ Arg: &format.HeapCountersArg{Allocated: e.heapStats.heapAlloc, NextGC: diff},
+ })
+ }
+ e.prevHeapStats = e.heapStats
+}
+
+// Err returns an error if the emitter is in an invalid state.
+func (e *Emitter) Err() error {
+ if e.gstates[GRunnable] < 0 || e.gstates[GRunning] < 0 || e.threadStats[ThreadStateInSyscall] < 0 || e.threadStats[ThreadStateInSyscallRuntime] < 0 {
+ return fmt.Errorf(
+ "runnable=%d running=%d insyscall=%d insyscallRuntime=%d",
+ e.gstates[GRunnable],
+ e.gstates[GRunning],
+ e.threadStats[ThreadStateInSyscall],
+ e.threadStats[ThreadStateInSyscallRuntime],
+ )
+ }
+ return nil
+}
+
+func (e *Emitter) tsWithinRange(ts time.Duration) bool {
+ return e.rangeStart <= ts && ts <= e.rangeEnd
+}
+
+// OptionalEvent emits ev if it's within the time range of of the consumer, i.e.
+// the selected trace split range.
+func (e *Emitter) OptionalEvent(ev *format.Event) {
+ e.c.ConsumeViewerEvent(ev, false)
+}
+
+func (e *Emitter) Flush() {
+ e.processMeta(format.StatsSection, "STATS", 0)
+
+ if len(e.tasks) != 0 {
+ e.processMeta(format.TasksSection, "TASKS", 1)
+ }
+ for id, task := range e.tasks {
+ e.threadMeta(format.TasksSection, id, task.name, task.sortIndex)
+ }
+
+ e.processMeta(format.ProcsSection, e.resourceType, 2)
+
+ e.threadMeta(format.ProcsSection, trace.GCP, "GC", -6)
+ e.threadMeta(format.ProcsSection, trace.NetpollP, "Network", -5)
+ e.threadMeta(format.ProcsSection, trace.TimerP, "Timers", -4)
+ e.threadMeta(format.ProcsSection, trace.SyscallP, "Syscalls", -3)
+
+ for id, name := range e.resources {
+ priority := int(id)
+ if e.focusResource != 0 && id == e.focusResource {
+ // Put the focus goroutine on top.
+ priority = -2
+ }
+ e.threadMeta(format.ProcsSection, id, name, priority)
+ }
+
+ e.c.Flush()
+}
+
+func (e *Emitter) threadMeta(sectionID, tid uint64, name string, priority int) {
+ e.Event(&format.Event{
+ Name: "thread_name",
+ Phase: "M",
+ PID: sectionID,
+ TID: tid,
+ Arg: &format.NameArg{Name: name},
+ })
+ e.Event(&format.Event{
+ Name: "thread_sort_index",
+ Phase: "M",
+ PID: sectionID,
+ TID: tid,
+ Arg: &format.SortIndexArg{Index: priority},
+ })
+}
+
+func (e *Emitter) processMeta(sectionID uint64, name string, priority int) {
+ e.Event(&format.Event{
+ Name: "process_name",
+ Phase: "M",
+ PID: sectionID,
+ Arg: &format.NameArg{Name: name},
+ })
+ e.Event(&format.Event{
+ Name: "process_sort_index",
+ Phase: "M",
+ PID: sectionID,
+ Arg: &format.SortIndexArg{Index: priority},
+ })
+}
+
+// Stack emits the given frames and returns a unique id for the stack. No
+// pointers to the given data are being retained beyond the call to Stack.
+func (e *Emitter) Stack(stk []*trace.Frame) int {
+ return e.buildBranch(e.frameTree, stk)
+}
+
+// buildBranch builds one branch in the prefix tree rooted at ctx.frameTree.
+func (e *Emitter) buildBranch(parent frameNode, stk []*trace.Frame) int {
+ if len(stk) == 0 {
+ return parent.id
+ }
+ last := len(stk) - 1
+ frame := stk[last]
+ stk = stk[:last]
+
+ node, ok := parent.children[frame.PC]
+ if !ok {
+ e.frameSeq++
+ node.id = e.frameSeq
+ node.children = make(map[uint64]frameNode)
+ parent.children[frame.PC] = node
+ e.c.ConsumeViewerFrame(strconv.Itoa(node.id), format.Frame{Name: fmt.Sprintf("%v:%v", frame.Fn, frame.Line), Parent: parent.id})
+ }
+ return e.buildBranch(node, stk)
+}
+
+type heapStats struct {
+ heapAlloc uint64
+ nextGC uint64
+}
+
+func viewerTime(t time.Duration) float64 {
+ return float64(t) / float64(time.Microsecond)
+}
+
+type GState int
+
+const (
+ GDead GState = iota
+ GRunnable
+ GRunning
+ GWaiting
+ GWaitingGC
+
+ gStateCount
+)
+
+type ThreadState int
+
+const (
+ ThreadStateInSyscall ThreadState = iota
+ ThreadStateInSyscallRuntime
+ ThreadStateRunning
+
+ threadStateCount
+)
+
+type frameNode struct {
+ id int
+ children map[uint64]frameNode
+}
+
+// Mapping from more reasonable color names to the reserved color names in
+// https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html#L50
+// The chrome trace viewer allows only those as cname values.
+const (
+ colorLightMauve = "thread_state_uninterruptible" // 182, 125, 143
+ colorOrange = "thread_state_iowait" // 255, 140, 0
+ colorSeafoamGreen = "thread_state_running" // 126, 200, 148
+ colorVistaBlue = "thread_state_runnable" // 133, 160, 210
+ colorTan = "thread_state_unknown" // 199, 155, 125
+ colorIrisBlue = "background_memory_dump" // 0, 180, 180
+ colorMidnightBlue = "light_memory_dump" // 0, 0, 180
+ colorDeepMagenta = "detailed_memory_dump" // 180, 0, 180
+ colorBlue = "vsync_highlight_color" // 0, 0, 255
+ colorGrey = "generic_work" // 125, 125, 125
+ colorGreen = "good" // 0, 125, 0
+ colorDarkGoldenrod = "bad" // 180, 125, 0
+ colorPeach = "terrible" // 180, 0, 0
+ colorBlack = "black" // 0, 0, 0
+ colorLightGrey = "grey" // 221, 221, 221
+ colorWhite = "white" // 255, 255, 255
+ colorYellow = "yellow" // 255, 255, 0
+ colorOlive = "olive" // 100, 100, 0
+ colorCornflowerBlue = "rail_response" // 67, 135, 253
+ colorSunsetOrange = "rail_animation" // 244, 74, 63
+ colorTangerine = "rail_idle" // 238, 142, 0
+ colorShamrockGreen = "rail_load" // 13, 168, 97
+ colorGreenishYellow = "startup" // 230, 230, 0
+ colorDarkGrey = "heap_dump_stack_frame" // 128, 128, 128
+ colorTawny = "heap_dump_child_node_arrow" // 204, 102, 0
+ colorLemon = "cq_build_running" // 255, 255, 119
+ colorLime = "cq_build_passed" // 153, 238, 102
+ colorPink = "cq_build_failed" // 238, 136, 136
+ colorSilver = "cq_build_abandoned" // 187, 187, 187
+ colorManzGreen = "cq_build_attempt_runnig" // 222, 222, 75
+ colorKellyGreen = "cq_build_attempt_passed" // 108, 218, 35
+ colorAnotherGrey = "cq_build_attempt_failed" // 187, 187, 187
+)
+
+var colorForTask = []string{
+ colorLightMauve,
+ colorOrange,
+ colorSeafoamGreen,
+ colorVistaBlue,
+ colorTan,
+ colorMidnightBlue,
+ colorIrisBlue,
+ colorDeepMagenta,
+ colorGreen,
+ colorDarkGoldenrod,
+ colorPeach,
+ colorOlive,
+ colorCornflowerBlue,
+ colorSunsetOrange,
+ colorTangerine,
+ colorShamrockGreen,
+ colorTawny,
+ colorLemon,
+ colorLime,
+ colorPink,
+ colorSilver,
+ colorManzGreen,
+ colorKellyGreen,
+}
+
+func pickTaskColor(id uint64) string {
+ idx := id % uint64(len(colorForTask))
+ return colorForTask[idx]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/format/format.go b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/format/format.go
new file mode 100644
index 0000000000000000000000000000000000000000..83f32767042d3a95814545d29d4a29de907a1200
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/format/format.go
@@ -0,0 +1,79 @@
+// 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 traceviewer provides definitions of the JSON data structures
+// used by the Chrome trace viewer.
+//
+// The official description of the format is in this file:
+// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
+//
+// Note: This can't be part of the parent traceviewer package as that would
+// throw. go_bootstrap cannot depend on the cgo version of package net in ./make.bash.
+package format
+
+type Data struct {
+ Events []*Event `json:"traceEvents"`
+ Frames map[string]Frame `json:"stackFrames"`
+ TimeUnit string `json:"displayTimeUnit"`
+}
+
+type Event struct {
+ Name string `json:"name,omitempty"`
+ Phase string `json:"ph"`
+ Scope string `json:"s,omitempty"`
+ Time float64 `json:"ts"`
+ Dur float64 `json:"dur,omitempty"`
+ PID uint64 `json:"pid"`
+ TID uint64 `json:"tid"`
+ ID uint64 `json:"id,omitempty"`
+ BindPoint string `json:"bp,omitempty"`
+ Stack int `json:"sf,omitempty"`
+ EndStack int `json:"esf,omitempty"`
+ Arg any `json:"args,omitempty"`
+ Cname string `json:"cname,omitempty"`
+ Category string `json:"cat,omitempty"`
+}
+
+type Frame struct {
+ Name string `json:"name"`
+ Parent int `json:"parent,omitempty"`
+}
+
+type NameArg struct {
+ Name string `json:"name"`
+}
+
+type BlockedArg struct {
+ Blocked string `json:"blocked"`
+}
+
+type SortIndexArg struct {
+ Index int `json:"sort_index"`
+}
+
+type HeapCountersArg struct {
+ Allocated uint64
+ NextGC uint64
+}
+
+const (
+ ProcsSection = 0 // where Goroutines or per-P timelines are presented.
+ StatsSection = 1 // where counters are presented.
+ TasksSection = 2 // where Task hierarchy & timeline is presented.
+)
+
+type GoroutineCountersArg struct {
+ Running uint64
+ Runnable uint64
+ GCWaiting uint64
+}
+
+type ThreadCountersArg struct {
+ Running int64
+ InSyscall int64
+}
+
+type ThreadIDArg struct {
+ ThreadID uint64
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/histogram.go b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/histogram.go
new file mode 100644
index 0000000000000000000000000000000000000000..d4c8749dc9a87bc16ec7c1cd6e43c69292dd0d7b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/histogram.go
@@ -0,0 +1,86 @@
+// 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 traceviewer
+
+import (
+ "fmt"
+ "html/template"
+ "math"
+ "strings"
+ "time"
+)
+
+// TimeHistogram is an high-dynamic-range histogram for durations.
+type TimeHistogram struct {
+ Count int
+ Buckets []int
+ MinBucket, MaxBucket int
+}
+
+// Five buckets for every power of 10.
+var logDiv = math.Log(math.Pow(10, 1.0/5))
+
+// Add adds a single sample to the histogram.
+func (h *TimeHistogram) Add(d time.Duration) {
+ var bucket int
+ if d > 0 {
+ bucket = int(math.Log(float64(d)) / logDiv)
+ }
+ if len(h.Buckets) <= bucket {
+ h.Buckets = append(h.Buckets, make([]int, bucket-len(h.Buckets)+1)...)
+ h.Buckets = h.Buckets[:cap(h.Buckets)]
+ }
+ h.Buckets[bucket]++
+ if bucket < h.MinBucket || h.MaxBucket == 0 {
+ h.MinBucket = bucket
+ }
+ if bucket > h.MaxBucket {
+ h.MaxBucket = bucket
+ }
+ h.Count++
+}
+
+// BucketMin returns the minimum duration value for a provided bucket.
+func (h *TimeHistogram) BucketMin(bucket int) time.Duration {
+ return time.Duration(math.Exp(float64(bucket) * logDiv))
+}
+
+// ToHTML renders the histogram as HTML.
+func (h *TimeHistogram) ToHTML(urlmaker func(min, max time.Duration) string) template.HTML {
+ if h == nil || h.Count == 0 {
+ return template.HTML("")
+ }
+
+ const barWidth = 400
+
+ maxCount := 0
+ for _, count := range h.Buckets {
+ if count > maxCount {
+ maxCount = count
+ }
+ }
+
+ w := new(strings.Builder)
+ fmt.Fprintf(w, `
+ This web server provides various visualizations of an event log gathered during
+ the execution of a Go program that uses the runtime/trace package.
+
+
+
+ Large traces are split into multiple sections of equal data size
+ (not duration) to avoid overwhelming the visualizer.
+
+{{end}}
+
+ This view displays a series of timelines for a type of resource.
+ The "by proc" view consists of a timeline for each of the GOMAXPROCS
+ logical processors, showing which goroutine (if any) was running on that
+ logical processor at each moment.
+ The "by thread" view (if available) consists of a similar timeline for each
+ OS thread.
+
+ Each goroutine has an identifying number (e.g. G123), main function,
+ and color.
+
+ A colored bar represents an uninterrupted span of execution.
+
+ Execution of a goroutine may migrate from one logical processor to another,
+ causing a single colored bar to be horizontally continuous but
+ vertically displaced.
+
+
+ Clicking on a span reveals information about it, such as its
+ duration, its causal predecessors and successors, and the stack trace
+ at the final moment when it yielded the logical processor, for example
+ because it made a system call or tried to acquire a mutex.
+
+ Directly underneath each bar, a smaller bar or more commonly a fine
+ vertical line indicates an event occurring during its execution.
+ Some of these are related to garbage collection; most indicate that
+ a goroutine yielded its logical processor but then immediately resumed execution
+ on the same logical processor. Clicking on the event displays the stack trace
+ at the moment it occurred.
+
+
+ The causal relationships between spans of goroutine execution
+ can be displayed by clicking the Flow Events button at the top.
+
+
+ At the top ("STATS"), there are three additional timelines that
+ display statistical information.
+
+ "Goroutines" is a time series of the count of existing goroutines;
+ clicking on it displays their breakdown by state at that moment:
+ running, runnable, or waiting.
+
+ "Heap" is a time series of the amount of heap memory allocated (in orange)
+ and (in green) the allocation limit at which the next GC cycle will begin.
+
+ "Threads" shows the number of kernel threads in existence: there is
+ always one kernel thread per logical processor, and additional threads
+ are created for calls to non-Go code such as a system call or a
+ function written in C.
+
+
+ Above the event trace for the first logical processor are
+ traces for various runtime-internal events.
+
+ The "GC" bar shows when the garbage collector is running, and in which stage.
+ Garbage collection may temporarily affect all the logical processors
+ and the other metrics.
+
+ The "Network", "Timers", and "Syscalls" traces indicate events in
+ the runtime that cause goroutines to wake up.
+
+
+ The visualization allows you to navigate events at scales ranging from several
+ seconds to a handful of nanoseconds.
+
+ Consult the documentation for the Chromium Trace Event Profiling Tool
+ for help navigating the view.
+
+
+
+ This view displays information about each set of goroutines that
+ shares the same main function.
+
+ Clicking on a main function shows links to the four types of
+ blocking profile (see below) applied to that subset of goroutines.
+
+ It also shows a table of specific goroutine instances, with various
+ execution statistics and a link to the event timeline for each one.
+
+ The timeline displays only the selected goroutine and any others it
+ interacts with via block/unblock events. (The timeline is
+ goroutine-oriented rather than logical processor-oriented.)
+
+
+
+ Each link below displays a global profile in zoomable graph form as
+ produced by pprof's "web" command.
+
+ In addition there is a link to download the profile for offline
+ analysis with pprof.
+
+ All four profiles represent causes of delay that prevent a goroutine
+ from running on a logical processor: because it was waiting for the network,
+ for a synchronization operation on a mutex or channel, for a system call,
+ or for a logical processor to become available.
+
+
+ The links below display, for each region and task, a histogram of its execution times.
+
+ Each histogram bucket contains a sample trace that records the
+ sequence of events such as goroutine creations, log events, and
+ subregion start/end times.
+
+ For each task, you can click through to a logical-processor or
+ goroutine-oriented view showing the tasks and regions on the
+ timeline.
+
+ Such information may help uncover which steps in a region are
+ unexpectedly slow, or reveal relationships between the data values
+ logged in a request and its running time.
+
+
+ This chart indicates the maximum GC pause time (the largest x value
+ for which y is zero), and more generally, the fraction of time that
+ the processors are available to application goroutines ("mutators"),
+ for any time window of a specified size, in the worst case.
+
+
+
+`))
+
+type View struct {
+ Type ViewType
+ Ranges []Range
+}
+
+type ViewType string
+
+const (
+ ViewProc ViewType = "proc"
+ ViewThread ViewType = "thread"
+)
+
+func (v View) URL(rangeIdx int) string {
+ if rangeIdx < 0 {
+ return fmt.Sprintf("/trace?view=%s", v.Type)
+ }
+ return v.Ranges[rangeIdx].URL(v.Type)
+}
+
+type Range struct {
+ Name string
+ Start int
+ End int
+ StartTime int64
+ EndTime int64
+}
+
+func (r Range) URL(viewType ViewType) string {
+ return fmt.Sprintf("/trace?view=%s&start=%d&end=%d", viewType, r.Start, r.End)
+}
+
+func TraceHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ html := strings.ReplaceAll(templTrace, "{{PARAMS}}", r.Form.Encode())
+ w.Write([]byte(html))
+ })
+}
+
+// https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962/tracing/docs/embedding-trace-viewer.md
+// This is almost verbatim copy of https://chromium-review.googlesource.com/c/catapult/+/2062938/2/tracing/bin/index.html
+var templTrace = `
+
+
+
+
+
+Select a point for details.
+
+
+`
+
+// HandleDetails serves details of an MMU graph at a particular window.
+func (m *mmu) HandleDetails(w http.ResponseWriter, r *http.Request) {
+ _, mmuCurve, err := m.get(requestUtilFlags(r))
+ if err != nil {
+ http.Error(w, fmt.Sprintf("failed to produce MMU data: %v", err), http.StatusInternalServerError)
+ return
+ }
+
+ windowStr := r.FormValue("window")
+ window, err := strconv.ParseUint(windowStr, 10, 64)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("failed to parse window parameter %q: %v", windowStr, err), http.StatusBadRequest)
+ return
+ }
+ worst := mmuCurve.Examples(time.Duration(window), 10)
+
+ // Construct a link for each window.
+ var links []linkedUtilWindow
+ for _, ui := range worst {
+ links = append(links, m.newLinkedUtilWindow(ui, time.Duration(window)))
+ }
+
+ err = json.NewEncoder(w).Encode(links)
+ if err != nil {
+ log.Printf("failed to serialize trace: %v", err)
+ return
+ }
+}
+
+type linkedUtilWindow struct {
+ trace.UtilWindow
+ URL string
+}
+
+func (m *mmu) newLinkedUtilWindow(ui trace.UtilWindow, window time.Duration) linkedUtilWindow {
+ // Find the range containing this window.
+ var r Range
+ for _, r = range m.ranges {
+ if r.EndTime > ui.Time {
+ break
+ }
+ }
+ return linkedUtilWindow{ui, fmt.Sprintf("%s#%v:%v", r.URL(ViewProc), float64(ui.Time)/1e6, float64(ui.Time+int64(window))/1e6)}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/pprof.go b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/pprof.go
new file mode 100644
index 0000000000000000000000000000000000000000..1377b3c614c81c6031300a1a0767267e6ffdcd85
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/pprof.go
@@ -0,0 +1,150 @@
+// 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.
+
+// Serving of pprof-like profiles.
+
+package traceviewer
+
+import (
+ "bufio"
+ "fmt"
+ "internal/profile"
+ "internal/trace"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "time"
+)
+
+type ProfileFunc func(r *http.Request) ([]ProfileRecord, error)
+
+// SVGProfileHandlerFunc serves pprof-like profile generated by prof as svg.
+func SVGProfileHandlerFunc(f ProfileFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if r.FormValue("raw") != "" {
+ w.Header().Set("Content-Type", "application/octet-stream")
+
+ failf := func(s string, args ...any) {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.Header().Set("X-Go-Pprof", "1")
+ http.Error(w, fmt.Sprintf(s, args...), http.StatusInternalServerError)
+ }
+ records, err := f(r)
+ if err != nil {
+ failf("failed to get records: %v", err)
+ return
+ }
+ if err := BuildProfile(records).Write(w); err != nil {
+ failf("failed to write profile: %v", err)
+ return
+ }
+ return
+ }
+
+ blockf, err := os.CreateTemp("", "block")
+ if err != nil {
+ http.Error(w, fmt.Sprintf("failed to create temp file: %v", err), http.StatusInternalServerError)
+ return
+ }
+ defer func() {
+ blockf.Close()
+ os.Remove(blockf.Name())
+ }()
+ records, err := f(r)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("failed to generate profile: %v", err), http.StatusInternalServerError)
+ }
+ blockb := bufio.NewWriter(blockf)
+ if err := BuildProfile(records).Write(blockb); err != nil {
+ http.Error(w, fmt.Sprintf("failed to write profile: %v", err), http.StatusInternalServerError)
+ return
+ }
+ if err := blockb.Flush(); err != nil {
+ http.Error(w, fmt.Sprintf("failed to flush temp file: %v", err), http.StatusInternalServerError)
+ return
+ }
+ if err := blockf.Close(); err != nil {
+ http.Error(w, fmt.Sprintf("failed to close temp file: %v", err), http.StatusInternalServerError)
+ return
+ }
+ svgFilename := blockf.Name() + ".svg"
+ if output, err := exec.Command(goCmd(), "tool", "pprof", "-svg", "-output", svgFilename, blockf.Name()).CombinedOutput(); err != nil {
+ http.Error(w, fmt.Sprintf("failed to execute go tool pprof: %v\n%s", err, output), http.StatusInternalServerError)
+ return
+ }
+ defer os.Remove(svgFilename)
+ w.Header().Set("Content-Type", "image/svg+xml")
+ http.ServeFile(w, r, svgFilename)
+ }
+}
+
+type ProfileRecord struct {
+ Stack []*trace.Frame
+ Count uint64
+ Time time.Duration
+}
+
+func BuildProfile(prof []ProfileRecord) *profile.Profile {
+ p := &profile.Profile{
+ PeriodType: &profile.ValueType{Type: "trace", Unit: "count"},
+ Period: 1,
+ SampleType: []*profile.ValueType{
+ {Type: "contentions", Unit: "count"},
+ {Type: "delay", Unit: "nanoseconds"},
+ },
+ }
+ locs := make(map[uint64]*profile.Location)
+ funcs := make(map[string]*profile.Function)
+ for _, rec := range prof {
+ var sloc []*profile.Location
+ for _, frame := range rec.Stack {
+ loc := locs[frame.PC]
+ if loc == nil {
+ fn := funcs[frame.File+frame.Fn]
+ if fn == nil {
+ fn = &profile.Function{
+ ID: uint64(len(p.Function) + 1),
+ Name: frame.Fn,
+ SystemName: frame.Fn,
+ Filename: frame.File,
+ }
+ p.Function = append(p.Function, fn)
+ funcs[frame.File+frame.Fn] = fn
+ }
+ loc = &profile.Location{
+ ID: uint64(len(p.Location) + 1),
+ Address: frame.PC,
+ Line: []profile.Line{
+ {
+ Function: fn,
+ Line: int64(frame.Line),
+ },
+ },
+ }
+ p.Location = append(p.Location, loc)
+ locs[frame.PC] = loc
+ }
+ sloc = append(sloc, loc)
+ }
+ p.Sample = append(p.Sample, &profile.Sample{
+ Value: []int64{int64(rec.Count), int64(rec.Time)},
+ Location: sloc,
+ })
+ }
+ return p
+}
+
+func goCmd() string {
+ var exeSuffix string
+ if runtime.GOOS == "windows" {
+ exeSuffix = ".exe"
+ }
+ path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
+ if _, err := os.Stat(path); err == nil {
+ return path
+ }
+ return "go"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/README.md b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b0ca86a39783c142d056c2a5114572828c8f6db2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/README.md
@@ -0,0 +1,106 @@
+## Resources for Go's trace viewer
+
+Go execution trace UI (`go tool trace`) embeds
+Chrome's trace viewer (Catapult) following the
+[instructions](
+https://chromium.googlesource.com/catapult/+/refs/heads/master/tracing/docs/embedding-trace-viewer.md). This directory contains
+the helper files to embed Chrome's trace viewer.
+
+The current resources were generated/copied from
+[`Catapult@9508452e18f130c98499cb4c4f1e1efaedee8962`](
+https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962).
+
+### Updating `trace_viewer_full.html`
+
+The file was generated by catapult's `vulcanize_trace_viewer` command.
+
+```
+$ git clone https://chromium.googlesource.com/catapult
+$ cd catapult
+$ ./tracing/bin/vulcanize_trace_viewer --config=full
+$ cp tracing/bin/trace_viewer_full.html $GOROOT/src/cmd/trace/static/trace_viewer_full.html
+```
+
+We are supposed to use --config=lean (produces smaller html),
+but it is broken at the moment:
+https://github.com/catapult-project/catapult/issues/2247
+
+### Updating `webcomponents.min.js`
+
+`webcomponents.min.js` is necessary to let the trace viewer page
+to import the `trace_viewer_full.html`.
+This is copied from the catapult repo.
+
+```
+$ cp third_party/polymer/components/webcomponentsjs/webcomponents.min.js $GOROOT/src/cmd/trace/static/webcomponents.min.js
+```
+
+## Licenses
+
+The license for trace-viewer is as follows:
+// Copyright (c) 2012 The Chromium 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:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+The license for webcomponents.min.js is as follows:
+
+/**
+ * @license
+ * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
+ * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
+ * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
+ * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
+ * Code distributed by Google as part of the polymer project is also
+ * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
+ */
+// Copyright (c) 2014 The Polymer 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:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/trace_viewer_full.html b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/trace_viewer_full.html
new file mode 100644
index 0000000000000000000000000000000000000000..ae6e35fca22badf007ee2a735c2937ebb7eba138
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/trace_viewer_full.html
@@ -0,0 +1,10441 @@
+
+
+
+ 0||n>0;)if(0!=t)if(0!=n){var l,u=e[t-1][n-1],d=e[t-1][n],p=e[t][n-1];l=d0){for(var u=0;u0&&r.length>0;){var i=n.pop(),a=r.pop();if(i!==a)break;o=i}return o}function u(e,t,n){t instanceof G.Window&&(t=t.document);var o,i=A(t),a=A(n),s=r(n,e),o=l(i,a);o||(o=a.root);for(var c=o;c;c=c.parent)for(var u=0;u0;i--)if(!g(t[i],e,o,t,r))return!1;return!0}function w(e,t,n,r){var o=ie,i=t[0]||n;return g(i,e,o,t,r)}function v(e,t,n,r){for(var o=ae,i=1;i0&&g(n,e,o,t,r)}function g(e,t,n,r,o){var i=z.get(e);if(!i)return!0;var a=o||s(r,e);if(a===e){if(n===oe)return!0;n===ae&&(n=ie)}else if(n===ae&&!t.bubbles)return!0;if("relatedTarget"in t){var c=B(t),l=c.relatedTarget;if(l){if(l instanceof Object&&l.addEventListener){var d=V(l),p=u(t,e,d);if(p===a)return!0}else p=null;Z.set(t,p)}}J.set(t,n);var h=t.type,f=!1;X.set(t,a),Y.set(t,e),i.depth++;for(var m=0,w=i.length;m=0;a--)e.removeChild(i[a]),i[a].parentNode_=t;U=!1;for(var a=0;a>>/g," ")}function r(e){return String(e).replace(/:host\(([^\s]+)\)/g,"$1").replace(/([^\s]):host/g,"$1").replace(":host","*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g," ")}function o(e,t){for(var n,r=e.firstElementChild;r;){if(r.matches(t))return r;if(n=o(r,t))return n;r=r.nextElementSibling}return null}function i(e,t){return e.matches(t)}function a(e,t,n){var r=e.localName;return r===t||r===n&&e.namespaceURI===j}function s(){return!0}function c(e,t,n){return e.localName===n}function l(e,t){return e.namespaceURI===t}function u(e,t,n){return e.namespaceURI===t&&e.localName===n}function d(e,t,n,r,o,i){for(var a=e.firstElementChild;a;)r(a,o,i)&&(n[t++]=a),t=d(a,t,n,r,o,i),a=a.nextElementSibling;return t}function p(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,null);if(c instanceof N)s=S.call(c,i);else{if(!(c instanceof C))return d(this,r,o,n,i,null);s=_.call(c,i)}return t(s,r,o,a)}function h(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=M.call(c,i,a);else{if(!(c instanceof C))return d(this,r,o,n,i,a);s=T.call(c,i,a)}return t(s,r,o,!1)}function f(n,r,o,i,a){var s,c=g(this),l=v(this).root;if(l instanceof e.wrappers.ShadowRoot)return d(this,r,o,n,i,a);if(c instanceof N)s=L.call(c,i,a);else{if(!(c instanceof C))return d(this,r,o,n,i,a);s=O.call(c,i,a)}return t(s,r,o,!1)}var m=e.wrappers.HTMLCollection,w=e.wrappers.NodeList,v=e.getTreeScope,g=e.unsafeUnwrap,b=e.wrap,y=document.querySelector,E=document.documentElement.querySelector,_=document.querySelectorAll,S=document.documentElement.querySelectorAll,T=document.getElementsByTagName,M=document.documentElement.getElementsByTagName,O=document.getElementsByTagNameNS,L=document.documentElement.getElementsByTagNameNS,N=window.Element,C=window.HTMLDocument||window.Document,j="http://www.w3.org/1999/xhtml",D={
+querySelector:function(t){var r=n(t),i=r!==t;t=r;var a,s=g(this),c=v(this).root;if(c instanceof e.wrappers.ShadowRoot)return o(this,t);if(s instanceof N)a=b(E.call(s,t));else{if(!(s instanceof C))return o(this,t);a=b(y.call(s,t))}return a&&!i&&(c=v(a).root)&&c instanceof e.wrappers.ShadowRoot?o(this,t):a},querySelectorAll:function(e){var t=n(e),r=t!==e;e=t;var o=new w;return o.length=p.call(this,i,0,o,e,r),o}},H={matches:function(t){return t=r(t),e.originalMatches.call(g(this),t)}},x={getElementsByTagName:function(e){var t=new m,n="*"===e?s:a;return t.length=h.call(this,n,0,t,e,e.toLowerCase()),t},getElementsByClassName:function(e){return this.querySelectorAll("."+e)},getElementsByTagNameNS:function(e,t){var n=new m,r=null;return r="*"===e?"*"===t?s:c:"*"===t?l:u,n.length=f.call(this,r,0,n,e||null,t),n}};e.GetElementsByInterface=x,e.SelectorsInterface=D,e.MatchesInterface=H}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;return e}function n(e){for(;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.previousSibling;return e}var r=e.wrappers.NodeList,o={get firstElementChild(){return t(this.firstChild)},get lastElementChild(){return n(this.lastChild)},get childElementCount(){for(var e=0,t=this.firstElementChild;t;t=t.nextElementSibling)e++;return e},get children(){for(var e=new r,t=0,n=this.firstElementChild;n;n=n.nextElementSibling)e[t++]=n;return e.length=t,e},remove:function(){var e=this.parentNode;e&&e.removeChild(this)}},i={get nextElementSibling(){return t(this.nextSibling)},get previousElementSibling(){return n(this.previousSibling)}},a={getElementById:function(e){return/[ \t\n\r\f]/.test(e)?null:this.querySelector('[id="'+e+'"]')}};e.ChildNodeInterface=i,e.NonElementParentNodeInterface=a,e.ParentNodeInterface=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}var n=e.ChildNodeInterface,r=e.wrappers.Node,o=e.enqueueMutation,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=window.CharacterData;t.prototype=Object.create(r.prototype),i(t.prototype,{get nodeValue(){return this.data},set nodeValue(e){this.data=e},get textContent(){return this.data},set textContent(e){this.data=e},get data(){return s(this).data},set data(e){var t=s(this).data;o(this,"characterData",{oldValue:t}),s(this).data=e}}),i(t.prototype,n),a(c,t,document.createTextNode("")),e.wrappers.CharacterData=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e>>>0}function n(e){r.call(this,e)}var r=e.wrappers.CharacterData,o=(e.enqueueMutation,e.mixin),i=e.registerWrapper,a=window.Text;n.prototype=Object.create(r.prototype),o(n.prototype,{splitText:function(e){e=t(e);var n=this.data;if(e>n.length)throw new Error("IndexSizeError");var r=n.slice(0,e),o=n.slice(e);this.data=r;var i=this.ownerDocument.createTextNode(o);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}}),i(a,n,document.createTextNode("")),e.wrappers.Text=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return i(e).getAttribute("class")}function n(e,t){a(e,"attributes",{name:"class",namespace:null,oldValue:t})}function r(t){e.invalidateRendererBasedOnAttribute(t,"class")}function o(e,o,i){var a=e.ownerElement_;if(null==a)return o.apply(e,i);var s=t(a),c=o.apply(e,i);return t(a)!==s&&(n(a,s),r(a)),c}if(!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH.");var i=e.unsafeUnwrap,a=e.enqueueMutation,s=DOMTokenList.prototype.add;DOMTokenList.prototype.add=function(){o(this,s,arguments)};var c=DOMTokenList.prototype.remove;DOMTokenList.prototype.remove=function(){o(this,c,arguments)};var l=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(){return o(this,l,arguments)}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(t,n){var r=t.parentNode;if(r&&r.shadowRoot){var o=e.getRendererForHost(r);o.dependsOnAttribute(n)&&o.invalidate()}}function n(e,t,n){u(e,"attributes",{name:t,namespace:null,oldValue:n})}function r(e){a.call(this,e)}var o=e.ChildNodeInterface,i=e.GetElementsByInterface,a=e.wrappers.Node,s=e.ParentNodeInterface,c=e.SelectorsInterface,l=e.MatchesInterface,u=(e.addWrapNodeListMethod,e.enqueueMutation),d=e.mixin,p=(e.oneOf,e.registerWrapper),h=e.unsafeUnwrap,f=e.wrappers,m=window.Element,w=["matches","mozMatchesSelector","msMatchesSelector","webkitMatchesSelector"].filter(function(e){return m.prototype[e]}),v=w[0],g=m.prototype[v],b=new WeakMap;r.prototype=Object.create(a.prototype),d(r.prototype,{createShadowRoot:function(){var t=new f.ShadowRoot(this);h(this).polymerShadowRoot_=t;var n=e.getRendererForHost(this);return n.invalidate(),t},get shadowRoot(){return h(this).polymerShadowRoot_||null},setAttribute:function(e,r){var o=h(this).getAttribute(e);h(this).setAttribute(e,r),n(this,e,o),t(this,e)},removeAttribute:function(e){var r=h(this).getAttribute(e);h(this).removeAttribute(e),n(this,e,r),t(this,e)},get classList(){var e=b.get(this);if(!e){if(e=h(this).classList,!e)return;e.ownerElement_=this,b.set(this,e)}return e},get className(){return h(this).className},set className(e){this.setAttribute("class",e)},get id(){return h(this).id},set id(e){this.setAttribute("id",e)}}),w.forEach(function(e){"matches"!==e&&(r.prototype[e]=function(e){return this.matches(e)})}),m.prototype.webkitCreateShadowRoot&&(r.prototype.webkitCreateShadowRoot=r.prototype.createShadowRoot),d(r.prototype,o),d(r.prototype,i),d(r.prototype,s),d(r.prototype,c),d(r.prototype,l),p(m,r,document.createElementNS(null,"x")),e.invalidateRendererBasedOnAttribute=t,e.matchesNames=w,e.originalMatches=g,e.wrappers.Element=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case" ":return" "}}function n(e){return e.replace(L,t)}function r(e){return e.replace(N,t)}function o(e){for(var t={},n=0;n"):c+">"+s(e)+""+a+">";case Node.TEXT_NODE:var d=e.data;return t&&j[t.localName]?d:r(d);case Node.COMMENT_NODE:return"";default:throw console.error(e),new Error("not implemented")}}function s(e){e instanceof O.HTMLTemplateElement&&(e=e.content);for(var t="",n=e.firstChild;n;n=n.nextSibling)t+=a(n,e);return t}function c(e,t,n){var r=n||"div";e.textContent="";var o=T(e.ownerDocument.createElement(r));o.innerHTML=t;for(var i;i=o.firstChild;)e.appendChild(M(i))}function l(e){m.call(this,e)}function u(e,t){var n=T(e.cloneNode(!1));n.innerHTML=t;for(var r,o=T(document.createDocumentFragment());r=n.firstChild;)o.appendChild(r);return M(o)}function d(t){return function(){return e.renderAllPending(),S(this)[t]}}function p(e){w(l,e,d(e))}function h(t){Object.defineProperty(l.prototype,t,{get:d(t),set:function(n){e.renderAllPending(),S(this)[t]=n},configurable:!0,enumerable:!0})}function f(t){Object.defineProperty(l.prototype,t,{value:function(){return e.renderAllPending(),S(this)[t].apply(S(this),arguments)},configurable:!0,enumerable:!0})}var m=e.wrappers.Element,w=e.defineGetter,v=e.enqueueMutation,g=e.mixin,b=e.nodesWereAdded,y=e.nodesWereRemoved,E=e.registerWrapper,_=e.snapshotNodeList,S=e.unsafeUnwrap,T=e.unwrap,M=e.wrap,O=e.wrappers,L=/[&\u00A0"]/g,N=/[&\u00A0<>]/g,C=o(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),j=o(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]),D="http://www.w3.org/1999/xhtml",H=/MSIE/.test(navigator.userAgent),x=window.HTMLElement,R=window.HTMLTemplateElement;l.prototype=Object.create(m.prototype),g(l.prototype,{get innerHTML(){return s(this)},set innerHTML(e){if(H&&j[this.localName])return void(this.textContent=e);var t=_(this.childNodes);this.invalidateShadowRenderer()?this instanceof O.HTMLTemplateElement?c(this.content,e):c(this,e,this.tagName):!R&&this instanceof O.HTMLTemplateElement?c(this.content,e):S(this).innerHTML=e;var n=_(this.childNodes);v(this,"childList",{addedNodes:n,removedNodes:t}),y(t),b(n,this)},get outerHTML(){return a(this,this.parentNode)},set outerHTML(e){var t=this.parentNode;if(t){t.invalidateShadowRenderer();var n=u(t,e);t.replaceChild(n,this)}},insertAdjacentHTML:function(e,t){var n,r;switch(String(e).toLowerCase()){case"beforebegin":n=this.parentNode,r=this;break;case"afterend":n=this.parentNode,r=this.nextSibling;break;case"afterbegin":n=this,r=this.firstChild;break;case"beforeend":n=this,r=null;break;default:return}var o=u(n,t);n.insertBefore(o,r)},get hidden(){return this.hasAttribute("hidden")},set hidden(e){e?this.setAttribute("hidden",""):this.removeAttribute("hidden")}}),["clientHeight","clientLeft","clientTop","clientWidth","offsetHeight","offsetLeft","offsetTop","offsetWidth","scrollHeight","scrollWidth"].forEach(p),["scrollLeft","scrollTop"].forEach(h),["focus","getBoundingClientRect","getClientRects","scrollIntoView"].forEach(f),E(x,l,document.createElement("b")),e.wrappers.HTMLElement=l,e.getInnerHTML=s,e.setInnerHTML=c}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.HTMLCanvasElement;t.prototype=Object.create(n.prototype),r(t.prototype,{getContext:function(){var e=i(this).getContext.apply(i(this),arguments);return e&&a(e)}}),o(s,t,document.createElement("canvas")),e.wrappers.HTMLCanvasElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=window.HTMLContentElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get select(){return this.getAttribute("select")},set select(e){this.setAttribute("select",e)},setAttribute:function(e,t){n.prototype.setAttribute.call(this,e,t),"select"===String(e).toLowerCase()&&this.invalidateShadowRenderer(!0)}}),i&&o(i,t),e.wrappers.HTMLContentElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=window.HTMLFormElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get elements(){return i(a(this).elements)}}),o(s,t,document.createElement("form")),e.wrappers.HTMLFormElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e,t){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var o=i(document.createElement("img"));r.call(this,o),a(o,this),void 0!==e&&(o.width=e),void 0!==t&&(o.height=t)}var r=e.wrappers.HTMLElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLImageElement;t.prototype=Object.create(r.prototype),o(s,t,document.createElement("img")),n.prototype=t.prototype,e.wrappers.HTMLImageElement=t,e.wrappers.Image=n}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=(e.mixin,e.wrappers.NodeList,e.registerWrapper),o=window.HTMLShadowElement;t.prototype=Object.create(n.prototype),t.prototype.constructor=t,o&&r(o,t),e.wrappers.HTMLShadowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){if(!e.defaultView)return e;var t=d.get(e);if(!t){for(t=e.implementation.createHTMLDocument("");t.lastChild;)t.removeChild(t.lastChild);d.set(e,t)}return t}function n(e){for(var n,r=t(e.ownerDocument),o=c(r.createDocumentFragment());n=e.firstChild;)o.appendChild(n);return o}function r(e){if(o.call(this,e),!p){var t=n(e);u.set(this,l(t))}}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.unsafeUnwrap,c=e.unwrap,l=e.wrap,u=new WeakMap,d=new WeakMap,p=window.HTMLTemplateElement;r.prototype=Object.create(o.prototype),i(r.prototype,{constructor:r,get content(){return p?l(s(this).content):u.get(this)}}),p&&a(p,r),e.wrappers.HTMLTemplateElement=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.registerWrapper,o=window.HTMLMediaElement;o&&(t.prototype=Object.create(n.prototype),r(o,t,document.createElement("audio")),e.wrappers.HTMLMediaElement=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){r.call(this,e)}function n(e){if(!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function.");var t=i(document.createElement("audio"));r.call(this,t),a(t,this),t.setAttribute("preload","auto"),void 0!==e&&t.setAttribute("src",e)}var r=e.wrappers.HTMLMediaElement,o=e.registerWrapper,i=e.unwrap,a=e.rewrap,s=window.HTMLAudioElement;s&&(t.prototype=Object.create(r.prototype),o(s,t,document.createElement("audio")),n.prototype=t.prototype,e.wrappers.HTMLAudioElement=t,e.wrappers.Audio=n)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){return e.replace(/\s+/g," ").trim()}function n(e){o.call(this,e)}function r(e,t,n,i){if(!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function.");var a=c(document.createElement("option"));o.call(this,a),s(a,this),void 0!==e&&(a.text=e),void 0!==t&&a.setAttribute("value",t),n===!0&&a.setAttribute("selected",""),a.selected=i===!0}var o=e.wrappers.HTMLElement,i=e.mixin,a=e.registerWrapper,s=e.rewrap,c=e.unwrap,l=e.wrap,u=window.HTMLOptionElement;n.prototype=Object.create(o.prototype),i(n.prototype,{get text(){return t(this.textContent)},set text(e){this.textContent=t(String(e))},get form(){return l(c(this).form)}}),a(u,n,document.createElement("option")),r.prototype=n.prototype,e.wrappers.HTMLOptionElement=n,e.wrappers.Option=r}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=window.HTMLSelectElement;t.prototype=Object.create(n.prototype),r(t.prototype,{add:function(e,t){"object"==typeof t&&(t=i(t)),i(this).add(i(e),t)},remove:function(e){return void 0===e?void n.prototype.remove.call(this):("object"==typeof e&&(e=i(e)),void i(this).remove(e))},get form(){return a(i(this).form)}}),o(s,t,document.createElement("select")),e.wrappers.HTMLSelectElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.unwrap,a=e.wrap,s=e.wrapHTMLCollection,c=window.HTMLTableElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get caption(){return a(i(this).caption)},createCaption:function(){return a(i(this).createCaption())},get tHead(){return a(i(this).tHead)},createTHead:function(){return a(i(this).createTHead())},createTFoot:function(){return a(i(this).createTFoot())},get tFoot(){return a(i(this).tFoot)},get tBodies(){return s(i(this).tBodies)},createTBody:function(){return a(i(this).createTBody())},get rows(){return s(i(this).rows)},insertRow:function(e){return a(i(this).insertRow(e))}}),o(c,t,document.createElement("table")),e.wrappers.HTMLTableElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableSectionElement;t.prototype=Object.create(n.prototype),r(t.prototype,{constructor:t,get rows(){return i(a(this).rows)},insertRow:function(e){return s(a(this).insertRow(e))}}),o(c,t,document.createElement("thead")),e.wrappers.HTMLTableSectionElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.HTMLElement,r=e.mixin,o=e.registerWrapper,i=e.wrapHTMLCollection,a=e.unwrap,s=e.wrap,c=window.HTMLTableRowElement;t.prototype=Object.create(n.prototype),r(t.prototype,{get cells(){return i(a(this).cells)},insertCell:function(e){return s(a(this).insertCell(e))}}),o(c,t,document.createElement("tr")),e.wrappers.HTMLTableRowElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){switch(e.localName){case"content":return new n(e);case"shadow":return new o(e);case"template":return new i(e)}r.call(this,e)}var n=e.wrappers.HTMLContentElement,r=e.wrappers.HTMLElement,o=e.wrappers.HTMLShadowElement,i=e.wrappers.HTMLTemplateElement,a=(e.mixin,e.registerWrapper),s=window.HTMLUnknownElement;t.prototype=Object.create(r.prototype),a(s,t),e.wrappers.HTMLUnknownElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Element,r=e.wrappers.HTMLElement,o=e.registerWrapper,i=(e.defineWrapGetter,e.unsafeUnwrap),a=e.wrap,s=e.mixin,c="http://www.w3.org/2000/svg",l=window.SVGElement,u=document.createElementNS(c,"title");if(!("classList"in u)){var d=Object.getOwnPropertyDescriptor(n.prototype,"classList");Object.defineProperty(r.prototype,"classList",d),delete n.prototype.classList}t.prototype=Object.create(n.prototype),s(t.prototype,{get ownerSVGElement(){return a(i(this).ownerSVGElement)}}),o(l,t,document.createElementNS(c,"title")),e.wrappers.SVGElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){p.call(this,e)}var n=e.mixin,r=e.registerWrapper,o=e.unwrap,i=e.wrap,a=window.SVGUseElement,s="http://www.w3.org/2000/svg",c=i(document.createElementNS(s,"g")),l=document.createElementNS(s,"use"),u=c.constructor,d=Object.getPrototypeOf(u.prototype),p=d.constructor;t.prototype=Object.create(d),"instanceRoot"in l&&n(t.prototype,{get instanceRoot(){return i(o(this).instanceRoot)},get animatedInstanceRoot(){return i(o(this).animatedInstanceRoot)}}),r(a,t,l),e.wrappers.SVGUseElement=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.mixin,o=e.registerWrapper,i=e.unsafeUnwrap,a=e.wrap,s=window.SVGElementInstance;s&&(t.prototype=Object.create(n.prototype),r(t.prototype,{get correspondingElement(){return a(i(this).correspondingElement)},get correspondingUseElement(){return a(i(this).correspondingUseElement)},get parentNode(){return a(i(this).parentNode)},get childNodes(){throw new Error("Not implemented")},get firstChild(){return a(i(this).firstChild)},get lastChild(){return a(i(this).lastChild)},get previousSibling(){return a(i(this).previousSibling)},get nextSibling(){return a(i(this).nextSibling)}}),o(s,t),e.wrappers.SVGElementInstance=t)}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){o(e,this)}var n=e.mixin,r=e.registerWrapper,o=e.setWrapper,i=e.unsafeUnwrap,a=e.unwrap,s=e.unwrapIfNeeded,c=e.wrap,l=window.CanvasRenderingContext2D;n(t.prototype,{get canvas(){return c(i(this).canvas)},drawImage:function(){arguments[0]=s(arguments[0]),i(this).drawImage.apply(i(this),arguments)},createPattern:function(){return arguments[0]=a(arguments[0]),i(this).createPattern.apply(i(this),arguments)}}),r(l,t,document.createElement("canvas").getContext("2d")),e.wrappers.CanvasRenderingContext2D=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){i(e,this)}var n=e.addForwardingProperties,r=e.mixin,o=e.registerWrapper,i=e.setWrapper,a=e.unsafeUnwrap,s=e.unwrapIfNeeded,c=e.wrap,l=window.WebGLRenderingContext;if(l){r(t.prototype,{get canvas(){return c(a(this).canvas)},texImage2D:function(){arguments[5]=s(arguments[5]),a(this).texImage2D.apply(a(this),arguments)},texSubImage2D:function(){arguments[6]=s(arguments[6]),a(this).texSubImage2D.apply(a(this),arguments)}});var u=Object.getPrototypeOf(l.prototype);u!==Object.prototype&&n(u,t.prototype);var d=/WebKit/.test(navigator.userAgent)?{drawingBufferHeight:null,drawingBufferWidth:null}:{};o(l,t,d),e.wrappers.WebGLRenderingContext=t}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.Node,r=e.GetElementsByInterface,o=e.NonElementParentNodeInterface,i=e.ParentNodeInterface,a=e.SelectorsInterface,s=e.mixin,c=e.registerObject,l=e.registerWrapper,u=window.DocumentFragment;t.prototype=Object.create(n.prototype),s(t.prototype,i),s(t.prototype,a),s(t.prototype,r),s(t.prototype,o),l(u,t,document.createDocumentFragment()),e.wrappers.DocumentFragment=t;var d=c(document.createComment(""));e.wrappers.Comment=d}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(u(e).ownerDocument.createDocumentFragment());n.call(this,t),c(t,this);var o=e.shadowRoot;f.set(this,o),this.treeScope_=new r(this,a(o||e)),h.set(this,e)}var n=e.wrappers.DocumentFragment,r=e.TreeScope,o=e.elementFromPoint,i=e.getInnerHTML,a=e.getTreeScope,s=e.mixin,c=e.rewrap,l=e.setInnerHTML,u=e.unsafeUnwrap,d=e.unwrap,p=e.wrap,h=new WeakMap,f=new WeakMap;t.prototype=Object.create(n.prototype),s(t.prototype,{constructor:t,get innerHTML(){return i(this)},set innerHTML(e){l(this,e),this.invalidateShadowRenderer()},get olderShadowRoot(){return f.get(this)||null},get host(){return h.get(this)||null},invalidateShadowRenderer:function(){return h.get(this).invalidateShadowRenderer()},elementFromPoint:function(e,t){return o(this,this.ownerDocument,e,t)},getSelection:function(){return document.getSelection()},get activeElement(){var e=d(this).ownerDocument.activeElement;if(!e||!e.nodeType)return null;for(var t=p(e);!this.contains(t);){for(;t.parentNode;)t=t.parentNode;if(!t.host)return null;t=t.host}return t}}),e.wrappers.ShadowRoot=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=d(e).root;return t instanceof h?t.host:null}function n(t,n){if(t.shadowRoot){n=Math.min(t.childNodes.length-1,n);var r=t.childNodes[n];if(r){var o=e.getDestinationInsertionPoints(r);if(o.length>0){var i=o[0].parentNode;i.nodeType==Node.ELEMENT_NODE&&(t=i)}}}return t}function r(e){return e=u(e),t(e)||e}function o(e){a(e,this)}var i=e.registerWrapper,a=e.setWrapper,s=e.unsafeUnwrap,c=e.unwrap,l=e.unwrapIfNeeded,u=e.wrap,d=e.getTreeScope,p=window.Range,h=e.wrappers.ShadowRoot;o.prototype={get startContainer(){return r(s(this).startContainer)},get endContainer(){return r(s(this).endContainer)},get commonAncestorContainer(){return r(s(this).commonAncestorContainer)},setStart:function(e,t){e=n(e,t),s(this).setStart(l(e),t)},setEnd:function(e,t){e=n(e,t),s(this).setEnd(l(e),t)},setStartBefore:function(e){s(this).setStartBefore(l(e))},setStartAfter:function(e){s(this).setStartAfter(l(e))},setEndBefore:function(e){s(this).setEndBefore(l(e))},setEndAfter:function(e){s(this).setEndAfter(l(e))},selectNode:function(e){s(this).selectNode(l(e))},selectNodeContents:function(e){s(this).selectNodeContents(l(e))},compareBoundaryPoints:function(e,t){return s(this).compareBoundaryPoints(e,c(t))},extractContents:function(){return u(s(this).extractContents())},cloneContents:function(){return u(s(this).cloneContents())},insertNode:function(e){s(this).insertNode(l(e))},surroundContents:function(e){s(this).surroundContents(l(e))},cloneRange:function(){return u(s(this).cloneRange())},isPointInRange:function(e,t){return s(this).isPointInRange(l(e),t)},comparePoint:function(e,t){return s(this).comparePoint(l(e),t)},intersectsNode:function(e){return s(this).intersectsNode(l(e))},toString:function(){return s(this).toString()}},p.prototype.createContextualFragment&&(o.prototype.createContextualFragment=function(e){return u(s(this).createContextualFragment(e))}),i(window.Range,o,document.createRange()),e.wrappers.Range=o}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){e.previousSibling_=e.previousSibling,e.nextSibling_=e.nextSibling,e.parentNode_=e.parentNode}function n(n,o,i){var a=x(n),s=x(o),c=i?x(i):null;if(r(o),t(o),i)n.firstChild===i&&(n.firstChild_=i),i.previousSibling_=i.previousSibling;else{n.lastChild_=n.lastChild,n.lastChild===n.firstChild&&(n.firstChild_=n.firstChild);var l=R(a.lastChild);l&&(l.nextSibling_=l.nextSibling)}e.originalInsertBefore.call(a,s,c)}function r(n){var r=x(n),o=r.parentNode;if(o){var i=R(o);t(n),n.previousSibling&&(n.previousSibling.nextSibling_=n),n.nextSibling&&(n.nextSibling.previousSibling_=n),i.lastChild===n&&(i.lastChild_=n),i.firstChild===n&&(i.firstChild_=n),e.originalRemoveChild.call(o,r)}}function o(e){P.set(e,[])}function i(e){var t=P.get(e);return t||P.set(e,t=[]),t}function a(e){for(var t=[],n=0,r=e.firstChild;r;r=r.nextSibling)t[n++]=r;return t}function s(){for(var e=0;e=0;o--){var i=r[o],a=m(i);if(a){var s=i.olderShadowRoot;s&&(n=f(s));for(var c=0;c=0;u--)l=Object.create(l);["createdCallback","attachedCallback","detachedCallback","attributeChangedCallback"].forEach(function(e){var t=o[e];t&&(l[e]=function(){j(this)instanceof r||O(this),t.apply(j(this),arguments)})});var d={prototype:l};i&&(d["extends"]=i),r.prototype=o,r.prototype.constructor=r,e.constructorTable.set(l,r),e.nativePrototypeTable.set(o,l);k.call(C(this),t,d);return r},E([window.HTMLDocument||window.Document],["registerElement"])}E([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement,window.HTMLHtmlElement],["appendChild","compareDocumentPosition","contains","getElementsByClassName","getElementsByTagName","getElementsByTagNameNS","insertBefore","querySelector","querySelectorAll","removeChild","replaceChild"]),E([window.HTMLBodyElement,window.HTMLHeadElement,window.HTMLHtmlElement],_),E([window.HTMLDocument||window.Document],["adoptNode","importNode","contains","createComment","createDocumentFragment","createElement","createElementNS","createEvent","createEventNS","createRange","createTextNode","createTreeWalker","elementFromPoint","getElementById","getElementsByName","getSelection"]),S(t.prototype,l),S(t.prototype,d),S(t.prototype,f),S(t.prototype,p),S(t.prototype,{get implementation(){var e=H.get(this);return e?e:(e=new a(C(this).implementation),H.set(this,e),e)},get defaultView(){return j(C(this).defaultView)}}),T(window.Document,t,document.implementation.createHTMLDocument("")),window.HTMLDocument&&T(window.HTMLDocument,t),D([window.HTMLBodyElement,window.HTMLDocument||window.Document,window.HTMLHeadElement]);var A=document.implementation.createDocument;a.prototype.createDocument=function(){return arguments[2]=C(arguments[2]),j(A.apply(N(this),arguments))},s(a,"createDocumentType"),s(a,"createHTMLDocument"),c(a,"hasFeature"),T(window.DOMImplementation,a),E([window.DOMImplementation],["createDocument","createDocumentType","createHTMLDocument","hasFeature"]),e.adoptNodeNoRemove=r,e.wrappers.DOMImplementation=a,e.wrappers.Document=t}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){n.call(this,e)}var n=e.wrappers.EventTarget,r=e.wrappers.Selection,o=e.mixin,i=e.registerWrapper,a=e.renderAllPending,s=e.unwrap,c=e.unwrapIfNeeded,l=e.wrap,u=window.Window,d=window.getComputedStyle,p=window.getDefaultComputedStyle,h=window.getSelection;t.prototype=Object.create(n.prototype),u.prototype.getComputedStyle=function(e,t){return l(this||window).getComputedStyle(c(e),t)},p&&(u.prototype.getDefaultComputedStyle=function(e,t){return l(this||window).getDefaultComputedStyle(c(e),t)}),u.prototype.getSelection=function(){return l(this||window).getSelection()},delete window.getComputedStyle,delete window.getDefaultComputedStyle,delete window.getSelection,["addEventListener","removeEventListener","dispatchEvent"].forEach(function(e){u.prototype[e]=function(){var t=l(this||window);return t[e].apply(t,arguments)},delete window[e]}),o(t.prototype,{getComputedStyle:function(e,t){return a(),d.call(s(this),c(e),t)},getSelection:function(){return a(),new r(h.call(s(this)))},get document(){return l(s(this).document)}}),p&&(t.prototype.getDefaultComputedStyle=function(e,t){return a(),p.call(s(this),c(e),t)}),i(u,t,window),e.wrappers.Window=t}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrap,n=window.DataTransfer||window.Clipboard,r=n.prototype.setDragImage;r&&(n.prototype.setDragImage=function(e,n,o){r.call(this,t(e),n,o)})}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t;t=e instanceof i?e:new i(e&&o(e)),r(t,this)}var n=e.registerWrapper,r=e.setWrapper,o=e.unwrap,i=window.FormData;i&&(n(i,t,new i),e.wrappers.FormData=t)}(window.ShadowDOMPolyfill),function(e){"use strict";var t=e.unwrapIfNeeded,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.send=function(e){return n.call(this,t(e))}}(window.ShadowDOMPolyfill),function(e){"use strict";function t(e){var t=n[e],r=window[t];if(r){var o=document.createElement(e),i=o.constructor;window[t]=i}}var n=(e.isWrapperFor,{a:"HTMLAnchorElement",area:"HTMLAreaElement",audio:"HTMLAudioElement",base:"HTMLBaseElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",col:"HTMLTableColElement",content:"HTMLContentElement",data:"HTMLDataElement",datalist:"HTMLDataListElement",del:"HTMLModElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",embed:"HTMLEmbedElement",fieldset:"HTMLFieldSetElement",font:"HTMLFontElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",head:"HTMLHeadElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",marquee:"HTMLMarqueeElement",menu:"HTMLMenuElement",menuitem:"HTMLMenuItemElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",script:"HTMLScriptElement",select:"HTMLSelectElement",shadow:"HTMLShadowElement",source:"HTMLSourceElement",span:"HTMLSpanElement",style:"HTMLStyleElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",template:"HTMLTemplateElement",textarea:"HTMLTextAreaElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",ul:"HTMLUListElement",video:"HTMLVideoElement"});Object.keys(n).forEach(t),Object.getOwnPropertyNames(e.wrappers).forEach(function(t){window[t]=e.wrappers[t]})}(window.ShadowDOMPolyfill),function(e){function t(e,t){var n="";return Array.prototype.forEach.call(e,function(e){n+=e.textContent+"\n\n"}),t||(n=n.replace(d,"")),n}function n(e){var t=document.createElement("style");return t.textContent=e,t}function r(e){var t=n(e);document.head.appendChild(t);var r=[];if(t.sheet)try{r=t.sheet.cssRules}catch(o){}else console.warn("sheet not found",t);return t.parentNode.removeChild(t),r}function o(){C.initialized=!0,document.body.appendChild(C);var e=C.contentDocument,t=e.createElement("base");t.href=document.baseURI,e.head.appendChild(t)}function i(e){C.initialized||o(),document.body.appendChild(C),e(C.contentDocument),document.body.removeChild(C)}function a(e,t){if(t){var o;if(e.match("@import")&&D){var a=n(e);i(function(e){e.head.appendChild(a.impl),o=Array.prototype.slice.call(a.sheet.cssRules,0),t(o)})}else o=r(e),t(o)}}function s(e){e&&l().appendChild(document.createTextNode(e))}function c(e,t){var r=n(e);r.setAttribute(t,""),r.setAttribute(x,""),document.head.appendChild(r)}function l(){return j||(j=document.createElement("style"),j.setAttribute(x,""),j[x]=!0),j}var u={strictStyling:!1,registry:{},shimStyling:function(e,n,r){var o=this.prepareRoot(e,n,r),i=this.isTypeExtension(r),a=this.makeScopeSelector(n,i),s=t(o,!0);s=this.scopeCssText(s,a),e&&(e.shimmedStyle=s),this.addCssToDocument(s,n)},shimStyle:function(e,t){return this.shimCssText(e.textContent,t)},shimCssText:function(e,t){return e=this.insertDirectives(e),this.scopeCssText(e,t)},makeScopeSelector:function(e,t){return e?t?"[is="+e+"]":e:""},isTypeExtension:function(e){return e&&e.indexOf("-")<0},prepareRoot:function(e,t,n){var r=this.registerRoot(e,t,n);return this.replaceTextInStyles(r.rootStyles,this.insertDirectives),this.removeStyles(e,r.rootStyles),this.strictStyling&&this.applyScopeToContent(e,t),r.scopeStyles},removeStyles:function(e,t){for(var n,r=0,o=t.length;r","+","~"],r=e,o="["+t+"]";return n.forEach(function(e){var t=r.split(e);r=t.map(function(e){var t=e.trim().replace(L,"");return t&&n.indexOf(t)<0&&t.indexOf(o)<0&&(e=t.replace(/([^:]*)(:*)(.*)/,"$1"+o+"$2$3")),e}).join(e)}),r},insertPolyfillHostInCssText:function(e){return e.replace(M,b).replace(T,g)},propertiesFromRule:function(e){var t=e.style.cssText;e.style.content&&!e.style.content.match(/['"]+|attr/)&&(t=t.replace(/content:[^;]*;/g,"content: '"+e.style.content+"';"));var n=e.style;for(var r in n)"initial"===n[r]&&(t+=r+": initial; ");return t},replaceTextInStyles:function(e,t){e&&t&&(e instanceof Array||(e=[e]),Array.prototype.forEach.call(e,function(e){e.textContent=t.call(this,e.textContent)},this))},addCssToDocument:function(e,t){e.match("@import")?c(e,t):s(e)}},d=/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//gim,p=/\/\*\s*@polyfill ([^*]*\*+([^\/*][^*]*\*+)*\/)([^{]*?){/gim,h=/polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim,f=/\/\*\s@polyfill-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,m=/(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,w=/\/\*\s@polyfill-unscoped-rule([^*]*\*+([^\/*][^*]*\*+)*)\//gim,v=/(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim,g="-shadowcsshost",b="-shadowcsscontext",y=")(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)",E=new RegExp("("+g+y,"gim"),_=new RegExp("("+b+y,"gim"),S="([>\\s~+[.,{:][\\s\\S]*)?$",T=/\:host/gim,M=/\:host-context/gim,O=g+"-no-combinator",L=new RegExp(g,"gim"),N=(new RegExp(b,"gim"),[/>>>/g,/::shadow/g,/::content/g,/\/deep\//g,/\/shadow\//g,/\/shadow-deep\//g,/\^\^/g,/\^(?!=)/g]),C=document.createElement("iframe");C.style.display="none";var j,D=navigator.userAgent.match("Chrome"),H="shim-shadowdom",x="shim-shadowdom-css",R="no-shim";if(window.ShadowDOMPolyfill){s("style { display: none !important; }\n");var I=ShadowDOMPolyfill.wrap(document),P=I.querySelector("head");P.insertBefore(l(),P.childNodes[0]),document.addEventListener("DOMContentLoaded",function(){e.urlResolver;if(window.HTMLImports&&!HTMLImports.useNative){var t="link[rel=stylesheet]["+H+"]",n="style["+H+"]";HTMLImports.importer.documentPreloadSelectors+=","+t,HTMLImports.importer.importsPreloadSelectors+=","+t,HTMLImports.parser.documentSelectors=[HTMLImports.parser.documentSelectors,t,n].join(",");var r=HTMLImports.parser.parseGeneric;HTMLImports.parser.parseGeneric=function(e){if(!e[x]){var t=e.__importElement||e;if(!t.hasAttribute(H))return void r.call(this,e);e.__resource&&(t=e.ownerDocument.createElement("style"),t.textContent=e.__resource),HTMLImports.path.resolveUrlsInStyle(t,e.href),t.textContent=u.shimStyle(t),t.removeAttribute(H,""),t.setAttribute(x,""),t[x]=!0,t.parentNode!==P&&(e.parentNode===P?P.replaceChild(t,e):this.addElementToDocument(t)),t.__importParsed=!0,this.markParsingComplete(e),this.parseNext()}};var o=HTMLImports.parser.hasResource;HTMLImports.parser.hasResource=function(e){return"link"===e.localName&&"stylesheet"===e.rel&&e.hasAttribute(H)?e.__resource:o.call(this,e)}}})}e.ShadowCSS=u}(window.WebComponents)),function(e){window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}}(window.WebComponents),function(e){"use strict";function t(e){return void 0!==p[e]}function n(){s.call(this),this._isInvalid=!0}function r(e){return""==e&&n.call(this),e.toLowerCase()}function o(e){var t=e.charCodeAt(0);return t>32&&t<127&&[34,35,60,62,63,96].indexOf(t)==-1?e:encodeURIComponent(e)}function i(e){var t=e.charCodeAt(0);return t>32&&t<127&&[34,35,60,62,96].indexOf(t)==-1?e:encodeURIComponent(e)}function a(e,a,s){function c(e){b.push(e)}var l=a||"scheme start",u=0,d="",v=!1,g=!1,b=[];e:for(;(e[u-1]!=f||0==u)&&!this._isInvalid;){var y=e[u];switch(l){case"scheme start":if(!y||!m.test(y)){if(a){c("Invalid scheme.");break e}d="",l="no scheme";continue}d+=y.toLowerCase(),l="scheme";break;case"scheme":if(y&&w.test(y))d+=y.toLowerCase();else{if(":"!=y){if(a){if(f==y)break e;c("Code point not allowed in scheme: "+y);break e}d="",u=0,l="no scheme";continue}if(this._scheme=d,d="",a)break e;t(this._scheme)&&(this._isRelative=!0),l="file"==this._scheme?"relative":this._isRelative&&s&&s._scheme==this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"==y?(this._query="?",l="query"):"#"==y?(this._fragment="#",l="fragment"):f!=y&&"\t"!=y&&"\n"!=y&&"\r"!=y&&(this._schemeData+=o(y));break;case"no scheme":if(s&&t(s._scheme)){l="relative";continue}c("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!=y||"/"!=e[u+1]){c("Expected /, got: "+y),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!=this._scheme&&(this._scheme=s._scheme),f==y){this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._username=s._username,this._password=s._password;break e}if("/"==y||"\\"==y)"\\"==y&&c("\\ is an invalid code point."),l="relative slash";else if("?"==y)this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query="?",this._username=s._username,this._password=s._password,l="query";else{if("#"!=y){var E=e[u+1],_=e[u+2];("file"!=this._scheme||!m.test(y)||":"!=E&&"|"!=E||f!=_&&"/"!=_&&"\\"!=_&&"?"!=_&&"#"!=_)&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password,this._path=s._path.slice(),this._path.pop()),l="relative path";continue}this._host=s._host,this._port=s._port,this._path=s._path.slice(),this._query=s._query,this._fragment="#",this._username=s._username,this._password=s._password,l="fragment"}break;case"relative slash":if("/"!=y&&"\\"!=y){"file"!=this._scheme&&(this._host=s._host,this._port=s._port,this._username=s._username,this._password=s._password),l="relative path";continue}"\\"==y&&c("\\ is an invalid code point."),l="file"==this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!=y){c("Expected '/', got: "+y),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!=y){c("Expected '/', got: "+y);continue}break;case"authority ignore slashes":if("/"!=y&&"\\"!=y){l="authority";continue}c("Expected authority, got: "+y);break;case"authority":if("@"==y){v&&(c("@ already seen."),d+="%40"),v=!0;for(var S=0;S0){var o=n[r-1],i=h(o,e);if(i)return void(n[r-1]=i)}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=w.get(e);t||w.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=w.get(e),n=0;n=200&&e.status<300||304===e.status||0===e.status},load:function(n,r,o){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=null;try{var a=i.getResponseHeader("Location");a&&(n="/"===a.substr(0,1)?location.origin+a:a)}catch(e){console.error(e.message)}r.call(o,!t.ok(i)&&i,i.response||i.responseText,n)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),window.HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;n-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,o){this.receive(e,r,t,n,o)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,o){this.cache[e]=r;for(var i,a=this.pending[e],s=0,c=a.length;s=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(e["import"]=e.__doc,window.HTMLImports.__importsParsingHook&&window.HTMLImports.__importsParsingHook(e),e["import"]&&(e["import"].__importParsed=!0),this.markParsingComplete(e),e.__resource&&!e.__error?e.dispatchEvent(new CustomEvent("load",{bubbles:!1})):e.dispatchEvent(new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(o){e.removeEventListener("load",r),e.removeEventListener("error",r),t&&t(o),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),l&&"style"===e.localName){var o=!1;if(e.textContent.indexOf("@import")==-1)o=!0;else if(e.sheet){o=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,c=0;c=0},hasResource:function(e){return!t(e)||void 0!==e.__doc}};e.parser=p,e.IMPORT_SELECTOR=d}),window.HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function o(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var o=n.createElement("base");o.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(o),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,c=e.rootDocument,l=e.Loader,u=e.Observer,d=e.parser,p={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){h.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);h.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===c?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var c=this.documents[e];void 0===c&&(c=a?null:o(r,s||e),c&&(c.__importLink=n,this.bootDocument(c)),this.documents[e]=c),n.__doc=c}d.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),d.parseNext()},loadedAll:function(){d.parseNext()}},h=new l(p.loaded.bind(p),p.loadedAll.bind(p));if(p.observer=new u,!document.baseURI){var f={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",f),Object.defineProperty(c,"baseURI",f)}e.importer=p,e.importLoader=h}),window.HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,o,i,a,s=0,c=e.length;s=0)){n.push(e);for(var r,o=e.querySelectorAll("link[rel="+a+"]"),s=0,c=o.length;s=0&&b(r,HTMLElement),r)}function f(e,t){var n=e[t];e[t]=function(){var e=n.apply(this,arguments);return v(e),e}}var m,w=(e.isIE,e.upgradeDocumentTree),v=e.upgradeAll,g=e.upgradeWithDefinition,b=e.implementPrototype,y=e.useNative,E=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],_={},S="http://www.w3.org/1999/xhtml",T=document.createElement.bind(document),M=document.createElementNS.bind(document);m=Object.__proto__||y?function(e,t){return e instanceof t}:function(e,t){if(e instanceof t)return!0;for(var n=e;n;){if(n===t.prototype)return!0;n=n.__proto__}return!1},f(Node.prototype,"cloneNode"),f(document,"importNode"),document.registerElement=t,document.createElement=h,document.createElementNS=p,e.registry=_,e["instanceof"]=m,e.reservedTagList=E,e.getRegisteredDefinition=l,document.register=document.registerElement}),function(e){function t(){i(window.wrap(document)),window.CustomElements.ready=!0;var e=window.requestAnimationFrame||function(e){setTimeout(e,16)};e(function(){setTimeout(function(){window.CustomElements.readyTime=Date.now(),window.HTMLImports&&(window.CustomElements.elapsed=window.CustomElements.readyTime-window.HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})})}var n=e.useNative,r=e.initializeModules;e.isIE;if(n){var o=function(){};e.watchShadow=o,e.upgrade=o,e.upgradeAll=o,e.upgradeDocumentTree=o,e.upgradeSubtree=o,e.takeRecords=o,e["instanceof"]=function(e,t){return e instanceof t}}else r();var i=e.upgradeDocumentTree,a=e.upgradeDocument;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=window.ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=window.ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(e){return e}),window.HTMLImports&&(window.HTMLImports.__importsParsingHook=function(e){e["import"]&&a(wrap(e["import"]))}),"complete"===document.readyState||e.flags.eager)t();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var s=window.HTMLImports&&!window.HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(s,t)}else t()}(window.CustomElements),function(e){Function.prototype.bind||(Function.prototype.bind=function(e){var t=this,n=Array.prototype.slice.call(arguments,1);return function(){var r=n.slice();return r.push.apply(r,arguments),t.apply(e,r)}})}(window.WebComponents),function(e){var t=document.createElement("style");t.textContent="body {transition: opacity ease-in 0.2s; } \nbody[unresolved] {opacity: 0; display: block; overflow: hidden; position: relative; } \n";var n=document.querySelector("head");n.insertBefore(t,n.firstChild)}(window.WebComponents),function(e){window.Platform=e}(window.WebComponents);
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/base.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/base.go
new file mode 100644
index 0000000000000000000000000000000000000000..57e580290263b61e1e70a010662fe2d96941ce67
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/base.go
@@ -0,0 +1,261 @@
+// 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.
+
+// This file contains data types that all implementations of the trace format
+// parser need to provide to the rest of the package.
+
+package trace
+
+import (
+ "fmt"
+ "math"
+ "strings"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+ "internal/trace/v2/version"
+)
+
+// maxArgs is the maximum number of arguments for "plain" events,
+// i.e. anything that could reasonably be represented as a Base.
+const maxArgs = 5
+
+// baseEvent is the basic unprocessed event. This serves as a common
+// fundamental data structure across.
+type baseEvent struct {
+ typ event.Type
+ time Time
+ args [maxArgs - 1]uint64
+}
+
+// extra returns a slice representing extra available space in args
+// that the parser can use to pass data up into Event.
+func (e *baseEvent) extra(v version.Version) []uint64 {
+ switch v {
+ case version.Go122:
+ return e.args[len(go122.Specs()[e.typ].Args)-1:]
+ }
+ panic(fmt.Sprintf("unsupported version: go 1.%d", v))
+}
+
+// evTable contains the per-generation data necessary to
+// interpret an individual event.
+type evTable struct {
+ freq frequency
+ strings dataTable[stringID, string]
+ stacks dataTable[stackID, stack]
+
+ // extraStrings are strings that get generated during
+ // parsing but haven't come directly from the trace, so
+ // they don't appear in strings.
+ extraStrings []string
+ extraStringIDs map[string]extraStringID
+ nextExtra extraStringID
+}
+
+// addExtraString adds an extra string to the evTable and returns
+// a unique ID for the string in the table.
+func (t *evTable) addExtraString(s string) extraStringID {
+ if s == "" {
+ return 0
+ }
+ if t.extraStringIDs == nil {
+ t.extraStringIDs = make(map[string]extraStringID)
+ }
+ if id, ok := t.extraStringIDs[s]; ok {
+ return id
+ }
+ t.nextExtra++
+ id := t.nextExtra
+ t.extraStrings = append(t.extraStrings, s)
+ t.extraStringIDs[s] = id
+ return id
+}
+
+// getExtraString returns the extra string for the provided ID.
+// The ID must have been produced by addExtraString for this evTable.
+func (t *evTable) getExtraString(id extraStringID) string {
+ if id == 0 {
+ return ""
+ }
+ return t.extraStrings[id-1]
+}
+
+// dataTable is a mapping from EIs to Es.
+type dataTable[EI ~uint64, E any] struct {
+ present []uint8
+ dense []E
+ sparse map[EI]E
+}
+
+// insert tries to add a mapping from id to s.
+//
+// Returns an error if a mapping for id already exists, regardless
+// of whether or not s is the same in content. This should be used
+// for validation during parsing.
+func (d *dataTable[EI, E]) insert(id EI, data E) error {
+ if d.sparse == nil {
+ d.sparse = make(map[EI]E)
+ }
+ if existing, ok := d.get(id); ok {
+ return fmt.Errorf("multiple %Ts with the same ID: id=%d, new=%v, existing=%v", data, id, data, existing)
+ }
+ d.sparse[id] = data
+ return nil
+}
+
+// compactify attempts to compact sparse into dense.
+//
+// This is intended to be called only once after insertions are done.
+func (d *dataTable[EI, E]) compactify() {
+ if d.sparse == nil || len(d.dense) != 0 {
+ // Already compactified.
+ return
+ }
+ // Find the range of IDs.
+ maxID := EI(0)
+ minID := ^EI(0)
+ for id := range d.sparse {
+ if id > maxID {
+ maxID = id
+ }
+ if id < minID {
+ minID = id
+ }
+ }
+ if maxID >= math.MaxInt {
+ // We can't create a slice big enough to hold maxID elements
+ return
+ }
+ // We're willing to waste at most 2x memory.
+ if int(maxID-minID) > max(len(d.sparse), 2*len(d.sparse)) {
+ return
+ }
+ if int(minID) > len(d.sparse) {
+ return
+ }
+ size := int(maxID) + 1
+ d.present = make([]uint8, (size+7)/8)
+ d.dense = make([]E, size)
+ for id, data := range d.sparse {
+ d.dense[id] = data
+ d.present[id/8] |= uint8(1) << (id % 8)
+ }
+ d.sparse = nil
+}
+
+// get returns the E for id or false if it doesn't
+// exist. This should be used for validation during parsing.
+func (d *dataTable[EI, E]) get(id EI) (E, bool) {
+ if id == 0 {
+ return *new(E), true
+ }
+ if uint64(id) < uint64(len(d.dense)) {
+ if d.present[id/8]&(uint8(1)<<(id%8)) != 0 {
+ return d.dense[id], true
+ }
+ } else if d.sparse != nil {
+ if data, ok := d.sparse[id]; ok {
+ return data, true
+ }
+ }
+ return *new(E), false
+}
+
+// forEach iterates over all ID/value pairs in the data table.
+func (d *dataTable[EI, E]) forEach(yield func(EI, E) bool) bool {
+ for id, value := range d.dense {
+ if d.present[id/8]&(uint8(1)<<(id%8)) == 0 {
+ continue
+ }
+ if !yield(EI(id), value) {
+ return false
+ }
+ }
+ if d.sparse == nil {
+ return true
+ }
+ for id, value := range d.sparse {
+ if !yield(id, value) {
+ return false
+ }
+ }
+ return true
+}
+
+// mustGet returns the E for id or panics if it fails.
+//
+// This should only be used if id has already been validated.
+func (d *dataTable[EI, E]) mustGet(id EI) E {
+ data, ok := d.get(id)
+ if !ok {
+ panic(fmt.Sprintf("expected id %d in %T table", id, data))
+ }
+ return data
+}
+
+// frequency is nanoseconds per timestamp unit.
+type frequency float64
+
+// mul multiplies an unprocessed to produce a time in nanoseconds.
+func (f frequency) mul(t timestamp) Time {
+ return Time(float64(t) * float64(f))
+}
+
+// stringID is an index into the string table for a generation.
+type stringID uint64
+
+// extraStringID is an index into the extra string table for a generation.
+type extraStringID uint64
+
+// stackID is an index into the stack table for a generation.
+type stackID uint64
+
+// cpuSample represents a CPU profiling sample captured by the trace.
+type cpuSample struct {
+ schedCtx
+ time Time
+ stack stackID
+}
+
+// asEvent produces a complete Event from a cpuSample. It needs
+// the evTable from the generation that created it.
+//
+// We don't just store it as an Event in generation to minimize
+// the amount of pointer data floating around.
+func (s cpuSample) asEvent(table *evTable) Event {
+ // TODO(mknyszek): This is go122-specific, but shouldn't be.
+ // Generalize this in the future.
+ e := Event{
+ table: table,
+ ctx: s.schedCtx,
+ base: baseEvent{
+ typ: go122.EvCPUSample,
+ time: s.time,
+ },
+ }
+ e.base.args[0] = uint64(s.stack)
+ return e
+}
+
+// stack represents a goroutine stack sample.
+type stack struct {
+ frames []frame
+}
+
+func (s stack) String() string {
+ var sb strings.Builder
+ for _, frame := range s.frames {
+ fmt.Fprintf(&sb, "\t%#v\n", frame)
+ }
+ return sb.String()
+}
+
+// frame represents a single stack frame.
+type frame struct {
+ pc uint64
+ funcID stringID
+ fileID stringID
+ line uint64
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/batch.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/batch.go
new file mode 100644
index 0000000000000000000000000000000000000000..899eb0f59bcf800bc92e629abadda9b2a68bbdc6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/batch.go
@@ -0,0 +1,97 @@
+// 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 (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "io"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+)
+
+// timestamp is an unprocessed timestamp.
+type timestamp uint64
+
+// batch represents a batch of trace events.
+// It is unparsed except for its header.
+type batch struct {
+ m ThreadID
+ time timestamp
+ data []byte
+}
+
+func (b *batch) isStringsBatch() bool {
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvStrings
+}
+
+func (b *batch) isStacksBatch() bool {
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvStacks
+}
+
+func (b *batch) isCPUSamplesBatch() bool {
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvCPUSamples
+}
+
+func (b *batch) isFreqBatch() bool {
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvFrequency
+}
+
+// readBatch reads the next full batch from r.
+func readBatch(r *bufio.Reader) (batch, uint64, error) {
+ // Read batch header byte.
+ b, err := r.ReadByte()
+ if err != nil {
+ return batch{}, 0, err
+ }
+ if typ := event.Type(b); typ != go122.EvEventBatch {
+ return batch{}, 0, fmt.Errorf("expected batch event (%s), got %s", go122.EventString(go122.EvEventBatch), go122.EventString(typ))
+ }
+
+ // Read the batch header: gen (generation), thread (M) ID, base timestamp
+ // for the batch.
+ gen, err := binary.ReadUvarint(r)
+ if err != nil {
+ return batch{}, gen, fmt.Errorf("error reading batch gen: %w", err)
+ }
+ m, err := binary.ReadUvarint(r)
+ if err != nil {
+ return batch{}, gen, fmt.Errorf("error reading batch M ID: %w", err)
+ }
+ ts, err := binary.ReadUvarint(r)
+ if err != nil {
+ return batch{}, gen, fmt.Errorf("error reading batch timestamp: %w", err)
+ }
+
+ // Read in the size of the batch to follow.
+ size, err := binary.ReadUvarint(r)
+ if err != nil {
+ return batch{}, gen, fmt.Errorf("error reading batch size: %w", err)
+ }
+ if size > go122.MaxBatchSize {
+ return batch{}, gen, fmt.Errorf("invalid batch size %d, maximum is %d", size, go122.MaxBatchSize)
+ }
+
+ // Copy out the batch for later processing.
+ var data bytes.Buffer
+ data.Grow(int(size))
+ n, err := io.CopyN(&data, r, int64(size))
+ if n != int64(size) {
+ return batch{}, gen, fmt.Errorf("failed to read full batch: read %d but wanted %d", n, size)
+ }
+ if err != nil {
+ return batch{}, gen, fmt.Errorf("copying batch data: %w", err)
+ }
+
+ // Return the batch.
+ return batch{
+ m: ThreadID(m),
+ time: timestamp(ts),
+ data: data.Bytes(),
+ }, gen, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor.go
new file mode 100644
index 0000000000000000000000000000000000000000..8dc34fd22f4e3f4de751f20de453840dac36d325
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor.go
@@ -0,0 +1,174 @@
+// 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 (
+ "cmp"
+ "encoding/binary"
+ "fmt"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+)
+
+type batchCursor struct {
+ m ThreadID
+ lastTs Time
+ idx int // next index into []batch
+ dataOff int // next index into batch.data
+ ev baseEvent // last read event
+}
+
+func (b *batchCursor) nextEvent(batches []batch, freq frequency) (ok bool, err error) {
+ // Batches should generally always have at least one event,
+ // but let's be defensive about that and accept empty batches.
+ for b.idx < len(batches) && len(batches[b.idx].data) == b.dataOff {
+ b.idx++
+ b.dataOff = 0
+ b.lastTs = 0
+ }
+ // Have we reached the end of the batches?
+ if b.idx == len(batches) {
+ return false, nil
+ }
+ // Initialize lastTs if it hasn't been yet.
+ if b.lastTs == 0 {
+ b.lastTs = freq.mul(batches[b.idx].time)
+ }
+ // Read an event out.
+ n, tsdiff, err := readTimedBaseEvent(batches[b.idx].data[b.dataOff:], &b.ev)
+ if err != nil {
+ return false, err
+ }
+ // Complete the timestamp from the cursor's last timestamp.
+ b.ev.time = freq.mul(tsdiff) + b.lastTs
+
+ // Move the cursor's timestamp forward.
+ b.lastTs = b.ev.time
+
+ // Move the cursor forward.
+ b.dataOff += n
+ return true, nil
+}
+
+func (b *batchCursor) compare(a *batchCursor) int {
+ return cmp.Compare(b.ev.time, a.ev.time)
+}
+
+// readTimedBaseEvent reads out the raw event data from b
+// into e. It does not try to interpret the arguments
+// but it does validate that the event is a regular
+// event with a timestamp (vs. a structural event).
+//
+// It requires that the event its reading be timed, which must
+// be the case for every event in a plain EventBatch.
+func readTimedBaseEvent(b []byte, e *baseEvent) (int, timestamp, error) {
+ // Get the event type.
+ typ := event.Type(b[0])
+ specs := go122.Specs()
+ if int(typ) >= len(specs) {
+ return 0, 0, fmt.Errorf("found invalid event type: %v", typ)
+ }
+ e.typ = typ
+
+ // Get spec.
+ spec := &specs[typ]
+ if len(spec.Args) == 0 || !spec.IsTimedEvent {
+ return 0, 0, fmt.Errorf("found event without a timestamp: type=%v", typ)
+ }
+ n := 1
+
+ // Read timestamp diff.
+ ts, nb := binary.Uvarint(b[n:])
+ if nb <= 0 {
+ return 0, 0, fmt.Errorf("found invalid uvarint for timestamp")
+ }
+ n += nb
+
+ // Read the rest of the arguments.
+ for i := 0; i < len(spec.Args)-1; i++ {
+ arg, nb := binary.Uvarint(b[n:])
+ if nb <= 0 {
+ return 0, 0, fmt.Errorf("found invalid uvarint")
+ }
+ e.args[i] = arg
+ n += nb
+ }
+ return n, timestamp(ts), nil
+}
+
+func heapInsert(heap []*batchCursor, bc *batchCursor) []*batchCursor {
+ // Add the cursor to the end of the heap.
+ heap = append(heap, bc)
+
+ // Sift the new entry up to the right place.
+ heapSiftUp(heap, len(heap)-1)
+ return heap
+}
+
+func heapUpdate(heap []*batchCursor, i int) {
+ // Try to sift up.
+ if heapSiftUp(heap, i) != i {
+ return
+ }
+ // Try to sift down, if sifting up failed.
+ heapSiftDown(heap, i)
+}
+
+func heapRemove(heap []*batchCursor, i int) []*batchCursor {
+ // Sift index i up to the root, ignoring actual values.
+ for i > 0 {
+ heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2]
+ i = (i - 1) / 2
+ }
+ // Swap the root with the last element, then remove it.
+ heap[0], heap[len(heap)-1] = heap[len(heap)-1], heap[0]
+ heap = heap[:len(heap)-1]
+ // Sift the root down.
+ heapSiftDown(heap, 0)
+ return heap
+}
+
+func heapSiftUp(heap []*batchCursor, i int) int {
+ for i > 0 && heap[(i-1)/2].ev.time > heap[i].ev.time {
+ heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2]
+ i = (i - 1) / 2
+ }
+ return i
+}
+
+func heapSiftDown(heap []*batchCursor, i int) int {
+ for {
+ m := min3(heap, i, 2*i+1, 2*i+2)
+ if m == i {
+ // Heap invariant already applies.
+ break
+ }
+ heap[i], heap[m] = heap[m], heap[i]
+ i = m
+ }
+ return i
+}
+
+func min3(b []*batchCursor, i0, i1, i2 int) int {
+ minIdx := i0
+ minT := maxTime
+ if i0 < len(b) {
+ minT = b[i0].ev.time
+ }
+ if i1 < len(b) {
+ if t := b[i1].ev.time; t < minT {
+ minT = t
+ minIdx = i1
+ }
+ }
+ if i2 < len(b) {
+ if t := b[i2].ev.time; t < minT {
+ minT = t
+ minIdx = i2
+ }
+ }
+ return minIdx
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor_test.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..69731e5254088262d77e488cece1fc186bbec22b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor_test.go
@@ -0,0 +1,126 @@
+// 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 (
+ "fmt"
+ "strings"
+ "testing"
+
+ "slices"
+)
+
+func TestHeap(t *testing.T) {
+ var heap []*batchCursor
+
+ // Insert a bunch of values into the heap.
+ checkHeap(t, heap)
+ heap = heapInsert(heap, makeBatchCursor(5))
+ checkHeap(t, heap)
+ for i := int64(-20); i < 20; i++ {
+ heap = heapInsert(heap, makeBatchCursor(i))
+ checkHeap(t, heap)
+ }
+
+ // Update an element in the middle to be the new minimum.
+ for i := range heap {
+ if heap[i].ev.time == 5 {
+ heap[i].ev.time = -21
+ heapUpdate(heap, i)
+ break
+ }
+ }
+ checkHeap(t, heap)
+ if heap[0].ev.time != -21 {
+ t.Fatalf("heap update failed, expected %d as heap min: %s", -21, heapDebugString(heap))
+ }
+
+ // Update the minimum element to be smaller. There should be no change.
+ heap[0].ev.time = -22
+ heapUpdate(heap, 0)
+ checkHeap(t, heap)
+ if heap[0].ev.time != -22 {
+ t.Fatalf("heap update failed, expected %d as heap min: %s", -22, heapDebugString(heap))
+ }
+
+ // Update the last element to be larger. There should be no change.
+ heap[len(heap)-1].ev.time = 21
+ heapUpdate(heap, len(heap)-1)
+ checkHeap(t, heap)
+ if heap[len(heap)-1].ev.time != 21 {
+ t.Fatalf("heap update failed, expected %d as heap min: %s", 21, heapDebugString(heap))
+ }
+
+ // Update the last element to be smaller.
+ heap[len(heap)-1].ev.time = 7
+ heapUpdate(heap, len(heap)-1)
+ checkHeap(t, heap)
+ if heap[len(heap)-1].ev.time == 21 {
+ t.Fatalf("heap update failed, unexpected %d as heap min: %s", 21, heapDebugString(heap))
+ }
+
+ // Remove an element in the middle.
+ for i := range heap {
+ if heap[i].ev.time == 5 {
+ heap = heapRemove(heap, i)
+ break
+ }
+ }
+ checkHeap(t, heap)
+ for i := range heap {
+ if heap[i].ev.time == 5 {
+ t.Fatalf("failed to remove heap elem with time %d: %s", 5, heapDebugString(heap))
+ }
+ }
+
+ // Remove tail.
+ heap = heapRemove(heap, len(heap)-1)
+ checkHeap(t, heap)
+
+ // Remove from the head, and make sure the result is sorted.
+ l := len(heap)
+ var removed []*batchCursor
+ for i := 0; i < l; i++ {
+ removed = append(removed, heap[0])
+ heap = heapRemove(heap, 0)
+ checkHeap(t, heap)
+ }
+ if !slices.IsSortedFunc(removed, (*batchCursor).compare) {
+ t.Fatalf("heap elements not removed in sorted order, got: %s", heapDebugString(removed))
+ }
+}
+
+func makeBatchCursor(v int64) *batchCursor {
+ return &batchCursor{ev: baseEvent{time: Time(v)}}
+}
+
+func heapDebugString(heap []*batchCursor) string {
+ var sb strings.Builder
+ fmt.Fprintf(&sb, "[")
+ for i := range heap {
+ if i != 0 {
+ fmt.Fprintf(&sb, ", ")
+ }
+ fmt.Fprintf(&sb, "%d", heap[i].ev.time)
+ }
+ fmt.Fprintf(&sb, "]")
+ return sb.String()
+}
+
+func checkHeap(t *testing.T, heap []*batchCursor) {
+ t.Helper()
+
+ for i := range heap {
+ if i == 0 {
+ continue
+ }
+ if heap[(i-1)/2].compare(heap[i]) > 0 {
+ t.Errorf("heap invariant not maintained between index %d and parent %d: %s", i, i/2, heapDebugString(heap))
+ }
+ }
+ if t.Failed() {
+ t.FailNow()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/event.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/event.go
new file mode 100644
index 0000000000000000000000000000000000000000..763313c3326943b5432b83b7330ccceda87a9c8c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/event.go
@@ -0,0 +1,780 @@
+// 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 (
+ "fmt"
+ "math"
+ "strings"
+ "time"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+ "internal/trace/v2/version"
+)
+
+// EventKind indicates the kind of event this is.
+//
+// Use this information to obtain a more specific event that
+// allows access to more detailed information.
+type EventKind uint16
+
+const (
+ EventBad EventKind = iota
+
+ // EventKindSync is an event that indicates a global synchronization
+ // point in the trace. At the point of a sync event, the
+ // trace reader can be certain that all resources (e.g. threads,
+ // goroutines) that have existed until that point have been enumerated.
+ EventSync
+
+ // EventMetric is an event that represents the value of a metric at
+ // a particular point in time.
+ EventMetric
+
+ // EventLabel attaches a label to a resource.
+ EventLabel
+
+ // EventStackSample represents an execution sample, indicating what a
+ // thread/proc/goroutine was doing at a particular point in time via
+ // its backtrace.
+ //
+ // Note: Samples should be considered a close approximation of
+ // what a thread/proc/goroutine was executing at a given point in time.
+ // These events may slightly contradict the situation StateTransitions
+ // describe, so they should only be treated as a best-effort annotation.
+ EventStackSample
+
+ // EventRangeBegin and EventRangeEnd are a pair of generic events representing
+ // a special range of time. Ranges are named and scoped to some resource
+ // (identified via ResourceKind). A range that has begun but has not ended
+ // is considered active.
+ //
+ // EvRangeBegin and EvRangeEnd will share the same name, and an End will always
+ // follow a Begin on the same instance of the resource. The associated
+ // resource ID can be obtained from the Event. ResourceNone indicates the
+ // range is globally scoped. That is, any goroutine/proc/thread can start or
+ // stop, but only one such range may be active at any given time.
+ //
+ // EventRangeActive is like EventRangeBegin, but indicates that the range was
+ // already active. In this case, the resource referenced may not be in the current
+ // context.
+ EventRangeBegin
+ EventRangeActive
+ EventRangeEnd
+
+ // EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task.
+ EventTaskBegin
+ EventTaskEnd
+
+ // EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region.
+ EventRegionBegin
+ EventRegionEnd
+
+ // EventLog represents a runtime/trace.Log call.
+ EventLog
+
+ // Transitions in state for some resource.
+ EventStateTransition
+)
+
+// String returns a string form of the EventKind.
+func (e EventKind) String() string {
+ if int(e) >= len(eventKindStrings) {
+ return eventKindStrings[0]
+ }
+ return eventKindStrings[e]
+}
+
+var eventKindStrings = [...]string{
+ EventBad: "Bad",
+ EventSync: "Sync",
+ EventMetric: "Metric",
+ EventLabel: "Label",
+ EventStackSample: "StackSample",
+ EventRangeBegin: "RangeBegin",
+ EventRangeActive: "RangeActive",
+ EventRangeEnd: "RangeEnd",
+ EventTaskBegin: "TaskBegin",
+ EventTaskEnd: "TaskEnd",
+ EventRegionBegin: "RegionBegin",
+ EventRegionEnd: "RegionEnd",
+ EventLog: "Log",
+ EventStateTransition: "StateTransition",
+}
+
+const maxTime = Time(math.MaxInt64)
+
+// Time is a timestamp in nanoseconds.
+//
+// It corresponds to the monotonic clock on the platform that the
+// trace was taken, and so is possible to correlate with timestamps
+// for other traces taken on the same machine using the same clock
+// (i.e. no reboots in between).
+//
+// The actual absolute value of the timestamp is only meaningful in
+// relation to other timestamps from the same clock.
+//
+// BUG: Timestamps coming from traces on Windows platforms are
+// only comparable with timestamps from the same trace. Timestamps
+// across traces cannot be compared, because the system clock is
+// not used as of Go 1.22.
+//
+// BUG: Traces produced by Go versions 1.21 and earlier cannot be
+// compared with timestamps from other traces taken on the same
+// machine. This is because the system clock was not used at all
+// to collect those timestamps.
+type Time int64
+
+// Sub subtracts t0 from t, returning the duration in nanoseconds.
+func (t Time) Sub(t0 Time) time.Duration {
+ return time.Duration(int64(t) - int64(t0))
+}
+
+// Metric provides details about a Metric event.
+type Metric struct {
+ // Name is the name of the sampled metric.
+ //
+ // Names follow the same convention as metric names in the
+ // runtime/metrics package, meaning they include the unit.
+ // Names that match with the runtime/metrics package represent
+ // the same quantity. Note that this corresponds to the
+ // runtime/metrics package for the Go version this trace was
+ // collected for.
+ Name string
+
+ // Value is the sampled value of the metric.
+ //
+ // The Value's Kind is tied to the name of the metric, and so is
+ // guaranteed to be the same for metric samples for the same metric.
+ Value Value
+}
+
+// Label provides details about a Label event.
+type Label struct {
+ // Label is the label applied to some resource.
+ Label string
+
+ // Resource is the resource to which this label should be applied.
+ Resource ResourceID
+}
+
+// Range provides details about a Range event.
+type Range struct {
+ // Name is a human-readable name for the range.
+ //
+ // This name can be used to identify the end of the range for the resource
+ // its scoped to, because only one of each type of range may be active on
+ // a particular resource. The relevant resource should be obtained from the
+ // Event that produced these details. The corresponding RangeEnd will have
+ // an identical name.
+ Name string
+
+ // Scope is the resource that the range is scoped to.
+ //
+ // For example, a ResourceGoroutine scope means that the same goroutine
+ // must have a start and end for the range, and that goroutine can only
+ // have one range of a particular name active at any given time. The
+ // ID that this range is scoped to may be obtained via Event.Goroutine.
+ //
+ // The ResourceNone scope means that the range is globally scoped. As a
+ // result, any goroutine/proc/thread may start or end the range, and only
+ // one such named range may be active globally at any given time.
+ //
+ // For RangeBegin and RangeEnd events, this will always reference some
+ // resource ID in the current execution context. For RangeActive events,
+ // this may reference a resource not in the current context. Prefer Scope
+ // over the current execution context.
+ Scope ResourceID
+}
+
+// RangeAttributes provides attributes about a completed Range.
+type RangeAttribute struct {
+ // Name is the human-readable name for the range.
+ Name string
+
+ // Value is the value of the attribute.
+ Value Value
+}
+
+// TaskID is the internal ID of a task used to disambiguate tasks (even if they
+// are of the same type).
+type TaskID uint64
+
+const (
+ // NoTask indicates the lack of a task.
+ NoTask = TaskID(^uint64(0))
+
+ // BackgroundTask is the global task that events are attached to if there was
+ // no other task in the context at the point the event was emitted.
+ BackgroundTask = TaskID(0)
+)
+
+// Task provides details about a Task event.
+type Task struct {
+ // ID is a unique identifier for the task.
+ //
+ // This can be used to associate the beginning of a task with its end.
+ ID TaskID
+
+ // ParentID is the ID of the parent task.
+ Parent TaskID
+
+ // Type is the taskType that was passed to runtime/trace.NewTask.
+ //
+ // May be "" if a task's TaskBegin event isn't present in the trace.
+ Type string
+}
+
+// Region provides details about a Region event.
+type Region struct {
+ // Task is the ID of the task this region is associated with.
+ Task TaskID
+
+ // Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion.
+ Type string
+}
+
+// Log provides details about a Log event.
+type Log struct {
+ // Task is the ID of the task this region is associated with.
+ Task TaskID
+
+ // Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf.
+ Category string
+
+ // Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf.
+ Message string
+}
+
+// Stack represents a stack. It's really a handle to a stack and it's trivially comparable.
+//
+// If two Stacks are equal then their Frames are guaranteed to be identical. If they are not
+// equal, however, their Frames may still be equal.
+type Stack struct {
+ table *evTable
+ id stackID
+}
+
+// Frames is an iterator over the frames in a Stack.
+func (s Stack) Frames(yield func(f StackFrame) bool) bool {
+ if s.id == 0 {
+ return true
+ }
+ stk := s.table.stacks.mustGet(s.id)
+ for _, f := range stk.frames {
+ sf := StackFrame{
+ PC: f.pc,
+ Func: s.table.strings.mustGet(f.funcID),
+ File: s.table.strings.mustGet(f.fileID),
+ Line: f.line,
+ }
+ if !yield(sf) {
+ return false
+ }
+ }
+ return true
+}
+
+// NoStack is a sentinel value that can be compared against any Stack value, indicating
+// a lack of a stack trace.
+var NoStack = Stack{}
+
+// StackFrame represents a single frame of a stack.
+type StackFrame struct {
+ // PC is the program counter of the function call if this
+ // is not a leaf frame. If it's a leaf frame, it's the point
+ // at which the stack trace was taken.
+ PC uint64
+
+ // Func is the name of the function this frame maps to.
+ Func string
+
+ // File is the file which contains the source code of Func.
+ File string
+
+ // Line is the line number within File which maps to PC.
+ Line uint64
+}
+
+// Event represents a single event in the trace.
+type Event struct {
+ table *evTable
+ ctx schedCtx
+ base baseEvent
+}
+
+// Kind returns the kind of event that this is.
+func (e Event) Kind() EventKind {
+ return go122Type2Kind[e.base.typ]
+}
+
+// Time returns the timestamp of the event.
+func (e Event) Time() Time {
+ return e.base.time
+}
+
+// Goroutine returns the ID of the goroutine that was executing when
+// this event happened. It describes part of the execution context
+// for this event.
+//
+// Note that for goroutine state transitions this always refers to the
+// state before the transition. For example, if a goroutine is just
+// starting to run on this thread and/or proc, then this will return
+// NoGoroutine. In this case, the goroutine starting to run will be
+// can be found at Event.StateTransition().Resource.
+func (e Event) Goroutine() GoID {
+ return e.ctx.G
+}
+
+// Proc returns the ID of the proc this event event pertains to.
+//
+// Note that for proc state transitions this always refers to the
+// state before the transition. For example, if a proc is just
+// starting to run on this thread, then this will return NoProc.
+func (e Event) Proc() ProcID {
+ return e.ctx.P
+}
+
+// Thread returns the ID of the thread this event pertains to.
+//
+// Note that for thread state transitions this always refers to the
+// state before the transition. For example, if a thread is just
+// starting to run, then this will return NoThread.
+//
+// Note: tracking thread state is not currently supported, so this
+// will always return a valid thread ID. However thread state transitions
+// may be tracked in the future, and callers must be robust to this
+// possibility.
+func (e Event) Thread() ThreadID {
+ return e.ctx.M
+}
+
+// Stack returns a handle to a stack associated with the event.
+//
+// This represents a stack trace at the current moment in time for
+// the current execution context.
+func (e Event) Stack() Stack {
+ if e.base.typ == evSync {
+ return NoStack
+ }
+ if e.base.typ == go122.EvCPUSample {
+ return Stack{table: e.table, id: stackID(e.base.args[0])}
+ }
+ spec := go122.Specs()[e.base.typ]
+ if len(spec.StackIDs) == 0 {
+ return NoStack
+ }
+ // The stack for the main execution context is always the
+ // first stack listed in StackIDs. Subtract one from this
+ // because we've peeled away the timestamp argument.
+ id := stackID(e.base.args[spec.StackIDs[0]-1])
+ if id == 0 {
+ return NoStack
+ }
+ return Stack{table: e.table, id: id}
+}
+
+// Metric returns details about a Metric event.
+//
+// Panics if Kind != EventMetric.
+func (e Event) Metric() Metric {
+ if e.Kind() != EventMetric {
+ panic("Metric called on non-Metric event")
+ }
+ var m Metric
+ switch e.base.typ {
+ case go122.EvProcsChange:
+ m.Name = "/sched/gomaxprocs:threads"
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
+ case go122.EvHeapAlloc:
+ m.Name = "/memory/classes/heap/objects:bytes"
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
+ case go122.EvHeapGoal:
+ m.Name = "/gc/heap/goal:bytes"
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
+ default:
+ panic(fmt.Sprintf("internal error: unexpected event type for Metric kind: %s", go122.EventString(e.base.typ)))
+ }
+ return m
+}
+
+// Label returns details about a Label event.
+//
+// Panics if Kind != EventLabel.
+func (e Event) Label() Label {
+ if e.Kind() != EventLabel {
+ panic("Label called on non-Label event")
+ }
+ if e.base.typ != go122.EvGoLabel {
+ panic(fmt.Sprintf("internal error: unexpected event type for Label kind: %s", go122.EventString(e.base.typ)))
+ }
+ return Label{
+ Label: e.table.strings.mustGet(stringID(e.base.args[0])),
+ Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)},
+ }
+}
+
+// Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
+//
+// Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
+func (e Event) Range() Range {
+ if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd {
+ panic("Range called on non-Range event")
+ }
+ var r Range
+ switch e.base.typ {
+ case go122.EvSTWBegin, go122.EvSTWEnd:
+ // N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
+ // for go122.EvSTWEnd (it's already there for Begin).
+ r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")"
+ r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())}
+ case go122.EvGCBegin, go122.EvGCActive, go122.EvGCEnd:
+ r.Name = "GC concurrent mark phase"
+ r.Scope = ResourceID{Kind: ResourceNone}
+ case go122.EvGCSweepBegin, go122.EvGCSweepActive, go122.EvGCSweepEnd:
+ r.Name = "GC incremental sweep"
+ r.Scope = ResourceID{Kind: ResourceProc}
+ if e.base.typ == go122.EvGCSweepActive {
+ r.Scope.id = int64(e.base.args[0])
+ } else {
+ r.Scope.id = int64(e.Proc())
+ }
+ r.Scope.id = int64(e.Proc())
+ case go122.EvGCMarkAssistBegin, go122.EvGCMarkAssistActive, go122.EvGCMarkAssistEnd:
+ r.Name = "GC mark assist"
+ r.Scope = ResourceID{Kind: ResourceGoroutine}
+ if e.base.typ == go122.EvGCMarkAssistActive {
+ r.Scope.id = int64(e.base.args[0])
+ } else {
+ r.Scope.id = int64(e.Goroutine())
+ }
+ default:
+ panic(fmt.Sprintf("internal error: unexpected event type for Range kind: %s", go122.EventString(e.base.typ)))
+ }
+ return r
+}
+
+// RangeAttributes returns attributes for a completed range.
+//
+// Panics if Kind != EventRangeEnd.
+func (e Event) RangeAttributes() []RangeAttribute {
+ if e.Kind() != EventRangeEnd {
+ panic("Range called on non-Range event")
+ }
+ if e.base.typ != go122.EvGCSweepEnd {
+ return nil
+ }
+ return []RangeAttribute{
+ {
+ Name: "bytes swept",
+ Value: Value{kind: ValueUint64, scalar: e.base.args[0]},
+ },
+ {
+ Name: "bytes reclaimed",
+ Value: Value{kind: ValueUint64, scalar: e.base.args[1]},
+ },
+ }
+}
+
+// Task returns details about a TaskBegin or TaskEnd event.
+//
+// Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
+func (e Event) Task() Task {
+ if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd {
+ panic("Task called on non-Task event")
+ }
+ parentID := NoTask
+ var typ string
+ switch e.base.typ {
+ case go122.EvUserTaskBegin:
+ parentID = TaskID(e.base.args[1])
+ typ = e.table.strings.mustGet(stringID(e.base.args[2]))
+ case go122.EvUserTaskEnd:
+ parentID = TaskID(e.base.extra(version.Go122)[0])
+ typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1]))
+ default:
+ panic(fmt.Sprintf("internal error: unexpected event type for Task kind: %s", go122.EventString(e.base.typ)))
+ }
+ return Task{
+ ID: TaskID(e.base.args[0]),
+ Parent: parentID,
+ Type: typ,
+ }
+}
+
+// Region returns details about a RegionBegin or RegionEnd event.
+//
+// Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
+func (e Event) Region() Region {
+ if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd {
+ panic("Region called on non-Region event")
+ }
+ if e.base.typ != go122.EvUserRegionBegin && e.base.typ != go122.EvUserRegionEnd {
+ panic(fmt.Sprintf("internal error: unexpected event type for Region kind: %s", go122.EventString(e.base.typ)))
+ }
+ return Region{
+ Task: TaskID(e.base.args[0]),
+ Type: e.table.strings.mustGet(stringID(e.base.args[1])),
+ }
+}
+
+// Log returns details about a Log event.
+//
+// Panics if Kind != EventLog.
+func (e Event) Log() Log {
+ if e.Kind() != EventLog {
+ panic("Log called on non-Log event")
+ }
+ if e.base.typ != go122.EvUserLog {
+ panic(fmt.Sprintf("internal error: unexpected event type for Log kind: %s", go122.EventString(e.base.typ)))
+ }
+ return Log{
+ Task: TaskID(e.base.args[0]),
+ Category: e.table.strings.mustGet(stringID(e.base.args[1])),
+ Message: e.table.strings.mustGet(stringID(e.base.args[2])),
+ }
+}
+
+// StateTransition returns details about a StateTransition event.
+//
+// Panics if Kind != EventStateTransition.
+func (e Event) StateTransition() StateTransition {
+ if e.Kind() != EventStateTransition {
+ panic("StateTransition called on non-StateTransition event")
+ }
+ var s StateTransition
+ switch e.base.typ {
+ case go122.EvProcStart:
+ s = procStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning)
+ case go122.EvProcStop:
+ s = procStateTransition(e.ctx.P, ProcRunning, ProcIdle)
+ case go122.EvProcSteal:
+ // N.B. ordering.advance populates e.base.extra.
+ beforeState := ProcRunning
+ if go122.ProcStatus(e.base.extra(version.Go122)[0]) == go122.ProcSyscallAbandoned {
+ // We've lost information because this ProcSteal advanced on a
+ // SyscallAbandoned state. Treat the P as idle because ProcStatus
+ // treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
+ // transition.
+ beforeState = ProcIdle
+ }
+ s = procStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle)
+ case go122.EvProcStatus:
+ // N.B. ordering.advance populates e.base.extra.
+ s = procStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), go122ProcStatus2ProcState[e.base.args[1]])
+ case go122.EvGoCreate:
+ s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoRunnable)
+ s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])}
+ case go122.EvGoCreateSyscall:
+ s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall)
+ case go122.EvGoStart:
+ s = goStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning)
+ case go122.EvGoDestroy:
+ s = goStateTransition(e.ctx.G, GoRunning, GoNotExist)
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoDestroySyscall:
+ s = goStateTransition(e.ctx.G, GoSyscall, GoNotExist)
+ case go122.EvGoStop:
+ s = goStateTransition(e.ctx.G, GoRunning, GoRunnable)
+ s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoBlock:
+ s = goStateTransition(e.ctx.G, GoRunning, GoWaiting)
+ s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoUnblock:
+ s = goStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable)
+ case go122.EvGoSyscallBegin:
+ s = goStateTransition(e.ctx.G, GoRunning, GoSyscall)
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoSyscallEnd:
+ s = goStateTransition(e.ctx.G, GoSyscall, GoRunning)
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoSyscallEndBlocked:
+ s = goStateTransition(e.ctx.G, GoSyscall, GoRunnable)
+ s.Stack = e.Stack() // This event references the resource the event happened on.
+ case go122.EvGoStatus:
+ // N.B. ordering.advance populates e.base.extra.
+ s = goStateTransition(GoID(e.base.args[0]), GoState(e.base.extra(version.Go122)[0]), go122GoStatus2GoState[e.base.args[2]])
+ default:
+ panic(fmt.Sprintf("internal error: unexpected event type for StateTransition kind: %s", go122.EventString(e.base.typ)))
+ }
+ return s
+}
+
+const evSync = ^event.Type(0)
+
+var go122Type2Kind = [...]EventKind{
+ go122.EvCPUSample: EventStackSample,
+ go122.EvProcsChange: EventMetric,
+ go122.EvProcStart: EventStateTransition,
+ go122.EvProcStop: EventStateTransition,
+ go122.EvProcSteal: EventStateTransition,
+ go122.EvProcStatus: EventStateTransition,
+ go122.EvGoCreate: EventStateTransition,
+ go122.EvGoCreateSyscall: EventStateTransition,
+ go122.EvGoStart: EventStateTransition,
+ go122.EvGoDestroy: EventStateTransition,
+ go122.EvGoDestroySyscall: EventStateTransition,
+ go122.EvGoStop: EventStateTransition,
+ go122.EvGoBlock: EventStateTransition,
+ go122.EvGoUnblock: EventStateTransition,
+ go122.EvGoSyscallBegin: EventStateTransition,
+ go122.EvGoSyscallEnd: EventStateTransition,
+ go122.EvGoSyscallEndBlocked: EventStateTransition,
+ go122.EvGoStatus: EventStateTransition,
+ go122.EvSTWBegin: EventRangeBegin,
+ go122.EvSTWEnd: EventRangeEnd,
+ go122.EvGCActive: EventRangeActive,
+ go122.EvGCBegin: EventRangeBegin,
+ go122.EvGCEnd: EventRangeEnd,
+ go122.EvGCSweepActive: EventRangeActive,
+ go122.EvGCSweepBegin: EventRangeBegin,
+ go122.EvGCSweepEnd: EventRangeEnd,
+ go122.EvGCMarkAssistActive: EventRangeActive,
+ go122.EvGCMarkAssistBegin: EventRangeBegin,
+ go122.EvGCMarkAssistEnd: EventRangeEnd,
+ go122.EvHeapAlloc: EventMetric,
+ go122.EvHeapGoal: EventMetric,
+ go122.EvGoLabel: EventLabel,
+ go122.EvUserTaskBegin: EventTaskBegin,
+ go122.EvUserTaskEnd: EventTaskEnd,
+ go122.EvUserRegionBegin: EventRegionBegin,
+ go122.EvUserRegionEnd: EventRegionEnd,
+ go122.EvUserLog: EventLog,
+ evSync: EventSync,
+}
+
+var go122GoStatus2GoState = [...]GoState{
+ go122.GoRunnable: GoRunnable,
+ go122.GoRunning: GoRunning,
+ go122.GoWaiting: GoWaiting,
+ go122.GoSyscall: GoSyscall,
+}
+
+var go122ProcStatus2ProcState = [...]ProcState{
+ go122.ProcRunning: ProcRunning,
+ go122.ProcIdle: ProcIdle,
+ go122.ProcSyscall: ProcRunning,
+ go122.ProcSyscallAbandoned: ProcIdle,
+}
+
+// String returns the event as a human-readable string.
+//
+// The format of the string is intended for debugging and is subject to change.
+func (e Event) String() string {
+ var sb strings.Builder
+ fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine())
+ fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time())
+ // Kind-specific fields.
+ switch kind := e.Kind(); kind {
+ case EventMetric:
+ m := e.Metric()
+ fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, valueAsString(m.Value))
+ case EventLabel:
+ l := e.Label()
+ fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource)
+ case EventRangeBegin, EventRangeActive, EventRangeEnd:
+ r := e.Range()
+ fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope)
+ if kind == EventRangeEnd {
+ fmt.Fprintf(&sb, " Attributes=[")
+ for i, attr := range e.RangeAttributes() {
+ if i != 0 {
+ fmt.Fprintf(&sb, " ")
+ }
+ fmt.Fprintf(&sb, "%q=%s", attr.Name, valueAsString(attr.Value))
+ }
+ fmt.Fprintf(&sb, "]")
+ }
+ case EventTaskBegin, EventTaskEnd:
+ t := e.Task()
+ fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type)
+ case EventRegionBegin, EventRegionEnd:
+ r := e.Region()
+ fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type)
+ case EventLog:
+ l := e.Log()
+ fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message)
+ case EventStateTransition:
+ s := e.StateTransition()
+ fmt.Fprintf(&sb, " Resource=%s Reason=%q", s.Resource, s.Reason)
+ switch s.Resource.Kind {
+ case ResourceGoroutine:
+ id := s.Resource.Goroutine()
+ old, new := s.Goroutine()
+ fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new)
+ case ResourceProc:
+ id := s.Resource.Proc()
+ old, new := s.Proc()
+ fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new)
+ }
+ if s.Stack != NoStack {
+ fmt.Fprintln(&sb)
+ fmt.Fprintln(&sb, "TransitionStack=")
+ s.Stack.Frames(func(f StackFrame) bool {
+ fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
+ fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
+ return true
+ })
+ }
+ }
+ if stk := e.Stack(); stk != NoStack {
+ fmt.Fprintln(&sb)
+ fmt.Fprintln(&sb, "Stack=")
+ stk.Frames(func(f StackFrame) bool {
+ fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
+ fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
+ return true
+ })
+ }
+ return sb.String()
+}
+
+// validateTableIDs checks to make sure lookups in e.table
+// will work.
+func (e Event) validateTableIDs() error {
+ if e.base.typ == evSync {
+ return nil
+ }
+ spec := go122.Specs()[e.base.typ]
+
+ // Check stacks.
+ for _, i := range spec.StackIDs {
+ id := stackID(e.base.args[i-1])
+ _, ok := e.table.stacks.get(id)
+ if !ok {
+ return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name)
+ }
+ }
+ // N.B. Strings referenced by stack frames are validated
+ // early on, when reading the stacks in to begin with.
+
+ // Check strings.
+ for _, i := range spec.StringIDs {
+ id := stringID(e.base.args[i-1])
+ _, ok := e.table.strings.get(id)
+ if !ok {
+ return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name)
+ }
+ }
+ return nil
+}
+
+func syncEvent(table *evTable, ts Time) Event {
+ return Event{
+ table: table,
+ ctx: schedCtx{
+ G: NoGoroutine,
+ P: NoProc,
+ M: NoThread,
+ },
+ base: baseEvent{
+ typ: evSync,
+ time: ts,
+ },
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/event/event.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/event.go
new file mode 100644
index 0000000000000000000000000000000000000000..111dde604c45267fb7d8054ab214e1d227db7767
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/event.go
@@ -0,0 +1,89 @@
+// 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 event
+
+// Type is the common in-memory representation of the low-leve
+type Type uint8
+
+// Spec is a specification for a trace event. It contains sufficient information
+// to perform basic parsing of any trace event for any version of Go.
+type Spec struct {
+ // Name is the human-readable name of the trace event.
+ Name string
+
+ // Args contains the names of each trace event's argument.
+ // Its length determines the number of arguments an event has.
+ //
+ // Argument names follow a certain structure and this structure
+ // is relied on by the testing framework to type-check arguments.
+ // The structure is is:
+ //
+ // (?P[A-Za-z]+_)?(?P[A-Za-z]+)
+ //
+ // In sum, it's an optional name followed by a type. If the name
+ // is present, it is separated from the type with an underscore.
+ // The valid argument types and the Go types they map to are listed
+ // in the ArgTypes variable.
+ Args []string
+
+ // StartEv indicates the event type of the corresponding "start"
+ // event, if this event is an "end," for a pair of events that
+ // represent a time range.
+ StartEv Type
+
+ // IsTimedEvent indicates whether this is an event that both
+ // appears in the main event stream and is surfaced to the
+ // trace reader.
+ //
+ // Events that are not "timed" are considered "structural"
+ // since they either need significant reinterpretation or
+ // otherwise aren't actually surfaced by the trace reader.
+ IsTimedEvent bool
+
+ // HasData is true if the event has trailer consisting of a
+ // varint length followed by unencoded bytes of some data.
+ HasData bool
+
+ // StringIDs indicates which of the arguments are string IDs.
+ StringIDs []int
+
+ // StackIDs indicates which of the arguments are stack IDs.
+ //
+ // The list is not sorted. The first index always refers to
+ // the main stack for the current execution context of the event.
+ StackIDs []int
+
+ // IsStack indicates that the event represents a complete
+ // stack trace. Specifically, it means that after the arguments
+ // there's a varint length, followed by 4*length varints. Each
+ // group of 4 represents the PC, file ID, func ID, and line number
+ // in that order.
+ IsStack bool
+}
+
+// ArgTypes is a list of valid argument types for use in Args.
+//
+// See the documentation of Args for more details.
+var ArgTypes = [...]string{
+ "seq", // sequence number
+ "pstatus", // P status
+ "gstatus", // G status
+ "g", // trace.GoID
+ "m", // trace.ThreadID
+ "p", // trace.ProcID
+ "string", // string ID
+ "stack", // stack ID
+ "value", // uint64
+ "task", // trace.TaskID
+}
+
+// Names is a helper that produces a mapping of event names to event types.
+func Names(specs []Spec) map[string]Type {
+ nameToType := make(map[string]Type)
+ for i, spec := range specs {
+ nameToType[spec.Name] = Type(byte(i))
+ }
+ return nameToType
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/event/go122/event.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/go122/event.go
new file mode 100644
index 0000000000000000000000000000000000000000..be7ce4c806a3e2ae45622efd3df4779aff6d80d8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/go122/event.go
@@ -0,0 +1,388 @@
+// 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 go122
+
+import (
+ "fmt"
+ "internal/trace/v2/event"
+)
+
+const (
+ EvNone event.Type = iota // unused
+
+ // Structural events.
+ EvEventBatch // start of per-M batch of events [generation, M ID, timestamp, batch length]
+ EvStacks // start of a section of the stack table [...EvStack]
+ EvStack // stack table entry [ID, ...{PC, func string ID, file string ID, line #}]
+ EvStrings // start of a section of the string dictionary [...EvString]
+ EvString // string dictionary entry [ID, length, string]
+ EvCPUSamples // start of a section of CPU samples [...EvCPUSample]
+ EvCPUSample // CPU profiling sample [timestamp, M ID, P ID, goroutine ID, stack ID]
+ EvFrequency // timestamp units per sec [freq]
+
+ // Procs.
+ EvProcsChange // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack ID]
+ EvProcStart // start of P [timestamp, P ID, P seq]
+ EvProcStop // stop of P [timestamp]
+ EvProcSteal // P was stolen [timestamp, P ID, P seq, M ID]
+ EvProcStatus // P status at the start of a generation [timestamp, P ID, status]
+
+ // Goroutines.
+ EvGoCreate // goroutine creation [timestamp, new goroutine ID, new stack ID, stack ID]
+ EvGoCreateSyscall // goroutine appears in syscall (cgo callback) [timestamp, new goroutine ID]
+ EvGoStart // goroutine starts running [timestamp, goroutine ID, goroutine seq]
+ EvGoDestroy // goroutine ends [timestamp]
+ EvGoDestroySyscall // goroutine ends in syscall (cgo callback) [timestamp]
+ EvGoStop // goroutine yields its time, but is runnable [timestamp, reason, stack ID]
+ EvGoBlock // goroutine blocks [timestamp, reason, stack ID]
+ EvGoUnblock // goroutine is unblocked [timestamp, goroutine ID, goroutine seq, stack ID]
+ EvGoSyscallBegin // syscall enter [timestamp, P seq, stack ID]
+ EvGoSyscallEnd // syscall exit [timestamp]
+ EvGoSyscallEndBlocked // syscall exit and it blocked at some point [timestamp]
+ EvGoStatus // goroutine status at the start of a generation [timestamp, goroutine ID, status]
+
+ // STW.
+ EvSTWBegin // STW start [timestamp, kind]
+ EvSTWEnd // STW done [timestamp]
+
+ // GC events.
+ EvGCActive // GC active [timestamp, seq]
+ EvGCBegin // GC start [timestamp, seq, stack ID]
+ EvGCEnd // GC done [timestamp, seq]
+ EvGCSweepActive // GC sweep active [timestamp, P ID]
+ EvGCSweepBegin // GC sweep start [timestamp, stack ID]
+ EvGCSweepEnd // GC sweep done [timestamp, swept bytes, reclaimed bytes]
+ EvGCMarkAssistActive // GC mark assist active [timestamp, goroutine ID]
+ EvGCMarkAssistBegin // GC mark assist start [timestamp, stack ID]
+ EvGCMarkAssistEnd // GC mark assist done [timestamp]
+ EvHeapAlloc // gcController.heapLive change [timestamp, heap alloc in bytes]
+ EvHeapGoal // gcController.heapGoal() change [timestamp, heap goal in bytes]
+
+ // Annotations.
+ EvGoLabel // apply string label to current running goroutine [timestamp, label string ID]
+ EvUserTaskBegin // trace.NewTask [timestamp, internal task ID, internal parent task ID, name string ID, stack ID]
+ EvUserTaskEnd // end of a task [timestamp, internal task ID, stack ID]
+ EvUserRegionBegin // trace.{Start,With}Region [timestamp, internal task ID, name string ID, stack ID]
+ EvUserRegionEnd // trace.{End,With}Region [timestamp, internal task ID, name string ID, stack ID]
+ EvUserLog // trace.Log [timestamp, internal task ID, key string ID, stack, value string ID]
+)
+
+// EventString returns the name of a Go 1.22 event.
+func EventString(typ event.Type) string {
+ if int(typ) < len(specs) {
+ return specs[typ].Name
+ }
+ return fmt.Sprintf("Invalid(%d)", typ)
+}
+
+func Specs() []event.Spec {
+ return specs[:]
+}
+
+var specs = [...]event.Spec{
+ // "Structural" Events.
+ EvEventBatch: event.Spec{
+ Name: "EventBatch",
+ Args: []string{"gen", "m", "time", "size"},
+ },
+ EvStacks: event.Spec{
+ Name: "Stacks",
+ },
+ EvStack: event.Spec{
+ Name: "Stack",
+ Args: []string{"id", "nframes"},
+ IsStack: true,
+ },
+ EvStrings: event.Spec{
+ Name: "Strings",
+ },
+ EvString: event.Spec{
+ Name: "String",
+ Args: []string{"id"},
+ HasData: true,
+ },
+ EvCPUSamples: event.Spec{
+ Name: "CPUSamples",
+ },
+ EvCPUSample: event.Spec{
+ Name: "CPUSample",
+ Args: []string{"time", "p", "g", "m", "stack"},
+ // N.B. There's clearly a timestamp here, but these Events
+ // are special in that they don't appear in the regular
+ // M streams.
+ },
+ EvFrequency: event.Spec{
+ Name: "Frequency",
+ Args: []string{"freq"},
+ },
+
+ // "Timed" Events.
+ EvProcsChange: event.Spec{
+ Name: "ProcsChange",
+ Args: []string{"dt", "procs_value", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ },
+ EvProcStart: event.Spec{
+ Name: "ProcStart",
+ Args: []string{"dt", "p", "p_seq"},
+ IsTimedEvent: true,
+ },
+ EvProcStop: event.Spec{
+ Name: "ProcStop",
+ Args: []string{"dt"},
+ IsTimedEvent: true,
+ },
+ EvProcSteal: event.Spec{
+ Name: "ProcSteal",
+ Args: []string{"dt", "p", "p_seq", "m"},
+ IsTimedEvent: true,
+ },
+ EvProcStatus: event.Spec{
+ Name: "ProcStatus",
+ Args: []string{"dt", "p", "pstatus"},
+ IsTimedEvent: true,
+ },
+ EvGoCreate: event.Spec{
+ Name: "GoCreate",
+ Args: []string{"dt", "new_g", "new_stack", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{3, 2},
+ },
+ EvGoCreateSyscall: event.Spec{
+ Name: "GoCreateSyscall",
+ Args: []string{"dt", "new_g"},
+ IsTimedEvent: true,
+ },
+ EvGoStart: event.Spec{
+ Name: "GoStart",
+ Args: []string{"dt", "g", "g_seq"},
+ IsTimedEvent: true,
+ },
+ EvGoDestroy: event.Spec{
+ Name: "GoDestroy",
+ Args: []string{"dt"},
+ IsTimedEvent: true,
+ },
+ EvGoDestroySyscall: event.Spec{
+ Name: "GoDestroySyscall",
+ Args: []string{"dt"},
+ IsTimedEvent: true,
+ },
+ EvGoStop: event.Spec{
+ Name: "GoStop",
+ Args: []string{"dt", "reason_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ StringIDs: []int{1},
+ },
+ EvGoBlock: event.Spec{
+ Name: "GoBlock",
+ Args: []string{"dt", "reason_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ StringIDs: []int{1},
+ },
+ EvGoUnblock: event.Spec{
+ Name: "GoUnblock",
+ Args: []string{"dt", "g", "g_seq", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{3},
+ },
+ EvGoSyscallBegin: event.Spec{
+ Name: "GoSyscallBegin",
+ Args: []string{"dt", "p_seq", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ },
+ EvGoSyscallEnd: event.Spec{
+ Name: "GoSyscallEnd",
+ Args: []string{"dt"},
+ StartEv: EvGoSyscallBegin,
+ IsTimedEvent: true,
+ },
+ EvGoSyscallEndBlocked: event.Spec{
+ Name: "GoSyscallEndBlocked",
+ Args: []string{"dt"},
+ StartEv: EvGoSyscallBegin,
+ IsTimedEvent: true,
+ },
+ EvGoStatus: event.Spec{
+ Name: "GoStatus",
+ Args: []string{"dt", "g", "m", "gstatus"},
+ IsTimedEvent: true,
+ },
+ EvSTWBegin: event.Spec{
+ Name: "STWBegin",
+ Args: []string{"dt", "kind_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ StringIDs: []int{1},
+ },
+ EvSTWEnd: event.Spec{
+ Name: "STWEnd",
+ Args: []string{"dt"},
+ StartEv: EvSTWBegin,
+ IsTimedEvent: true,
+ },
+ EvGCActive: event.Spec{
+ Name: "GCActive",
+ Args: []string{"dt", "gc_seq"},
+ IsTimedEvent: true,
+ StartEv: EvGCBegin,
+ },
+ EvGCBegin: event.Spec{
+ Name: "GCBegin",
+ Args: []string{"dt", "gc_seq", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ },
+ EvGCEnd: event.Spec{
+ Name: "GCEnd",
+ Args: []string{"dt", "gc_seq"},
+ StartEv: EvGCBegin,
+ IsTimedEvent: true,
+ },
+ EvGCSweepActive: event.Spec{
+ Name: "GCSweepActive",
+ Args: []string{"dt", "p"},
+ StartEv: EvGCSweepBegin,
+ IsTimedEvent: true,
+ },
+ EvGCSweepBegin: event.Spec{
+ Name: "GCSweepBegin",
+ Args: []string{"dt", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{1},
+ },
+ EvGCSweepEnd: event.Spec{
+ Name: "GCSweepEnd",
+ Args: []string{"dt", "swept_value", "reclaimed_value"},
+ StartEv: EvGCSweepBegin,
+ IsTimedEvent: true,
+ },
+ EvGCMarkAssistActive: event.Spec{
+ Name: "GCMarkAssistActive",
+ Args: []string{"dt", "g"},
+ StartEv: EvGCMarkAssistBegin,
+ IsTimedEvent: true,
+ },
+ EvGCMarkAssistBegin: event.Spec{
+ Name: "GCMarkAssistBegin",
+ Args: []string{"dt", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{1},
+ },
+ EvGCMarkAssistEnd: event.Spec{
+ Name: "GCMarkAssistEnd",
+ Args: []string{"dt"},
+ StartEv: EvGCMarkAssistBegin,
+ IsTimedEvent: true,
+ },
+ EvHeapAlloc: event.Spec{
+ Name: "HeapAlloc",
+ Args: []string{"dt", "heapalloc_value"},
+ IsTimedEvent: true,
+ },
+ EvHeapGoal: event.Spec{
+ Name: "HeapGoal",
+ Args: []string{"dt", "heapgoal_value"},
+ IsTimedEvent: true,
+ },
+ EvGoLabel: event.Spec{
+ Name: "GoLabel",
+ Args: []string{"dt", "label_string"},
+ IsTimedEvent: true,
+ StringIDs: []int{1},
+ },
+ EvUserTaskBegin: event.Spec{
+ Name: "UserTaskBegin",
+ Args: []string{"dt", "task", "parent_task", "name_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{4},
+ StringIDs: []int{3},
+ },
+ EvUserTaskEnd: event.Spec{
+ Name: "UserTaskEnd",
+ Args: []string{"dt", "task", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{2},
+ },
+ EvUserRegionBegin: event.Spec{
+ Name: "UserRegionBegin",
+ Args: []string{"dt", "task", "name_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{3},
+ StringIDs: []int{2},
+ },
+ EvUserRegionEnd: event.Spec{
+ Name: "UserRegionEnd",
+ Args: []string{"dt", "task", "name_string", "stack"},
+ StartEv: EvUserRegionBegin,
+ IsTimedEvent: true,
+ StackIDs: []int{3},
+ StringIDs: []int{2},
+ },
+ EvUserLog: event.Spec{
+ Name: "UserLog",
+ Args: []string{"dt", "task", "key_string", "value_string", "stack"},
+ IsTimedEvent: true,
+ StackIDs: []int{4},
+ StringIDs: []int{2, 3},
+ },
+}
+
+type GoStatus uint8
+
+const (
+ GoBad GoStatus = iota
+ GoRunnable
+ GoRunning
+ GoSyscall
+ GoWaiting
+)
+
+func (s GoStatus) String() string {
+ switch s {
+ case GoRunnable:
+ return "Runnable"
+ case GoRunning:
+ return "Running"
+ case GoSyscall:
+ return "Syscall"
+ case GoWaiting:
+ return "Waiting"
+ }
+ return "Bad"
+}
+
+type ProcStatus uint8
+
+const (
+ ProcBad ProcStatus = iota
+ ProcRunning
+ ProcIdle
+ ProcSyscall
+ ProcSyscallAbandoned
+)
+
+func (s ProcStatus) String() string {
+ switch s {
+ case ProcRunning:
+ return "Running"
+ case ProcIdle:
+ return "Idle"
+ case ProcSyscall:
+ return "Syscall"
+ }
+ return "Bad"
+}
+
+const (
+ // Various format-specific constants.
+ MaxBatchSize = 64 << 10
+ MaxFramesPerStack = 128
+ MaxStringSize = 1 << 10
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/event/requirements.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/requirements.go
new file mode 100644
index 0000000000000000000000000000000000000000..c5adf2e0c239d180516860eefa06d2fc7c7dca29
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/event/requirements.go
@@ -0,0 +1,26 @@
+// 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 event
+
+// SchedReqs is a set of constraints on what the scheduling
+// context must look like.
+type SchedReqs struct {
+ Thread Constraint
+ Proc Constraint
+ Goroutine Constraint
+}
+
+// Constraint represents a various presence requirements.
+type Constraint uint8
+
+const (
+ MustNotHave Constraint = iota
+ MayHave
+ MustHave
+)
+
+// UserGoReqs is a common requirement among events that are running
+// or are close to running user code.
+var UserGoReqs = SchedReqs{Thread: MustHave, Proc: MustHave, Goroutine: MustHave}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/event_test.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/event_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c81a45185dc475f2c154eef6673697e8dce8e59a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/event_test.go
@@ -0,0 +1,43 @@
+// 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()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/generation.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/generation.go
new file mode 100644
index 0000000000000000000000000000000000000000..4cdf76e21c06f95463fbff4d819a4f837f23ceac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/generation.go
@@ -0,0 +1,399 @@
+// 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 (
+ "bufio"
+ "bytes"
+ "cmp"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "slices"
+ "strings"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+)
+
+// generation contains all the trace data for a single
+// trace generation. It is purely data: it does not
+// track any parse state nor does it contain a cursor
+// into the generation.
+type generation struct {
+ gen uint64
+ batches map[ThreadID][]batch
+ cpuSamples []cpuSample
+ *evTable
+}
+
+// spilledBatch represents a batch that was read out for the next generation,
+// while reading the previous one. It's passed on when parsing the next
+// generation.
+type spilledBatch struct {
+ gen uint64
+ *batch
+}
+
+// readGeneration buffers and decodes the structural elements of a trace generation
+// out of r. spill is the first batch of the new generation (already buffered and
+// parsed from reading the last generation). Returns the generation and the first
+// batch read of the next generation, if any.
+func readGeneration(r *bufio.Reader, spill *spilledBatch) (*generation, *spilledBatch, error) {
+ g := &generation{
+ evTable: new(evTable),
+ batches: make(map[ThreadID][]batch),
+ }
+ // Process the spilled batch.
+ if spill != nil {
+ g.gen = spill.gen
+ if err := processBatch(g, *spill.batch); err != nil {
+ return nil, nil, err
+ }
+ spill = nil
+ }
+ // Read batches one at a time until we either hit EOF or
+ // the next generation.
+ for {
+ b, gen, err := readBatch(r)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ if gen == 0 {
+ // 0 is a sentinel used by the runtime, so we'll never see it.
+ return nil, nil, fmt.Errorf("invalid generation number %d", gen)
+ }
+ if g.gen == 0 {
+ // Initialize gen.
+ g.gen = gen
+ }
+ if gen == g.gen+1 { // TODO: advance this the same way the runtime does.
+ spill = &spilledBatch{gen: gen, batch: &b}
+ break
+ }
+ if gen != g.gen {
+ // N.B. Fail as fast as possible if we see this. At first it
+ // may seem prudent to be fault-tolerant and assume we have a
+ // complete generation, parsing and returning that first. However,
+ // if the batches are mixed across generations then it's likely
+ // we won't be able to parse this generation correctly at all.
+ // Rather than return a cryptic error in that case, indicate the
+ // problem as soon as we see it.
+ return nil, nil, fmt.Errorf("generations out of order")
+ }
+ if err := processBatch(g, b); err != nil {
+ return nil, nil, err
+ }
+ }
+
+ // Check some invariants.
+ if g.freq == 0 {
+ return nil, nil, fmt.Errorf("no frequency event found")
+ }
+ // N.B. Trust that the batch order is correct. We can't validate the batch order
+ // by timestamp because the timestamps could just be plain wrong. The source of
+ // truth is the order things appear in the trace and the partial order sequence
+ // numbers on certain events. If it turns out the batch order is actually incorrect
+ // we'll very likely fail to advance a partial order from the frontier.
+
+ // Compactify stacks and strings for better lookup performance later.
+ g.stacks.compactify()
+ g.strings.compactify()
+
+ // Validate stacks.
+ if err := validateStackStrings(&g.stacks, &g.strings); err != nil {
+ return nil, nil, err
+ }
+
+ // Fix up the CPU sample timestamps, now that we have freq.
+ for i := range g.cpuSamples {
+ s := &g.cpuSamples[i]
+ s.time = g.freq.mul(timestamp(s.time))
+ }
+ // Sort the CPU samples.
+ slices.SortFunc(g.cpuSamples, func(a, b cpuSample) int {
+ return cmp.Compare(a.time, b.time)
+ })
+ return g, spill, nil
+}
+
+// processBatch adds the batch to the generation.
+func processBatch(g *generation, b batch) error {
+ switch {
+ case b.isStringsBatch():
+ if err := addStrings(&g.strings, b); err != nil {
+ return err
+ }
+ case b.isStacksBatch():
+ if err := addStacks(&g.stacks, b); err != nil {
+ return err
+ }
+ case b.isCPUSamplesBatch():
+ samples, err := addCPUSamples(g.cpuSamples, b)
+ if err != nil {
+ return err
+ }
+ g.cpuSamples = samples
+ case b.isFreqBatch():
+ freq, err := parseFreq(b)
+ if err != nil {
+ return err
+ }
+ if g.freq != 0 {
+ return fmt.Errorf("found multiple frequency events")
+ }
+ g.freq = freq
+ default:
+ g.batches[b.m] = append(g.batches[b.m], b)
+ }
+ return nil
+}
+
+// validateStackStrings makes sure all the string references in
+// the stack table are present in the string table.
+func validateStackStrings(stacks *dataTable[stackID, stack], strings *dataTable[stringID, string]) error {
+ var err error
+ stacks.forEach(func(id stackID, stk stack) bool {
+ for _, frame := range stk.frames {
+ _, ok := strings.get(frame.funcID)
+ if !ok {
+ err = fmt.Errorf("found invalid func string ID %d for stack %d", frame.funcID, id)
+ return false
+ }
+ _, ok = strings.get(frame.fileID)
+ if !ok {
+ err = fmt.Errorf("found invalid file string ID %d for stack %d", frame.fileID, id)
+ return false
+ }
+ }
+ return true
+ })
+ return err
+}
+
+// addStrings takes a batch whose first byte is an EvStrings event
+// (indicating that the batch contains only strings) and adds each
+// string contained therein to the provided strings map.
+func addStrings(stringTable *dataTable[stringID, string], b batch) error {
+ if !b.isStringsBatch() {
+ return fmt.Errorf("internal error: addStrings called on non-string batch")
+ }
+ r := bytes.NewReader(b.data)
+ hdr, err := r.ReadByte() // Consume the EvStrings byte.
+ if err != nil || event.Type(hdr) != go122.EvStrings {
+ return fmt.Errorf("missing strings batch header")
+ }
+
+ var sb strings.Builder
+ for r.Len() != 0 {
+ // Read the header.
+ ev, err := r.ReadByte()
+ if err != nil {
+ return err
+ }
+ if event.Type(ev) != go122.EvString {
+ return fmt.Errorf("expected string event, got %d", ev)
+ }
+
+ // Read the string's ID.
+ id, err := binary.ReadUvarint(r)
+ if err != nil {
+ return err
+ }
+
+ // Read the string's length.
+ len, err := binary.ReadUvarint(r)
+ if err != nil {
+ return err
+ }
+ if len > go122.MaxStringSize {
+ return fmt.Errorf("invalid string size %d, maximum is %d", len, go122.MaxStringSize)
+ }
+
+ // Copy out the string.
+ n, err := io.CopyN(&sb, r, int64(len))
+ if n != int64(len) {
+ return fmt.Errorf("failed to read full string: read %d but wanted %d", n, len)
+ }
+ if err != nil {
+ return fmt.Errorf("copying string data: %w", err)
+ }
+
+ // Add the string to the map.
+ s := sb.String()
+ sb.Reset()
+ if err := stringTable.insert(stringID(id), s); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// addStacks takes a batch whose first byte is an EvStacks event
+// (indicating that the batch contains only stacks) and adds each
+// string contained therein to the provided stacks map.
+func addStacks(stackTable *dataTable[stackID, stack], b batch) error {
+ if !b.isStacksBatch() {
+ return fmt.Errorf("internal error: addStacks called on non-stacks batch")
+ }
+ r := bytes.NewReader(b.data)
+ hdr, err := r.ReadByte() // Consume the EvStacks byte.
+ if err != nil || event.Type(hdr) != go122.EvStacks {
+ return fmt.Errorf("missing stacks batch header")
+ }
+
+ for r.Len() != 0 {
+ // Read the header.
+ ev, err := r.ReadByte()
+ if err != nil {
+ return err
+ }
+ if event.Type(ev) != go122.EvStack {
+ return fmt.Errorf("expected stack event, got %d", ev)
+ }
+
+ // Read the stack's ID.
+ id, err := binary.ReadUvarint(r)
+ if err != nil {
+ return err
+ }
+
+ // Read how many frames are in each stack.
+ nFrames, err := binary.ReadUvarint(r)
+ if err != nil {
+ return err
+ }
+ if nFrames > go122.MaxFramesPerStack {
+ return fmt.Errorf("invalid stack size %d, maximum is %d", nFrames, go122.MaxFramesPerStack)
+ }
+
+ // Each frame consists of 4 fields: pc, funcID (string), fileID (string), line.
+ frames := make([]frame, 0, nFrames)
+ for i := uint64(0); i < nFrames; i++ {
+ // Read the frame data.
+ pc, err := binary.ReadUvarint(r)
+ if err != nil {
+ return fmt.Errorf("reading frame %d's PC for stack %d: %w", i+1, id, err)
+ }
+ funcID, err := binary.ReadUvarint(r)
+ if err != nil {
+ return fmt.Errorf("reading frame %d's funcID for stack %d: %w", i+1, id, err)
+ }
+ fileID, err := binary.ReadUvarint(r)
+ if err != nil {
+ return fmt.Errorf("reading frame %d's fileID for stack %d: %w", i+1, id, err)
+ }
+ line, err := binary.ReadUvarint(r)
+ if err != nil {
+ return fmt.Errorf("reading frame %d's line for stack %d: %w", i+1, id, err)
+ }
+ frames = append(frames, frame{
+ pc: pc,
+ funcID: stringID(funcID),
+ fileID: stringID(fileID),
+ line: line,
+ })
+ }
+
+ // Add the stack to the map.
+ if err := stackTable.insert(stackID(id), stack{frames: frames}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// addCPUSamples takes a batch whose first byte is an EvCPUSamples event
+// (indicating that the batch contains only CPU samples) and adds each
+// sample contained therein to the provided samples list.
+func addCPUSamples(samples []cpuSample, b batch) ([]cpuSample, error) {
+ if !b.isCPUSamplesBatch() {
+ return nil, fmt.Errorf("internal error: addStrings called on non-string batch")
+ }
+ r := bytes.NewReader(b.data)
+ hdr, err := r.ReadByte() // Consume the EvCPUSamples byte.
+ if err != nil || event.Type(hdr) != go122.EvCPUSamples {
+ return nil, fmt.Errorf("missing CPU samples batch header")
+ }
+
+ for r.Len() != 0 {
+ // Read the header.
+ ev, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ if event.Type(ev) != go122.EvCPUSample {
+ return nil, fmt.Errorf("expected CPU sample event, got %d", ev)
+ }
+
+ // Read the sample's timestamp.
+ ts, err := binary.ReadUvarint(r)
+ if err != nil {
+ return nil, err
+ }
+
+ // Read the sample's M.
+ m, err := binary.ReadUvarint(r)
+ if err != nil {
+ return nil, err
+ }
+ mid := ThreadID(m)
+
+ // Read the sample's P.
+ p, err := binary.ReadUvarint(r)
+ if err != nil {
+ return nil, err
+ }
+ pid := ProcID(p)
+
+ // Read the sample's G.
+ g, err := binary.ReadUvarint(r)
+ if err != nil {
+ return nil, err
+ }
+ goid := GoID(g)
+ if g == 0 {
+ goid = NoGoroutine
+ }
+
+ // Read the sample's stack.
+ s, err := binary.ReadUvarint(r)
+ if err != nil {
+ return nil, err
+ }
+
+ // Add the sample to the slice.
+ samples = append(samples, cpuSample{
+ schedCtx: schedCtx{
+ M: mid,
+ P: pid,
+ G: goid,
+ },
+ time: Time(ts), // N.B. this is really a "timestamp," not a Time.
+ stack: stackID(s),
+ })
+ }
+ return samples, nil
+}
+
+// parseFreq parses out a lone EvFrequency from a batch.
+func parseFreq(b batch) (frequency, error) {
+ if !b.isFreqBatch() {
+ return 0, fmt.Errorf("internal error: parseFreq called on non-frequency batch")
+ }
+ r := bytes.NewReader(b.data)
+ r.ReadByte() // Consume the EvFrequency byte.
+
+ // Read the frequency. It'll come out as timestamp units per second.
+ f, err := binary.ReadUvarint(r)
+ if err != nil {
+ return 0, err
+ }
+ // Convert to nanoseconds per timestamp unit.
+ return frequency(1.0 / (float64(f) / 1e9)), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/internal/testgen/go122/trace.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/internal/testgen/go122/trace.go
new file mode 100644
index 0000000000000000000000000000000000000000..42bb40348206f11625649ed8cdb45c31433d2e27
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/internal/testgen/go122/trace.go
@@ -0,0 +1,401 @@
+// 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 testkit
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "os"
+ "regexp"
+ "strings"
+
+ "internal/trace/v2"
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+ "internal/trace/v2/raw"
+ "internal/trace/v2/version"
+ "internal/txtar"
+)
+
+func Main(f func(*Trace)) {
+ // Create an output file.
+ out, err := os.Create(os.Args[1])
+ if err != nil {
+ panic(err.Error())
+ }
+ defer out.Close()
+
+ // Create a new trace.
+ trace := NewTrace()
+
+ // Call the generator.
+ f(trace)
+
+ // Write out the generator's state.
+ if _, err := out.Write(trace.Generate()); err != nil {
+ panic(err.Error())
+ }
+}
+
+// Trace represents an execution trace for testing.
+//
+// It does a little bit of work to ensure that the produced trace is valid,
+// just for convenience. It mainly tracks batches and batch sizes (so they're
+// trivially correct), tracks strings and stacks, and makes sure emitted string
+// and stack batches are valid. That last part can be controlled by a few options.
+//
+// Otherwise, it performs no validation on the trace at all.
+type Trace struct {
+ // Trace data state.
+ ver version.Version
+ names map[string]event.Type
+ specs []event.Spec
+ events []raw.Event
+ gens []*Generation
+ validTimestamps bool
+
+ // Expectation state.
+ bad bool
+ badMatch *regexp.Regexp
+}
+
+// NewTrace creates a new trace.
+func NewTrace() *Trace {
+ ver := version.Go122
+ return &Trace{
+ names: event.Names(ver.Specs()),
+ specs: ver.Specs(),
+ validTimestamps: true,
+ }
+}
+
+// ExpectFailure writes down that the trace should be broken. The caller
+// must provide a pattern matching the expected error produced by the parser.
+func (t *Trace) ExpectFailure(pattern string) {
+ t.bad = true
+ t.badMatch = regexp.MustCompile(pattern)
+}
+
+// ExpectSuccess writes down that the trace should successfully parse.
+func (t *Trace) ExpectSuccess() {
+ t.bad = false
+}
+
+// RawEvent emits an event into the trace. name must correspond to one
+// of the names in Specs() result for the version that was passed to
+// this trace.
+func (t *Trace) RawEvent(typ event.Type, data []byte, args ...uint64) {
+ t.events = append(t.events, t.createEvent(typ, data, args...))
+}
+
+// DisableTimestamps makes the timestamps for all events generated after
+// this call zero. Raw events are exempted from this because the caller
+// has to pass their own timestamp into those events anyway.
+func (t *Trace) DisableTimestamps() {
+ t.validTimestamps = false
+}
+
+// Generation creates a new trace generation.
+//
+// This provides more structure than Event to allow for more easily
+// creating complex traces that are mostly or completely correct.
+func (t *Trace) Generation(gen uint64) *Generation {
+ g := &Generation{
+ trace: t,
+ gen: gen,
+ strings: make(map[string]uint64),
+ stacks: make(map[stack]uint64),
+ }
+ t.gens = append(t.gens, g)
+ return g
+}
+
+// Generate creates a test file for the trace.
+func (t *Trace) Generate() []byte {
+ // Trace file contents.
+ var buf bytes.Buffer
+ tw, err := raw.NewTextWriter(&buf, version.Go122)
+ if err != nil {
+ panic(err.Error())
+ }
+
+ // Write raw top-level events.
+ for _, e := range t.events {
+ tw.WriteEvent(e)
+ }
+
+ // Write generations.
+ for _, g := range t.gens {
+ g.writeEventsTo(tw)
+ }
+
+ // Expectation file contents.
+ expect := []byte("SUCCESS\n")
+ if t.bad {
+ expect = []byte(fmt.Sprintf("FAILURE %q\n", t.badMatch))
+ }
+
+ // Create the test file's contents.
+ return txtar.Format(&txtar.Archive{
+ Files: []txtar.File{
+ {Name: "expect", Data: expect},
+ {Name: "trace", Data: buf.Bytes()},
+ },
+ })
+}
+
+func (t *Trace) createEvent(ev event.Type, data []byte, args ...uint64) raw.Event {
+ spec := t.specs[ev]
+ if ev != go122.EvStack {
+ if arity := len(spec.Args); len(args) != arity {
+ panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args)))
+ }
+ }
+ return raw.Event{
+ Version: version.Go122,
+ Ev: ev,
+ Args: args,
+ Data: data,
+ }
+}
+
+type stack struct {
+ stk [32]trace.StackFrame
+ len int
+}
+
+var (
+ NoString = ""
+ NoStack = []trace.StackFrame{}
+)
+
+// Generation represents a single generation in the trace.
+type Generation struct {
+ trace *Trace
+ gen uint64
+ batches []*Batch
+ strings map[string]uint64
+ stacks map[stack]uint64
+
+ // Options applied when Trace.Generate is called.
+ ignoreStringBatchSizeLimit bool
+ ignoreStackBatchSizeLimit bool
+}
+
+// Batch starts a new event batch in the trace data.
+//
+// This is convenience function for generating correct batches.
+func (g *Generation) Batch(thread trace.ThreadID, time Time) *Batch {
+ if !g.trace.validTimestamps {
+ time = 0
+ }
+ b := &Batch{
+ gen: g,
+ thread: thread,
+ timestamp: time,
+ }
+ g.batches = append(g.batches, b)
+ return b
+}
+
+// String registers a string with the trace.
+//
+// This is a convenience function for easily adding correct
+// strings to traces.
+func (g *Generation) String(s string) uint64 {
+ if len(s) == 0 {
+ return 0
+ }
+ if id, ok := g.strings[s]; ok {
+ return id
+ }
+ id := uint64(len(g.strings) + 1)
+ g.strings[s] = id
+ return id
+}
+
+// Stack registers a stack with the trace.
+//
+// This is a convenience function for easily adding correct
+// stacks to traces.
+func (g *Generation) Stack(stk []trace.StackFrame) uint64 {
+ if len(stk) == 0 {
+ return 0
+ }
+ if len(stk) > 32 {
+ panic("stack too big for test")
+ }
+ var stkc stack
+ copy(stkc.stk[:], stk)
+ stkc.len = len(stk)
+ if id, ok := g.stacks[stkc]; ok {
+ return id
+ }
+ id := uint64(len(g.stacks) + 1)
+ g.stacks[stkc] = id
+ return id
+}
+
+// writeEventsTo emits event batches in the generation to tw.
+func (g *Generation) writeEventsTo(tw *raw.TextWriter) {
+ // Write event batches for the generation.
+ for _, b := range g.batches {
+ b.writeEventsTo(tw)
+ }
+
+ // Write frequency.
+ b := g.newStructuralBatch()
+ b.RawEvent(go122.EvFrequency, nil, 15625000)
+ b.writeEventsTo(tw)
+
+ // Write stacks.
+ b = g.newStructuralBatch()
+ b.RawEvent(go122.EvStacks, nil)
+ for stk, id := range g.stacks {
+ stk := stk.stk[:stk.len]
+ args := []uint64{id}
+ for _, f := range stk {
+ args = append(args, f.PC, g.String(f.Func), g.String(f.File), f.Line)
+ }
+ b.RawEvent(go122.EvStack, nil, args...)
+
+ // Flush the batch if necessary.
+ if !g.ignoreStackBatchSizeLimit && b.size > go122.MaxBatchSize/2 {
+ b.writeEventsTo(tw)
+ b = g.newStructuralBatch()
+ }
+ }
+ b.writeEventsTo(tw)
+
+ // Write strings.
+ b = g.newStructuralBatch()
+ b.RawEvent(go122.EvStrings, nil)
+ for s, id := range g.strings {
+ b.RawEvent(go122.EvString, []byte(s), id)
+
+ // Flush the batch if necessary.
+ if !g.ignoreStringBatchSizeLimit && b.size > go122.MaxBatchSize/2 {
+ b.writeEventsTo(tw)
+ b = g.newStructuralBatch()
+ }
+ }
+ b.writeEventsTo(tw)
+}
+
+func (g *Generation) newStructuralBatch() *Batch {
+ return &Batch{gen: g, thread: trace.NoThread}
+}
+
+// Batch represents an event batch.
+type Batch struct {
+ gen *Generation
+ thread trace.ThreadID
+ timestamp Time
+ size uint64
+ events []raw.Event
+}
+
+// Event emits an event into a batch. name must correspond to one
+// of the names in Specs() result for the version that was passed to
+// this trace. Callers must omit the timestamp delta.
+func (b *Batch) Event(name string, args ...any) {
+ ev, ok := b.gen.trace.names[name]
+ if !ok {
+ panic(fmt.Sprintf("invalid or unknown event %s", name))
+ }
+ var uintArgs []uint64
+ argOff := 0
+ if b.gen.trace.specs[ev].IsTimedEvent {
+ if b.gen.trace.validTimestamps {
+ uintArgs = []uint64{1}
+ } else {
+ uintArgs = []uint64{0}
+ }
+ argOff = 1
+ }
+ spec := b.gen.trace.specs[ev]
+ if arity := len(spec.Args) - argOff; len(args) != arity {
+ panic(fmt.Sprintf("expected %d args for %s, got %d", arity, spec.Name, len(args)))
+ }
+ for i, arg := range args {
+ uintArgs = append(uintArgs, b.uintArgFor(arg, spec.Args[i+argOff]))
+ }
+ b.RawEvent(ev, nil, uintArgs...)
+}
+
+func (b *Batch) uintArgFor(arg any, argSpec string) uint64 {
+ components := strings.SplitN(argSpec, "_", 2)
+ typStr := components[0]
+ if len(components) == 2 {
+ typStr = components[1]
+ }
+ var u uint64
+ switch typStr {
+ case "value":
+ u = arg.(uint64)
+ case "stack":
+ u = b.gen.Stack(arg.([]trace.StackFrame))
+ case "seq":
+ u = uint64(arg.(Seq))
+ case "pstatus":
+ u = uint64(arg.(go122.ProcStatus))
+ case "gstatus":
+ u = uint64(arg.(go122.GoStatus))
+ case "g":
+ u = uint64(arg.(trace.GoID))
+ case "m":
+ u = uint64(arg.(trace.ThreadID))
+ case "p":
+ u = uint64(arg.(trace.ProcID))
+ case "string":
+ u = b.gen.String(arg.(string))
+ case "task":
+ u = uint64(arg.(trace.TaskID))
+ default:
+ panic(fmt.Sprintf("unsupported arg type %q for spec %q", typStr, argSpec))
+ }
+ return u
+}
+
+// RawEvent emits an event into a batch. name must correspond to one
+// of the names in Specs() result for the version that was passed to
+// this trace.
+func (b *Batch) RawEvent(typ event.Type, data []byte, args ...uint64) {
+ ev := b.gen.trace.createEvent(typ, data, args...)
+
+ // Compute the size of the event and add it to the batch.
+ b.size += 1 // One byte for the event header.
+ var buf [binary.MaxVarintLen64]byte
+ for _, arg := range args {
+ b.size += uint64(binary.PutUvarint(buf[:], arg))
+ }
+ if len(data) != 0 {
+ b.size += uint64(binary.PutUvarint(buf[:], uint64(len(data))))
+ b.size += uint64(len(data))
+ }
+
+ // Add the event.
+ b.events = append(b.events, ev)
+}
+
+// writeEventsTo emits events in the batch, including the batch header, to tw.
+func (b *Batch) writeEventsTo(tw *raw.TextWriter) {
+ tw.WriteEvent(raw.Event{
+ Version: version.Go122,
+ Ev: go122.EvEventBatch,
+ Args: []uint64{b.gen.gen, uint64(b.thread), uint64(b.timestamp), b.size},
+ })
+ for _, e := range b.events {
+ tw.WriteEvent(e)
+ }
+}
+
+// Seq represents a sequence counter.
+type Seq uint64
+
+// Time represents a low-level trace timestamp (which does not necessarily
+// correspond to nanoseconds, like trace.Time does).
+type Time uint64
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/mkexp.bash b/platform/dbops/binaries/go/go/src/internal/trace/v2/mkexp.bash
new file mode 100644
index 0000000000000000000000000000000000000000..8a737198c85d2483a7e0ffd7945dfaf4033637dc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/mkexp.bash
@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+# 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.
+
+# This script copies this directory to golang.org/x/exp/trace.
+# Just point it at an golang.org/x/exp checkout.
+
+set -e
+if [ ! -f mkexp.bash ]; then
+ echo 'mkexp.bash must be run from $GOROOT/src/internal/trace/v2' 1>&2
+ exit 1
+fi
+
+if [ "$#" -ne 1 ]; then
+ echo 'mkexp.bash expects one argument: a path to a golang.org/x/exp git checkout'
+ exit 1
+fi
+
+# Copy.
+mkdir -p $1/trace
+cp -r ./* $1/trace
+
+# Cleanup.
+
+# Delete mkexp.bash.
+rm $1/trace/mkexp.bash
+
+# Move tools to cmd. Can't be cmd here because dist will try to build them.
+mv $1/trace/tools $1/trace/cmd
+
+# Make some packages internal.
+mv $1/trace/raw $1/trace/internal/raw
+mv $1/trace/event $1/trace/internal/event
+mv $1/trace/version $1/trace/internal/version
+mv $1/trace/testtrace $1/trace/internal/testtrace
+
+# Move the debug commands out of testdata.
+mv $1/trace/testdata/cmd $1/trace/cmd
+
+# Fix up import paths.
+find $1/trace -name '*.go' | xargs -- sed -i 's/internal\/trace\/v2/golang.org\/x\/exp\/trace/'
+find $1/trace -name '*.go' | xargs -- sed -i 's/golang.org\/x\/exp\/trace\/raw/golang.org\/x\/exp\/trace\/internal\/raw/'
+find $1/trace -name '*.go' | xargs -- sed -i 's/golang.org\/x\/exp\/trace\/event/golang.org\/x\/exp\/trace\/internal\/event/'
+find $1/trace -name '*.go' | xargs -- sed -i 's/golang.org\/x\/exp\/trace\/event\/go122/golang.org\/x\/exp\/trace\/internal\/event\/go122/'
+find $1/trace -name '*.go' | xargs -- sed -i 's/golang.org\/x\/exp\/trace\/version/golang.org\/x\/exp\/trace\/internal\/version/'
+find $1/trace -name '*.go' | xargs -- sed -i 's/golang.org\/x\/exp\/trace\/testtrace/golang.org\/x\/exp\/trace\/internal\/testtrace/'
+
+# Format the files.
+find $1/trace -name '*.go' | xargs -- gofmt -w -s
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/order.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/order.go
new file mode 100644
index 0000000000000000000000000000000000000000..cedb29726ec339b2f13e379dc627e166b19b03a8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/order.go
@@ -0,0 +1,1094 @@
+// 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 (
+ "fmt"
+ "strings"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+ "internal/trace/v2/version"
+)
+
+// ordering emulates Go scheduler state for both validation and
+// for putting events in the right order.
+type ordering struct {
+ gStates map[GoID]*gState
+ pStates map[ProcID]*pState // TODO: The keys are dense, so this can be a slice.
+ mStates map[ThreadID]*mState
+ activeTasks map[TaskID]taskState
+ gcSeq uint64
+ gcState gcState
+ initialGen uint64
+
+ // Some events like GoDestroySyscall produce two events instead of one.
+ // extraEvent is this extra space. advance must not be called unless
+ // the extraEvent has been consumed with consumeExtraEvent.
+ //
+ // TODO(mknyszek): Replace this with a more formal queue.
+ extraEvent Event
+}
+
+// consumeExtraEvent consumes the extra event.
+func (o *ordering) consumeExtraEvent() Event {
+ if o.extraEvent.Kind() == EventBad {
+ return Event{}
+ }
+ r := o.extraEvent
+ o.extraEvent = Event{}
+ return r
+}
+
+// advance checks if it's valid to proceed with ev which came from thread m.
+//
+// Returns the schedCtx at the point of the event, whether it's OK to advance
+// with this event, and any error encountered in validation.
+//
+// It assumes the gen value passed to it is monotonically increasing across calls.
+//
+// If any error is returned, then the trace is broken and trace parsing must cease.
+// If it's not valid to advance with ev, but no error was encountered, the caller
+// should attempt to advance with other candidate events from other threads. If the
+// caller runs out of candidates, the trace is invalid.
+func (o *ordering) advance(ev *baseEvent, evt *evTable, m ThreadID, gen uint64) (schedCtx, bool, error) {
+ if o.initialGen == 0 {
+ // Set the initial gen if necessary.
+ o.initialGen = gen
+ }
+
+ var curCtx, newCtx schedCtx
+ curCtx.M = m
+ newCtx.M = m
+
+ if m == NoThread {
+ curCtx.P = NoProc
+ curCtx.G = NoGoroutine
+ newCtx = curCtx
+ } else {
+ // Pull out or create the mState for this event.
+ ms, ok := o.mStates[m]
+ if !ok {
+ ms = &mState{
+ g: NoGoroutine,
+ p: NoProc,
+ }
+ o.mStates[m] = ms
+ }
+ curCtx.P = ms.p
+ curCtx.G = ms.g
+ newCtx = curCtx
+ defer func() {
+ // Update the mState for this event.
+ ms.p = newCtx.P
+ ms.g = newCtx.G
+ }()
+ }
+
+ switch typ := ev.typ; typ {
+ // Handle procs.
+ case go122.EvProcStatus:
+ pid := ProcID(ev.args[0])
+ status := go122.ProcStatus(ev.args[1])
+ if int(status) >= len(go122ProcStatus2ProcState) {
+ return curCtx, false, fmt.Errorf("invalid status for proc %d: %d", pid, status)
+ }
+ oldState := go122ProcStatus2ProcState[status]
+ if s, ok := o.pStates[pid]; ok {
+ if status == go122.ProcSyscallAbandoned && s.status == go122.ProcSyscall {
+ // ProcSyscallAbandoned is a special case of ProcSyscall. It indicates a
+ // potential loss of information, but if we're already in ProcSyscall,
+ // we haven't lost the relevant information. Promote the status and advance.
+ oldState = ProcRunning
+ ev.args[1] = uint64(go122.ProcSyscall)
+ } else if status == go122.ProcSyscallAbandoned && s.status == go122.ProcSyscallAbandoned {
+ // If we're passing through ProcSyscallAbandoned, then there's no promotion
+ // to do. We've lost the M that this P is associated with. However it got there,
+ // it's going to appear as idle in the API, so pass through as idle.
+ oldState = ProcIdle
+ ev.args[1] = uint64(go122.ProcSyscallAbandoned)
+ } else if s.status != status {
+ return curCtx, false, fmt.Errorf("inconsistent status for proc %d: old %v vs. new %v", pid, s.status, status)
+ }
+ s.seq = makeSeq(gen, 0) // Reset seq.
+ } else {
+ o.pStates[pid] = &pState{id: pid, status: status, seq: makeSeq(gen, 0)}
+ if gen == o.initialGen {
+ oldState = ProcUndetermined
+ } else {
+ oldState = ProcNotExist
+ }
+ }
+ ev.extra(version.Go122)[0] = uint64(oldState) // Smuggle in the old state for StateTransition.
+
+ // Bind the proc to the new context, if it's running.
+ if status == go122.ProcRunning || status == go122.ProcSyscall {
+ newCtx.P = pid
+ }
+ // If we're advancing through ProcSyscallAbandoned *but* oldState is running then we've
+ // promoted it to ProcSyscall. However, because it's ProcSyscallAbandoned, we know this
+ // P is about to get stolen and its status very likely isn't being emitted by the same
+ // thread it was bound to. Since this status is Running -> Running and Running is binding,
+ // we need to make sure we emit it in the right context: the context to which it is bound.
+ // Find it, and set our current context to it.
+ if status == go122.ProcSyscallAbandoned && oldState == ProcRunning {
+ // N.B. This is slow but it should be fairly rare.
+ found := false
+ for mid, ms := range o.mStates {
+ if ms.p == pid {
+ curCtx.M = mid
+ curCtx.P = pid
+ curCtx.G = ms.g
+ found = true
+ }
+ }
+ if !found {
+ return curCtx, false, fmt.Errorf("failed to find sched context for proc %d that's about to be stolen", pid)
+ }
+ }
+ return curCtx, true, nil
+ case go122.EvProcStart:
+ pid := ProcID(ev.args[0])
+ seq := makeSeq(gen, ev.args[1])
+
+ // Try to advance. We might fail here due to sequencing, because the P hasn't
+ // had a status emitted, or because we already have a P and we're in a syscall,
+ // and we haven't observed that it was stolen from us yet.
+ state, ok := o.pStates[pid]
+ if !ok || state.status != go122.ProcIdle || !seq.succeeds(state.seq) || curCtx.P != NoProc {
+ // We can't make an inference as to whether this is bad. We could just be seeing
+ // a ProcStart on a different M before the proc's state was emitted, or before we
+ // got to the right point in the trace.
+ //
+ // Note that we also don't advance here if we have a P and we're in a syscall.
+ return curCtx, false, nil
+ }
+ // We can advance this P. Check some invariants.
+ //
+ // We might have a goroutine if a goroutine is exiting a syscall.
+ reqs := event.SchedReqs{Thread: event.MustHave, Proc: event.MustNotHave, Goroutine: event.MayHave}
+ if err := validateCtx(curCtx, reqs); err != nil {
+ return curCtx, false, err
+ }
+ state.status = go122.ProcRunning
+ state.seq = seq
+ newCtx.P = pid
+ return curCtx, true, nil
+ case go122.EvProcStop:
+ // We must be able to advance this P.
+ //
+ // There are 2 ways a P can stop: ProcStop and ProcSteal. ProcStop is used when the P
+ // is stopped by the same M that started it, while ProcSteal is used when another M
+ // steals the P by stopping it from a distance.
+ //
+ // Since a P is bound to an M, and we're stopping on the same M we started, it must
+ // always be possible to advance the current M's P from a ProcStop. This is also why
+ // ProcStop doesn't need a sequence number.
+ state, ok := o.pStates[curCtx.P]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for proc (%v) that doesn't exist", go122.EventString(typ), curCtx.P)
+ }
+ if state.status != go122.ProcRunning && state.status != go122.ProcSyscall {
+ return curCtx, false, fmt.Errorf("%s event for proc that's not %s or %s", go122.EventString(typ), go122.ProcRunning, go122.ProcSyscall)
+ }
+ reqs := event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MayHave}
+ if err := validateCtx(curCtx, reqs); err != nil {
+ return curCtx, false, err
+ }
+ state.status = go122.ProcIdle
+ newCtx.P = NoProc
+ return curCtx, true, nil
+ case go122.EvProcSteal:
+ pid := ProcID(ev.args[0])
+ seq := makeSeq(gen, ev.args[1])
+ state, ok := o.pStates[pid]
+ if !ok || (state.status != go122.ProcSyscall && state.status != go122.ProcSyscallAbandoned) || !seq.succeeds(state.seq) {
+ // We can't make an inference as to whether this is bad. We could just be seeing
+ // a ProcStart on a different M before the proc's state was emitted, or before we
+ // got to the right point in the trace.
+ return curCtx, false, nil
+ }
+ // We can advance this P. Check some invariants.
+ reqs := event.SchedReqs{Thread: event.MustHave, Proc: event.MayHave, Goroutine: event.MayHave}
+ if err := validateCtx(curCtx, reqs); err != nil {
+ return curCtx, false, err
+ }
+ // Smuggle in the P state that let us advance so we can surface information to the event.
+ // Specifically, we need to make sure that the event is interpreted not as a transition of
+ // ProcRunning -> ProcIdle but ProcIdle -> ProcIdle instead.
+ //
+ // ProcRunning is binding, but we may be running with a P on the current M and we can't
+ // bind another P. This P is about to go ProcIdle anyway.
+ oldStatus := state.status
+ ev.extra(version.Go122)[0] = uint64(oldStatus)
+
+ // Update the P's status and sequence number.
+ state.status = go122.ProcIdle
+ state.seq = seq
+
+ // If we've lost information then don't try to do anything with the M.
+ // It may have moved on and we can't be sure.
+ if oldStatus == go122.ProcSyscallAbandoned {
+ return curCtx, true, nil
+ }
+
+ // Validate that the M we're stealing from is what we expect.
+ mid := ThreadID(ev.args[2]) // The M we're stealing from.
+
+ if mid == curCtx.M {
+ // We're stealing from ourselves. This behaves like a ProcStop.
+ if curCtx.P != pid {
+ return curCtx, false, fmt.Errorf("tried to self-steal proc %d (thread %d), but got proc %d instead", pid, mid, curCtx.P)
+ }
+ newCtx.P = NoProc
+ return curCtx, true, nil
+ }
+
+ // We're stealing from some other M.
+ mState, ok := o.mStates[mid]
+ if !ok {
+ return curCtx, false, fmt.Errorf("stole proc from non-existent thread %d", mid)
+ }
+
+ // Make sure we're actually stealing the right P.
+ if mState.p != pid {
+ return curCtx, false, fmt.Errorf("tried to steal proc %d from thread %d, but got proc %d instead", pid, mid, mState.p)
+ }
+
+ // Tell the M it has no P so it can proceed.
+ //
+ // This is safe because we know the P was in a syscall and
+ // the other M must be trying to get out of the syscall.
+ // GoSyscallEndBlocked cannot advance until the corresponding
+ // M loses its P.
+ mState.p = NoProc
+ return curCtx, true, nil
+
+ // Handle goroutines.
+ case go122.EvGoStatus:
+ gid := GoID(ev.args[0])
+ mid := ThreadID(ev.args[1])
+ status := go122.GoStatus(ev.args[2])
+
+ if int(status) >= len(go122GoStatus2GoState) {
+ return curCtx, false, fmt.Errorf("invalid status for goroutine %d: %d", gid, status)
+ }
+ oldState := go122GoStatus2GoState[status]
+ if s, ok := o.gStates[gid]; ok {
+ if s.status != status {
+ return curCtx, false, fmt.Errorf("inconsistent status for goroutine %d: old %v vs. new %v", gid, s.status, status)
+ }
+ s.seq = makeSeq(gen, 0) // Reset seq.
+ } else if gen == o.initialGen {
+ // Set the state.
+ o.gStates[gid] = &gState{id: gid, status: status, seq: makeSeq(gen, 0)}
+ oldState = GoUndetermined
+ } else {
+ return curCtx, false, fmt.Errorf("found goroutine status for new goroutine after the first generation: id=%v status=%v", gid, status)
+ }
+ ev.extra(version.Go122)[0] = uint64(oldState) // Smuggle in the old state for StateTransition.
+
+ switch status {
+ case go122.GoRunning:
+ // Bind the goroutine to the new context, since it's running.
+ newCtx.G = gid
+ case go122.GoSyscall:
+ if mid == NoThread {
+ return curCtx, false, fmt.Errorf("found goroutine %d in syscall without a thread", gid)
+ }
+ // Is the syscall on this thread? If so, bind it to the context.
+ // Otherwise, we're talking about a G sitting in a syscall on an M.
+ // Validate the named M.
+ if mid == curCtx.M {
+ if gen != o.initialGen && curCtx.G != gid {
+ // If this isn't the first generation, we *must* have seen this
+ // binding occur already. Even if the G was blocked in a syscall
+ // for multiple generations since trace start, we would have seen
+ // a previous GoStatus event that bound the goroutine to an M.
+ return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, curCtx.G)
+ }
+ newCtx.G = gid
+ break
+ }
+ // Now we're talking about a thread and goroutine that have been
+ // blocked on a syscall for the entire generation. This case must
+ // not have a P; the runtime makes sure that all Ps are traced at
+ // the beginning of a generation, which involves taking a P back
+ // from every thread.
+ ms, ok := o.mStates[mid]
+ if ok {
+ // This M has been seen. That means we must have seen this
+ // goroutine go into a syscall on this thread at some point.
+ if ms.g != gid {
+ // But the G on the M doesn't match. Something's wrong.
+ return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, ms.g)
+ }
+ // This case is just a Syscall->Syscall event, which needs to
+ // appear as having the G currently bound to this M.
+ curCtx.G = ms.g
+ } else if !ok {
+ // The M hasn't been seen yet. That means this goroutine
+ // has just been sitting in a syscall on this M. Create
+ // a state for it.
+ o.mStates[mid] = &mState{g: gid, p: NoProc}
+ // Don't set curCtx.G in this case because this event is the
+ // binding event (and curCtx represents the "before" state).
+ }
+ // Update the current context to the M we're talking about.
+ curCtx.M = mid
+ }
+ return curCtx, true, nil
+ case go122.EvGoCreate:
+ // Goroutines must be created on a running P, but may or may not be created
+ // by a running goroutine.
+ reqs := event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MayHave}
+ if err := validateCtx(curCtx, reqs); err != nil {
+ return curCtx, false, err
+ }
+ // If we have a goroutine, it must be running.
+ if state, ok := o.gStates[curCtx.G]; ok && state.status != go122.GoRunning {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", go122.EventString(typ), GoRunning)
+ }
+ // This goroutine created another. Add a state for it.
+ newgid := GoID(ev.args[0])
+ if _, ok := o.gStates[newgid]; ok {
+ return curCtx, false, fmt.Errorf("tried to create goroutine (%v) that already exists", newgid)
+ }
+ o.gStates[newgid] = &gState{id: newgid, status: go122.GoRunnable, seq: makeSeq(gen, 0)}
+ return curCtx, true, nil
+ case go122.EvGoDestroy, go122.EvGoStop, go122.EvGoBlock:
+ // These are goroutine events that all require an active running
+ // goroutine on some thread. They must *always* be advance-able,
+ // since running goroutines are bound to their M.
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ state, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", go122.EventString(typ), curCtx.G)
+ }
+ if state.status != go122.GoRunning {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", go122.EventString(typ), GoRunning)
+ }
+ // Handle each case slightly differently; we just group them together
+ // because they have shared preconditions.
+ switch typ {
+ case go122.EvGoDestroy:
+ // This goroutine is exiting itself.
+ delete(o.gStates, curCtx.G)
+ newCtx.G = NoGoroutine
+ case go122.EvGoStop:
+ // Goroutine stopped (yielded). It's runnable but not running on this M.
+ state.status = go122.GoRunnable
+ newCtx.G = NoGoroutine
+ case go122.EvGoBlock:
+ // Goroutine blocked. It's waiting now and not running on this M.
+ state.status = go122.GoWaiting
+ newCtx.G = NoGoroutine
+ }
+ return curCtx, true, nil
+ case go122.EvGoStart:
+ gid := GoID(ev.args[0])
+ seq := makeSeq(gen, ev.args[1])
+ state, ok := o.gStates[gid]
+ if !ok || state.status != go122.GoRunnable || !seq.succeeds(state.seq) {
+ // We can't make an inference as to whether this is bad. We could just be seeing
+ // a GoStart on a different M before the goroutine was created, before it had its
+ // state emitted, or before we got to the right point in the trace yet.
+ return curCtx, false, nil
+ }
+ // We can advance this goroutine. Check some invariants.
+ reqs := event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MustNotHave}
+ if err := validateCtx(curCtx, reqs); err != nil {
+ return curCtx, false, err
+ }
+ state.status = go122.GoRunning
+ state.seq = seq
+ newCtx.G = gid
+ return curCtx, true, nil
+ case go122.EvGoUnblock:
+ // N.B. These both reference the goroutine to unblock, not the current goroutine.
+ gid := GoID(ev.args[0])
+ seq := makeSeq(gen, ev.args[1])
+ state, ok := o.gStates[gid]
+ if !ok || state.status != go122.GoWaiting || !seq.succeeds(state.seq) {
+ // We can't make an inference as to whether this is bad. We could just be seeing
+ // a GoUnblock on a different M before the goroutine was created and blocked itself,
+ // before it had its state emitted, or before we got to the right point in the trace yet.
+ return curCtx, false, nil
+ }
+ state.status = go122.GoRunnable
+ state.seq = seq
+ // N.B. No context to validate. Basically anything can unblock
+ // a goroutine (e.g. sysmon).
+ return curCtx, true, nil
+ case go122.EvGoSyscallBegin:
+ // Entering a syscall requires an active running goroutine with a
+ // proc on some thread. It is always advancable.
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ state, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", go122.EventString(typ), curCtx.G)
+ }
+ if state.status != go122.GoRunning {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", go122.EventString(typ), GoRunning)
+ }
+ // Goroutine entered a syscall. It's still running on this P and M.
+ state.status = go122.GoSyscall
+ pState, ok := o.pStates[curCtx.P]
+ if !ok {
+ return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, go122.EventString(typ))
+ }
+ pState.status = go122.ProcSyscall
+ // Validate the P sequence number on the event and advance it.
+ //
+ // We have a P sequence number for what is supposed to be a goroutine event
+ // so that we can correctly model P stealing. Without this sequence number here,
+ // the syscall from which a ProcSteal event is stealing can be ambiguous in the
+ // face of broken timestamps. See the go122-syscall-steal-proc-ambiguous test for
+ // more details.
+ //
+ // Note that because this sequence number only exists as a tool for disambiguation,
+ // we can enforce that we have the right sequence number at this point; we don't need
+ // to back off and see if any other events will advance. This is a running P.
+ pSeq := makeSeq(gen, ev.args[0])
+ if !pSeq.succeeds(pState.seq) {
+ return curCtx, false, fmt.Errorf("failed to advance %s: can't make sequence: %s -> %s", go122.EventString(typ), pState.seq, pSeq)
+ }
+ pState.seq = pSeq
+ return curCtx, true, nil
+ case go122.EvGoSyscallEnd:
+ // This event is always advance-able because it happens on the same
+ // thread that EvGoSyscallStart happened, and the goroutine can't leave
+ // that thread until its done.
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ state, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", go122.EventString(typ), curCtx.G)
+ }
+ if state.status != go122.GoSyscall {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", go122.EventString(typ), GoRunning)
+ }
+ state.status = go122.GoRunning
+
+ // Transfer the P back to running from syscall.
+ pState, ok := o.pStates[curCtx.P]
+ if !ok {
+ return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, go122.EventString(typ))
+ }
+ if pState.status != go122.ProcSyscall {
+ return curCtx, false, fmt.Errorf("expected proc %d in state %v, but got %v instead", curCtx.P, go122.ProcSyscall, pState.status)
+ }
+ pState.status = go122.ProcRunning
+ return curCtx, true, nil
+ case go122.EvGoSyscallEndBlocked:
+ // This event becomes advanceable when its P is not in a syscall state
+ // (lack of a P altogether is also acceptable for advancing).
+ // The transfer out of ProcSyscall can happen either voluntarily via
+ // ProcStop or involuntarily via ProcSteal. We may also acquire a new P
+ // before we get here (after the transfer out) but that's OK: that new
+ // P won't be in the ProcSyscall state anymore.
+ //
+ // Basically: while we have a preemptible P, don't advance, because we
+ // *know* from the event that we're going to lose it at some point during
+ // the syscall. We shouldn't advance until that happens.
+ if curCtx.P != NoProc {
+ pState, ok := o.pStates[curCtx.P]
+ if !ok {
+ return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, go122.EventString(typ))
+ }
+ if pState.status == go122.ProcSyscall {
+ return curCtx, false, nil
+ }
+ }
+ // As mentioned above, we may have a P here if we ProcStart
+ // before this event.
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MayHave, Goroutine: event.MustHave}); err != nil {
+ return curCtx, false, err
+ }
+ state, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", go122.EventString(typ), curCtx.G)
+ }
+ if state.status != go122.GoSyscall {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", go122.EventString(typ), GoRunning)
+ }
+ newCtx.G = NoGoroutine
+ state.status = go122.GoRunnable
+ return curCtx, true, nil
+ case go122.EvGoCreateSyscall:
+ // This event indicates that a goroutine is effectively
+ // being created out of a cgo callback. Such a goroutine
+ // is 'created' in the syscall state.
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MayHave, Goroutine: event.MustNotHave}); err != nil {
+ return curCtx, false, err
+ }
+ // This goroutine is effectively being created. Add a state for it.
+ newgid := GoID(ev.args[0])
+ if _, ok := o.gStates[newgid]; ok {
+ return curCtx, false, fmt.Errorf("tried to create goroutine (%v) in syscall that already exists", newgid)
+ }
+ o.gStates[newgid] = &gState{id: newgid, status: go122.GoSyscall, seq: makeSeq(gen, 0)}
+ // Goroutine is executing. Bind it to the context.
+ newCtx.G = newgid
+ return curCtx, true, nil
+ case go122.EvGoDestroySyscall:
+ // This event indicates that a goroutine created for a
+ // cgo callback is disappearing, either because the callback
+ // ending or the C thread that called it is being destroyed.
+ //
+ // Also, treat this as if we lost our P too.
+ // The thread ID may be reused by the platform and we'll get
+ // really confused if we try to steal the P is this is running
+ // with later. The new M with the same ID could even try to
+ // steal back this P from itself!
+ //
+ // The runtime is careful to make sure that any GoCreateSyscall
+ // event will enter the runtime emitting events for reacquiring a P.
+ //
+ // Note: we might have a P here. The P might not be released
+ // eagerly by the runtime, and it might get stolen back later
+ // (or never again, if the program is going to exit).
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MayHave, Goroutine: event.MustHave}); err != nil {
+ return curCtx, false, err
+ }
+ // Check to make sure the goroutine exists in the right state.
+ state, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", go122.EventString(typ), curCtx.G)
+ }
+ if state.status != go122.GoSyscall {
+ return curCtx, false, fmt.Errorf("%s event for goroutine that's not %v", go122.EventString(typ), GoSyscall)
+ }
+ // This goroutine is exiting itself.
+ delete(o.gStates, curCtx.G)
+ newCtx.G = NoGoroutine
+
+ // If we have a proc, then we're dissociating from it now. See the comment at the top of the case.
+ if curCtx.P != NoProc {
+ pState, ok := o.pStates[curCtx.P]
+ if !ok {
+ return curCtx, false, fmt.Errorf("found invalid proc %d during %s", curCtx.P, go122.EventString(typ))
+ }
+ if pState.status != go122.ProcSyscall {
+ return curCtx, false, fmt.Errorf("proc %d in unexpected state %s during %s", curCtx.P, pState.status, go122.EventString(typ))
+ }
+ // See the go122-create-syscall-reuse-thread-id test case for more details.
+ pState.status = go122.ProcSyscallAbandoned
+ newCtx.P = NoProc
+
+ // Queue an extra self-ProcSteal event.
+ o.extraEvent = Event{
+ table: evt,
+ ctx: curCtx,
+ base: baseEvent{
+ typ: go122.EvProcSteal,
+ time: ev.time,
+ },
+ }
+ o.extraEvent.base.args[0] = uint64(curCtx.P)
+ o.extraEvent.base.extra(version.Go122)[0] = uint64(go122.ProcSyscall)
+ }
+ return curCtx, true, nil
+
+ // Handle tasks. Tasks are interesting because:
+ // - There's no Begin event required to reference a task.
+ // - End for a particular task ID can appear multiple times.
+ // As a result, there's very little to validate. The only
+ // thing we have to be sure of is that a task didn't begin
+ // after it had already begun. Task IDs are allowed to be
+ // reused, so we don't care about a Begin after an End.
+ case go122.EvUserTaskBegin:
+ id := TaskID(ev.args[0])
+ if _, ok := o.activeTasks[id]; ok {
+ return curCtx, false, fmt.Errorf("task ID conflict: %d", id)
+ }
+ // Get the parent ID, but don't validate it. There's no guarantee
+ // we actually have information on whether it's active.
+ parentID := TaskID(ev.args[1])
+ if parentID == BackgroundTask {
+ // Note: a value of 0 here actually means no parent, *not* the
+ // background task. Automatic background task attachment only
+ // applies to regions.
+ parentID = NoTask
+ ev.args[1] = uint64(NoTask)
+ }
+
+ // Validate the name and record it. We'll need to pass it through to
+ // EvUserTaskEnd.
+ nameID := stringID(ev.args[2])
+ name, ok := evt.strings.get(nameID)
+ if !ok {
+ return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, typ)
+ }
+ o.activeTasks[id] = taskState{name: name, parentID: parentID}
+ return curCtx, true, validateCtx(curCtx, event.UserGoReqs)
+ case go122.EvUserTaskEnd:
+ id := TaskID(ev.args[0])
+ if ts, ok := o.activeTasks[id]; ok {
+ // Smuggle the task info. This may happen in a different generation,
+ // which may not have the name in its string table. Add it to the extra
+ // strings table so we can look it up later.
+ ev.extra(version.Go122)[0] = uint64(ts.parentID)
+ ev.extra(version.Go122)[1] = uint64(evt.addExtraString(ts.name))
+ delete(o.activeTasks, id)
+ } else {
+ // Explicitly clear the task info.
+ ev.extra(version.Go122)[0] = uint64(NoTask)
+ ev.extra(version.Go122)[1] = uint64(evt.addExtraString(""))
+ }
+ return curCtx, true, validateCtx(curCtx, event.UserGoReqs)
+
+ // Handle user regions.
+ case go122.EvUserRegionBegin:
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ tid := TaskID(ev.args[0])
+ nameID := stringID(ev.args[1])
+ name, ok := evt.strings.get(nameID)
+ if !ok {
+ return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, typ)
+ }
+ gState, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("encountered EvUserRegionBegin without known state for current goroutine %d", curCtx.G)
+ }
+ if err := gState.beginRegion(userRegion{tid, name}); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvUserRegionEnd:
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ tid := TaskID(ev.args[0])
+ nameID := stringID(ev.args[1])
+ name, ok := evt.strings.get(nameID)
+ if !ok {
+ return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, typ)
+ }
+ gState, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("encountered EvUserRegionEnd without known state for current goroutine %d", curCtx.G)
+ }
+ if err := gState.endRegion(userRegion{tid, name}); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+
+ // Handle the GC mark phase.
+ //
+ // We have sequence numbers for both start and end because they
+ // can happen on completely different threads. We want an explicit
+ // partial order edge between start and end here, otherwise we're
+ // relying entirely on timestamps to make sure we don't advance a
+ // GCEnd for a _different_ GC cycle if timestamps are wildly broken.
+ case go122.EvGCActive:
+ seq := ev.args[0]
+ if gen == o.initialGen {
+ if o.gcState != gcUndetermined {
+ return curCtx, false, fmt.Errorf("GCActive in the first generation isn't first GC event")
+ }
+ o.gcSeq = seq
+ o.gcState = gcRunning
+ return curCtx, true, nil
+ }
+ if seq != o.gcSeq+1 {
+ // This is not the right GC cycle.
+ return curCtx, false, nil
+ }
+ if o.gcState != gcRunning {
+ return curCtx, false, fmt.Errorf("encountered GCActive while GC was not in progress")
+ }
+ o.gcSeq = seq
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvGCBegin:
+ seq := ev.args[0]
+ if o.gcState == gcUndetermined {
+ o.gcSeq = seq
+ o.gcState = gcRunning
+ return curCtx, true, nil
+ }
+ if seq != o.gcSeq+1 {
+ // This is not the right GC cycle.
+ return curCtx, false, nil
+ }
+ if o.gcState == gcRunning {
+ return curCtx, false, fmt.Errorf("encountered GCBegin while GC was already in progress")
+ }
+ o.gcSeq = seq
+ o.gcState = gcRunning
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvGCEnd:
+ seq := ev.args[0]
+ if seq != o.gcSeq+1 {
+ // This is not the right GC cycle.
+ return curCtx, false, nil
+ }
+ if o.gcState == gcNotRunning {
+ return curCtx, false, fmt.Errorf("encountered GCEnd when GC was not in progress")
+ }
+ if o.gcState == gcUndetermined {
+ return curCtx, false, fmt.Errorf("encountered GCEnd when GC was in an undetermined state")
+ }
+ o.gcSeq = seq
+ o.gcState = gcNotRunning
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+
+ // Handle simple instantaneous events that require a G.
+ case go122.EvGoLabel, go122.EvProcsChange, go122.EvUserLog:
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+
+ // Handle allocation states, which don't require a G.
+ case go122.EvHeapAlloc, go122.EvHeapGoal:
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MayHave}); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+
+ // Handle sweep, which is bound to a P and doesn't require a G.
+ case go122.EvGCSweepBegin:
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MayHave}); err != nil {
+ return curCtx, false, err
+ }
+ if err := o.pStates[curCtx.P].beginRange(makeRangeType(typ, 0)); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvGCSweepActive:
+ pid := ProcID(ev.args[0])
+ // N.B. In practice Ps can't block while they're sweeping, so this can only
+ // ever reference curCtx.P. However, be lenient about this like we are with
+ // GCMarkAssistActive; there's no reason the runtime couldn't change to block
+ // in the middle of a sweep.
+ pState, ok := o.pStates[pid]
+ if !ok {
+ return curCtx, false, fmt.Errorf("encountered GCSweepActive for unknown proc %d", pid)
+ }
+ if err := pState.activeRange(makeRangeType(typ, 0), gen == o.initialGen); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvGCSweepEnd:
+ if err := validateCtx(curCtx, event.SchedReqs{Thread: event.MustHave, Proc: event.MustHave, Goroutine: event.MayHave}); err != nil {
+ return curCtx, false, err
+ }
+ _, err := o.pStates[curCtx.P].endRange(typ)
+ if err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+
+ // Handle special goroutine-bound event ranges.
+ case go122.EvSTWBegin, go122.EvGCMarkAssistBegin:
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ desc := stringID(0)
+ if typ == go122.EvSTWBegin {
+ desc = stringID(ev.args[0])
+ }
+ gState, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", typ, curCtx.G)
+ }
+ if err := gState.beginRange(makeRangeType(typ, desc)); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvGCMarkAssistActive:
+ gid := GoID(ev.args[0])
+ // N.B. Like GoStatus, this can happen at any time, because it can
+ // reference a non-running goroutine. Don't check anything about the
+ // current scheduler context.
+ gState, ok := o.gStates[gid]
+ if !ok {
+ return curCtx, false, fmt.Errorf("uninitialized goroutine %d found during %s", gid, go122.EventString(typ))
+ }
+ if err := gState.activeRange(makeRangeType(typ, 0), gen == o.initialGen); err != nil {
+ return curCtx, false, err
+ }
+ return curCtx, true, nil
+ case go122.EvSTWEnd, go122.EvGCMarkAssistEnd:
+ if err := validateCtx(curCtx, event.UserGoReqs); err != nil {
+ return curCtx, false, err
+ }
+ gState, ok := o.gStates[curCtx.G]
+ if !ok {
+ return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", typ, curCtx.G)
+ }
+ desc, err := gState.endRange(typ)
+ if err != nil {
+ return curCtx, false, err
+ }
+ if typ == go122.EvSTWEnd {
+ // Smuggle the kind into the event.
+ // Don't use ev.extra here so we have symmetry with STWBegin.
+ ev.args[0] = uint64(desc)
+ }
+ return curCtx, true, nil
+ }
+ return curCtx, false, fmt.Errorf("bad event type found while ordering: %v", ev.typ)
+}
+
+// schedCtx represents the scheduling resources associated with an event.
+type schedCtx struct {
+ G GoID
+ P ProcID
+ M ThreadID
+}
+
+// validateCtx ensures that ctx conforms to some reqs, returning an error if
+// it doesn't.
+func validateCtx(ctx schedCtx, reqs event.SchedReqs) error {
+ // Check thread requirements.
+ if reqs.Thread == event.MustHave && ctx.M == NoThread {
+ return fmt.Errorf("expected a thread but didn't have one")
+ } else if reqs.Thread == event.MustNotHave && ctx.M != NoThread {
+ return fmt.Errorf("expected no thread but had one")
+ }
+
+ // Check proc requirements.
+ if reqs.Proc == event.MustHave && ctx.P == NoProc {
+ return fmt.Errorf("expected a proc but didn't have one")
+ } else if reqs.Proc == event.MustNotHave && ctx.P != NoProc {
+ return fmt.Errorf("expected no proc but had one")
+ }
+
+ // Check goroutine requirements.
+ if reqs.Goroutine == event.MustHave && ctx.G == NoGoroutine {
+ return fmt.Errorf("expected a goroutine but didn't have one")
+ } else if reqs.Goroutine == event.MustNotHave && ctx.G != NoGoroutine {
+ return fmt.Errorf("expected no goroutine but had one")
+ }
+ return nil
+}
+
+// gcState is a trinary variable for the current state of the GC.
+//
+// The third state besides "enabled" and "disabled" is "undetermined."
+type gcState uint8
+
+const (
+ gcUndetermined gcState = iota
+ gcNotRunning
+ gcRunning
+)
+
+// String returns a human-readable string for the GC state.
+func (s gcState) String() string {
+ switch s {
+ case gcUndetermined:
+ return "Undetermined"
+ case gcNotRunning:
+ return "NotRunning"
+ case gcRunning:
+ return "Running"
+ }
+ return "Bad"
+}
+
+// userRegion represents a unique user region when attached to some gState.
+type userRegion struct {
+ // name must be a resolved string because the string ID for the same
+ // string may change across generations, but we care about checking
+ // the value itself.
+ taskID TaskID
+ name string
+}
+
+// rangeType is a way to classify special ranges of time.
+//
+// These typically correspond 1:1 with "Begin" events, but
+// they may have an optional subtype that describes the range
+// in more detail.
+type rangeType struct {
+ typ event.Type // "Begin" event.
+ desc stringID // Optional subtype.
+}
+
+// makeRangeType constructs a new rangeType.
+func makeRangeType(typ event.Type, desc stringID) rangeType {
+ if styp := go122.Specs()[typ].StartEv; styp != go122.EvNone {
+ typ = styp
+ }
+ return rangeType{typ, desc}
+}
+
+// gState is the state of a goroutine at a point in the trace.
+type gState struct {
+ id GoID
+ status go122.GoStatus
+ seq seqCounter
+
+ // regions are the active user regions for this goroutine.
+ regions []userRegion
+
+ // rangeState is the state of special time ranges bound to this goroutine.
+ rangeState
+}
+
+// beginRegion starts a user region on the goroutine.
+func (s *gState) beginRegion(r userRegion) error {
+ s.regions = append(s.regions, r)
+ return nil
+}
+
+// endRegion ends a user region on the goroutine.
+func (s *gState) endRegion(r userRegion) error {
+ if len(s.regions) == 0 {
+ // We do not know about regions that began before tracing started.
+ return nil
+ }
+ if next := s.regions[len(s.regions)-1]; next != r {
+ return fmt.Errorf("misuse of region in goroutine %v: region end %v when the inner-most active region start event is %v", s.id, r, next)
+ }
+ s.regions = s.regions[:len(s.regions)-1]
+ return nil
+}
+
+// pState is the state of a proc at a point in the trace.
+type pState struct {
+ id ProcID
+ status go122.ProcStatus
+ seq seqCounter
+
+ // rangeState is the state of special time ranges bound to this proc.
+ rangeState
+}
+
+// mState is the state of a thread at a point in the trace.
+type mState struct {
+ g GoID // Goroutine bound to this M. (The goroutine's state is Executing.)
+ p ProcID // Proc bound to this M. (The proc's state is Executing.)
+}
+
+// rangeState represents the state of special time ranges.
+type rangeState struct {
+ // inFlight contains the rangeTypes of any ranges bound to a resource.
+ inFlight []rangeType
+}
+
+// beginRange begins a special range in time on the goroutine.
+//
+// Returns an error if the range is already in progress.
+func (s *rangeState) beginRange(typ rangeType) error {
+ if s.hasRange(typ) {
+ return fmt.Errorf("discovered event already in-flight for when starting event %v", go122.Specs()[typ.typ].Name)
+ }
+ s.inFlight = append(s.inFlight, typ)
+ return nil
+}
+
+// activeRange marks special range in time on the goroutine as active in the
+// initial generation, or confirms that it is indeed active in later generations.
+func (s *rangeState) activeRange(typ rangeType, isInitialGen bool) error {
+ if isInitialGen {
+ if s.hasRange(typ) {
+ return fmt.Errorf("found named active range already in first gen: %v", typ)
+ }
+ s.inFlight = append(s.inFlight, typ)
+ } else if !s.hasRange(typ) {
+ return fmt.Errorf("resource is missing active range: %v %v", go122.Specs()[typ.typ].Name, s.inFlight)
+ }
+ return nil
+}
+
+// hasRange returns true if a special time range on the goroutine as in progress.
+func (s *rangeState) hasRange(typ rangeType) bool {
+ for _, ftyp := range s.inFlight {
+ if ftyp == typ {
+ return true
+ }
+ }
+ return false
+}
+
+// endsRange ends a special range in time on the goroutine.
+//
+// This must line up with the start event type of the range the goroutine is currently in.
+func (s *rangeState) endRange(typ event.Type) (stringID, error) {
+ st := go122.Specs()[typ].StartEv
+ idx := -1
+ for i, r := range s.inFlight {
+ if r.typ == st {
+ idx = i
+ break
+ }
+ }
+ if idx < 0 {
+ return 0, fmt.Errorf("tried to end event %v, but not in-flight", go122.Specs()[st].Name)
+ }
+ // Swap remove.
+ desc := s.inFlight[idx].desc
+ s.inFlight[idx], s.inFlight[len(s.inFlight)-1] = s.inFlight[len(s.inFlight)-1], s.inFlight[idx]
+ s.inFlight = s.inFlight[:len(s.inFlight)-1]
+ return desc, nil
+}
+
+// seqCounter represents a global sequence counter for a resource.
+type seqCounter struct {
+ gen uint64 // The generation for the local sequence counter seq.
+ seq uint64 // The sequence number local to the generation.
+}
+
+// makeSeq creates a new seqCounter.
+func makeSeq(gen, seq uint64) seqCounter {
+ return seqCounter{gen: gen, seq: seq}
+}
+
+// succeeds returns true if a is the immediate successor of b.
+func (a seqCounter) succeeds(b seqCounter) bool {
+ return a.gen == b.gen && a.seq == b.seq+1
+}
+
+// String returns a debug string representation of the seqCounter.
+func (c seqCounter) String() string {
+ return fmt.Sprintf("%d (gen=%d)", c.seq, c.gen)
+}
+
+func dumpOrdering(order *ordering) string {
+ var sb strings.Builder
+ for id, state := range order.gStates {
+ fmt.Fprintf(&sb, "G %d [status=%s seq=%s]\n", id, state.status, state.seq)
+ }
+ fmt.Fprintln(&sb)
+ for id, state := range order.pStates {
+ fmt.Fprintf(&sb, "P %d [status=%s seq=%s]\n", id, state.status, state.seq)
+ }
+ fmt.Fprintln(&sb)
+ for id, state := range order.mStates {
+ fmt.Fprintf(&sb, "M %d [g=%d p=%d]\n", id, state.g, state.p)
+ }
+ fmt.Fprintln(&sb)
+ fmt.Fprintf(&sb, "GC %d %s\n", order.gcSeq, order.gcState)
+ return sb.String()
+}
+
+// taskState represents an active task.
+type taskState struct {
+ // name is the type of the active task.
+ name string
+
+ // parentID is the parent ID of the active task.
+ parentID TaskID
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/doc.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..53487372b75e084b9aeb4de8218a5a2d2cdaf769
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/doc.go
@@ -0,0 +1,66 @@
+// 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 provides an interface to interpret and emit Go execution traces.
+It can interpret and emit execution traces in its wire format as well as a
+bespoke but simple text format.
+
+The readers and writers in this package perform no validation on or ordering of
+the input, and so are generally unsuitable for analysis. However, they're very
+useful for testing and debugging the tracer in the runtime and more sophisticated
+trace parsers.
+
+# Text format specification
+
+The trace text format produced and consumed by this package is a line-oriented
+format.
+
+The first line in each text trace is the header line.
+
+ Trace Go1.XX
+
+Following that is a series of event lines. Each event begins with an
+event name, followed by zero or more named unsigned integer arguments.
+Names are separated from their integer values by an '=' sign. Names can
+consist of any UTF-8 character except '='.
+
+For example:
+
+ EventName arg1=23 arg2=55 arg3=53
+
+Any amount of whitespace is allowed to separate each token. Whitespace
+is identified via unicode.IsSpace.
+
+Some events have additional data on following lines. There are two such
+special cases.
+
+The first special case consists of events with trailing byte-oriented data.
+The trailer begins on the following line from the event. That line consists
+of a single argument 'data' and a Go-quoted string representing the byte data
+within. Note: an explicit argument for the length is elided, because it's
+just the length of the unquoted string.
+
+For example:
+
+ String id=5
+ data="hello world\x00"
+
+These events are identified in their spec by the HasData flag.
+
+The second special case consists of stack events. These events are identified
+by the IsStack flag. These events also have a trailing unsigned integer argument
+describing the number of stack frame descriptors that follow. Each stack frame
+descriptor is on its own line following the event, consisting of four signed
+integer arguments: the PC, an integer describing the function name, an integer
+describing the file name, and the line number in that file that function was at
+at the time the stack trace was taken.
+
+For example:
+
+ Stack id=5 n=2
+ pc=1241251 func=3 file=6 line=124
+ pc=7534345 func=6 file=3 line=64
+*/
+package raw
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/event.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/event.go
new file mode 100644
index 0000000000000000000000000000000000000000..6f09f1f4c2374934142e488a12db10bf1ec3f102
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/event.go
@@ -0,0 +1,60 @@
+// 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 (
+ "strconv"
+ "strings"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/version"
+)
+
+// Event is a simple representation of a trace event.
+//
+// Note that this typically includes much more than just
+// timestamped events, and it also represents parts of the
+// trace format's framing. (But not interpreted.)
+type Event struct {
+ Version version.Version
+ Ev event.Type
+ Args []uint64
+ Data []byte
+}
+
+// String returns the canonical string representation of the event.
+//
+// This format is the same format that is parsed by the TextReader
+// and emitted by the TextWriter.
+func (e *Event) String() string {
+ spec := e.Version.Specs()[e.Ev]
+
+ var s strings.Builder
+ s.WriteString(spec.Name)
+ for i := range spec.Args {
+ s.WriteString(" ")
+ s.WriteString(spec.Args[i])
+ s.WriteString("=")
+ s.WriteString(strconv.FormatUint(e.Args[i], 10))
+ }
+ if spec.IsStack {
+ frames := e.Args[len(spec.Args):]
+ for i := 0; i < len(frames); i++ {
+ if i%4 == 0 {
+ s.WriteString("\n\t")
+ } else {
+ s.WriteString(" ")
+ }
+ s.WriteString(frameFields[i%4])
+ s.WriteString("=")
+ s.WriteString(strconv.FormatUint(frames[i], 10))
+ }
+ }
+ if e.Data != nil {
+ s.WriteString("\n\tdata=")
+ s.WriteString(strconv.Quote(string(e.Data)))
+ }
+ return s.String()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/reader.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/reader.go
new file mode 100644
index 0000000000000000000000000000000000000000..fdcd47f7c5f78282d4974ea79bebbb195ff03980
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/reader.go
@@ -0,0 +1,110 @@
+// 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 (
+ "bufio"
+ "encoding/binary"
+ "fmt"
+ "io"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/version"
+)
+
+// Reader parses trace bytes with only very basic validation
+// into an event stream.
+type Reader struct {
+ r *bufio.Reader
+ v version.Version
+ specs []event.Spec
+}
+
+// NewReader creates a new reader for the trace wire format.
+func NewReader(r io.Reader) (*Reader, error) {
+ br := bufio.NewReader(r)
+ v, err := version.ReadHeader(br)
+ if err != nil {
+ return nil, err
+ }
+ return &Reader{r: br, v: v, specs: v.Specs()}, nil
+}
+
+// Version returns the version of the trace that we're reading.
+func (r *Reader) Version() version.Version {
+ return r.v
+}
+
+// ReadEvent reads and returns the next trace event in the byte stream.
+func (r *Reader) ReadEvent() (Event, error) {
+ evb, err := r.r.ReadByte()
+ if err == io.EOF {
+ return Event{}, io.EOF
+ }
+ if err != nil {
+ return Event{}, err
+ }
+ if int(evb) >= len(r.specs) || evb == 0 {
+ return Event{}, fmt.Errorf("invalid event type: %d", evb)
+ }
+ ev := event.Type(evb)
+ spec := r.specs[ev]
+ args, err := r.readArgs(len(spec.Args))
+ if err != nil {
+ return Event{}, err
+ }
+ if spec.IsStack {
+ len := int(args[1])
+ for i := 0; i < len; i++ {
+ // Each stack frame has four args: pc, func ID, file ID, line number.
+ frame, err := r.readArgs(4)
+ if err != nil {
+ return Event{}, err
+ }
+ args = append(args, frame...)
+ }
+ }
+ var data []byte
+ if spec.HasData {
+ data, err = r.readData()
+ if err != nil {
+ return Event{}, err
+ }
+ }
+ return Event{
+ Version: r.v,
+ Ev: ev,
+ Args: args,
+ Data: data,
+ }, nil
+}
+
+func (r *Reader) readArgs(n int) ([]uint64, error) {
+ var args []uint64
+ for i := 0; i < n; i++ {
+ val, err := binary.ReadUvarint(r.r)
+ if err != nil {
+ return nil, err
+ }
+ args = append(args, val)
+ }
+ return args, nil
+}
+
+func (r *Reader) readData() ([]byte, error) {
+ len, err := binary.ReadUvarint(r.r)
+ if err != nil {
+ return nil, err
+ }
+ var data []byte
+ for i := 0; i < int(len); i++ {
+ b, err := r.r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ data = append(data, b)
+ }
+ return data, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textreader.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textreader.go
new file mode 100644
index 0000000000000000000000000000000000000000..07785f35a3166f32be34f0d5a7adaa13e1d98823
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textreader.go
@@ -0,0 +1,217 @@
+// 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 (
+ "bufio"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+ "unicode"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/version"
+)
+
+// TextReader parses a text format trace with only very basic validation
+// into an event stream.
+type TextReader struct {
+ v version.Version
+ specs []event.Spec
+ names map[string]event.Type
+ s *bufio.Scanner
+}
+
+// NewTextReader creates a new reader for the trace text format.
+func NewTextReader(r io.Reader) (*TextReader, error) {
+ tr := &TextReader{s: bufio.NewScanner(r)}
+ line, err := tr.nextLine()
+ if err != nil {
+ return nil, err
+ }
+ trace, line := readToken(line)
+ if trace != "Trace" {
+ return nil, fmt.Errorf("failed to parse header")
+ }
+ gover, line := readToken(line)
+ if !strings.HasPrefix(gover, "Go1.") {
+ return nil, fmt.Errorf("failed to parse header Go version")
+ }
+ rawv, err := strconv.ParseUint(gover[len("Go1."):], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse header Go version: %v", err)
+ }
+ v := version.Version(rawv)
+ if !v.Valid() {
+ return nil, fmt.Errorf("unknown or unsupported Go version 1.%d", v)
+ }
+ tr.v = v
+ tr.specs = v.Specs()
+ tr.names = event.Names(tr.specs)
+ for _, r := range line {
+ if !unicode.IsSpace(r) {
+ return nil, fmt.Errorf("encountered unexpected non-space at the end of the header: %q", line)
+ }
+ }
+ return tr, nil
+}
+
+// Version returns the version of the trace that we're reading.
+func (r *TextReader) Version() version.Version {
+ return r.v
+}
+
+// ReadEvent reads and returns the next trace event in the text stream.
+func (r *TextReader) ReadEvent() (Event, error) {
+ line, err := r.nextLine()
+ if err != nil {
+ return Event{}, err
+ }
+ evStr, line := readToken(line)
+ ev, ok := r.names[evStr]
+ if !ok {
+ return Event{}, fmt.Errorf("unidentified event: %s", evStr)
+ }
+ spec := r.specs[ev]
+ args, err := readArgs(line, spec.Args)
+ if err != nil {
+ return Event{}, fmt.Errorf("reading args for %s: %v", evStr, err)
+ }
+ if spec.IsStack {
+ len := int(args[1])
+ for i := 0; i < len; i++ {
+ line, err := r.nextLine()
+ if err == io.EOF {
+ return Event{}, fmt.Errorf("unexpected EOF while reading stack: args=%v", args)
+ }
+ if err != nil {
+ return Event{}, err
+ }
+ frame, err := readArgs(line, frameFields)
+ if err != nil {
+ return Event{}, err
+ }
+ args = append(args, frame...)
+ }
+ }
+ var data []byte
+ if spec.HasData {
+ line, err := r.nextLine()
+ if err == io.EOF {
+ return Event{}, fmt.Errorf("unexpected EOF while reading data for %s: args=%v", evStr, args)
+ }
+ if err != nil {
+ return Event{}, err
+ }
+ data, err = readData(line)
+ if err != nil {
+ return Event{}, err
+ }
+ }
+ return Event{
+ Version: r.v,
+ Ev: ev,
+ Args: args,
+ Data: data,
+ }, nil
+}
+
+func (r *TextReader) nextLine() (string, error) {
+ for {
+ if !r.s.Scan() {
+ if err := r.s.Err(); err != nil {
+ return "", err
+ }
+ return "", io.EOF
+ }
+ txt := r.s.Text()
+ tok, _ := readToken(txt)
+ if tok == "" {
+ continue // Empty line or comment.
+ }
+ return txt, nil
+ }
+}
+
+var frameFields = []string{"pc", "func", "file", "line"}
+
+func readArgs(s string, names []string) ([]uint64, error) {
+ var args []uint64
+ for _, name := range names {
+ arg, value, rest, err := readArg(s)
+ if err != nil {
+ return nil, err
+ }
+ if arg != name {
+ return nil, fmt.Errorf("expected argument %q, but got %q", name, arg)
+ }
+ args = append(args, value)
+ s = rest
+ }
+ for _, r := range s {
+ if !unicode.IsSpace(r) {
+ return nil, fmt.Errorf("encountered unexpected non-space at the end of an event: %q", s)
+ }
+ }
+ return args, nil
+}
+
+func readArg(s string) (arg string, value uint64, rest string, err error) {
+ var tok string
+ tok, rest = readToken(s)
+ if len(tok) == 0 {
+ return "", 0, s, fmt.Errorf("no argument")
+ }
+ parts := strings.SplitN(tok, "=", 2)
+ if len(parts) < 2 {
+ return "", 0, s, fmt.Errorf("malformed argument: %q", tok)
+ }
+ arg = parts[0]
+ value, err = strconv.ParseUint(parts[1], 10, 64)
+ if err != nil {
+ return arg, value, s, fmt.Errorf("failed to parse argument value %q for arg %q", parts[1], parts[0])
+ }
+ return
+}
+
+func readToken(s string) (token, rest string) {
+ tkStart := -1
+ for i, r := range s {
+ if r == '#' {
+ return "", ""
+ }
+ if !unicode.IsSpace(r) {
+ tkStart = i
+ break
+ }
+ }
+ if tkStart < 0 {
+ return "", ""
+ }
+ tkEnd := -1
+ for i, r := range s[tkStart:] {
+ if unicode.IsSpace(r) || r == '#' {
+ tkEnd = i + tkStart
+ break
+ }
+ }
+ if tkEnd < 0 {
+ return s[tkStart:], ""
+ }
+ return s[tkStart:tkEnd], s[tkEnd:]
+}
+
+func readData(line string) ([]byte, error) {
+ parts := strings.SplitN(line, "=", 2)
+ if len(parts) < 2 || strings.TrimSpace(parts[0]) != "data" {
+ return nil, fmt.Errorf("malformed data: %q", line)
+ }
+ data, err := strconv.Unquote(strings.TrimSpace(parts[1]))
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse data: %q: %v", line, err)
+ }
+ return []byte(data), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textwriter.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textwriter.go
new file mode 100644
index 0000000000000000000000000000000000000000..367a80bbb6a9626e518d635e240b76e7d5945ae2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/textwriter.go
@@ -0,0 +1,39 @@
+// 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/v2/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
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/writer.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/writer.go
new file mode 100644
index 0000000000000000000000000000000000000000..80596ebe9a4ce36fc7c72cabdf8387f1d0957f56
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/raw/writer.go
@@ -0,0 +1,75 @@
+// 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 (
+ "encoding/binary"
+ "fmt"
+ "io"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/version"
+)
+
+// Writer emits the wire format of a trace.
+//
+// It may not produce a byte-for-byte compatible trace from what is
+// produced by the runtime, because it may be missing extra padding
+// in the LEB128 encoding that the runtime adds but isn't necessary
+// when you know the data up-front.
+type Writer struct {
+ w io.Writer
+ buf []byte
+ v version.Version
+ specs []event.Spec
+}
+
+// NewWriter creates a new byte format writer.
+func NewWriter(w io.Writer, v version.Version) (*Writer, error) {
+ _, err := version.WriteHeader(w, v)
+ return &Writer{w: w, v: v, specs: v.Specs()}, err
+}
+
+// WriteEvent writes a single event to the trace wire format stream.
+func (w *Writer) 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 header byte.
+ w.buf = append(w.buf, uint8(e.Ev))
+
+ // Write out all arguments.
+ spec := w.specs[e.Ev]
+ for _, arg := range e.Args[:len(spec.Args)] {
+ w.buf = binary.AppendUvarint(w.buf, arg)
+ }
+ if spec.IsStack {
+ frameArgs := e.Args[len(spec.Args):]
+ for i := 0; i < len(frameArgs); i++ {
+ w.buf = binary.AppendUvarint(w.buf, frameArgs[i])
+ }
+ }
+
+ // Write out the length of the data.
+ if spec.HasData {
+ w.buf = binary.AppendUvarint(w.buf, uint64(len(e.Data)))
+ }
+
+ // Write out varint events.
+ _, err := w.w.Write(w.buf)
+ w.buf = w.buf[:0]
+ if err != nil {
+ return err
+ }
+
+ // Write out data.
+ if spec.HasData {
+ _, err := w.w.Write(e.Data)
+ return err
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/reader.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/reader.go
new file mode 100644
index 0000000000000000000000000000000000000000..824ca23df39e43c8ea385e817d52e034210df20f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/reader.go
@@ -0,0 +1,198 @@
+// 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 (
+ "bufio"
+ "fmt"
+ "io"
+ "slices"
+ "strings"
+
+ "internal/trace/v2/event/go122"
+ "internal/trace/v2/version"
+)
+
+// Reader reads a byte stream, validates it, and produces trace events.
+type Reader struct {
+ r *bufio.Reader
+ lastTs Time
+ gen *generation
+ spill *spilledBatch
+ frontier []*batchCursor
+ cpuSamples []cpuSample
+ order ordering
+ emittedSync bool
+}
+
+// NewReader creates a new trace reader.
+func NewReader(r io.Reader) (*Reader, error) {
+ br := bufio.NewReader(r)
+ v, err := version.ReadHeader(br)
+ if err != nil {
+ return nil, err
+ }
+ if v != version.Go122 {
+ return nil, fmt.Errorf("unknown or unsupported version go 1.%d", v)
+ }
+ return &Reader{
+ r: br,
+ order: ordering{
+ mStates: make(map[ThreadID]*mState),
+ pStates: make(map[ProcID]*pState),
+ gStates: make(map[GoID]*gState),
+ activeTasks: make(map[TaskID]taskState),
+ },
+ // Don't emit a sync event when we first go to emit events.
+ emittedSync: true,
+ }, nil
+}
+
+// ReadEvent reads a single event from the stream.
+//
+// If the stream has been exhausted, it returns an invalid
+// event and io.EOF.
+func (r *Reader) ReadEvent() (e Event, err error) {
+ // Go 1.22+ trace parsing algorithm.
+ //
+ // (1) Read in all the batches for the next generation from the stream.
+ // (a) Use the size field in the header to quickly find all batches.
+ // (2) Parse out the strings, stacks, CPU samples, and timestamp conversion data.
+ // (3) Group each event batch by M, sorted by timestamp. (batchCursor contains the groups.)
+ // (4) Organize batchCursors in a min-heap, ordered by the timestamp of the next event for each M.
+ // (5) Try to advance the next event for the M at the top of the min-heap.
+ // (a) On success, select that M.
+ // (b) On failure, sort the min-heap and try to advance other Ms. Select the first M that advances.
+ // (c) If there's nothing left to advance, goto (1).
+ // (6) Select the latest event for the selected M and get it ready to be returned.
+ // (7) Read the next event for the selected M and update the min-heap.
+ // (8) Return the selected event, goto (5) on the next call.
+
+ // Set us up to track the last timestamp and fix up
+ // the timestamp of any event that comes through.
+ defer func() {
+ if err != nil {
+ return
+ }
+ if err = e.validateTableIDs(); err != nil {
+ return
+ }
+ if e.base.time <= r.lastTs {
+ e.base.time = r.lastTs + 1
+ }
+ r.lastTs = e.base.time
+ }()
+
+ // Consume any extra events produced during parsing.
+ if ev := r.order.consumeExtraEvent(); ev.Kind() != EventBad {
+ return ev, nil
+ }
+
+ // Check if we need to refresh the generation.
+ if len(r.frontier) == 0 && len(r.cpuSamples) == 0 {
+ if !r.emittedSync {
+ r.emittedSync = true
+ return syncEvent(r.gen.evTable, r.lastTs), nil
+ }
+ if r.gen != nil && r.spill == nil {
+ // If we have a generation from the last read,
+ // and there's nothing left in the frontier, and
+ // there's no spilled batch, indicating that there's
+ // no further generation, it means we're done.
+ // Return io.EOF.
+ return Event{}, io.EOF
+ }
+ // Read the next generation.
+ r.gen, r.spill, err = readGeneration(r.r, r.spill)
+ if err != nil {
+ return Event{}, err
+ }
+
+ // Reset CPU samples cursor.
+ r.cpuSamples = r.gen.cpuSamples
+
+ // Reset frontier.
+ for m, batches := range r.gen.batches {
+ bc := &batchCursor{m: m}
+ ok, err := bc.nextEvent(batches, r.gen.freq)
+ if err != nil {
+ return Event{}, err
+ }
+ if !ok {
+ // Turns out there aren't actually any events in these batches.
+ continue
+ }
+ r.frontier = heapInsert(r.frontier, bc)
+ }
+
+ // Reset emittedSync.
+ r.emittedSync = false
+ }
+ refresh := func(i int) error {
+ bc := r.frontier[i]
+
+ // Refresh the cursor's event.
+ ok, err := bc.nextEvent(r.gen.batches[bc.m], r.gen.freq)
+ if err != nil {
+ return err
+ }
+ if ok {
+ // If we successfully refreshed, update the heap.
+ heapUpdate(r.frontier, i)
+ } else {
+ // There's nothing else to read. Delete this cursor from the frontier.
+ r.frontier = heapRemove(r.frontier, i)
+ }
+ return nil
+ }
+ // Inject a CPU sample if it comes next.
+ if len(r.cpuSamples) != 0 {
+ if len(r.frontier) == 0 || r.cpuSamples[0].time < r.frontier[0].ev.time {
+ e := r.cpuSamples[0].asEvent(r.gen.evTable)
+ r.cpuSamples = r.cpuSamples[1:]
+ return e, nil
+ }
+ }
+ // Try to advance the head of the frontier, which should have the minimum timestamp.
+ // This should be by far the most common case
+ if len(r.frontier) == 0 {
+ return Event{}, fmt.Errorf("broken trace: frontier is empty:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order))
+ }
+ bc := r.frontier[0]
+ if ctx, ok, err := r.order.advance(&bc.ev, r.gen.evTable, bc.m, r.gen.gen); err != nil {
+ return Event{}, err
+ } else if ok {
+ e := Event{table: r.gen.evTable, ctx: ctx, base: bc.ev}
+ return e, refresh(0)
+ }
+ // Sort the min-heap. A sorted min-heap is still a min-heap,
+ // but now we can iterate over the rest and try to advance in
+ // order. This path should be rare.
+ slices.SortFunc(r.frontier, (*batchCursor).compare)
+ // Try to advance the rest of the frontier, in timestamp order.
+ for i := 1; i < len(r.frontier); i++ {
+ bc := r.frontier[i]
+ if ctx, ok, err := r.order.advance(&bc.ev, r.gen.evTable, bc.m, r.gen.gen); err != nil {
+ return Event{}, err
+ } else if ok {
+ e := Event{table: r.gen.evTable, ctx: ctx, base: bc.ev}
+ return e, refresh(i)
+ }
+ }
+ return Event{}, fmt.Errorf("broken trace: failed to advance: frontier:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order))
+}
+
+func dumpFrontier(frontier []*batchCursor) string {
+ var sb strings.Builder
+ for _, bc := range frontier {
+ spec := go122.Specs()[bc.ev.typ]
+ fmt.Fprintf(&sb, "M %d [%s time=%d", bc.m, spec.Name, bc.ev.time)
+ for i, arg := range spec.Args[1:] {
+ fmt.Fprintf(&sb, " %s=%d", arg, bc.ev.args[i])
+ }
+ fmt.Fprintf(&sb, "]\n")
+ }
+ return sb.String()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/reader_test.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/reader_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..393e1c80b060c0847d53908cff33e5e9ebfdeef5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/reader_test.go
@@ -0,0 +1,172 @@
+// 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 (
+ "bytes"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "internal/trace/v2"
+ "internal/trace/v2/raw"
+ "internal/trace/v2/testtrace"
+ "internal/trace/v2/version"
+)
+
+var (
+ logEvents = flag.Bool("log-events", false, "whether to log high-level events; significantly slows down tests")
+ dumpTraces = flag.Bool("dump-traces", false, "dump traces even on success")
+)
+
+func TestReaderGolden(t *testing.T) {
+ matches, err := filepath.Glob("./testdata/tests/*.test")
+ if err != nil {
+ t.Fatalf("failed to glob for tests: %v", err)
+ }
+ for _, testPath := range matches {
+ testPath := testPath
+ testName, err := filepath.Rel("./testdata", testPath)
+ if err != nil {
+ t.Fatalf("failed to relativize testdata path: %v", err)
+ }
+ t.Run(testName, func(t *testing.T) {
+ tr, exp, err := testtrace.ParseFile(testPath)
+ if err != nil {
+ t.Fatalf("failed to parse test file at %s: %v", testPath, err)
+ }
+ testReader(t, tr, exp)
+ })
+ }
+}
+
+func FuzzReader(f *testing.F) {
+ // Currently disabled because the parser doesn't do much validation and most
+ // getters can be made to panic. Turn this on once the parser is meant to
+ // reject invalid traces.
+ const testGetters = false
+
+ f.Fuzz(func(t *testing.T, b []byte) {
+ r, err := trace.NewReader(bytes.NewReader(b))
+ if err != nil {
+ return
+ }
+ for {
+ ev, err := r.ReadEvent()
+ if err != nil {
+ break
+ }
+
+ if !testGetters {
+ continue
+ }
+ // Make sure getters don't do anything that panics
+ switch ev.Kind() {
+ case trace.EventLabel:
+ ev.Label()
+ case trace.EventLog:
+ ev.Log()
+ case trace.EventMetric:
+ ev.Metric()
+ case trace.EventRangeActive, trace.EventRangeBegin:
+ ev.Range()
+ case trace.EventRangeEnd:
+ ev.Range()
+ ev.RangeAttributes()
+ case trace.EventStateTransition:
+ ev.StateTransition()
+ case trace.EventRegionBegin, trace.EventRegionEnd:
+ ev.Region()
+ case trace.EventTaskBegin, trace.EventTaskEnd:
+ ev.Task()
+ case trace.EventSync:
+ case trace.EventStackSample:
+ case trace.EventBad:
+ }
+ }
+ })
+}
+
+func testReader(t *testing.T, tr io.Reader, exp *testtrace.Expectation) {
+ r, err := trace.NewReader(tr)
+ if err != nil {
+ if err := exp.Check(err); err != nil {
+ t.Error(err)
+ }
+ return
+ }
+ v := testtrace.NewValidator()
+ for {
+ ev, err := r.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ if err := exp.Check(err); err != nil {
+ t.Error(err)
+ }
+ return
+ }
+ if *logEvents {
+ t.Log(ev.String())
+ }
+ if err := v.Event(ev); err != nil {
+ t.Error(err)
+ }
+ }
+ if err := exp.Check(nil); err != nil {
+ t.Error(err)
+ }
+}
+
+func dumpTraceToText(t *testing.T, b []byte) string {
+ t.Helper()
+
+ br, err := raw.NewReader(bytes.NewReader(b))
+ if err != nil {
+ t.Fatalf("dumping trace: %v", err)
+ }
+ var sb strings.Builder
+ tw, err := raw.NewTextWriter(&sb, version.Go122)
+ if err != nil {
+ t.Fatalf("dumping trace: %v", err)
+ }
+ for {
+ ev, err := br.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatalf("dumping trace: %v", err)
+ }
+ if err := tw.WriteEvent(ev); err != nil {
+ t.Fatalf("dumping trace: %v", err)
+ }
+ }
+ return sb.String()
+}
+
+func dumpTraceToFile(t *testing.T, testName string, stress bool, b []byte) string {
+ t.Helper()
+
+ desc := "default"
+ if stress {
+ desc = "stress"
+ }
+ name := fmt.Sprintf("%s.%s.trace.", testName, desc)
+ f, err := os.CreateTemp("", name)
+ if err != nil {
+ t.Fatalf("creating temp file: %v", err)
+ }
+ defer f.Close()
+ if _, err := io.Copy(f, bytes.NewReader(b)); err != nil {
+ t.Fatalf("writing trace dump to %q: %v", f.Name(), err)
+ }
+ return f.Name()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/resources.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/resources.go
new file mode 100644
index 0000000000000000000000000000000000000000..f49696f91c56bd5015ed73a24ba1ea82462d5cdd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/resources.go
@@ -0,0 +1,274 @@
+// 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 "fmt"
+
+// ThreadID is the runtime-internal M structure's ID. This is unique
+// for each OS thread.
+type ThreadID int64
+
+// NoThread indicates that the relevant events don't correspond to any
+// thread in particular.
+const NoThread = ThreadID(-1)
+
+// ProcID is the runtime-internal G structure's id field. This is unique
+// for each P.
+type ProcID int64
+
+// NoProc indicates that the relevant events don't correspond to any
+// P in particular.
+const NoProc = ProcID(-1)
+
+// GoID is the runtime-internal G structure's goid field. This is unique
+// for each goroutine.
+type GoID int64
+
+// NoGoroutine indicates that the relevant events don't correspond to any
+// goroutine in particular.
+const NoGoroutine = GoID(-1)
+
+// GoState represents the state of a goroutine.
+//
+// New GoStates may be added in the future. Users of this type must be robust
+// to that possibility.
+type GoState uint8
+
+const (
+ GoUndetermined GoState = iota // No information is known about the goroutine.
+ GoNotExist // Goroutine does not exist.
+ GoRunnable // Goroutine is runnable but not running.
+ GoRunning // Goroutine is running.
+ GoWaiting // Goroutine is waiting on something to happen.
+ GoSyscall // Goroutine is in a system call.
+)
+
+// Executing returns true if the state indicates that the goroutine is executing
+// and bound to its thread.
+func (s GoState) Executing() bool {
+ return s == GoRunning || s == GoSyscall
+}
+
+// String returns a human-readable representation of a GoState.
+//
+// The format of the returned string is for debugging purposes and is subject to change.
+func (s GoState) String() string {
+ switch s {
+ case GoUndetermined:
+ return "Undetermined"
+ case GoNotExist:
+ return "NotExist"
+ case GoRunnable:
+ return "Runnable"
+ case GoRunning:
+ return "Running"
+ case GoWaiting:
+ return "Waiting"
+ case GoSyscall:
+ return "Syscall"
+ }
+ return "Bad"
+}
+
+// ProcState represents the state of a proc.
+//
+// New ProcStates may be added in the future. Users of this type must be robust
+// to that possibility.
+type ProcState uint8
+
+const (
+ ProcUndetermined ProcState = iota // No information is known about the proc.
+ ProcNotExist // Proc does not exist.
+ ProcRunning // Proc is running.
+ ProcIdle // Proc is idle.
+)
+
+// Executing returns true if the state indicates that the proc is executing
+// and bound to its thread.
+func (s ProcState) Executing() bool {
+ return s == ProcRunning
+}
+
+// String returns a human-readable representation of a ProcState.
+//
+// The format of the returned string is for debugging purposes and is subject to change.
+func (s ProcState) String() string {
+ switch s {
+ case ProcUndetermined:
+ return "Undetermined"
+ case ProcNotExist:
+ return "NotExist"
+ case ProcRunning:
+ return "Running"
+ case ProcIdle:
+ return "Idle"
+ }
+ return "Bad"
+}
+
+// ResourceKind indicates a kind of resource that has a state machine.
+//
+// New ResourceKinds may be added in the future. Users of this type must be robust
+// to that possibility.
+type ResourceKind uint8
+
+const (
+ ResourceNone ResourceKind = iota // No resource.
+ ResourceGoroutine // Goroutine.
+ ResourceProc // Proc.
+ ResourceThread // Thread.
+)
+
+// String returns a human-readable representation of a ResourceKind.
+//
+// The format of the returned string is for debugging purposes and is subject to change.
+func (r ResourceKind) String() string {
+ switch r {
+ case ResourceNone:
+ return "None"
+ case ResourceGoroutine:
+ return "Goroutine"
+ case ResourceProc:
+ return "Proc"
+ case ResourceThread:
+ return "Thread"
+ }
+ return "Bad"
+}
+
+// ResourceID represents a generic resource ID.
+type ResourceID struct {
+ // Kind is the kind of resource this ID is for.
+ Kind ResourceKind
+ id int64
+}
+
+// MakeResourceID creates a general resource ID from a specific resource's ID.
+func MakeResourceID[T interface{ GoID | ProcID | ThreadID }](id T) ResourceID {
+ var rd ResourceID
+ var a any = id
+ switch a.(type) {
+ case GoID:
+ rd.Kind = ResourceGoroutine
+ case ProcID:
+ rd.Kind = ResourceProc
+ case ThreadID:
+ rd.Kind = ResourceThread
+ }
+ rd.id = int64(id)
+ return rd
+}
+
+// Goroutine obtains a GoID from the resource ID.
+//
+// r.Kind must be ResourceGoroutine or this function will panic.
+func (r ResourceID) Goroutine() GoID {
+ if r.Kind != ResourceGoroutine {
+ panic(fmt.Sprintf("attempted to get GoID from %s resource ID", r.Kind))
+ }
+ return GoID(r.id)
+}
+
+// Proc obtains a ProcID from the resource ID.
+//
+// r.Kind must be ResourceProc or this function will panic.
+func (r ResourceID) Proc() ProcID {
+ if r.Kind != ResourceProc {
+ panic(fmt.Sprintf("attempted to get ProcID from %s resource ID", r.Kind))
+ }
+ return ProcID(r.id)
+}
+
+// Thread obtains a ThreadID from the resource ID.
+//
+// r.Kind must be ResourceThread or this function will panic.
+func (r ResourceID) Thread() ThreadID {
+ if r.Kind != ResourceThread {
+ panic(fmt.Sprintf("attempted to get ThreadID from %s resource ID", r.Kind))
+ }
+ return ThreadID(r.id)
+}
+
+// String returns a human-readable string representation of the ResourceID.
+//
+// This representation is subject to change and is intended primarily for debugging.
+func (r ResourceID) String() string {
+ if r.Kind == ResourceNone {
+ return r.Kind.String()
+ }
+ return fmt.Sprintf("%s(%d)", r.Kind, r.id)
+}
+
+// StateTransition provides details about a StateTransition event.
+type StateTransition struct {
+ // Resource is the resource this state transition is for.
+ Resource ResourceID
+
+ // Reason is a human-readable reason for the state transition.
+ Reason string
+
+ // Stack is the stack trace of the resource making the state transition.
+ //
+ // This is distinct from the result (Event).Stack because it pertains to
+ // the transitioning resource, not any of the ones executing the event
+ // this StateTransition came from.
+ //
+ // An example of this difference is the NotExist -> Runnable transition for
+ // goroutines, which indicates goroutine creation. In this particular case,
+ // a Stack here would refer to the starting stack of the new goroutine, and
+ // an (Event).Stack would refer to the stack trace of whoever created the
+ // goroutine.
+ Stack Stack
+
+ // The actual transition data. Stored in a neutral form so that
+ // we don't need fields for every kind of resource.
+ id int64
+ oldState uint8
+ newState uint8
+}
+
+func goStateTransition(id GoID, from, to GoState) StateTransition {
+ return StateTransition{
+ Resource: ResourceID{Kind: ResourceGoroutine, id: int64(id)},
+ oldState: uint8(from),
+ newState: uint8(to),
+ }
+}
+
+func procStateTransition(id ProcID, from, to ProcState) StateTransition {
+ return StateTransition{
+ Resource: ResourceID{Kind: ResourceProc, id: int64(id)},
+ oldState: uint8(from),
+ newState: uint8(to),
+ }
+}
+
+// Goroutine returns the state transition for a goroutine.
+//
+// Transitions to and from states that are Executing are special in that
+// they change the future execution context. In other words, future events
+// on the same thread will feature the same goroutine until it stops running.
+//
+// Panics if d.Resource.Kind is not ResourceGoroutine.
+func (d StateTransition) Goroutine() (from, to GoState) {
+ if d.Resource.Kind != ResourceGoroutine {
+ panic("Goroutine called on non-Goroutine state transition")
+ }
+ return GoState(d.oldState), GoState(d.newState)
+}
+
+// Proc returns the state transition for a proc.
+//
+// Transitions to and from states that are Executing are special in that
+// they change the future execution context. In other words, future events
+// on the same thread will feature the same goroutine until it stops running.
+//
+// Panics if d.Resource.Kind is not ResourceProc.
+func (d StateTransition) Proc() (from, to ProcState) {
+ if d.Resource.Kind != ResourceProc {
+ panic("Proc called on non-Proc state transition")
+ }
+ return ProcState(d.oldState), ProcState(d.newState)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/README.md b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0fae9caf3711eada6856a795ab7178070abf4d00
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/README.md
@@ -0,0 +1,38 @@
+# Trace test data
+
+## Trace golden tests
+
+Trace tests can be generated by running
+
+```
+go generate .
+```
+
+with the relevant toolchain in this directory.
+
+This will put the tests into a `tests` directory where the trace reader
+tests will find them.
+
+A subset of tests can be regenerated by specifying a regexp pattern for
+the names of tests to generate in the `GOTRACETEST` environment
+variable.
+Test names are defined as the name of the `.go` file that generates the
+trace, but with the `.go` extension removed.
+
+## Trace test programs
+
+The trace test programs in the `testprog` directory generate traces to
+stdout.
+Otherwise they're just normal programs.
+
+## Trace debug commands
+
+The `cmd` directory contains helpful tools for debugging traces.
+
+* `gotraceraw` parses traces without validation.
+ It can produce a text version of the trace wire format, or convert
+ the text format back into bytes.
+* `gotracevalidate` parses traces and validates them.
+ It performs more rigorous checks than the parser does on its own,
+ which helps for debugging the parser as well.
+ In fact, it performs the exact same checks that the tests do.
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotraceraw/main.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotraceraw/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..a0d595dec11dfd585d9e1bfb14a5379151529a65
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotraceraw/main.go
@@ -0,0 +1,88 @@
+// 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 (
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+
+ "internal/trace/v2/raw"
+ "internal/trace/v2/version"
+)
+
+func init() {
+ flag.Usage = func() {
+ fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [mode]\n", os.Args[0])
+ fmt.Fprintf(flag.CommandLine.Output(), "\n")
+ fmt.Fprintf(flag.CommandLine.Output(), "Supported modes:")
+ fmt.Fprintf(flag.CommandLine.Output(), "\n")
+ fmt.Fprintf(flag.CommandLine.Output(), "* text2bytes - converts a text format trace to bytes\n")
+ fmt.Fprintf(flag.CommandLine.Output(), "* bytes2text - converts a byte format trace to text\n")
+ fmt.Fprintf(flag.CommandLine.Output(), "\n")
+ flag.PrintDefaults()
+ }
+ log.SetFlags(0)
+}
+
+func main() {
+ flag.Parse()
+ if narg := flag.NArg(); narg != 1 {
+ log.Fatal("expected exactly one positional argument: the mode to operate in; see -h output")
+ }
+
+ r := os.Stdin
+ w := os.Stdout
+
+ var tr traceReader
+ var tw traceWriter
+ var err error
+
+ switch flag.Arg(0) {
+ case "text2bytes":
+ tr, err = raw.NewTextReader(r)
+ if err != nil {
+ log.Fatal(err)
+ }
+ tw, err = raw.NewWriter(w, tr.Version())
+ if err != nil {
+ log.Fatal(err)
+ }
+ case "bytes2text":
+ tr, err = raw.NewReader(r)
+ if err != nil {
+ log.Fatal(err)
+ }
+ tw, err = raw.NewTextWriter(w, tr.Version())
+ if err != nil {
+ log.Fatal(err)
+ }
+ }
+ for {
+ ev, err := tr.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatal(err)
+ break
+ }
+ if err := tw.WriteEvent(ev); err != nil {
+ log.Fatal(err)
+ break
+ }
+ }
+}
+
+type traceReader interface {
+ Version() version.Version
+ ReadEvent() (raw.Event, error)
+}
+
+type traceWriter interface {
+ WriteEvent(raw.Event) error
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotracevalidate/main.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotracevalidate/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..944d19f85ee53521cb88dfa512f9ebcf2958306d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/cmd/gotracevalidate/main.go
@@ -0,0 +1,53 @@
+// 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 (
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+
+ "internal/trace/v2"
+ "internal/trace/v2/testtrace"
+)
+
+func init() {
+ flag.Usage = func() {
+ fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s\n", os.Args[0])
+ fmt.Fprintf(flag.CommandLine.Output(), "\n")
+ fmt.Fprintf(flag.CommandLine.Output(), "Accepts a trace at stdin and validates it.\n")
+ flag.PrintDefaults()
+ }
+ log.SetFlags(0)
+}
+
+var logEvents = flag.Bool("log-events", false, "whether to log events")
+
+func main() {
+ flag.Parse()
+
+ r, err := trace.NewReader(os.Stdin)
+ if err != nil {
+ log.Fatal(err)
+ }
+ v := testtrace.NewValidator()
+ for {
+ ev, err := r.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+ if *logEvents {
+ log.Println(ev.String())
+ }
+ if err := v.Event(ev); err != nil {
+ log.Fatal(err)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/0cb1786dee0f090b b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/0cb1786dee0f090b
new file mode 100644
index 0000000000000000000000000000000000000000..326ebe1c6e59bc49d8ebf139b7ea520d24c95f2c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/0cb1786dee0f090b
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x190000\x01\x0100\x88\x00\b0000000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/1e45307d5b2ec36d b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/1e45307d5b2ec36d
new file mode 100644
index 0000000000000000000000000000000000000000..406af9caa6b37e5959bad4978f4cb90230a0b692
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/1e45307d5b2ec36d
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01000\x85\x00\b0001")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b05796f9b2fc48d b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b05796f9b2fc48d
new file mode 100644
index 0000000000000000000000000000000000000000..50fdccda6b228954c54c158b7536bd3f49620cc2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b05796f9b2fc48d
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00-0000\x01\x0100\x88\x00\b0000000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b9be9aebe08d511 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b9be9aebe08d511
new file mode 100644
index 0000000000000000000000000000000000000000..6bcb99adfc639a34d47e1a39f681a7dd2ff71db6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/2b9be9aebe08d511
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x0f00\x120\x01\x0100\x88\x00\b0000000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/344331b314da0b08 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/344331b314da0b08
new file mode 100644
index 0000000000000000000000000000000000000000..de6e4694be8bca95e35adc94bc2d7752c9daad4e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/344331b314da0b08
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\b0000\x01\x01\xff00\xb8\x00\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1900\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x04\x1901\xff\xff\xff\xff\xff\xff\xff\xff0\x800")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/365d7b5b633b3f97 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/365d7b5b633b3f97
new file mode 100644
index 0000000000000000000000000000000000000000..8dc370f383c22549750a05244c9fc57380c41d48
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/365d7b5b633b3f97
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x0100\x8c0\x85\x00\b0000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/4d9ddc909984e871 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/4d9ddc909984e871
new file mode 100644
index 0000000000000000000000000000000000000000..040b2a4cae3f2eecd30f092b7ebca1dd04055a52
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/4d9ddc909984e871
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x11\r\xa700\x01\x19000\x02$000000\x01\x0100\x05\b0000\x01\x0110\x11\r\xa700\x01\x19 00\x02\x110 0000")
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/56f073e57903588c b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/56f073e57903588c
new file mode 100644
index 0000000000000000000000000000000000000000..d34fe3f06c800f1a46c300ece073d492d188484b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/56f073e57903588c
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x1f0000\x01\x0100\x88\x00\b0000000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566
new file mode 100644
index 0000000000000000000000000000000000000000..56772611555a7e27e7d57f1ebb8c9fa9743066ba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/9d6ee7d3ddf8d566
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x11\r\xa700\x01\x19000\x02#000000\x01\x0100\x05\b0000\x01\x0110\x11\r\xa700\x01\x19 00\x02\x110 0000")
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/aeb749b6bc317b66 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/aeb749b6bc317b66
new file mode 100644
index 0000000000000000000000000000000000000000..f93b5a90dad804a64d1002c76df65fc403636079
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/aeb749b6bc317b66
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01000\x85\x00\b0000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/closing-unknown-region b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/closing-unknown-region
new file mode 100644
index 0000000000000000000000000000000000000000..743321403038a25732ef8ba70ff0c105b7f3d3cd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/closing-unknown-region
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xf6\x9f\n\x9fÕ\xb4\x99\xb2\x06\x11\r\xa7\x02\x00\x01\x19\x05\x01\xf6\x9f\n\x02+\x04\x01\x00\x00")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d478e18d2d6756b7 b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d478e18d2d6756b7
new file mode 100644
index 0000000000000000000000000000000000000000..3e5fda833a93f1ab150098f6cedf40d408235d9c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d478e18d2d6756b7
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\"0000\x01\x0100\x88\x00\b0000000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d91203cd397aa0bc b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d91203cd397aa0bc
new file mode 100644
index 0000000000000000000000000000000000000000..d24b94ac9778aa1ee1e43d4b9b01d7170580ea55
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/d91203cd397aa0bc
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01001\x85\x00\b0000")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/invalid-proc-state b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/invalid-proc-state
new file mode 100644
index 0000000000000000000000000000000000000000..e5d3258111361dc30b31466720ea1a68a045727e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/invalid-proc-state
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x94镴\x99\xb2\x06\x05\r\xa7\x02\x00E")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/large-id b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/large-id
new file mode 100644
index 0000000000000000000000000000000000000000..0fb6273b443fab77d511874404d0f88c7cb37c4b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/large-id
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x94镴\x99\xb2\x06\f\x02\x03\xff\xff\xff\xff\xff\xff\xff\x9f\x1d\x00")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/malformed-timestamp b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/malformed-timestamp
new file mode 100644
index 0000000000000000000000000000000000000000..850ca50f87f35c999566f4c136ab2aba82bd777f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/fuzz/FuzzReader/malformed-timestamp
@@ -0,0 +1,2 @@
+go test fuzz v1
+[]byte("go 1.22 trace\x00\x00\x00\x01\x01\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x87ߕ\xb4\x99\xb2\x06\x05\b\xa8ֹ\a\x01\x01\xfa\x9f\n\xa5ѕ\xb4\x99\xb2\x06\x0e\n\x97\x96\x96\x96\x96\x96\x96\x96\x96\x96\x01\x01\x01")
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generate.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generate.go
new file mode 100644
index 0000000000000000000000000000000000000000..c0658b2329667c3c341cad241403543cf2e6fa41
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generate.go
@@ -0,0 +1,6 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:generate go run mktests.go
+package testdata
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-confuse-seq-across-generations.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-confuse-seq-across-generations.go
new file mode 100644
index 0000000000000000000000000000000000000000..f618c41e78ba85faacbc9b258494296ef3fa21e7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-confuse-seq-across-generations.go
@@ -0,0 +1,62 @@
+// 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.
+
+// Regression test for an issue found in development.
+//
+// The core of the issue is that if generation counters
+// aren't considered as part of sequence numbers, then
+// it's possible to accidentally advance without a
+// GoStatus event.
+//
+// The situation is one in which it just so happens that
+// an event on the frontier for a following generation
+// has a sequence number exactly one higher than the last
+// sequence number for e.g. a goroutine in the previous
+// generation. The parser should wait to find a GoStatus
+// event before advancing into the next generation at all.
+// It turns out this situation is pretty rare; the GoStatus
+// event almost always shows up first in practice. But it
+// can and did happen.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g1 := t.Generation(1)
+
+ // A running goroutine blocks.
+ b10 := g1.Batch(trace.ThreadID(0), 0)
+ b10.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b10.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b10.Event("GoStop", "whatever", testgen.NoStack)
+
+ // The running goroutine gets unblocked.
+ b11 := g1.Batch(trace.ThreadID(1), 0)
+ b11.Event("ProcStatus", trace.ProcID(1), go122.ProcRunning)
+ b11.Event("GoStart", trace.GoID(1), testgen.Seq(1))
+ b11.Event("GoStop", "whatever", testgen.NoStack)
+
+ g2 := t.Generation(2)
+
+ // Start running the goroutine, but later.
+ b21 := g2.Batch(trace.ThreadID(1), 3)
+ b21.Event("ProcStatus", trace.ProcID(1), go122.ProcRunning)
+ b21.Event("GoStart", trace.GoID(1), testgen.Seq(2))
+
+ // The goroutine starts running, then stops, then starts again.
+ b20 := g2.Batch(trace.ThreadID(0), 5)
+ b20.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b20.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunnable)
+ b20.Event("GoStart", trace.GoID(1), testgen.Seq(1))
+ b20.Event("GoStop", "whatever", testgen.NoStack)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-reuse-thread-id.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-reuse-thread-id.go
new file mode 100644
index 0000000000000000000000000000000000000000..107cce2cc29c2d032ff48692801198301e56efce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-reuse-thread-id.go
@@ -0,0 +1,61 @@
+// 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 a G being created from within a syscall.
+//
+// Specifically, it tests a scenerio wherein a C
+// thread is calling into Go, creating a goroutine in
+// a syscall (in the tracer's model). The system is free
+// to reuse thread IDs, so first a thread ID is used to
+// call into Go, and then is used for a Go-created thread.
+//
+// This is a regression test. The trace parser didn't correctly
+// model GoDestroySyscall as dropping its P (even if the runtime
+// did). It turns out this is actually fine if all the threads
+// in the trace have unique IDs, since the P just stays associated
+// with an eternally dead thread, and it's stolen by some other
+// thread later. But if thread IDs are reused, then the tracer
+// gets confused when trying to advance events on the new thread.
+// The now-dead thread which exited on a GoDestroySyscall still has
+// its P associated and this transfers to the newly-live thread
+// in the parser's state because they share a thread ID.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // A C thread calls into Go and acquires a P. It returns
+ // back to C, destroying the G.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("GoCreateSyscall", trace.GoID(4))
+ b0.Event("GoSyscallEndBlocked")
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcIdle)
+ b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(1))
+ b0.Event("GoStatus", trace.GoID(4), trace.NoThread, go122.GoRunnable)
+ b0.Event("GoStart", trace.GoID(4), testgen.Seq(1))
+ b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack)
+ b0.Event("GoDestroySyscall")
+
+ // A new Go-created thread with the same ID appears and
+ // starts running, then tries to steal the P from the
+ // first thread. The stealing is interesting because if
+ // the parser handles GoDestroySyscall wrong, then we
+ // have a self-steal here potentially that doesn't make
+ // sense.
+ b1 := g.Batch(trace.ThreadID(0), 0)
+ b1.Event("ProcStatus", trace.ProcID(1), go122.ProcIdle)
+ b1.Event("ProcStart", trace.ProcID(1), testgen.Seq(1))
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(3), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-with-p.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-with-p.go
new file mode 100644
index 0000000000000000000000000000000000000000..4cb1c4a9a770a2545eb35fdc6fa4e80e77ca8049
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-create-syscall-with-p.go
@@ -0,0 +1,52 @@
+// 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 a G being created from within a syscall.
+//
+// Specifically, it tests a scenerio wherein a C
+// thread is calling into Go, creating a goroutine in
+// a syscall (in the tracer's model). Because the actual
+// m can be reused, it's possible for that m to have never
+// had its P (in _Psyscall) stolen if the runtime doesn't
+// model the scenario correctly. Make sure we reject such
+// traces.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ t.ExpectFailure(".*expected a proc but didn't have one.*")
+
+ g := t.Generation(1)
+
+ // A C thread calls into Go and acquires a P. It returns
+ // back to C, destroying the G. It then comes back to Go
+ // on the same thread and again returns to C.
+ //
+ // Note: on pthread platforms this can't happen on the
+ // same thread because the m is stashed in TLS between
+ // calls into Go, until the thread dies. This is still
+ // possible on other platforms, however.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("GoCreateSyscall", trace.GoID(4))
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcIdle)
+ b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(1))
+ b0.Event("GoSyscallEndBlocked")
+ b0.Event("GoStart", trace.GoID(4), testgen.Seq(1))
+ b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack)
+ b0.Event("GoDestroySyscall")
+ b0.Event("GoCreateSyscall", trace.GoID(4))
+ b0.Event("GoSyscallEnd")
+ b0.Event("GoSyscallBegin", testgen.Seq(3), testgen.NoStack)
+ b0.Event("GoDestroySyscall")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-go-create-without-running-g.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-go-create-without-running-g.go
new file mode 100644
index 0000000000000000000000000000000000000000..b693245b5b47c769c3e4145a303b18b2f53e6aea
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-go-create-without-running-g.go
@@ -0,0 +1,33 @@
+// 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.
+
+// Regression test for an issue found in development.
+//
+// GoCreate events can happen on bare Ps in a variety of situations and
+// and earlier version of the parser assumed this wasn't possible. At
+// the time of writing, one such example is goroutines created by expiring
+// timers.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g1 := t.Generation(1)
+
+ // A goroutine gets created on a running P, then starts running.
+ b0 := g1.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoCreate", trace.GoID(5), testgen.NoStack, testgen.NoStack)
+ b0.Event("GoStart", trace.GoID(5), testgen.Seq(1))
+ b0.Event("GoStop", "whatever", testgen.NoStack)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-ambiguous.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-ambiguous.go
new file mode 100644
index 0000000000000000000000000000000000000000..349a575ef385cb8351472fb6f8c671351ef3a87b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-ambiguous.go
@@ -0,0 +1,46 @@
+// 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.
+//
+// Specifically, it tests a scenerio wherein, without a
+// P sequence number of GoSyscallBegin, the syscall that
+// a ProcSteal applies to is ambiguous. This only happens in
+// practice when the events aren't already properly ordered
+// by timestamp, since the ProcSteal won't be seen until after
+// the correct GoSyscallBegin appears on the frontier.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ t.DisableTimestamps()
+
+ g := t.Generation(1)
+
+ // One goroutine does a syscall without blocking, then another one where
+ // it's P gets stolen.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("GoSyscallEnd")
+ b0.Event("GoSyscallBegin", testgen.Seq(2), testgen.NoStack)
+ b0.Event("GoSyscallEndBlocked")
+
+ // A running goroutine steals proc 0.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcStatus", trace.ProcID(2), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), go122.GoRunning)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(3), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go
new file mode 100644
index 0000000000000000000000000000000000000000..f4c9f6ecf3bab77cf020b13f12ce46a0c74e04ee
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go
@@ -0,0 +1,33 @@
+// 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/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/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))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go
new file mode 100644
index 0000000000000000000000000000000000000000..e6023ba70194f0d188bdc70e2b571e065dddff9f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.go
@@ -0,0 +1,34 @@
+// 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/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/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("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoSyscall)
+ b0.Event("ProcStatus", trace.ProcID(1), go122.ProcIdle)
+ b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1))
+ 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))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go
new file mode 100644
index 0000000000000000000000000000000000000000..2232dca5dc46dc6a3586fe82b54e64b252e7e59f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.go
@@ -0,0 +1,36 @@
+// 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/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/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("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoSyscall)
+ b0.Event("ProcStatus", trace.ProcID(1), go122.ProcIdle)
+ b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1))
+ b0.Event("GoSyscallEndBlocked")
+
+ // A running goroutine stole P0 at the generation boundary.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcStatus", trace.ProcID(2), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), go122.GoRunning)
+ b1.Event("ProcStatus", trace.ProcID(0), go122.ProcSyscallAbandoned)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary.go
new file mode 100644
index 0000000000000000000000000000000000000000..710827a8f65b388122a488f97e5fdf8ff001b434
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-gen-boundary.go
@@ -0,0 +1,35 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Tests syscall P stealing at a generation boundary.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/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 running goroutine stole P0 at the generation boundary.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcStatus", trace.ProcID(2), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), go122.GoRunning)
+ b1.Event("ProcStatus", trace.ProcID(0), go122.ProcSyscallAbandoned)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go
new file mode 100644
index 0000000000000000000000000000000000000000..24e5cb2a3eb75fc90ce15a619157ee289fa6fd1a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc-bare-m.go
@@ -0,0 +1,34 @@
+// 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.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // One goroutine enters a syscall, grabs a P, and starts running.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(1), go122.ProcIdle)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1))
+ b0.Event("GoSyscallEndBlocked")
+
+ // A bare M steals the goroutine's P.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go
new file mode 100644
index 0000000000000000000000000000000000000000..2caefe8be5c00646bc949bf49dd23d69c8654dab
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-reacquire-new-proc.go
@@ -0,0 +1,36 @@
+// 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.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // One goroutine enters a syscall, grabs a P, and starts running.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(1), go122.ProcIdle)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("ProcStart", trace.ProcID(1), testgen.Seq(1))
+ b0.Event("GoSyscallEndBlocked")
+
+ // A running goroutine steals proc 0.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcStatus", trace.ProcID(2), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), go122.GoRunning)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-self.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-self.go
new file mode 100644
index 0000000000000000000000000000000000000000..dd947346c6f7ebc6cffe89b8a215d4458d2c7190
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-self.go
@@ -0,0 +1,37 @@
+// 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.
+//
+// Specifically, it tests a scenario where a thread 'steals'
+// a P from itself. It's just a ProcStop with extra steps when
+// it happens on the same P.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ t.DisableTimestamps()
+
+ g := t.Generation(1)
+
+ // A goroutine execute a syscall and steals its own P, then starts running
+ // on that P.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0))
+ b0.Event("ProcStart", trace.ProcID(0), testgen.Seq(3))
+ b0.Event("GoSyscallEndBlocked")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go
new file mode 100644
index 0000000000000000000000000000000000000000..630eba8cf298587a01f1ace8de220cd7cfbdb36d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple-bare-m.go
@@ -0,0 +1,32 @@
+// 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.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // One goroutine enters a syscall.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("GoSyscallEndBlocked")
+
+ // A bare M steals the goroutine's P.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple.go
new file mode 100644
index 0000000000000000000000000000000000000000..54b43f4f0b1394c6e6b0cb3438b777fa438332c2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-simple.go
@@ -0,0 +1,34 @@
+// 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.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // One goroutine enters a syscall.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b0.Event("GoSyscallBegin", testgen.Seq(1), testgen.NoStack)
+ b0.Event("GoSyscallEndBlocked")
+
+ // A running goroutine steals proc 0.
+ b1 := g.Batch(trace.ThreadID(1), 0)
+ b1.Event("ProcStatus", trace.ProcID(2), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(2), trace.ThreadID(1), go122.GoRunning)
+ b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(2), trace.ThreadID(0))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go
new file mode 100644
index 0000000000000000000000000000000000000000..870f8f69f601016777fd8e50d215048146deb1f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-syscall-steal-proc-sitting-in-syscall.go
@@ -0,0 +1,32 @@
+// 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 from a goroutine and thread
+// that have been in a syscall the entire generation.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g := t.Generation(1)
+
+ // Steal proc from a goroutine that's been blocked
+ // in a syscall the entire generation.
+ b0 := g.Batch(trace.ThreadID(0), 0)
+ b0.Event("ProcStatus", trace.ProcID(0), go122.ProcSyscallAbandoned)
+ b0.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(1))
+
+ // Status event for a goroutine blocked in a syscall for the entire generation.
+ bz := g.Batch(trace.NoThread, 0)
+ bz.Event("GoStatus", trace.GoID(1), trace.ThreadID(1), go122.GoSyscall)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-task-across-generations.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-task-across-generations.go
new file mode 100644
index 0000000000000000000000000000000000000000..06ef96e51a235832e87cc50dfd8b69f3da73eda9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/generators/go122-task-across-generations.go
@@ -0,0 +1,41 @@
+// 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.
+
+// Regression test for an issue found in development.
+//
+// The issue is that EvUserTaskEnd events don't carry the
+// task type with them, so the parser needs to track that
+// information. But if the parser just tracks the string ID
+// and not the string itself, that string ID may not be valid
+// for use in future generations.
+
+package main
+
+import (
+ "internal/trace/v2"
+ "internal/trace/v2/event/go122"
+ testgen "internal/trace/v2/internal/testgen/go122"
+)
+
+func main() {
+ testgen.Main(gen)
+}
+
+func gen(t *testgen.Trace) {
+ g1 := t.Generation(1)
+
+ // A running goroutine emits a task begin.
+ b1 := g1.Batch(trace.ThreadID(0), 0)
+ b1.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b1.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b1.Event("UserTaskBegin", trace.TaskID(2), trace.TaskID(0) /* 0 means no parent, not background */, "my task", testgen.NoStack)
+
+ g2 := t.Generation(2)
+
+ // That same goroutine emits a task end in the following generation.
+ b2 := g2.Batch(trace.ThreadID(0), 5)
+ b2.Event("ProcStatus", trace.ProcID(0), go122.ProcRunning)
+ b2.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoRunning)
+ b2.Event("UserTaskEnd", trace.TaskID(2), testgen.NoStack)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/mktests.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/mktests.go
new file mode 100644
index 0000000000000000000000000000000000000000..96cbbe4b1fd6d2f69e0222d22c18b1a79e0509be
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/mktests.go
@@ -0,0 +1,162 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build ignore
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "internal/trace/v2/raw"
+ "internal/trace/v2/version"
+ "internal/txtar"
+ "io"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+)
+
+func main() {
+ log.SetFlags(0)
+ ctx, err := newContext()
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := ctx.runGenerators(); err != nil {
+ log.Fatal(err)
+ }
+ if err := ctx.runTestProg("./testprog/annotations.go"); err != nil {
+ log.Fatal(err)
+ }
+ if err := ctx.runTestProg("./testprog/annotations-stress.go"); err != nil {
+ log.Fatal(err)
+ }
+}
+
+type context struct {
+ testNames map[string]struct{}
+ filter *regexp.Regexp
+}
+
+func newContext() (*context, error) {
+ var filter *regexp.Regexp
+ var err error
+ if pattern := os.Getenv("GOTRACETEST"); pattern != "" {
+ filter, err = regexp.Compile(pattern)
+ if err != nil {
+ return nil, fmt.Errorf("compiling regexp %q for GOTRACETEST: %v", pattern, err)
+ }
+ }
+ return &context{
+ testNames: make(map[string]struct{}),
+ filter: filter,
+ }, nil
+}
+
+func (ctx *context) register(testName string) (skip bool, err error) {
+ if _, ok := ctx.testNames[testName]; ok {
+ return true, fmt.Errorf("duplicate test %s found", testName)
+ }
+ if ctx.filter != nil {
+ return !ctx.filter.MatchString(testName), nil
+ }
+ return false, nil
+}
+
+func (ctx *context) runGenerators() error {
+ generators, err := filepath.Glob("./generators/*.go")
+ if err != nil {
+ return fmt.Errorf("reading generators: %v", err)
+ }
+ genroot := "./tests"
+
+ if err := os.MkdirAll(genroot, 0777); err != nil {
+ return fmt.Errorf("creating generated root: %v", err)
+ }
+ for _, path := range generators {
+ name := filepath.Base(path)
+ name = name[:len(name)-len(filepath.Ext(name))]
+
+ // Skip if we have a pattern and this test doesn't match.
+ skip, err := ctx.register(name)
+ if err != nil {
+ return err
+ }
+ if skip {
+ continue
+ }
+
+ fmt.Fprintf(os.Stderr, "generating %s... ", name)
+
+ // Get the test path.
+ testPath := filepath.Join(genroot, fmt.Sprintf("%s.test", name))
+
+ // Run generator.
+ cmd := exec.Command("go", "run", path, testPath)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("running generator %s: %v:\n%s", name, err, out)
+ }
+ fmt.Fprintln(os.Stderr)
+ }
+ return nil
+}
+
+func (ctx *context) runTestProg(progPath string) error {
+ name := filepath.Base(progPath)
+ name = name[:len(name)-len(filepath.Ext(name))]
+ name = fmt.Sprintf("go1%d-%s", version.Current, name)
+
+ // Skip if we have a pattern and this test doesn't match.
+ skip, err := ctx.register(name)
+ if err != nil {
+ return err
+ }
+ if skip {
+ return nil
+ }
+
+ // Create command.
+ var trace, stderr bytes.Buffer
+ cmd := exec.Command("go", "run", progPath)
+ // TODO(mknyszek): Remove if goexperiment.Exectracer2 becomes the default.
+ cmd.Env = append(os.Environ(), "GOEXPERIMENT=exectracer2")
+ cmd.Stdout = &trace
+ cmd.Stderr = &stderr
+
+ // Run trace program; the trace will appear in stdout.
+ fmt.Fprintf(os.Stderr, "running trace program %s...\n", name)
+ if err := cmd.Run(); err != nil {
+ log.Fatalf("running trace program: %v:\n%s", err, stderr.String())
+ }
+
+ // Write out the trace.
+ var textTrace bytes.Buffer
+ r, err := raw.NewReader(&trace)
+ if err != nil {
+ log.Fatalf("reading trace: %v", err)
+ }
+ w, err := raw.NewTextWriter(&textTrace, version.Current)
+ for {
+ ev, err := r.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ log.Fatalf("reading trace: %v", err)
+ }
+ if err := w.WriteEvent(ev); err != nil {
+ log.Fatalf("writing trace: %v", err)
+ }
+ }
+ testData := txtar.Format(&txtar.Archive{
+ Files: []txtar.File{
+ {Name: "expect", Data: []byte("SUCCESS")},
+ {Name: "trace", Data: textTrace.Bytes()},
+ },
+ })
+ return os.WriteFile(fmt.Sprintf("./tests/%s.test", name), testData, 0o664)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations-stress.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations-stress.go
new file mode 100644
index 0000000000000000000000000000000000000000..511d6ed890b25c0e19e67e6425813ef4bea618a7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations-stress.go
@@ -0,0 +1,84 @@
+// 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 user tasks, regions, and logging.
+
+//go:build ignore
+
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "runtime/trace"
+ "time"
+)
+
+func main() {
+ baseCtx := context.Background()
+
+ // Create a task that starts and ends entirely outside of the trace.
+ ctx0, t0 := trace.NewTask(baseCtx, "parent")
+
+ // Create a task that starts before the trace and ends during the trace.
+ ctx1, t1 := trace.NewTask(ctx0, "type1")
+
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ t1.End()
+
+ // Create a task that starts during the trace and ends after.
+ ctx2, t2 := trace.NewTask(ctx0, "type2")
+
+ // Create a task that starts and ends during the trace.
+ ctx3, t3 := trace.NewTask(baseCtx, "type3")
+
+ // Generate some events.
+ for i := 0; i < 2; i++ {
+ do(baseCtx, 4)
+ do(ctx0, 2)
+ do(ctx1, 3)
+ do(ctx2, 6)
+ do(ctx3, 5)
+ }
+
+ // Finish up tasks according to their lifetime relative to the trace.
+ t3.End()
+ trace.Stop()
+ t2.End()
+ t0.End()
+}
+
+func do(ctx context.Context, k int) {
+ trace.Log(ctx, "log", "before do")
+
+ var t *trace.Task
+ ctx, t = trace.NewTask(ctx, "do")
+ defer t.End()
+
+ trace.Log(ctx, "log2", "do")
+
+ // Create a region and spawn more tasks and more workers.
+ trace.WithRegion(ctx, "fanout", func() {
+ for i := 0; i < k; i++ {
+ go func(i int) {
+ trace.WithRegion(ctx, fmt.Sprintf("region%d", i), func() {
+ trace.Logf(ctx, "log", "fanout region%d", i)
+ if i == 2 {
+ do(ctx, 0)
+ return
+ }
+ })
+ }(i)
+ }
+ })
+
+ // Sleep to let things happen, but also increase the chance that we
+ // advance a generation.
+ time.Sleep(10 * time.Millisecond)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations.go
new file mode 100644
index 0000000000000000000000000000000000000000..2507bc4d3890d1f7a1cbb8c99106b3ecce8595f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/annotations.go
@@ -0,0 +1,60 @@
+// 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 user tasks, regions, and logging.
+
+//go:build ignore
+
+package main
+
+import (
+ "context"
+ "log"
+ "os"
+ "runtime/trace"
+ "sync"
+)
+
+func main() {
+ bgctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ // Create a pre-existing region. This won't end up in the trace.
+ preExistingRegion := trace.StartRegion(bgctx, "pre-existing region")
+
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+
+ // Beginning of traced execution.
+ var wg sync.WaitGroup
+ ctx, task := trace.NewTask(bgctx, "task0") // EvUserTaskCreate("task0")
+ trace.StartRegion(ctx, "task0 region")
+
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer task.End() // EvUserTaskEnd("task0")
+
+ trace.StartRegion(ctx, "unended region")
+
+ trace.WithRegion(ctx, "region0", func() {
+ // EvUserRegionBegin("region0", start)
+ trace.WithRegion(ctx, "region1", func() {
+ trace.Log(ctx, "key0", "0123456789abcdef") // EvUserLog("task0", "key0", "0....f")
+ })
+ // EvUserRegionEnd("region0", end)
+ })
+ }()
+ wg.Wait()
+
+ preExistingRegion.End()
+ postExistingRegion := trace.StartRegion(bgctx, "post-existing region")
+
+ // End of traced execution.
+ trace.Stop()
+
+ postExistingRegion.End()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cgo-callback.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cgo-callback.go
new file mode 100644
index 0000000000000000000000000000000000000000..d63650047e584f50bf493c54669d1945dce7fb48
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cgo-callback.go
@@ -0,0 +1,80 @@
+// 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 CPU profiling.
+
+//go:build ignore
+
+package main
+
+/*
+#include
+
+void go_callback();
+void go_callback2();
+
+static void *thr(void *arg) {
+ go_callback();
+ return 0;
+}
+
+static void foo() {
+ pthread_t th;
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setstacksize(&attr, 256 << 10);
+ pthread_create(&th, &attr, thr, 0);
+ pthread_join(th, 0);
+}
+
+static void bar() {
+ go_callback2();
+}
+*/
+import "C"
+
+import (
+ "log"
+ "os"
+ "runtime"
+ "runtime/trace"
+)
+
+//export go_callback
+func go_callback() {
+ // Do another call into C, just to test that path too.
+ C.bar()
+}
+
+//export go_callback2
+func go_callback2() {
+ runtime.GC()
+}
+
+func main() {
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+
+ // Do a whole bunch of cgocallbacks.
+ const n = 10
+ done := make(chan bool)
+ for i := 0; i < n; i++ {
+ go func() {
+ C.foo()
+ done <- true
+ }()
+ }
+ for i := 0; i < n; i++ {
+ <-done
+ }
+
+ // Do something to steal back any Ps from the Ms, just
+ // for coverage.
+ runtime.GC()
+
+ // End of traced execution.
+ trace.Stop()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cpu-profile.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cpu-profile.go
new file mode 100644
index 0000000000000000000000000000000000000000..293a2acac8a2bf2434b868fbb68c4f28cacb6f6a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/cpu-profile.go
@@ -0,0 +1,137 @@
+// 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 CPU profiling.
+
+//go:build ignore
+
+package main
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "internal/profile"
+ "log"
+ "os"
+ "runtime"
+ "runtime/pprof"
+ "runtime/trace"
+ "strings"
+ "time"
+)
+
+func main() {
+ cpuBuf := new(bytes.Buffer)
+ if err := pprof.StartCPUProfile(cpuBuf); err != nil {
+ log.Fatalf("failed to start CPU profile: %v", err)
+ }
+
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+
+ dur := 100 * time.Millisecond
+ func() {
+ // Create a region in the execution trace. Set and clear goroutine
+ // labels fully within that region, so we know that any CPU profile
+ // sample with the label must also be eligible for inclusion in the
+ // execution trace.
+ ctx := context.Background()
+ defer trace.StartRegion(ctx, "cpuHogger").End()
+ pprof.Do(ctx, pprof.Labels("tracing", "on"), func(ctx context.Context) {
+ cpuHogger(cpuHog1, &salt1, dur)
+ })
+ // Be sure the execution trace's view, when filtered to this goroutine
+ // via the explicit goroutine ID in each event, gets many more samples
+ // than the CPU profiler when filtered to this goroutine via labels.
+ cpuHogger(cpuHog1, &salt1, dur)
+ }()
+
+ trace.Stop()
+ pprof.StopCPUProfile()
+
+ // Summarize the CPU profile to stderr so the test can check against it.
+
+ prof, err := profile.Parse(cpuBuf)
+ if err != nil {
+ log.Fatalf("failed to parse CPU profile: %v", err)
+ }
+ // Examine the CPU profiler's view. Filter it to only include samples from
+ // the single test goroutine. Use labels to execute that filter: they should
+ // apply to all work done while that goroutine is getg().m.curg, and they
+ // should apply to no other goroutines.
+ pprofStacks := make(map[string]int)
+ for _, s := range prof.Sample {
+ if s.Label["tracing"] != nil {
+ var fns []string
+ var leaf string
+ for _, loc := range s.Location {
+ for _, line := range loc.Line {
+ fns = append(fns, fmt.Sprintf("%s:%d", line.Function.Name, line.Line))
+ leaf = line.Function.Name
+ }
+ }
+ // runtime.sigprof synthesizes call stacks when "normal traceback is
+ // impossible or has failed", using particular placeholder functions
+ // to represent common failure cases. Look for those functions in
+ // the leaf position as a sign that the call stack and its
+ // symbolization are more complex than this test can handle.
+ //
+ // TODO: Make the symbolization done by the execution tracer and CPU
+ // profiler match up even in these harder cases. See #53378.
+ switch leaf {
+ case "runtime._System", "runtime._GC", "runtime._ExternalCode", "runtime._VDSO":
+ continue
+ }
+ stack := strings.Join(fns, "|")
+ samples := int(s.Value[0])
+ pprofStacks[stack] += samples
+ }
+ }
+ for stack, samples := range pprofStacks {
+ fmt.Fprintf(os.Stderr, "%s\t%d\n", stack, samples)
+ }
+}
+
+func cpuHogger(f func(x int) int, y *int, dur time.Duration) {
+ // We only need to get one 100 Hz clock tick, so we've got
+ // a large safety buffer.
+ // But do at least 500 iterations (which should take about 100ms),
+ // otherwise TestCPUProfileMultithreaded can fail if only one
+ // thread is scheduled during the testing period.
+ t0 := time.Now()
+ accum := *y
+ for i := 0; i < 500 || time.Since(t0) < dur; i++ {
+ accum = f(accum)
+ }
+ *y = accum
+}
+
+var (
+ salt1 = 0
+)
+
+// The actual CPU hogging function.
+// Must not call other functions nor access heap/globals in the loop,
+// otherwise under race detector the samples will be in the race runtime.
+func cpuHog1(x int) int {
+ return cpuHog0(x, 1e5)
+}
+
+func cpuHog0(x, n int) int {
+ foo := x
+ for i := 0; i < n; i++ {
+ if i%1000 == 0 {
+ // Spend time in mcall, stored as gp.m.curg, with g0 running
+ runtime.Gosched()
+ }
+ if foo > 0 {
+ foo *= foo
+ } else {
+ foo *= foo + 1
+ }
+ }
+ return foo
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/futile-wakeup.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/futile-wakeup.go
new file mode 100644
index 0000000000000000000000000000000000000000..cc489818fc9fcb5bf98d15b705198c0450bff15f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/futile-wakeup.go
@@ -0,0 +1,84 @@
+// 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()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gc-stress.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gc-stress.go
new file mode 100644
index 0000000000000000000000000000000000000000..70d3a246c397f46e8dfc3b9d7031fcc181a629b4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gc-stress.go
@@ -0,0 +1,76 @@
+// 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 a GC-heavy program. This is useful for shaking out
+// all sorts of corner cases about GC-related ranges.
+
+//go:build ignore
+
+package main
+
+import (
+ "log"
+ "math/rand"
+ "os"
+ "runtime"
+ "runtime/trace"
+ "time"
+)
+
+type node struct {
+ children [4]*node
+ data [128]byte
+}
+
+func makeTree(depth int) *node {
+ if depth == 0 {
+ return new(node)
+ }
+ return &node{
+ children: [4]*node{
+ makeTree(depth - 1),
+ makeTree(depth - 1),
+ makeTree(depth - 1),
+ makeTree(depth - 1),
+ },
+ }
+}
+
+var trees [16]*node
+var ballast *[16]*[8192]*node
+var sink []byte
+
+func main() {
+ for i := range trees {
+ trees[i] = makeTree(6)
+ }
+ ballast = new([16]*[8192]*node)
+ for i := range ballast {
+ ballast[i] = new([8192]*node)
+ for j := range ballast[i] {
+ ballast[i][j] = &node{
+ data: [128]byte{1, 2, 3, 4},
+ }
+ }
+ }
+ for i := 0; i < runtime.GOMAXPROCS(-1); i++ {
+ go func() {
+ for {
+ sink = make([]byte, rand.Intn(32<<10))
+ }
+ }()
+ }
+ // Increase the chance that we end up starting and stopping
+ // mid-GC by only starting to trace after a few milliseconds.
+ time.Sleep(5 * time.Millisecond)
+
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ defer trace.Stop()
+
+ // Let the tracing happen for a bit.
+ time.Sleep(400 * time.Millisecond)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gomaxprocs.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gomaxprocs.go
new file mode 100644
index 0000000000000000000000000000000000000000..265120767d6771f45edce77f15c4e8d4d3caf87f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/gomaxprocs.go
@@ -0,0 +1,46 @@
+// 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 increasing and decreasing GOMAXPROCS to try and
+// catch issues with stale proc state.
+
+//go:build ignore
+
+package main
+
+import (
+ "log"
+ "os"
+ "runtime"
+ "runtime/trace"
+ "time"
+)
+
+func main() {
+ // Start a goroutine that calls runtime.GC to try and
+ // introduce some interesting events in between the
+ // GOMAXPROCS calls.
+ go func() {
+ for {
+ runtime.GC()
+ time.Sleep(1 * time.Millisecond)
+ }
+ }()
+
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ // Run GOMAXPROCS a bunch of times, up and down.
+ for i := 1; i <= 16; i *= 2 {
+ runtime.GOMAXPROCS(i)
+ time.Sleep(1 * time.Millisecond)
+ }
+ for i := 16; i >= 1; i /= 2 {
+ runtime.GOMAXPROCS(i)
+ time.Sleep(1 * time.Millisecond)
+ }
+ // Stop tracing.
+ trace.Stop()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/many-start-stop.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/many-start-stop.go
new file mode 100644
index 0000000000000000000000000000000000000000..2d5d0634f0f7ba5fc59630f1c5c419e71db329d8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/many-start-stop.go
@@ -0,0 +1,38 @@
+// 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 simply starting and stopping tracing multiple times.
+//
+// This is useful for finding bugs in trace state reset.
+
+//go:build ignore
+
+package main
+
+import (
+ "bytes"
+ "log"
+ "os"
+ "runtime"
+ "runtime/trace"
+)
+
+func main() {
+ // Trace a few times.
+ for i := 0; i < 10; i++ {
+ var buf bytes.Buffer
+ if err := trace.Start(&buf); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ runtime.GC()
+ trace.Stop()
+ }
+
+ // Start tracing again, this time writing out the result.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ runtime.GC()
+ trace.Stop()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stacks.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stacks.go
new file mode 100644
index 0000000000000000000000000000000000000000..e64bc86844c4c109794f4ba38751d27f88aec43c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stacks.go
@@ -0,0 +1,129 @@
+// 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 stack symbolization.
+
+//go:build ignore
+
+package main
+
+import (
+ "log"
+ "net"
+ "os"
+ "runtime"
+ "runtime/trace"
+ "sync"
+ "time"
+)
+
+func main() {
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ defer trace.Stop() // in case of early return
+
+ // Now we will do a bunch of things for which we verify stacks later.
+ // It is impossible to ensure that a goroutine has actually blocked
+ // on a channel, in a select or otherwise. So we kick off goroutines
+ // that need to block first in the hope that while we are executing
+ // the rest of the test, they will block.
+ go func() { // func1
+ select {}
+ }()
+ go func() { // func2
+ var c chan int
+ c <- 0
+ }()
+ go func() { // func3
+ var c chan int
+ <-c
+ }()
+ done1 := make(chan bool)
+ go func() { // func4
+ <-done1
+ }()
+ done2 := make(chan bool)
+ go func() { // func5
+ done2 <- true
+ }()
+ c1 := make(chan int)
+ c2 := make(chan int)
+ go func() { // func6
+ select {
+ case <-c1:
+ case <-c2:
+ }
+ }()
+ var mu sync.Mutex
+ mu.Lock()
+ go func() { // func7
+ mu.Lock()
+ mu.Unlock()
+ }()
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() { // func8
+ wg.Wait()
+ }()
+ cv := sync.NewCond(&sync.Mutex{})
+ go func() { // func9
+ cv.L.Lock()
+ cv.Wait()
+ cv.L.Unlock()
+ }()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ log.Fatalf("failed to listen: %v", err)
+ }
+ go func() { // func10
+ c, err := ln.Accept()
+ if err != nil {
+ log.Printf("failed to accept: %v", err)
+ return
+ }
+ c.Close()
+ }()
+ rp, wp, err := os.Pipe()
+ if err != nil {
+ log.Fatalf("failed to create a pipe: %v", err)
+ }
+ defer rp.Close()
+ defer wp.Close()
+ pipeReadDone := make(chan bool)
+ go func() { // func11
+ var data [1]byte
+ rp.Read(data[:])
+ pipeReadDone <- true
+ }()
+
+ time.Sleep(100 * time.Millisecond)
+ runtime.GC()
+ runtime.Gosched()
+ time.Sleep(100 * time.Millisecond) // the last chance for the goroutines above to block
+ done1 <- true
+ <-done2
+ select {
+ case c1 <- 0:
+ case c2 <- 0:
+ }
+ mu.Unlock()
+ wg.Done()
+ cv.Signal()
+ c, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ log.Fatalf("failed to dial: %v", err)
+ }
+ c.Close()
+ var data [1]byte
+ wp.Write(data[:])
+ <-pipeReadDone
+
+ oldGoMaxProcs := runtime.GOMAXPROCS(0)
+ runtime.GOMAXPROCS(oldGoMaxProcs + 1)
+
+ trace.Stop()
+
+ runtime.GOMAXPROCS(oldGoMaxProcs)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress-start-stop.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress-start-stop.go
new file mode 100644
index 0000000000000000000000000000000000000000..72c1c5941711e4bc711a4584b4dcc4d23f573ca0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress-start-stop.go
@@ -0,0 +1,166 @@
+// 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 a many interesting cases (network, syscalls, a little GC, busy goroutines,
+// blocked goroutines, LockOSThread, pipes, and GOMAXPROCS).
+
+//go:build ignore
+
+package main
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "net"
+ "os"
+ "runtime"
+ "runtime/trace"
+ "sync"
+ "time"
+)
+
+func main() {
+ defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8))
+ outerDone := make(chan bool)
+
+ go func() {
+ defer func() {
+ outerDone <- true
+ }()
+
+ var wg sync.WaitGroup
+ done := make(chan bool)
+
+ wg.Add(1)
+ go func() {
+ <-done
+ wg.Done()
+ }()
+
+ rp, wp, err := os.Pipe()
+ if err != nil {
+ log.Fatalf("failed to create pipe: %v", err)
+ return
+ }
+ defer func() {
+ rp.Close()
+ wp.Close()
+ }()
+ wg.Add(1)
+ go func() {
+ var tmp [1]byte
+ rp.Read(tmp[:])
+ <-done
+ wg.Done()
+ }()
+ time.Sleep(time.Millisecond)
+
+ go func() {
+ runtime.LockOSThread()
+ for {
+ select {
+ case <-done:
+ return
+ default:
+ runtime.Gosched()
+ }
+ }
+ }()
+
+ runtime.GC()
+ // Trigger GC from malloc.
+ n := 512
+ for i := 0; i < n; i++ {
+ _ = make([]byte, 1<<20)
+ }
+
+ // Create a bunch of busy goroutines to load all Ps.
+ for p := 0; p < 10; p++ {
+ wg.Add(1)
+ go func() {
+ // Do something useful.
+ tmp := make([]byte, 1<<16)
+ for i := range tmp {
+ tmp[i]++
+ }
+ _ = tmp
+ <-done
+ wg.Done()
+ }()
+ }
+
+ // Block in syscall.
+ wg.Add(1)
+ go func() {
+ var tmp [1]byte
+ rp.Read(tmp[:])
+ <-done
+ wg.Done()
+ }()
+
+ runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
+
+ // Test timers.
+ timerDone := make(chan bool)
+ go func() {
+ time.Sleep(time.Millisecond)
+ timerDone <- true
+ }()
+ <-timerDone
+
+ // A bit of network.
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ log.Fatalf("listen failed: %v", err)
+ return
+ }
+ defer ln.Close()
+ go func() {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ time.Sleep(time.Millisecond)
+ var buf [1]byte
+ c.Write(buf[:])
+ c.Close()
+ }()
+ c, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ log.Fatalf("dial failed: %v", err)
+ return
+ }
+ var tmp [1]byte
+ c.Read(tmp[:])
+ c.Close()
+
+ go func() {
+ runtime.Gosched()
+ select {}
+ }()
+
+ // Unblock helper goroutines and wait them to finish.
+ wp.Write(tmp[:])
+ wp.Write(tmp[:])
+ close(done)
+ wg.Wait()
+ }()
+
+ const iters = 5
+ for i := 0; i < iters; i++ {
+ var w io.Writer
+ if i == iters-1 {
+ w = os.Stdout
+ } else {
+ w = new(bytes.Buffer)
+ }
+ if err := trace.Start(w); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ time.Sleep(time.Millisecond)
+ trace.Stop()
+ }
+ <-outerDone
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress.go
new file mode 100644
index 0000000000000000000000000000000000000000..99696d17569a45bb5da10122d22262afdf54c6ef
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/stress.go
@@ -0,0 +1,146 @@
+// 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 a many interesting cases (network, syscalls, a little GC, busy goroutines,
+// blocked goroutines, LockOSThread, pipes, and GOMAXPROCS).
+
+//go:build ignore
+
+package main
+
+import (
+ "log"
+ "net"
+ "os"
+ "runtime"
+ "runtime/trace"
+ "sync"
+ "time"
+)
+
+func main() {
+ var wg sync.WaitGroup
+ done := make(chan bool)
+
+ // Create a goroutine blocked before tracing.
+ wg.Add(1)
+ go func() {
+ <-done
+ wg.Done()
+ }()
+
+ // Create a goroutine blocked in syscall before tracing.
+ rp, wp, err := os.Pipe()
+ if err != nil {
+ log.Fatalf("failed to create pipe: %v", err)
+ }
+ defer func() {
+ rp.Close()
+ wp.Close()
+ }()
+ wg.Add(1)
+ go func() {
+ var tmp [1]byte
+ rp.Read(tmp[:])
+ <-done
+ wg.Done()
+ }()
+ time.Sleep(time.Millisecond) // give the goroutine above time to block
+
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+ defer trace.Stop()
+
+ procs := runtime.GOMAXPROCS(10)
+ time.Sleep(50 * time.Millisecond) // test proc stop/start events
+
+ go func() {
+ runtime.LockOSThread()
+ for {
+ select {
+ case <-done:
+ return
+ default:
+ runtime.Gosched()
+ }
+ }
+ }()
+
+ runtime.GC()
+ // Trigger GC from malloc.
+ n := 512
+ for i := 0; i < n; i++ {
+ _ = make([]byte, 1<<20)
+ }
+
+ // Create a bunch of busy goroutines to load all Ps.
+ for p := 0; p < 10; p++ {
+ wg.Add(1)
+ go func() {
+ // Do something useful.
+ tmp := make([]byte, 1<<16)
+ for i := range tmp {
+ tmp[i]++
+ }
+ _ = tmp
+ <-done
+ wg.Done()
+ }()
+ }
+
+ // Block in syscall.
+ wg.Add(1)
+ go func() {
+ var tmp [1]byte
+ rp.Read(tmp[:])
+ <-done
+ wg.Done()
+ }()
+
+ // Test timers.
+ timerDone := make(chan bool)
+ go func() {
+ time.Sleep(time.Millisecond)
+ timerDone <- true
+ }()
+ <-timerDone
+
+ // A bit of network.
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ log.Fatalf("listen failed: %v", err)
+ }
+ defer ln.Close()
+ go func() {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ time.Sleep(time.Millisecond)
+ var buf [1]byte
+ c.Write(buf[:])
+ c.Close()
+ }()
+ c, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ log.Fatalf("dial failed: %v", err)
+ }
+ var tmp [1]byte
+ c.Read(tmp[:])
+ c.Close()
+
+ go func() {
+ runtime.Gosched()
+ select {}
+ }()
+
+ // Unblock helper goroutines and wait them to finish.
+ wp.Write(tmp[:])
+ wp.Write(tmp[:])
+ close(done)
+ wg.Wait()
+
+ runtime.GOMAXPROCS(procs)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/wait-on-pipe.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/wait-on-pipe.go
new file mode 100644
index 0000000000000000000000000000000000000000..912f5dd3bcae62a97532039bc8140356b62dfc3d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/testprog/wait-on-pipe.go
@@ -0,0 +1,66 @@
+// 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 a goroutine sitting blocked in a syscall for
+// an entire generation. This is a regression test for
+// #65196.
+
+//go:build ignore
+
+package main
+
+import (
+ "log"
+ "os"
+ "runtime/trace"
+ "syscall"
+ "time"
+)
+
+func main() {
+ // Create a pipe to block on.
+ var p [2]int
+ if err := syscall.Pipe(p[:]); err != nil {
+ log.Fatalf("failed to create pipe: %v", err)
+ }
+ rfd, wfd := p[0], p[1]
+
+ // Create a goroutine that blocks on the pipe.
+ done := make(chan struct{})
+ go func() {
+ var data [1]byte
+ _, err := syscall.Read(rfd, data[:])
+ if err != nil {
+ log.Fatalf("failed to read from pipe: %v", err)
+ }
+ done <- struct{}{}
+ }()
+
+ // Give the goroutine ample chance to block on the pipe.
+ time.Sleep(10 * time.Millisecond)
+
+ // Start tracing.
+ if err := trace.Start(os.Stdout); err != nil {
+ log.Fatalf("failed to start tracing: %v", err)
+ }
+
+ // This isn't enough to have a full generation pass by default,
+ // but it is generally enough in stress mode.
+ time.Sleep(100 * time.Millisecond)
+
+ // Write to the pipe to unblock it.
+ if _, err := syscall.Write(wfd, []byte{10}); err != nil {
+ log.Fatalf("failed to write to pipe: %v", err)
+ }
+
+ // Wait for the goroutine to unblock and start running.
+ // This is helpful to catch incorrect information written
+ // down for the syscall-blocked goroutine, since it'll start
+ // executing, and that execution information will be
+ // inconsistent.
+ <-done
+
+ // Stop tracing.
+ trace.Stop()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations-stress.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations-stress.test
new file mode 100644
index 0000000000000000000000000000000000000000..8da8c0f318a56506de800b527ad8037d888c3e01
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations-stress.test
@@ -0,0 +1,1179 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=18446744073709551615 time=2753926854385 size=5
+Frequency freq=15625000
+EventBatch gen=1 m=1986497 time=2753925247434 size=1430
+ProcStart dt=336 p=2 p_seq=1
+GoStart dt=191 g=19 g_seq=1
+HeapAlloc dt=389 heapalloc_value=1622016
+HeapAlloc dt=4453 heapalloc_value=1662976
+GoBlock dt=572 reason_string=12 stack=29
+ProcStop dt=26
+ProcStart dt=160734 p=2 p_seq=2
+ProcStop dt=21
+ProcStart dt=159292 p=0 p_seq=7
+GoStart dt=299 g=49 g_seq=1
+UserRegionBegin dt=183 task=8 name_string=33 stack=26
+UserLog dt=26 task=8 key_string=24 value_string=49 stack=27
+UserRegionEnd dt=8 task=8 name_string=33 stack=28
+GoDestroy dt=3
+GoStart dt=20 g=50 g_seq=1
+UserRegionBegin dt=40 task=8 name_string=35 stack=26
+UserLog dt=9 task=8 key_string=24 value_string=50 stack=27
+UserRegionEnd dt=2 task=8 name_string=35 stack=28
+GoDestroy dt=1
+ProcStop dt=18
+ProcStart dt=141801 p=4 p_seq=5
+ProcStop dt=18
+ProcStart dt=16860 p=4 p_seq=6
+GoUnblock dt=53 g=1 g_seq=5 stack=0
+GoUnblock dt=9 g=51 g_seq=3 stack=0
+GoStart dt=162 g=51 g_seq=4
+UserTaskEnd dt=35 task=9 stack=36
+UserRegionEnd dt=16 task=8 name_string=31 stack=28
+GoDestroy dt=2
+GoStart dt=20 g=1 g_seq=6
+UserTaskEnd dt=14 task=8 stack=54
+UserLog dt=26 task=3 key_string=24 value_string=51 stack=55
+UserTaskBegin dt=14 task=10 parent_task=3 name_string=26 stack=56
+UserLog dt=42 task=10 key_string=27 value_string=52 stack=57
+UserRegionBegin dt=12 task=10 name_string=29 stack=58
+GoCreate dt=36 new_g=35 new_stack=17 stack=59
+GoCreate dt=11 new_g=36 new_stack=17 stack=59
+GoCreate dt=18 new_g=37 new_stack=17 stack=59
+GoCreate dt=10 new_g=38 new_stack=17 stack=59
+GoCreate dt=6 new_g=39 new_stack=17 stack=59
+GoCreate dt=8 new_g=40 new_stack=17 stack=59
+UserRegionEnd dt=7 task=10 name_string=29 stack=60
+GoBlock dt=9 reason_string=19 stack=61
+GoStart dt=15 g=40 g_seq=1
+UserRegionBegin dt=110 task=10 name_string=53 stack=26
+UserLog dt=16 task=10 key_string=24 value_string=54 stack=27
+UserRegionEnd dt=2 task=10 name_string=53 stack=28
+GoDestroy dt=2
+GoStart dt=6 g=38 g_seq=1
+UserRegionBegin dt=31 task=10 name_string=30 stack=26
+UserLog dt=5 task=10 key_string=24 value_string=55 stack=27
+UserRegionEnd dt=2 task=10 name_string=30 stack=28
+GoDestroy dt=1
+GoStart dt=2 g=39 g_seq=1
+UserRegionBegin dt=23 task=10 name_string=56 stack=26
+UserLog dt=6 task=10 key_string=24 value_string=57 stack=27
+UserRegionEnd dt=1 task=10 name_string=56 stack=28
+GoDestroy dt=1
+GoStart dt=8 g=35 g_seq=1
+UserRegionBegin dt=17 task=10 name_string=33 stack=26
+UserLog dt=4 task=10 key_string=24 value_string=58 stack=27
+UserRegionEnd dt=2 task=10 name_string=33 stack=28
+GoDestroy dt=1
+GoStart dt=3 g=36 g_seq=1
+UserRegionBegin dt=19 task=10 name_string=35 stack=26
+UserLog dt=4 task=10 key_string=24 value_string=59 stack=27
+UserRegionEnd dt=2 task=10 name_string=35 stack=28
+GoDestroy dt=1
+ProcStop dt=11
+ProcStart dt=142205 p=0 p_seq=9
+ProcStop dt=19
+ProcStart dt=16811 p=0 p_seq=10
+GoUnblock dt=26 g=1 g_seq=7 stack=0
+GoStart dt=201 g=1 g_seq=8
+UserTaskEnd dt=24 task=10 stack=62
+UserLog dt=18 task=4 key_string=24 value_string=63 stack=63
+UserTaskBegin dt=11 task=12 parent_task=4 name_string=26 stack=64
+UserLog dt=21 task=12 key_string=27 value_string=64 stack=65
+UserRegionBegin dt=7 task=12 name_string=29 stack=66
+GoCreate dt=33 new_g=5 new_stack=17 stack=67
+GoCreate dt=12 new_g=6 new_stack=17 stack=67
+GoCreate dt=9 new_g=7 new_stack=17 stack=67
+GoCreate dt=8 new_g=8 new_stack=17 stack=67
+GoCreate dt=19 new_g=9 new_stack=17 stack=67
+UserRegionEnd dt=14 task=12 name_string=29 stack=68
+GoBlock dt=11 reason_string=19 stack=69
+GoStart dt=13 g=9 g_seq=1
+UserRegionBegin dt=70 task=12 name_string=56 stack=26
+UserLog dt=11 task=12 key_string=24 value_string=65 stack=27
+UserRegionEnd dt=3 task=12 name_string=56 stack=28
+GoDestroy dt=2
+GoStart dt=7 g=5 g_seq=1
+UserRegionBegin dt=24 task=12 name_string=33 stack=26
+UserLog dt=5 task=12 key_string=24 value_string=66 stack=27
+UserRegionEnd dt=2 task=12 name_string=33 stack=28
+GoDestroy dt=2
+GoStart dt=8 g=6 g_seq=1
+UserRegionBegin dt=15 task=12 name_string=35 stack=26
+UserLog dt=7 task=12 key_string=24 value_string=67 stack=27
+UserRegionEnd dt=2 task=12 name_string=35 stack=28
+GoDestroy dt=1
+GoStart dt=2 g=7 g_seq=1
+UserRegionBegin dt=13 task=12 name_string=31 stack=26
+UserLog dt=5 task=12 key_string=24 value_string=68 stack=27
+UserLog dt=6 task=12 key_string=24 value_string=69 stack=30
+UserTaskBegin dt=5 task=13 parent_task=12 name_string=26 stack=31
+UserLog dt=7 task=13 key_string=27 value_string=70 stack=32
+UserRegionBegin dt=4 task=13 name_string=29 stack=33
+UserRegionEnd dt=6 task=13 name_string=29 stack=34
+GoBlock dt=18 reason_string=19 stack=35
+GoStart dt=12 g=8 g_seq=1
+UserRegionBegin dt=22 task=12 name_string=30 stack=26
+UserLog dt=5 task=12 key_string=24 value_string=71 stack=27
+UserRegionEnd dt=2 task=12 name_string=30 stack=28
+GoDestroy dt=1
+ProcStop dt=20
+ProcStart dt=141838 p=4 p_seq=8
+ProcStop dt=16
+ProcStart dt=17652 p=4 p_seq=9
+GoUnblock dt=48 g=1 g_seq=9 stack=0
+GoUnblock dt=8 g=7 g_seq=2 stack=0
+GoStart dt=271 g=7 g_seq=3
+UserTaskEnd dt=25 task=13 stack=36
+UserRegionEnd dt=15 task=12 name_string=31 stack=28
+GoDestroy dt=4
+GoStart dt=19 g=1 g_seq=10
+UserTaskEnd dt=19 task=12 stack=70
+UserLog dt=21 task=0 key_string=24 value_string=72 stack=13
+UserTaskBegin dt=19 task=14 parent_task=0 name_string=26 stack=14
+UserLog dt=37 task=14 key_string=27 value_string=73 stack=15
+UserRegionBegin dt=6 task=14 name_string=29 stack=16
+GoCreate dt=28 new_g=41 new_stack=17 stack=18
+GoCreate dt=14 new_g=42 new_stack=17 stack=18
+GoCreate dt=12 new_g=43 new_stack=17 stack=18
+GoCreate dt=10 new_g=44 new_stack=17 stack=18
+UserRegionEnd dt=5 task=14 name_string=29 stack=19
+GoBlock dt=9 reason_string=19 stack=20
+GoStart dt=16 g=44 g_seq=1
+UserRegionBegin dt=107 task=14 name_string=30 stack=26
+UserLog dt=16 task=14 key_string=24 value_string=74 stack=27
+UserRegionEnd dt=3 task=14 name_string=30 stack=28
+GoDestroy dt=2
+GoStart dt=7 g=41 g_seq=1
+UserRegionBegin dt=30 task=14 name_string=33 stack=26
+UserLog dt=7 task=14 key_string=24 value_string=75 stack=27
+UserRegionEnd dt=2 task=14 name_string=33 stack=28
+GoDestroy dt=2
+GoStart dt=7 g=42 g_seq=1
+UserRegionBegin dt=27 task=14 name_string=35 stack=26
+UserLog dt=7 task=14 key_string=24 value_string=76 stack=27
+UserRegionEnd dt=2 task=14 name_string=35 stack=28
+GoDestroy dt=2
+ProcStop dt=28
+ProcStart dt=141923 p=0 p_seq=12
+ProcStop dt=19
+ProcStart dt=16780 p=0 p_seq=13
+GoUnblock dt=22 g=43 g_seq=2 stack=0
+GoStart dt=162 g=43 g_seq=3
+UserTaskEnd dt=16 task=15 stack=36
+UserRegionEnd dt=12 task=14 name_string=31 stack=28
+GoDestroy dt=2
+ProcStop dt=8
+ProcStart dt=1532 p=2 p_seq=9
+ProcStop dt=12
+ProcStart dt=141906 p=4 p_seq=11
+ProcStop dt=16
+ProcStart dt=16784 p=4 p_seq=12
+GoUnblock dt=20 g=1 g_seq=13 stack=0
+GoStart dt=191 g=1 g_seq=14
+UserTaskEnd dt=15 task=16 stack=45
+UserLog dt=17 task=2 key_string=24 value_string=84 stack=46
+UserTaskBegin dt=8 task=17 parent_task=2 name_string=26 stack=47
+UserLog dt=20 task=17 key_string=27 value_string=85 stack=48
+UserRegionBegin dt=6 task=17 name_string=29 stack=49
+GoCreate dt=28 new_g=45 new_stack=17 stack=50
+GoCreate dt=9 new_g=46 new_stack=17 stack=50
+GoCreate dt=10 new_g=47 new_stack=17 stack=50
+UserRegionEnd dt=5 task=17 name_string=29 stack=51
+GoBlock dt=6 reason_string=19 stack=52
+GoStart dt=10 g=47 g_seq=1
+UserRegionBegin dt=69 task=17 name_string=31 stack=26
+UserLog dt=11 task=17 key_string=24 value_string=86 stack=27
+UserLog dt=7 task=17 key_string=24 value_string=87 stack=30
+UserTaskBegin dt=5 task=18 parent_task=17 name_string=26 stack=31
+UserLog dt=7 task=18 key_string=27 value_string=88 stack=32
+UserRegionBegin dt=5 task=18 name_string=29 stack=33
+UserRegionEnd dt=4 task=18 name_string=29 stack=34
+HeapAlloc dt=35 heapalloc_value=1818624
+GoBlock dt=14 reason_string=19 stack=35
+HeapAlloc dt=11 heapalloc_value=1826816
+GoStart dt=10 g=45 g_seq=1
+UserRegionBegin dt=29 task=17 name_string=33 stack=26
+UserLog dt=9 task=17 key_string=24 value_string=89 stack=27
+UserRegionEnd dt=3 task=17 name_string=33 stack=28
+GoDestroy dt=1
+GoStart dt=5 g=46 g_seq=1
+UserRegionBegin dt=15 task=17 name_string=35 stack=26
+UserLog dt=8 task=17 key_string=24 value_string=90 stack=27
+UserRegionEnd dt=2 task=17 name_string=35 stack=28
+GoDestroy dt=1
+ProcStop dt=3
+ProcStart dt=141981 p=0 p_seq=16
+ProcStop dt=19
+ProcStart dt=17153 p=0 p_seq=17
+GoUnblock dt=44 g=1 g_seq=15 stack=0
+GoUnblock dt=11 g=47 g_seq=2 stack=0
+GoStart dt=215 g=47 g_seq=3
+UserTaskEnd dt=22 task=18 stack=36
+UserRegionEnd dt=9 task=17 name_string=31 stack=28
+GoDestroy dt=3
+GoStart dt=19 g=1 g_seq=16
+UserTaskEnd dt=13 task=17 stack=54
+UserLog dt=18 task=3 key_string=24 value_string=91 stack=55
+UserTaskBegin dt=7 task=19 parent_task=3 name_string=26 stack=56
+UserLog dt=27 task=19 key_string=27 value_string=92 stack=57
+UserRegionBegin dt=8 task=19 name_string=29 stack=58
+GoCreate dt=30 new_g=10 new_stack=17 stack=59
+GoCreate dt=9 new_g=11 new_stack=17 stack=59
+GoCreate dt=11 new_g=12 new_stack=17 stack=59
+GoCreate dt=7 new_g=13 new_stack=17 stack=59
+GoCreate dt=7 new_g=14 new_stack=17 stack=59
+GoCreate dt=9 new_g=15 new_stack=17 stack=59
+UserRegionEnd dt=5 task=19 name_string=29 stack=60
+GoBlock dt=7 reason_string=19 stack=61
+GoStart dt=17 g=15 g_seq=1
+UserRegionBegin dt=61 task=19 name_string=53 stack=26
+UserLog dt=10 task=19 key_string=24 value_string=93 stack=27
+UserRegionEnd dt=3 task=19 name_string=53 stack=28
+GoDestroy dt=1
+GoStart dt=4 g=10 g_seq=1
+UserRegionBegin dt=26 task=19 name_string=33 stack=26
+UserLog dt=7 task=19 key_string=24 value_string=94 stack=27
+UserRegionEnd dt=2 task=19 name_string=33 stack=28
+GoDestroy dt=1
+GoStart dt=4 g=11 g_seq=1
+UserRegionBegin dt=20 task=19 name_string=35 stack=26
+UserLog dt=5 task=19 key_string=24 value_string=95 stack=27
+UserRegionEnd dt=2 task=19 name_string=35 stack=28
+GoDestroy dt=1
+GoStart dt=7 g=12 g_seq=1
+UserRegionBegin dt=14 task=19 name_string=31 stack=26
+UserLog dt=4 task=19 key_string=24 value_string=96 stack=27
+UserLog dt=4 task=19 key_string=24 value_string=97 stack=30
+UserTaskBegin dt=7 task=20 parent_task=19 name_string=26 stack=31
+UserLog dt=5 task=20 key_string=27 value_string=98 stack=32
+UserRegionBegin dt=4 task=20 name_string=29 stack=33
+UserRegionEnd dt=5 task=20 name_string=29 stack=34
+GoBlock dt=9 reason_string=19 stack=35
+GoStart dt=9 g=14 g_seq=1
+UserRegionBegin dt=28 task=19 name_string=56 stack=26
+UserLog dt=7 task=19 key_string=24 value_string=99 stack=27
+UserRegionEnd dt=2 task=19 name_string=56 stack=28
+GoDestroy dt=2
+ProcStop dt=17
+ProcStart dt=141933 p=2 p_seq=11
+ProcStop dt=13
+ProcStart dt=16744 p=2 p_seq=12
+GoUnblock dt=29 g=1 g_seq=17 stack=0
+GoUnblock dt=7 g=12 g_seq=2 stack=0
+GoStart dt=172 g=12 g_seq=3
+UserTaskEnd dt=15 task=20 stack=36
+UserRegionEnd dt=8 task=19 name_string=31 stack=28
+GoDestroy dt=2
+GoStart dt=11 g=1 g_seq=18
+UserTaskEnd dt=14 task=19 stack=62
+UserLog dt=16 task=4 key_string=24 value_string=101 stack=63
+UserTaskBegin dt=6 task=21 parent_task=4 name_string=26 stack=64
+UserLog dt=25 task=21 key_string=27 value_string=102 stack=65
+UserRegionBegin dt=7 task=21 name_string=29 stack=66
+GoCreate dt=23 new_g=54 new_stack=17 stack=67
+GoCreate dt=8 new_g=55 new_stack=17 stack=67
+GoCreate dt=17 new_g=56 new_stack=17 stack=67
+GoCreate dt=8 new_g=57 new_stack=17 stack=67
+GoCreate dt=7 new_g=58 new_stack=17 stack=67
+UserRegionEnd dt=4 task=21 name_string=29 stack=68
+GoBlock dt=9 reason_string=19 stack=69
+GoStart dt=7 g=58 g_seq=1
+UserRegionBegin dt=46 task=21 name_string=56 stack=26
+UserLog dt=8 task=21 key_string=24 value_string=103 stack=27
+UserRegionEnd dt=4 task=21 name_string=56 stack=28
+GoDestroy dt=1
+GoStart dt=3 g=54 g_seq=1
+UserRegionBegin dt=19 task=21 name_string=33 stack=26
+UserLog dt=7 task=21 key_string=24 value_string=104 stack=27
+UserRegionEnd dt=2 task=21 name_string=33 stack=28
+GoDestroy dt=1
+GoStart dt=2 g=55 g_seq=1
+UserRegionBegin dt=17 task=21 name_string=35 stack=26
+UserLog dt=4 task=21 key_string=24 value_string=105 stack=27
+UserRegionEnd dt=2 task=21 name_string=35 stack=28
+GoDestroy dt=1
+GoStart dt=5 g=56 g_seq=1
+UserRegionBegin dt=16 task=21 name_string=31 stack=26
+UserLog dt=4 task=21 key_string=24 value_string=106 stack=27
+UserLog dt=3 task=21 key_string=24 value_string=107 stack=30
+UserTaskBegin dt=4 task=22 parent_task=21 name_string=26 stack=31
+UserLog dt=6 task=22 key_string=27 value_string=108 stack=32
+UserRegionBegin dt=4 task=22 name_string=29 stack=33
+UserRegionEnd dt=7 task=22 name_string=29 stack=34
+GoBlock dt=14 reason_string=19 stack=35
+GoStart dt=3 g=57 g_seq=1
+UserRegionBegin dt=22 task=21 name_string=30 stack=26
+UserLog dt=6 task=21 key_string=24 value_string=109 stack=27
+UserRegionEnd dt=2 task=21 name_string=30 stack=28
+GoDestroy dt=2
+ProcStop dt=10
+ProcStart dt=128031 p=4 p_seq=15
+ProcStop dt=16
+ProcStart dt=33758 p=2 p_seq=15
+ProcStop dt=18
+EventBatch gen=1 m=1986496 time=2753925246280 size=267
+ProcStart dt=549 p=0 p_seq=1
+GoStart dt=211 g=18 g_seq=1
+GoBlock dt=3533 reason_string=12 stack=21
+GoStart dt=41 g=21 g_seq=1
+GoBlock dt=150 reason_string=10 stack=22
+GoStart dt=93 g=20 g_seq=1
+GoSyscallBegin dt=51 p_seq=2 stack=23
+GoSyscallEnd dt=400
+GoBlock dt=582 reason_string=15 stack=25
+GoStart dt=26 g=23 g_seq=1
+HeapAlloc dt=50 heapalloc_value=1646592
+UserRegionBegin dt=2921 task=5 name_string=31 stack=26
+UserLog dt=28 task=5 key_string=24 value_string=37 stack=27
+UserLog dt=13 task=5 key_string=24 value_string=38 stack=30
+UserTaskBegin dt=15 task=6 parent_task=5 name_string=26 stack=31
+HeapAlloc dt=26 heapalloc_value=1687552
+UserLog dt=14 task=6 key_string=27 value_string=39 stack=32
+UserRegionBegin dt=9 task=6 name_string=29 stack=33
+UserRegionEnd dt=6 task=6 name_string=29 stack=34
+GoBlock dt=15 reason_string=19 stack=35
+ProcStop dt=30
+ProcStart dt=156949 p=4 p_seq=2
+GoUnblock dt=46 g=1 g_seq=1 stack=0
+GoStart dt=253 g=1 g_seq=2
+UserTaskEnd dt=27 task=5 stack=37
+UserLog dt=23 task=1 key_string=24 value_string=40 stack=38
+UserTaskBegin dt=14 task=7 parent_task=1 name_string=26 stack=39
+HeapAlloc dt=596 heapalloc_value=1695744
+HeapAlloc dt=18 heapalloc_value=1703936
+UserLog dt=17 task=7 key_string=27 value_string=41 stack=40
+UserRegionBegin dt=14 task=7 name_string=29 stack=41
+HeapAlloc dt=10 heapalloc_value=1712128
+HeapAlloc dt=17 heapalloc_value=1720320
+GoCreate dt=44 new_g=33 new_stack=17 stack=42
+GoCreate dt=175 new_g=34 new_stack=17 stack=42
+UserRegionEnd dt=50 task=7 name_string=29 stack=43
+GoBlock dt=9 reason_string=19 stack=44
+HeapAlloc dt=16 heapalloc_value=1728512
+GoStart dt=239 g=34 g_seq=1
+HeapAlloc dt=21 heapalloc_value=1736704
+UserRegionBegin dt=92 task=7 name_string=35 stack=26
+UserLog dt=15 task=7 key_string=24 value_string=42 stack=27
+UserRegionEnd dt=4 task=7 name_string=35 stack=28
+GoDestroy dt=2
+ProcStop dt=21
+ProcStart dt=800974 p=4 p_seq=10
+ProcStop dt=39
+ProcStart dt=158775 p=0 p_seq=15
+ProcStop dt=24
+ProcStart dt=159722 p=4 p_seq=13
+GoStart dt=254 g=13 g_seq=1
+UserRegionBegin dt=239 task=19 name_string=30 stack=26
+UserLog dt=23 task=19 key_string=24 value_string=100 stack=27
+UserRegionEnd dt=6 task=19 name_string=30 stack=28
+GoDestroy dt=7
+ProcStop dt=22
+EventBatch gen=1 m=1986495 time=2753925251756 size=320
+ProcStart dt=705 p=4 p_seq=1
+ProcStop dt=1279
+ProcStart dt=158975 p=0 p_seq=5
+ProcStop dt=23
+ProcStart dt=792 p=0 p_seq=6
+GoStart dt=187 g=33 g_seq=1
+UserRegionBegin dt=244 task=7 name_string=33 stack=26
+UserLog dt=32 task=7 key_string=24 value_string=43 stack=27
+UserRegionEnd dt=7 task=7 name_string=33 stack=28
+GoDestroy dt=5
+ProcStop dt=24
+ProcStart dt=160255 p=4 p_seq=4
+ProcStop dt=27
+ProcStart dt=159067 p=2 p_seq=5
+GoStart dt=222 g=37 g_seq=1
+UserRegionBegin dt=114 task=10 name_string=31 stack=26
+UserLog dt=16 task=10 key_string=24 value_string=60 stack=27
+UserLog dt=8 task=10 key_string=24 value_string=61 stack=30
+UserTaskBegin dt=8 task=11 parent_task=10 name_string=26 stack=31
+UserLog dt=19 task=11 key_string=27 value_string=62 stack=32
+UserRegionBegin dt=6 task=11 name_string=29 stack=33
+UserRegionEnd dt=7 task=11 name_string=29 stack=34
+GoBlock dt=15 reason_string=19 stack=35
+ProcStop dt=11
+ProcStart dt=160101 p=4 p_seq=7
+ProcStop dt=21
+ProcStart dt=159647 p=2 p_seq=7
+GoStart dt=277 g=43 g_seq=1
+UserRegionBegin dt=126 task=14 name_string=31 stack=26
+UserLog dt=21 task=14 key_string=24 value_string=77 stack=27
+UserLog dt=9 task=14 key_string=24 value_string=78 stack=30
+UserTaskBegin dt=8 task=15 parent_task=14 name_string=26 stack=31
+UserLog dt=17 task=15 key_string=27 value_string=79 stack=32
+UserRegionBegin dt=6 task=15 name_string=29 stack=33
+UserRegionEnd dt=8 task=15 name_string=29 stack=34
+GoBlock dt=23 reason_string=19 stack=35
+ProcStop dt=17
+ProcStart dt=159706 p=0 p_seq=14
+GoStart dt=229 g=52 g_seq=1
+UserRegionBegin dt=103 task=16 name_string=33 stack=26
+UserLog dt=20 task=16 key_string=24 value_string=83 stack=27
+UserRegionEnd dt=4 task=16 name_string=33 stack=28
+GoDestroy dt=3
+ProcStop dt=17
+ProcStart dt=319699 p=2 p_seq=10
+ProcStop dt=20
+ProcStart dt=158728 p=4 p_seq=14
+ProcStop dt=17
+ProcStart dt=110606 p=2 p_seq=13
+ProcStop dt=10
+ProcStart dt=16732 p=2 p_seq=14
+GoUnblock dt=45 g=18 g_seq=2 stack=0
+GoStart dt=184 g=18 g_seq=3
+GoBlock dt=114 reason_string=12 stack=21
+ProcStop dt=8
+ProcStart dt=16779 p=4 p_seq=16
+ProcStop dt=11
+ProcStart dt=16790 p=4 p_seq=17
+GoUnblock dt=23 g=1 g_seq=19 stack=0
+GoUnblock dt=8 g=56 g_seq=2 stack=0
+GoStart dt=142 g=56 g_seq=3
+UserTaskEnd dt=14 task=22 stack=36
+UserRegionEnd dt=8 task=21 name_string=31 stack=28
+GoDestroy dt=5
+GoStart dt=18 g=1 g_seq=20
+UserTaskEnd dt=17 task=21 stack=70
+UserTaskEnd dt=12 task=4 stack=71
+HeapAlloc dt=802 heapalloc_value=1835008
+HeapAlloc dt=41 heapalloc_value=1843200
+HeapAlloc dt=13 heapalloc_value=1851392
+EventBatch gen=1 m=1986494 time=2753925248778 size=47
+ProcStart dt=390 p=3 p_seq=1
+GoStart dt=1718 g=22 g_seq=1
+HeapAlloc dt=1807 heapalloc_value=1654784
+HeapAlloc dt=406 heapalloc_value=1671168
+HeapAlloc dt=15 heapalloc_value=1679360
+UserRegionBegin dt=49 task=5 name_string=35 stack=26
+UserLog dt=30 task=5 key_string=24 value_string=36 stack=27
+UserRegionEnd dt=5 task=5 name_string=35 stack=28
+GoDestroy dt=5
+ProcStop dt=42
+EventBatch gen=1 m=1986492 time=2753925244400 size=582
+ProcStatus dt=67 p=1 pstatus=1
+GoStatus dt=4 g=1 m=1986492 gstatus=2
+ProcsChange dt=220 procs_value=8 stack=1
+STWBegin dt=127 kind_string=21 stack=2
+HeapGoal dt=3 heapgoal_value=4194304
+ProcStatus dt=2 p=0 pstatus=2
+ProcStatus dt=2 p=2 pstatus=2
+ProcStatus dt=1 p=3 pstatus=2
+ProcStatus dt=1 p=4 pstatus=2
+ProcStatus dt=1 p=5 pstatus=2
+ProcStatus dt=1 p=6 pstatus=2
+ProcStatus dt=1 p=7 pstatus=2
+ProcsChange dt=353 procs_value=8 stack=3
+STWEnd dt=277
+HeapAlloc dt=243 heapalloc_value=1605632
+HeapAlloc dt=24 heapalloc_value=1613824
+GoCreate dt=209 new_g=18 new_stack=4 stack=5
+GoCreate dt=561 new_g=19 new_stack=6 stack=7
+GoCreate dt=25 new_g=20 new_stack=8 stack=9
+UserTaskEnd dt=309 task=2 stack=10
+UserTaskBegin dt=26 task=3 parent_task=1 name_string=22 stack=11
+UserTaskBegin dt=918 task=4 parent_task=0 name_string=23 stack=12
+UserLog dt=461 task=0 key_string=24 value_string=25 stack=13
+UserTaskBegin dt=420 task=5 parent_task=0 name_string=26 stack=14
+UserLog dt=673 task=5 key_string=27 value_string=28 stack=15
+UserRegionBegin dt=15 task=5 name_string=29 stack=16
+HeapAlloc dt=51 heapalloc_value=1630208
+GoCreate dt=24 new_g=21 new_stack=17 stack=18
+GoCreate dt=17 new_g=22 new_stack=17 stack=18
+GoCreate dt=10 new_g=23 new_stack=17 stack=18
+GoCreate dt=9 new_g=24 new_stack=17 stack=18
+UserRegionEnd dt=549 task=5 name_string=29 stack=19
+GoBlock dt=14 reason_string=19 stack=20
+GoStart dt=378 g=24 g_seq=1
+HeapAlloc dt=65 heapalloc_value=1638400
+GoUnblock dt=559 g=21 g_seq=2 stack=24
+UserRegionBegin dt=1498 task=5 name_string=30 stack=26
+UserLog dt=35 task=5 key_string=24 value_string=32 stack=27
+UserRegionEnd dt=8 task=5 name_string=30 stack=28
+GoDestroy dt=5
+GoStart dt=24 g=21 g_seq=3
+UserRegionBegin dt=60 task=5 name_string=33 stack=26
+UserLog dt=7 task=5 key_string=24 value_string=34 stack=27
+UserRegionEnd dt=2 task=5 name_string=33 stack=28
+GoDestroy dt=2
+ProcStop dt=34
+ProcStart dt=141874 p=0 p_seq=3
+ProcStop dt=21
+ProcStart dt=16770 p=0 p_seq=4
+GoUnblock dt=29 g=23 g_seq=2 stack=0
+GoStart dt=176 g=23 g_seq=3
+UserTaskEnd dt=19 task=6 stack=36
+UserRegionEnd dt=14 task=5 name_string=31 stack=28
+GoDestroy dt=2
+ProcStop dt=12
+ProcStart dt=2251 p=4 p_seq=3
+ProcStop dt=22
+ProcStart dt=141952 p=2 p_seq=3
+ProcStop dt=27
+ProcStart dt=16789 p=2 p_seq=4
+GoUnblock dt=35 g=1 g_seq=3 stack=0
+GoStart dt=214 g=1 g_seq=4
+UserTaskEnd dt=26 task=7 stack=45
+UserLog dt=27 task=2 key_string=24 value_string=44 stack=46
+UserTaskBegin dt=10 task=8 parent_task=2 name_string=26 stack=47
+HeapAlloc dt=52 heapalloc_value=1744896
+HeapAlloc dt=22 heapalloc_value=1753088
+UserLog dt=13 task=8 key_string=27 value_string=45 stack=48
+UserRegionBegin dt=11 task=8 name_string=29 stack=49
+HeapAlloc dt=7 heapalloc_value=1761280
+HeapAlloc dt=18 heapalloc_value=1769472
+GoCreate dt=52 new_g=49 new_stack=17 stack=50
+GoCreate dt=12 new_g=50 new_stack=17 stack=50
+HeapAlloc dt=11 heapalloc_value=1777664
+GoCreate dt=9 new_g=51 new_stack=17 stack=50
+UserRegionEnd dt=9 task=8 name_string=29 stack=51
+GoBlock dt=11 reason_string=19 stack=52
+HeapAlloc dt=12 heapalloc_value=1785856
+GoStart dt=14 g=51 g_seq=1
+HeapAlloc dt=18 heapalloc_value=1794048
+UserRegionBegin dt=95 task=8 name_string=31 stack=26
+UserLog dt=22 task=8 key_string=24 value_string=46 stack=27
+UserLog dt=8 task=8 key_string=24 value_string=47 stack=30
+UserTaskBegin dt=5 task=9 parent_task=8 name_string=26 stack=31
+UserLog dt=7 task=9 key_string=27 value_string=48 stack=32
+UserRegionBegin dt=4 task=9 name_string=29 stack=33
+UserRegionEnd dt=7 task=9 name_string=29 stack=34
+HeapAlloc dt=11 heapalloc_value=1802240
+GoStop dt=674 reason_string=16 stack=53
+GoStart dt=12 g=51 g_seq=2
+GoBlock dt=8 reason_string=19 stack=35
+HeapAlloc dt=16 heapalloc_value=1810432
+ProcStop dt=8
+ProcStart dt=159907 p=0 p_seq=8
+ProcStop dt=25
+ProcStart dt=159186 p=2 p_seq=6
+GoUnblock dt=22 g=37 g_seq=2 stack=0
+GoStart dt=217 g=37 g_seq=3
+UserTaskEnd dt=19 task=11 stack=36
+UserRegionEnd dt=15 task=10 name_string=31 stack=28
+GoDestroy dt=5
+ProcStop dt=16
+ProcStart dt=160988 p=0 p_seq=11
+ProcStop dt=29
+ProcStart dt=158554 p=2 p_seq=8
+GoUnblock dt=38 g=1 g_seq=11 stack=0
+GoStart dt=240 g=1 g_seq=12
+UserTaskEnd dt=25 task=14 stack=37
+UserLog dt=23 task=1 key_string=24 value_string=80 stack=38
+UserTaskBegin dt=11 task=16 parent_task=1 name_string=26 stack=39
+UserLog dt=36 task=16 key_string=27 value_string=81 stack=40
+UserRegionBegin dt=13 task=16 name_string=29 stack=41
+GoCreate dt=39 new_g=52 new_stack=17 stack=42
+GoCreate dt=23 new_g=53 new_stack=17 stack=42
+UserRegionEnd dt=11 task=16 name_string=29 stack=43
+GoBlock dt=9 reason_string=19 stack=44
+GoStart dt=244 g=53 g_seq=1
+UserRegionBegin dt=101 task=16 name_string=35 stack=26
+UserLog dt=17 task=16 key_string=24 value_string=82 stack=27
+UserRegionEnd dt=4 task=16 name_string=35 stack=28
+GoDestroy dt=3
+ProcStop dt=28
+EventBatch gen=1 m=18446744073709551615 time=2753926855140 size=56
+GoStatus dt=74 g=2 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=3 m=18446744073709551615 gstatus=4
+GoStatus dt=1 g=4 m=18446744073709551615 gstatus=4
+GoStatus dt=1 g=17 m=18446744073709551615 gstatus=4
+EventBatch gen=1 m=18446744073709551615 time=2753926855560 size=1759
+Stacks
+Stack id=45 nframes=3
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4803566 func=114 file=113 line=44
+Stack id=22 nframes=7
+ pc=4633935 func=115 file=116 line=90
+ pc=4633896 func=117 file=118 line=223
+ pc=4633765 func=119 file=118 line=216
+ pc=4633083 func=120 file=118 line=131
+ pc=4764601 func=121 file=122 line=152
+ pc=4765335 func=123 file=122 line=238
+ pc=4804612 func=124 file=113 line=70
+Stack id=9 nframes=2
+ pc=4802543 func=125 file=126 line=128
+ pc=4803332 func=114 file=113 line=30
+Stack id=71 nframes=2
+ pc=4803671 func=110 file=111 line=80
+ pc=4803666 func=114 file=113 line=51
+Stack id=10 nframes=2
+ pc=4803415 func=110 file=111 line=80
+ pc=4803410 func=114 file=113 line=33
+Stack id=18 nframes=4
+ pc=4804196 func=127 file=113 line=69
+ pc=4802140 func=128 file=111 line=141
+ pc=4804022 func=112 file=113 line=67
+ pc=4803543 func=114 file=113 line=43
+Stack id=37 nframes=3
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4803543 func=114 file=113 line=43
+Stack id=31 nframes=4
+ pc=4803865 func=112 file=113 line=61
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=55 nframes=2
+ pc=4803832 func=112 file=113 line=58
+ pc=4803609 func=114 file=113 line=46
+Stack id=47 nframes=2
+ pc=4803865 func=112 file=113 line=61
+ pc=4803589 func=114 file=113 line=45
+Stack id=38 nframes=2
+ pc=4803832 func=112 file=113 line=58
+ pc=4803566 func=114 file=113 line=44
+Stack id=56 nframes=2
+ pc=4803865 func=112 file=113 line=61
+ pc=4803609 func=114 file=113 line=46
+Stack id=33 nframes=4
+ pc=4804022 func=112 file=113 line=67
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=44 nframes=3
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4803566 func=114 file=113 line=44
+Stack id=3 nframes=4
+ pc=4421707 func=132 file=133 line=1382
+ pc=4533555 func=134 file=135 line=255
+ pc=4802469 func=125 file=126 line=125
+ pc=4803332 func=114 file=113 line=30
+Stack id=6 nframes=1
+ pc=4539520 func=136 file=135 line=868
+Stack id=58 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803609 func=114 file=113 line=46
+Stack id=64 nframes=2
+ pc=4803865 func=112 file=113 line=61
+ pc=4803629 func=114 file=113 line=47
+Stack id=62 nframes=3
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4803609 func=114 file=113 line=46
+Stack id=34 nframes=4
+ pc=4804022 func=112 file=113 line=67
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=30 nframes=4
+ pc=4803832 func=112 file=113 line=58
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=32 nframes=4
+ pc=4803943 func=112 file=113 line=64
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=26 nframes=1
+ pc=4804691 func=124 file=113 line=70
+Stack id=46 nframes=2
+ pc=4803832 func=112 file=113 line=58
+ pc=4803589 func=114 file=113 line=45
+Stack id=50 nframes=4
+ pc=4804196 func=127 file=113 line=69
+ pc=4802140 func=128 file=111 line=141
+ pc=4804022 func=112 file=113 line=67
+ pc=4803589 func=114 file=113 line=45
+Stack id=59 nframes=4
+ pc=4804196 func=127 file=113 line=69
+ pc=4802140 func=128 file=111 line=141
+ pc=4804022 func=112 file=113 line=67
+ pc=4803609 func=114 file=113 line=46
+Stack id=7 nframes=4
+ pc=4539492 func=137 file=135 line=868
+ pc=4533572 func=134 file=135 line=258
+ pc=4802469 func=125 file=126 line=125
+ pc=4803332 func=114 file=113 line=30
+Stack id=17 nframes=1
+ pc=4804512 func=124 file=113 line=69
+Stack id=57 nframes=2
+ pc=4803943 func=112 file=113 line=64
+ pc=4803609 func=114 file=113 line=46
+Stack id=41 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803566 func=114 file=113 line=44
+Stack id=63 nframes=2
+ pc=4803832 func=112 file=113 line=58
+ pc=4803629 func=114 file=113 line=47
+Stack id=60 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803609 func=114 file=113 line=46
+Stack id=5 nframes=4
+ pc=4542549 func=138 file=139 line=42
+ pc=4533560 func=134 file=135 line=257
+ pc=4802469 func=125 file=126 line=125
+ pc=4803332 func=114 file=113 line=30
+Stack id=40 nframes=2
+ pc=4803943 func=112 file=113 line=64
+ pc=4803566 func=114 file=113 line=44
+Stack id=21 nframes=3
+ pc=4217905 func=140 file=141 line=442
+ pc=4539946 func=142 file=135 line=928
+ pc=4542714 func=143 file=139 line=54
+Stack id=2 nframes=3
+ pc=4533284 func=134 file=135 line=238
+ pc=4802469 func=125 file=126 line=125
+ pc=4803332 func=114 file=113 line=30
+Stack id=53 nframes=6
+ pc=4247492 func=144 file=145 line=1374
+ pc=4599676 func=130 file=131 line=186
+ pc=4804036 func=112 file=113 line=83
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=20 nframes=3
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4803543 func=114 file=113 line=43
+Stack id=70 nframes=3
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4803629 func=114 file=113 line=47
+Stack id=15 nframes=2
+ pc=4803943 func=112 file=113 line=64
+ pc=4803543 func=114 file=113 line=43
+Stack id=65 nframes=2
+ pc=4803943 func=112 file=113 line=64
+ pc=4803629 func=114 file=113 line=47
+Stack id=28 nframes=1
+ pc=4804691 func=124 file=113 line=70
+Stack id=48 nframes=2
+ pc=4803943 func=112 file=113 line=64
+ pc=4803589 func=114 file=113 line=45
+Stack id=61 nframes=3
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4803609 func=114 file=113 line=46
+Stack id=13 nframes=2
+ pc=4803832 func=112 file=113 line=58
+ pc=4803543 func=114 file=113 line=43
+Stack id=29 nframes=3
+ pc=4217905 func=140 file=141 line=442
+ pc=4539946 func=142 file=135 line=928
+ pc=4539559 func=136 file=135 line=871
+Stack id=51 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803589 func=114 file=113 line=45
+Stack id=42 nframes=4
+ pc=4804196 func=127 file=113 line=69
+ pc=4802140 func=128 file=111 line=141
+ pc=4804022 func=112 file=113 line=67
+ pc=4803566 func=114 file=113 line=44
+Stack id=14 nframes=2
+ pc=4803865 func=112 file=113 line=61
+ pc=4803543 func=114 file=113 line=43
+Stack id=39 nframes=2
+ pc=4803865 func=112 file=113 line=61
+ pc=4803566 func=114 file=113 line=44
+Stack id=49 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803589 func=114 file=113 line=45
+Stack id=52 nframes=3
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4803589 func=114 file=113 line=45
+Stack id=24 nframes=7
+ pc=4634510 func=146 file=116 line=223
+ pc=4634311 func=117 file=118 line=240
+ pc=4633765 func=119 file=118 line=216
+ pc=4633083 func=120 file=118 line=131
+ pc=4764601 func=121 file=122 line=152
+ pc=4765335 func=123 file=122 line=238
+ pc=4804612 func=124 file=113 line=70
+Stack id=43 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803566 func=114 file=113 line=44
+Stack id=19 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803543 func=114 file=113 line=43
+Stack id=69 nframes=3
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4803629 func=114 file=113 line=47
+Stack id=16 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803543 func=114 file=113 line=43
+Stack id=54 nframes=3
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4803589 func=114 file=113 line=45
+Stack id=35 nframes=5
+ pc=4599892 func=130 file=131 line=195
+ pc=4804036 func=112 file=113 line=83
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=27 nframes=3
+ pc=4804862 func=129 file=113 line=71
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=4 nframes=1
+ pc=4542656 func=143 file=139 line=42
+Stack id=8 nframes=1
+ pc=4802720 func=147 file=126 line=128
+Stack id=66 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803629 func=114 file=113 line=47
+Stack id=1 nframes=4
+ pc=4548715 func=148 file=149 line=255
+ pc=4533263 func=134 file=135 line=237
+ pc=4802469 func=125 file=126 line=125
+ pc=4803332 func=114 file=113 line=30
+Stack id=67 nframes=4
+ pc=4804196 func=127 file=113 line=69
+ pc=4802140 func=128 file=111 line=141
+ pc=4804022 func=112 file=113 line=67
+ pc=4803629 func=114 file=113 line=47
+Stack id=23 nframes=7
+ pc=4641050 func=150 file=151 line=964
+ pc=4751591 func=152 file=153 line=209
+ pc=4751583 func=154 file=155 line=736
+ pc=4751136 func=156 file=155 line=380
+ pc=4753008 func=157 file=158 line=46
+ pc=4753000 func=159 file=160 line=183
+ pc=4802778 func=147 file=126 line=134
+Stack id=11 nframes=1
+ pc=4803445 func=114 file=113 line=36
+Stack id=68 nframes=2
+ pc=4804022 func=112 file=113 line=67
+ pc=4803629 func=114 file=113 line=47
+Stack id=36 nframes=5
+ pc=4804964 func=110 file=111 line=80
+ pc=4804052 func=112 file=113 line=84
+ pc=4804890 func=129 file=113 line=73
+ pc=4802140 func=128 file=111 line=141
+ pc=4804691 func=124 file=113 line=70
+Stack id=12 nframes=1
+ pc=4803492 func=114 file=113 line=39
+Stack id=25 nframes=1
+ pc=4802788 func=147 file=126 line=130
+EventBatch gen=1 m=18446744073709551615 time=2753925243266 size=3466
+Strings
+String id=1
+ data="Not worker"
+String id=2
+ data="GC (dedicated)"
+String id=3
+ data="GC (fractional)"
+String id=4
+ data="GC (idle)"
+String id=5
+ data="unspecified"
+String id=6
+ data="forever"
+String id=7
+ data="network"
+String id=8
+ data="select"
+String id=9
+ data="sync.(*Cond).Wait"
+String id=10
+ data="sync"
+String id=11
+ data="chan send"
+String id=12
+ data="chan receive"
+String id=13
+ data="GC mark assist wait for work"
+String id=14
+ data="GC background sweeper wait"
+String id=15
+ data="system goroutine wait"
+String id=16
+ data="preempted"
+String id=17
+ data="wait for debug call"
+String id=18
+ data="wait until GC ends"
+String id=19
+ data="sleep"
+String id=20
+ data="runtime.Gosched"
+String id=21
+ data="start trace"
+String id=22
+ data="type2"
+String id=23
+ data="type3"
+String id=24
+ data="log"
+String id=25
+ data="before do"
+String id=26
+ data="do"
+String id=27
+ data="log2"
+String id=28
+ data="do"
+String id=29
+ data="fanout"
+String id=30
+ data="region3"
+String id=31
+ data="region2"
+String id=32
+ data="fanout region3"
+String id=33
+ data="region0"
+String id=34
+ data="fanout region0"
+String id=35
+ data="region1"
+String id=36
+ data="fanout region1"
+String id=37
+ data="fanout region2"
+String id=38
+ data="before do"
+String id=39
+ data="do"
+String id=40
+ data="before do"
+String id=41
+ data="do"
+String id=42
+ data="fanout region1"
+String id=43
+ data="fanout region0"
+String id=44
+ data="before do"
+String id=45
+ data="do"
+String id=46
+ data="fanout region2"
+String id=47
+ data="before do"
+String id=48
+ data="do"
+String id=49
+ data="fanout region0"
+String id=50
+ data="fanout region1"
+String id=51
+ data="before do"
+String id=52
+ data="do"
+String id=53
+ data="region5"
+String id=54
+ data="fanout region5"
+String id=55
+ data="fanout region3"
+String id=56
+ data="region4"
+String id=57
+ data="fanout region4"
+String id=58
+ data="fanout region0"
+String id=59
+ data="fanout region1"
+String id=60
+ data="fanout region2"
+String id=61
+ data="before do"
+String id=62
+ data="do"
+String id=63
+ data="before do"
+String id=64
+ data="do"
+String id=65
+ data="fanout region4"
+String id=66
+ data="fanout region0"
+String id=67
+ data="fanout region1"
+String id=68
+ data="fanout region2"
+String id=69
+ data="before do"
+String id=70
+ data="do"
+String id=71
+ data="fanout region3"
+String id=72
+ data="before do"
+String id=73
+ data="do"
+String id=74
+ data="fanout region3"
+String id=75
+ data="fanout region0"
+String id=76
+ data="fanout region1"
+String id=77
+ data="fanout region2"
+String id=78
+ data="before do"
+String id=79
+ data="do"
+String id=80
+ data="before do"
+String id=81
+ data="do"
+String id=82
+ data="fanout region1"
+String id=83
+ data="fanout region0"
+String id=84
+ data="before do"
+String id=85
+ data="do"
+String id=86
+ data="fanout region2"
+String id=87
+ data="before do"
+String id=88
+ data="do"
+String id=89
+ data="fanout region0"
+String id=90
+ data="fanout region1"
+String id=91
+ data="before do"
+String id=92
+ data="do"
+String id=93
+ data="fanout region5"
+String id=94
+ data="fanout region0"
+String id=95
+ data="fanout region1"
+String id=96
+ data="fanout region2"
+String id=97
+ data="before do"
+String id=98
+ data="do"
+String id=99
+ data="fanout region4"
+String id=100
+ data="fanout region3"
+String id=101
+ data="before do"
+String id=102
+ data="do"
+String id=103
+ data="fanout region4"
+String id=104
+ data="fanout region0"
+String id=105
+ data="fanout region1"
+String id=106
+ data="fanout region2"
+String id=107
+ data="before do"
+String id=108
+ data="do"
+String id=109
+ data="fanout region3"
+String id=110
+ data="runtime/trace.(*Task).End"
+String id=111
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/annotation.go"
+String id=112
+ data="main.do"
+String id=113
+ data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/annotations-stress.go"
+String id=114
+ data="main.main"
+String id=115
+ data="sync.(*Mutex).Lock"
+String id=116
+ data="/usr/local/google/home/mknyszek/work/go-1/src/sync/mutex.go"
+String id=117
+ data="sync.(*Pool).pinSlow"
+String id=118
+ data="/usr/local/google/home/mknyszek/work/go-1/src/sync/pool.go"
+String id=119
+ data="sync.(*Pool).pin"
+String id=120
+ data="sync.(*Pool).Get"
+String id=121
+ data="fmt.newPrinter"
+String id=122
+ data="/usr/local/google/home/mknyszek/work/go-1/src/fmt/print.go"
+String id=123
+ data="fmt.Sprintf"
+String id=124
+ data="main.do.func1.1"
+String id=125
+ data="runtime/trace.Start"
+String id=126
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go"
+String id=127
+ data="main.do.func1"
+String id=128
+ data="runtime/trace.WithRegion"
+String id=129
+ data="main.do.func1.1.1"
+String id=130
+ data="time.Sleep"
+String id=131
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/time.go"
+String id=132
+ data="runtime.startTheWorld"
+String id=133
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go"
+String id=134
+ data="runtime.StartTrace"
+String id=135
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go"
+String id=136
+ data="runtime.(*traceAdvancerState).start.func1"
+String id=137
+ data="runtime.(*traceAdvancerState).start"
+String id=138
+ data="runtime.traceStartReadCPU"
+String id=139
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2cpu.go"
+String id=140
+ data="runtime.chanrecv1"
+String id=141
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go"
+String id=142
+ data="runtime.(*wakeableSleep).sleep"
+String id=143
+ data="runtime.traceStartReadCPU.func1"
+String id=144
+ data="runtime.newobject"
+String id=145
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/malloc.go"
+String id=146
+ data="sync.(*Mutex).Unlock"
+String id=147
+ data="runtime/trace.Start.func1"
+String id=148
+ data="runtime.traceLocker.Gomaxprocs"
+String id=149
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go"
+String id=150
+ data="syscall.write"
+String id=151
+ data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/zsyscall_linux_amd64.go"
+String id=152
+ data="syscall.Write"
+String id=153
+ data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/syscall_unix.go"
+String id=154
+ data="internal/poll.ignoringEINTRIO"
+String id=155
+ data="/usr/local/google/home/mknyszek/work/go-1/src/internal/poll/fd_unix.go"
+String id=156
+ data="internal/poll.(*FD).Write"
+String id=157
+ data="os.(*File).write"
+String id=158
+ data="/usr/local/google/home/mknyszek/work/go-1/src/os/file_posix.go"
+String id=159
+ data="os.(*File).Write"
+String id=160
+ data="/usr/local/google/home/mknyszek/work/go-1/src/os/file.go"
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations.test
new file mode 100644
index 0000000000000000000000000000000000000000..e4686734973d314bcee472fb98c89f4cd1271664
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-annotations.test
@@ -0,0 +1,299 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=18446744073709551615 time=28113086279559 size=5
+Frequency freq=15625000
+EventBatch gen=1 m=167930 time=28113086277797 size=41
+ProcStart dt=505 p=1 p_seq=1
+GoStart dt=303 g=7 g_seq=1
+HeapAlloc dt=646 heapalloc_value=1892352
+HeapAlloc dt=149 heapalloc_value=1900544
+GoBlock dt=146 reason_string=12 stack=24
+GoStart dt=14 g=6 g_seq=1
+HeapAlloc dt=16 heapalloc_value=1908736
+GoBlock dt=347 reason_string=12 stack=25
+EventBatch gen=1 m=167928 time=28113086279032 size=10
+ProcStart dt=451 p=2 p_seq=1
+GoStart dt=188 g=8 g_seq=1
+EventBatch gen=1 m=167926 time=28113086275999 size=324
+ProcStatus dt=295 p=0 pstatus=1
+GoStatus dt=5 g=1 m=167926 gstatus=2
+ProcsChange dt=405 procs_value=48 stack=1
+STWBegin dt=65 kind_string=21 stack=2
+HeapGoal dt=2 heapgoal_value=4194304
+ProcStatus dt=4 p=1 pstatus=2
+ProcStatus dt=1 p=2 pstatus=2
+ProcStatus dt=1 p=3 pstatus=2
+ProcStatus dt=1 p=4 pstatus=2
+ProcStatus dt=1 p=5 pstatus=2
+ProcStatus dt=1 p=6 pstatus=2
+ProcStatus dt=1 p=7 pstatus=2
+ProcStatus dt=1 p=8 pstatus=2
+ProcStatus dt=1 p=9 pstatus=2
+ProcStatus dt=1 p=10 pstatus=2
+ProcStatus dt=1 p=11 pstatus=2
+ProcStatus dt=1 p=12 pstatus=2
+ProcStatus dt=1 p=13 pstatus=2
+ProcStatus dt=1 p=14 pstatus=2
+ProcStatus dt=1 p=15 pstatus=2
+ProcStatus dt=1 p=16 pstatus=2
+ProcStatus dt=1 p=17 pstatus=2
+ProcStatus dt=1 p=18 pstatus=2
+ProcStatus dt=1 p=19 pstatus=2
+ProcStatus dt=1 p=20 pstatus=2
+ProcStatus dt=1 p=21 pstatus=2
+ProcStatus dt=1 p=22 pstatus=2
+ProcStatus dt=1 p=23 pstatus=2
+ProcStatus dt=1 p=24 pstatus=2
+ProcStatus dt=1 p=25 pstatus=2
+ProcStatus dt=1 p=26 pstatus=2
+ProcStatus dt=1 p=27 pstatus=2
+ProcStatus dt=1 p=28 pstatus=2
+ProcStatus dt=1 p=29 pstatus=2
+ProcStatus dt=1 p=30 pstatus=2
+ProcStatus dt=1 p=31 pstatus=2
+ProcStatus dt=1 p=32 pstatus=2
+ProcStatus dt=1 p=33 pstatus=2
+ProcStatus dt=1 p=34 pstatus=2
+ProcStatus dt=1 p=35 pstatus=2
+ProcStatus dt=1 p=36 pstatus=2
+ProcStatus dt=1 p=37 pstatus=2
+ProcStatus dt=1 p=38 pstatus=2
+ProcStatus dt=1 p=39 pstatus=2
+ProcStatus dt=1 p=40 pstatus=2
+ProcStatus dt=1 p=41 pstatus=2
+ProcStatus dt=1 p=42 pstatus=2
+ProcStatus dt=1 p=43 pstatus=2
+ProcStatus dt=1 p=44 pstatus=2
+ProcStatus dt=1 p=45 pstatus=2
+ProcStatus dt=1 p=46 pstatus=2
+ProcStatus dt=1 p=47 pstatus=2
+ProcsChange dt=1 procs_value=48 stack=3
+STWEnd dt=184
+GoCreate dt=252 new_g=6 new_stack=4 stack=5
+GoCreate dt=78 new_g=7 new_stack=6 stack=7
+GoCreate dt=73 new_g=8 new_stack=8 stack=9
+UserTaskBegin dt=71 task=1 parent_task=0 name_string=22 stack=10
+UserRegionBegin dt=535 task=1 name_string=23 stack=11
+HeapAlloc dt=26 heapalloc_value=1884160
+GoCreate dt=8 new_g=9 new_stack=12 stack=13
+GoBlock dt=249 reason_string=10 stack=14
+GoStart dt=8 g=9 g_seq=1
+UserRegionBegin dt=286 task=1 name_string=24 stack=15
+UserRegionBegin dt=244 task=1 name_string=25 stack=16
+UserRegionBegin dt=6 task=1 name_string=26 stack=17
+UserLog dt=6 task=1 key_string=27 value_string=28 stack=18
+UserRegionEnd dt=4 task=1 name_string=26 stack=19
+UserRegionEnd dt=315 task=1 name_string=25 stack=20
+UserTaskEnd dt=5 task=1 stack=21
+GoUnblock dt=11 g=1 g_seq=1 stack=22
+GoDestroy dt=6
+GoStart dt=10 g=1 g_seq=2
+UserRegionBegin dt=278 task=0 name_string=29 stack=23
+EventBatch gen=1 m=18446744073709551615 time=28113086280061 size=57
+GoStatus dt=318 g=2 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=3 m=18446744073709551615 gstatus=4
+GoStatus dt=1 g=4 m=18446744073709551615 gstatus=4
+GoStatus dt=1 g=5 m=18446744073709551615 gstatus=4
+EventBatch gen=1 m=18446744073709551615 time=28113086280852 size=488
+Stacks
+Stack id=17 nframes=3
+ pc=4816080 func=30 file=31 line=45
+ pc=4813660 func=32 file=33 line=141
+ pc=4815908 func=34 file=31 line=43
+Stack id=8 nframes=1
+ pc=4814528 func=35 file=36 line=128
+Stack id=9 nframes=2
+ pc=4814351 func=37 file=36 line=128
+ pc=4815228 func=38 file=31 line=27
+Stack id=24 nframes=3
+ pc=4217457 func=39 file=40 line=442
+ pc=4544973 func=41 file=42 line=918
+ pc=4544806 func=43 file=42 line=871
+Stack id=7 nframes=4
+ pc=4544740 func=44 file=42 line=868
+ pc=4538792 func=45 file=42 line=258
+ pc=4814277 func=37 file=36 line=125
+ pc=4815228 func=38 file=31 line=27
+Stack id=22 nframes=3
+ pc=4642148 func=46 file=47 line=81
+ pc=4816326 func=48 file=47 line=87
+ pc=4815941 func=34 file=31 line=50
+Stack id=11 nframes=1
+ pc=4815364 func=38 file=31 line=34
+Stack id=5 nframes=4
+ pc=4547349 func=49 file=50 line=42
+ pc=4538780 func=45 file=42 line=257
+ pc=4814277 func=37 file=36 line=125
+ pc=4815228 func=38 file=31 line=27
+Stack id=23 nframes=1
+ pc=4815568 func=38 file=31 line=54
+Stack id=3 nframes=4
+ pc=4421860 func=51 file=52 line=1360
+ pc=4538775 func=45 file=42 line=255
+ pc=4814277 func=37 file=36 line=125
+ pc=4815228 func=38 file=31 line=27
+Stack id=21 nframes=2
+ pc=4816228 func=53 file=33 line=80
+ pc=4815926 func=34 file=31 line=50
+Stack id=1 nframes=4
+ pc=4553515 func=54 file=55 line=255
+ pc=4538503 func=45 file=42 line=237
+ pc=4814277 func=37 file=36 line=125
+ pc=4815228 func=38 file=31 line=27
+Stack id=12 nframes=1
+ pc=4815680 func=34 file=31 line=37
+Stack id=6 nframes=1
+ pc=4544768 func=43 file=42 line=868
+Stack id=2 nframes=3
+ pc=4538523 func=45 file=42 line=238
+ pc=4814277 func=37 file=36 line=125
+ pc=4815228 func=38 file=31 line=27
+Stack id=13 nframes=1
+ pc=4815492 func=38 file=31 line=37
+Stack id=4 nframes=1
+ pc=4547456 func=56 file=50 line=42
+Stack id=14 nframes=2
+ pc=4642407 func=57 file=47 line=116
+ pc=4815502 func=38 file=31 line=51
+Stack id=18 nframes=5
+ pc=4816147 func=58 file=31 line=46
+ pc=4813660 func=32 file=33 line=141
+ pc=4816080 func=30 file=31 line=45
+ pc=4813660 func=32 file=33 line=141
+ pc=4815908 func=34 file=31 line=43
+Stack id=20 nframes=1
+ pc=4815908 func=34 file=31 line=43
+Stack id=25 nframes=3
+ pc=4217457 func=39 file=40 line=442
+ pc=4544973 func=41 file=42 line=918
+ pc=4547514 func=56 file=50 line=54
+Stack id=16 nframes=1
+ pc=4815908 func=34 file=31 line=43
+Stack id=15 nframes=1
+ pc=4815838 func=34 file=31 line=41
+Stack id=19 nframes=3
+ pc=4816080 func=30 file=31 line=45
+ pc=4813660 func=32 file=33 line=141
+ pc=4815908 func=34 file=31 line=43
+Stack id=10 nframes=1
+ pc=4815332 func=38 file=31 line=33
+EventBatch gen=1 m=18446744073709551615 time=28113086274600 size=1620
+Strings
+String id=1
+ data="Not worker"
+String id=2
+ data="GC (dedicated)"
+String id=3
+ data="GC (fractional)"
+String id=4
+ data="GC (idle)"
+String id=5
+ data="unspecified"
+String id=6
+ data="forever"
+String id=7
+ data="network"
+String id=8
+ data="select"
+String id=9
+ data="sync.(*Cond).Wait"
+String id=10
+ data="sync"
+String id=11
+ data="chan send"
+String id=12
+ data="chan receive"
+String id=13
+ data="GC mark assist wait for work"
+String id=14
+ data="GC background sweeper wait"
+String id=15
+ data="system goroutine wait"
+String id=16
+ data="preempted"
+String id=17
+ data="wait for debug call"
+String id=18
+ data="wait until GC ends"
+String id=19
+ data="sleep"
+String id=20
+ data="runtime.Gosched"
+String id=21
+ data="start trace"
+String id=22
+ data="task0"
+String id=23
+ data="task0 region"
+String id=24
+ data="unended region"
+String id=25
+ data="region0"
+String id=26
+ data="region1"
+String id=27
+ data="key0"
+String id=28
+ data="0123456789abcdef"
+String id=29
+ data="post-existing region"
+String id=30
+ data="main.main.func1.1"
+String id=31
+ data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/annotations.go"
+String id=32
+ data="runtime/trace.WithRegion"
+String id=33
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/annotation.go"
+String id=34
+ data="main.main.func1"
+String id=35
+ data="runtime/trace.Start.func1"
+String id=36
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go"
+String id=37
+ data="runtime/trace.Start"
+String id=38
+ data="main.main"
+String id=39
+ data="runtime.chanrecv1"
+String id=40
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go"
+String id=41
+ data="runtime.(*wakeableSleep).sleep"
+String id=42
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go"
+String id=43
+ data="runtime.(*traceAdvancerState).start.func1"
+String id=44
+ data="runtime.(*traceAdvancerState).start"
+String id=45
+ data="runtime.StartTrace"
+String id=46
+ data="sync.(*WaitGroup).Add"
+String id=47
+ data="/usr/local/google/home/mknyszek/work/go-1/src/sync/waitgroup.go"
+String id=48
+ data="sync.(*WaitGroup).Done"
+String id=49
+ data="runtime.traceStartReadCPU"
+String id=50
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2cpu.go"
+String id=51
+ data="runtime.startTheWorld"
+String id=52
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go"
+String id=53
+ data="runtime/trace.(*Task).End"
+String id=54
+ data="runtime.traceLocker.Gomaxprocs"
+String id=55
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go"
+String id=56
+ data="runtime.traceStartReadCPU.func1"
+String id=57
+ data="sync.(*WaitGroup).Wait"
+String id=58
+ data="main.main.func1.1.1"
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-confuse-seq-across-generations.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-confuse-seq-across-generations.test
new file mode 100644
index 0000000000000000000000000000000000000000..c0d6f0d3dd310140ee029cbf4177774e9f4891e4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-confuse-seq-across-generations.test
@@ -0,0 +1,36 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=13
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+GoStop dt=1 reason_string=1 stack=0
+EventBatch gen=1 m=1 time=0 size=12
+ProcStatus dt=1 p=1 pstatus=1
+GoStart dt=1 g=1 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"
+EventBatch gen=2 m=1 time=3 size=8
+ProcStatus dt=1 p=1 pstatus=1
+GoStart dt=1 g=1 g_seq=2
+EventBatch gen=2 m=0 time=5 size=17
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=1
+GoStart dt=1 g=1 g_seq=1
+GoStop dt=1 reason_string=1 stack=0
+EventBatch gen=2 m=18446744073709551615 time=0 size=5
+Frequency freq=15625000
+EventBatch gen=2 m=18446744073709551615 time=0 size=1
+Stacks
+EventBatch gen=2 m=18446744073709551615 time=0 size=12
+Strings
+String id=1
+ data="whatever"
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-reuse-thread-id.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-reuse-thread-id.test
new file mode 100644
index 0000000000000000000000000000000000000000..182073838493c367f3dd38ef5bb83c0a8d0ea3ee
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-reuse-thread-id.test
@@ -0,0 +1,23 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=37
+GoCreateSyscall dt=1 new_g=4
+GoSyscallEndBlocked dt=1
+ProcStatus dt=1 p=0 pstatus=2
+ProcStart dt=1 p=0 p_seq=1
+GoStatus dt=1 g=4 m=18446744073709551615 gstatus=1
+GoStart dt=1 g=4 g_seq=1
+GoSyscallBegin dt=1 p_seq=2 stack=0
+GoDestroySyscall dt=1
+EventBatch gen=1 m=0 time=0 size=13
+ProcStatus dt=1 p=1 pstatus=2
+ProcStart dt=1 p=1 p_seq=1
+ProcSteal dt=1 p=0 p_seq=3 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-with-p.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-with-p.test
new file mode 100644
index 0000000000000000000000000000000000000000..9b329b8bae953948e1324558ab8c160bede056bb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-create-syscall-with-p.test
@@ -0,0 +1,22 @@
+-- expect --
+FAILURE ".*expected a proc but didn't have one.*"
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=34
+GoCreateSyscall dt=1 new_g=4
+ProcStatus dt=1 p=0 pstatus=2
+ProcStart dt=1 p=0 p_seq=1
+GoSyscallEndBlocked dt=1
+GoStart dt=1 g=4 g_seq=1
+GoSyscallBegin dt=1 p_seq=2 stack=0
+GoDestroySyscall dt=1
+GoCreateSyscall dt=1 new_g=4
+GoSyscallEnd dt=1
+GoSyscallBegin dt=1 p_seq=3 stack=0
+GoDestroySyscall dt=1
+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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-gc-stress.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-gc-stress.test
new file mode 100644
index 0000000000000000000000000000000000000000..d5e7266f1e4b2eae68555d4db13518c1801e41cf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-gc-stress.test
@@ -0,0 +1,4207 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=3 m=18446744073709551615 time=28114950954550 size=5
+Frequency freq=15625000
+EventBatch gen=3 m=169438 time=28114950899454 size=615
+ProcStatus dt=2 p=47 pstatus=1
+GoStatus dt=1 g=111 m=169438 gstatus=2
+GCMarkAssistActive dt=1 g=111
+GCMarkAssistEnd dt=1
+HeapAlloc dt=38 heapalloc_value=191159744
+HeapAlloc dt=134 heapalloc_value=191192512
+GCMarkAssistBegin dt=60 stack=3
+GoStop dt=2288 reason_string=20 stack=9
+GoStart dt=15 g=111 g_seq=1
+GCMarkAssistEnd dt=1860
+HeapAlloc dt=46 heapalloc_value=191585728
+GCMarkAssistBegin dt=35 stack=3
+GoBlock dt=32 reason_string=13 stack=11
+GoUnblock dt=14 g=57 g_seq=5 stack=0
+GoStart dt=9 g=57 g_seq=6
+GoLabel dt=3 label_string=2
+GoBlock dt=2925 reason_string=15 stack=5
+GoUnblock dt=12 g=57 g_seq=7 stack=0
+GoStart dt=5 g=57 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=391 reason_string=15 stack=5
+GoUnblock dt=15 g=57 g_seq=9 stack=0
+GoStart dt=7 g=57 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=307 reason_string=15 stack=5
+GoUnblock dt=7 g=57 g_seq=11 stack=0
+GoStart dt=3 g=57 g_seq=12
+GoLabel dt=2 label_string=2
+GoBlock dt=1049 reason_string=15 stack=5
+GoUnblock dt=23 g=58 g_seq=7 stack=0
+GoStart dt=8 g=58 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=1126 reason_string=15 stack=5
+GoUnblock dt=12 g=53 g_seq=3 stack=0
+GoStart dt=5 g=53 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=1751 reason_string=15 stack=5
+GoUnblock dt=12 g=53 g_seq=5 stack=0
+GoStart dt=6 g=53 g_seq=6
+GoLabel dt=3 label_string=2
+GoBlock dt=119 reason_string=15 stack=5
+GoStart dt=15 g=88 g_seq=4
+GoBlock dt=50 reason_string=13 stack=11
+GoUnblock dt=1212 g=54 g_seq=15 stack=0
+GoStart dt=6 g=54 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=2984 reason_string=15 stack=5
+GoUnblock dt=2696 g=52 g_seq=21 stack=0
+GoStart dt=3 g=52 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=2013 reason_string=15 stack=5
+GoStart dt=18 g=98 g_seq=6
+GCMarkAssistEnd dt=6
+HeapAlloc dt=44 heapalloc_value=192003520
+GCMarkAssistBegin dt=54 stack=3
+GoBlock dt=481 reason_string=13 stack=11
+GoUnblock dt=51 g=14 g_seq=17 stack=0
+GoStart dt=4 g=14 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=3954 reason_string=15 stack=5
+GoUnblock dt=59 g=57 g_seq=41 stack=0
+GoStart dt=8 g=57 g_seq=42
+GoLabel dt=1 label_string=4
+GoBlock dt=63 reason_string=15 stack=5
+GoUnblock dt=11 g=57 g_seq=43 stack=0
+GoStart dt=4 g=57 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=3186 reason_string=15 stack=5
+GoUnblock dt=11 g=57 g_seq=45 stack=0
+GoStart dt=3 g=57 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+ProcStop dt=60
+ProcStart dt=50 p=47 p_seq=1
+GoUnblock dt=9 g=22 g_seq=33 stack=0
+GoStart dt=4 g=22 g_seq=34
+GoLabel dt=1 label_string=4
+GoBlock dt=97 reason_string=15 stack=5
+GoUnblock dt=9 g=22 g_seq=35 stack=0
+GoStart dt=5 g=22 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=2605 reason_string=15 stack=5
+GoUnblock dt=10 g=22 g_seq=37 stack=0
+GoStart dt=4 g=22 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=13 reason_string=15 stack=5
+ProcStop dt=37
+ProcStart dt=582 p=47 p_seq=2
+GoStart dt=504 g=97 g_seq=4
+GCMarkAssistEnd dt=5
+GCMarkAssistBegin dt=34 stack=3
+GoBlock dt=279 reason_string=13 stack=11
+ProcStop dt=30
+ProcStart dt=3780 p=47 p_seq=3
+GoUnblock dt=9 g=71 g_seq=25 stack=0
+GoStart dt=128 g=71 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=210 reason_string=15 stack=5
+GoUnblock dt=8 g=71 g_seq=27 stack=0
+GoStart dt=1 g=71 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=1627 reason_string=15 stack=5
+GoStart dt=27 g=105 g_seq=6
+GCMarkAssistEnd dt=3
+HeapAlloc dt=44 heapalloc_value=192477912
+GCMarkAssistBegin dt=77 stack=3
+GoStop dt=873 reason_string=20 stack=9
+GoUnblock dt=12 g=23 g_seq=47 stack=0
+GoStart dt=3 g=23 g_seq=48
+GoLabel dt=1 label_string=2
+GoBlock dt=36 reason_string=15 stack=5
+GoUnblock dt=6 g=23 g_seq=49 stack=0
+GoStart dt=1 g=23 g_seq=50
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+GoUnblock dt=8 g=23 g_seq=51 stack=0
+GoStart dt=3 g=23 g_seq=52
+GoLabel dt=1 label_string=2
+GoBlock dt=15 reason_string=15 stack=5
+GoStart dt=10 g=105 g_seq=7
+GoStop dt=16 reason_string=20 stack=9
+GoUnblock dt=7 g=23 g_seq=53 stack=0
+GoStart dt=3 g=23 g_seq=54
+GoLabel dt=1 label_string=2
+GoBlock dt=10 reason_string=15 stack=5
+GoUnblock dt=12 g=23 g_seq=55 stack=0
+GoStart dt=3 g=23 g_seq=56
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+GoUnblock dt=4 g=23 g_seq=57 stack=0
+GoStart dt=1 g=23 g_seq=58
+GoLabel dt=1 label_string=2
+GoBlock dt=4554 reason_string=15 stack=5
+GoStart dt=14 g=105 g_seq=10
+GCMarkAssistEnd dt=5
+HeapAlloc dt=65 heapalloc_value=193682136
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=44 reason_string=13 stack=11
+GoStart dt=15 g=83 g_seq=8
+HeapAlloc dt=221 heapalloc_value=194173656
+HeapAlloc dt=1927 heapalloc_value=195443416
+GoStop dt=5838 reason_string=16 stack=6
+GoStart dt=51 g=83 g_seq=9
+GCMarkAssistBegin dt=12 stack=3
+GoBlock dt=35 reason_string=10 stack=18
+GoStart dt=70 g=87 g_seq=6
+GCMarkAssistBegin dt=14 stack=3
+GoBlock dt=35 reason_string=13 stack=11
+ProcStop dt=77
+EventBatch gen=3 m=169436 time=28114950894898 size=160
+ProcStatus dt=2 p=34 pstatus=1
+GoStatus dt=3 g=107 m=169436 gstatus=2
+GCMarkAssistBegin dt=15 stack=3
+GoBlock dt=4050 reason_string=13 stack=11
+GoStatus dt=20 g=23 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=23 g_seq=1 stack=0
+GoStart dt=8 g=23 g_seq=2
+GoLabel dt=1 label_string=2
+GoUnblock dt=2316 g=81 g_seq=1 stack=12
+GoBlock dt=626 reason_string=15 stack=5
+GoUnblock dt=9 g=23 g_seq=3 stack=0
+GoStart dt=9 g=23 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=3975 reason_string=15 stack=5
+GoUnblock dt=35 g=23 g_seq=5 stack=0
+GoStart dt=6 g=23 g_seq=6
+GoLabel dt=1 label_string=2
+GoBlock dt=142 reason_string=15 stack=5
+GoUnblock dt=9 g=23 g_seq=7 stack=0
+GoStart dt=4 g=23 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=3815 reason_string=15 stack=5
+GoUnblock dt=10 g=23 g_seq=9 stack=0
+GoStart dt=6 g=23 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=3560 reason_string=15 stack=5
+GoUnblock dt=8 g=23 g_seq=11 stack=0
+GoStart dt=4 g=23 g_seq=12
+GoLabel dt=3 label_string=2
+GoBlock dt=2781 reason_string=15 stack=5
+GoUnblock dt=13 g=23 g_seq=13 stack=0
+GoStart dt=4 g=23 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=1277 reason_string=15 stack=5
+ProcStop dt=16
+EventBatch gen=3 m=169435 time=28114950897148 size=522
+ProcStatus dt=2 p=24 pstatus=1
+GoStatus dt=2 g=122 m=169435 gstatus=2
+GCMarkAssistActive dt=1 g=122
+GCMarkAssistEnd dt=3
+HeapAlloc dt=24 heapalloc_value=190602688
+GCMarkAssistBegin dt=95 stack=3
+GCMarkAssistEnd dt=4651
+GCMarkAssistBegin dt=50 stack=3
+GoBlock dt=2931 reason_string=13 stack=11
+ProcStop dt=1401
+ProcStart dt=18 p=24 p_seq=1
+GoUnblock dt=3524 g=28 g_seq=5 stack=0
+GoStart dt=10 g=28 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=42 reason_string=15 stack=5
+GoUnblock dt=1162 g=24 g_seq=11 stack=0
+GoStart dt=7 g=24 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=3050 reason_string=15 stack=5
+GoUnblock dt=5301 g=67 g_seq=15 stack=0
+GoStart dt=4 g=67 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=40 reason_string=15 stack=5
+ProcStop dt=64
+ProcStart dt=841 p=24 p_seq=2
+GoStatus dt=58 g=16 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=16 g_seq=1 stack=0
+GoStart dt=273 g=16 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=139 reason_string=15 stack=5
+ProcStop dt=52
+ProcStart dt=97 p=24 p_seq=3
+GoUnblock dt=5 g=16 g_seq=3 stack=0
+GoStart dt=2 g=16 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=471 reason_string=15 stack=5
+GoUnblock dt=58 g=16 g_seq=5 stack=0
+GoStart dt=6 g=16 g_seq=6
+GoLabel dt=3 label_string=4
+GoBlock dt=912 reason_string=15 stack=5
+GoUnblock dt=9 g=16 g_seq=7 stack=0
+GoStart dt=6 g=16 g_seq=8
+GoLabel dt=1 label_string=2
+GoUnblock dt=6571 g=113 g_seq=5 stack=12
+GoBlock dt=22 reason_string=15 stack=5
+ProcStop dt=73
+ProcStart dt=22914 p=30 p_seq=16
+GoStart dt=342 g=117 g_seq=4
+GCMarkAssistEnd dt=8
+HeapAlloc dt=67 heapalloc_value=196467152
+GoStop dt=5253 reason_string=16 stack=6
+GoStart dt=44 g=128 g_seq=7
+GCMarkAssistBegin dt=21 stack=3
+GoBlock dt=37 reason_string=10 stack=18
+GoStart dt=7 g=130 g_seq=5
+GoBlock dt=182 reason_string=10 stack=20
+ProcStop dt=81
+ProcStart dt=8287 p=2 p_seq=2
+GoStart dt=164 g=82 g_seq=11
+GCMarkAssistEnd dt=8
+HeapAlloc dt=169 heapalloc_value=104038048
+HeapAlloc dt=135 heapalloc_value=104189856
+HeapAlloc dt=126 heapalloc_value=104287136
+HeapAlloc dt=24 heapalloc_value=104308256
+HeapAlloc dt=28 heapalloc_value=104313888
+HeapAlloc dt=14 heapalloc_value=104399904
+GCSweepBegin dt=43 stack=28
+GCSweepEnd dt=8 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=4 heapalloc_value=104473632
+HeapAlloc dt=58 heapalloc_value=104510496
+HeapAlloc dt=22 heapalloc_value=104534432
+HeapAlloc dt=51 heapalloc_value=104654624
+GCSweepBegin dt=146 stack=28
+GCSweepEnd dt=8 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=4 heapalloc_value=104878624
+HeapAlloc dt=42 heapalloc_value=105007648
+HeapAlloc dt=29 heapalloc_value=105077280
+HeapAlloc dt=36 heapalloc_value=105105952
+HeapAlloc dt=44 heapalloc_value=105242784
+HeapAlloc dt=58 heapalloc_value=105431200
+HeapAlloc dt=128 heapalloc_value=105593760
+HeapAlloc dt=199 heapalloc_value=106209440
+GCSweepBegin dt=155 stack=28
+GCSweepEnd dt=13 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=106666272
+HeapAlloc dt=77 heapalloc_value=106901152
+HeapAlloc dt=64 heapalloc_value=107211808
+HeapAlloc dt=133 heapalloc_value=107661088
+HeapAlloc dt=34 heapalloc_value=107722528
+HeapAlloc dt=108 heapalloc_value=108207392
+GCSweepBegin dt=202 stack=28
+GCSweepEnd dt=13 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=108742816
+HeapAlloc dt=112 heapalloc_value=109093664
+HeapAlloc dt=207 heapalloc_value=109913120
+HeapAlloc dt=271 heapalloc_value=110834560
+HeapAlloc dt=212 heapalloc_value=111566720
+HeapAlloc dt=148 heapalloc_value=112190720
+HeapAlloc dt=74 heapalloc_value=112528128
+HeapAlloc dt=143 heapalloc_value=113050240
+HeapAlloc dt=19 heapalloc_value=113194368
+HeapAlloc dt=135 heapalloc_value=113615232
+GCSweepBegin dt=251 stack=27
+EventBatch gen=3 m=169434 time=28114950909315 size=660
+ProcStatus dt=2 p=7 pstatus=1
+GoStatus dt=2 g=71 m=169434 gstatus=2
+GoBlock dt=6 reason_string=15 stack=5
+GoUnblock dt=2633 g=53 g_seq=7 stack=0
+GoStart dt=7 g=53 g_seq=8
+GoLabel dt=3 label_string=4
+GoBlock dt=127 reason_string=15 stack=5
+GoUnblock dt=1358 g=52 g_seq=15 stack=0
+GoStart dt=7 g=52 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=27 reason_string=15 stack=5
+GoStart dt=1150 g=93 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=39 heapalloc_value=191897024
+GCMarkAssistBegin dt=27 stack=3
+GoStop dt=894 reason_string=20 stack=9
+GoStart dt=13 g=93 g_seq=5
+GoBlock dt=150 reason_string=13 stack=11
+ProcStop dt=57
+ProcStart dt=14 p=7 p_seq=1
+ProcStop dt=4205
+ProcStart dt=18 p=7 p_seq=2
+GoUnblock dt=4 g=22 g_seq=17 stack=0
+GoStart dt=172 g=22 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=1298 reason_string=15 stack=5
+GoUnblock dt=12 g=22 g_seq=19 stack=0
+GoStart dt=7 g=22 g_seq=20
+GoLabel dt=1 label_string=2
+GoBlock dt=108 reason_string=15 stack=5
+GoUnblock dt=9 g=22 g_seq=21 stack=0
+GoStart dt=4 g=22 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=309 reason_string=15 stack=5
+GoUnblock dt=19 g=57 g_seq=35 stack=0
+GoStart dt=6 g=57 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=26 reason_string=15 stack=5
+GoUnblock dt=12 g=30 g_seq=15 stack=0
+GoStart dt=4 g=30 g_seq=16
+GoLabel dt=1 label_string=2
+GoBlock dt=410 reason_string=15 stack=5
+GoUnblock dt=2384 g=23 g_seq=37 stack=0
+GoStart dt=7 g=23 g_seq=38
+GoLabel dt=1 label_string=4
+GoBlock dt=119 reason_string=15 stack=5
+GoUnblock dt=58 g=25 g_seq=21 stack=0
+GoStart dt=4 g=25 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=1875 reason_string=15 stack=5
+GoUnblock dt=53 g=29 g_seq=15 stack=0
+GoStart dt=3 g=29 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=133 reason_string=15 stack=5
+GoUnblock dt=51 g=25 g_seq=25 stack=0
+GoStart dt=5 g=25 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=14 reason_string=15 stack=5
+GoUnblock dt=42 g=25 g_seq=27 stack=0
+GoStart dt=3 g=25 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=56 reason_string=15 stack=5
+GoUnblock dt=1741 g=24 g_seq=41 stack=0
+GoStart dt=4 g=24 g_seq=42
+GoLabel dt=3 label_string=2
+GoBlock dt=15 reason_string=15 stack=5
+GoUnblock dt=26 g=25 g_seq=31 stack=0
+GoStart dt=4 g=25 g_seq=32
+GoLabel dt=1 label_string=2
+GoBlock dt=2653 reason_string=15 stack=5
+GoUnblock dt=10 g=25 g_seq=33 stack=0
+GoStart dt=6 g=25 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=151 reason_string=15 stack=5
+GoUnblock dt=37 g=25 g_seq=35 stack=0
+GoStart dt=3 g=25 g_seq=36
+GoLabel dt=1 label_string=4
+GoBlock dt=12 reason_string=15 stack=5
+GoUnblock dt=8 g=25 g_seq=37 stack=0
+GoStart dt=3 g=25 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=1197 reason_string=15 stack=5
+GoUnblock dt=38 g=22 g_seq=43 stack=0
+GoStart dt=7 g=22 g_seq=44
+GoLabel dt=1 label_string=4
+GoBlock dt=16 reason_string=15 stack=5
+ProcStop dt=28
+ProcStart dt=2728 p=7 p_seq=3
+GoUnblock dt=10 g=25 g_seq=39 stack=0
+GoStart dt=162 g=25 g_seq=40
+GoLabel dt=2 label_string=2
+GoBlock dt=36 reason_string=15 stack=5
+GoUnblock dt=10 g=25 g_seq=41 stack=0
+GoStart dt=4 g=25 g_seq=42
+GoLabel dt=1 label_string=2
+GoBlock dt=19 reason_string=15 stack=5
+GoUnblock dt=7 g=25 g_seq=43 stack=0
+GoStart dt=1 g=25 g_seq=44
+GoLabel dt=1 label_string=2
+GoUnblock dt=616 g=81 g_seq=6 stack=12
+GoBlock dt=1549 reason_string=15 stack=5
+GoStart dt=12 g=112 g_seq=5
+GoBlock dt=22 reason_string=13 stack=11
+GoStart dt=8 g=90 g_seq=4
+GCMarkAssistEnd dt=3
+HeapAlloc dt=2613 heapalloc_value=192625368
+GoStop dt=48 reason_string=16 stack=6
+GoUnblock dt=13 g=54 g_seq=35 stack=0
+GoStart dt=4 g=54 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=269 reason_string=15 stack=5
+GoUnblock dt=6 g=54 g_seq=37 stack=0
+GoStart dt=5 g=54 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=856 reason_string=15 stack=5
+GoUnblock dt=23 g=52 g_seq=61 stack=0
+GoStart dt=4 g=52 g_seq=62
+GoLabel dt=1 label_string=2
+GoBlock dt=33 reason_string=15 stack=5
+GoUnblock dt=13 g=52 g_seq=63 stack=0
+GoStart dt=2 g=52 g_seq=64
+GoLabel dt=1 label_string=2
+GoBlock dt=38 reason_string=15 stack=5
+GoUnblock dt=17 g=52 g_seq=65 stack=0
+GoStart dt=3 g=52 g_seq=66
+GoLabel dt=1 label_string=2
+GoBlock dt=37 reason_string=15 stack=5
+GoUnblock dt=11 g=52 g_seq=67 stack=0
+GoStart dt=4 g=52 g_seq=68
+GoLabel dt=1 label_string=2
+GoBlock dt=2457 reason_string=15 stack=5
+GoUnblock dt=11 g=52 g_seq=69 stack=0
+GoStart dt=4 g=52 g_seq=70
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+GoStart dt=23 g=114 g_seq=4
+GCMarkAssistEnd dt=457
+HeapAlloc dt=223 heapalloc_value=194968280
+GoStop dt=6900 reason_string=16 stack=4
+GoStart dt=24 g=114 g_seq=5
+GCMarkAssistBegin dt=86 stack=3
+GoBlock dt=43 reason_string=10 stack=18
+ProcStop dt=49
+ProcStart dt=475 p=7 p_seq=4
+ProcStop dt=40
+ProcStart dt=1388 p=7 p_seq=5
+GoUnblock dt=9 g=131 g_seq=8 stack=0
+GoStart dt=169 g=131 g_seq=9
+GoSyscallBegin dt=24 p_seq=6 stack=7
+GoSyscallEnd dt=184
+GoBlock dt=11 reason_string=15 stack=2
+ProcStop dt=42
+ProcStart dt=18109 p=16 p_seq=2
+GoStart dt=176 g=91 g_seq=4
+GCMarkAssistEnd dt=8
+HeapAlloc dt=22 heapalloc_value=114837120
+HeapAlloc dt=88 heapalloc_value=114853504
+GCSweepBegin dt=145 stack=27
+EventBatch gen=3 m=169433 time=28114950897465 size=806
+ProcStatus dt=2 p=2 pstatus=1
+GoStatus dt=1 g=24 m=169433 gstatus=2
+GoBlock dt=9 reason_string=15 stack=5
+GoUnblock dt=19 g=24 g_seq=1 stack=0
+GoStart dt=5 g=24 g_seq=2
+GoLabel dt=2 label_string=2
+GoBlock dt=4044 reason_string=15 stack=5
+GoUnblock dt=17 g=24 g_seq=3 stack=0
+GoStart dt=4 g=24 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=4262 reason_string=15 stack=5
+GoUnblock dt=19 g=28 g_seq=3 stack=0
+GoStart dt=4 g=28 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=461 reason_string=15 stack=5
+GoUnblock dt=4544 g=72 g_seq=15 stack=0
+GoStart dt=9 g=72 g_seq=16
+GoLabel dt=3 label_string=4
+GoBlock dt=32 reason_string=15 stack=5
+GoUnblock dt=9 g=72 g_seq=17 stack=0
+GoStart dt=2 g=72 g_seq=18
+GoLabel dt=2 label_string=2
+GoBlock dt=13 reason_string=15 stack=5
+GoUnblock dt=3 g=72 g_seq=19 stack=0
+GoStart dt=1 g=72 g_seq=20
+GoLabel dt=1 label_string=2
+GoBlock dt=237 reason_string=15 stack=5
+GoUnblock dt=8 g=72 g_seq=21 stack=0
+GoStart dt=3 g=72 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=151 reason_string=15 stack=5
+GoUnblock dt=11 g=72 g_seq=23 stack=0
+GoStart dt=6 g=72 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=3418 reason_string=15 stack=5
+ProcStop dt=1573
+ProcStart dt=17 p=2 p_seq=1
+ProcStop dt=1102
+ProcStart dt=21668 p=19 p_seq=4
+GoUnblock dt=16 g=51 g_seq=47 stack=0
+GoStart dt=7 g=51 g_seq=48
+GoLabel dt=1 label_string=2
+GoBlock dt=60 reason_string=15 stack=5
+GoUnblock dt=6 g=51 g_seq=49 stack=0
+GoStart dt=1 g=51 g_seq=50
+GoLabel dt=3 label_string=2
+GoBlock dt=5166 reason_string=15 stack=5
+GoStart dt=18 g=106 g_seq=5
+GCMarkAssistEnd dt=10
+HeapAlloc dt=56 heapalloc_value=193452760
+GCMarkAssistBegin dt=116 stack=3
+GCMarkAssistEnd dt=58
+HeapAlloc dt=47 heapalloc_value=193714904
+GoStop dt=54 reason_string=16 stack=6
+GoUnblock dt=18 g=54 g_seq=41 stack=0
+GoStart dt=4 g=54 g_seq=42
+GoLabel dt=2 label_string=2
+GoUnblock dt=16 g=105 g_seq=11 stack=12
+GoBlock dt=21 reason_string=15 stack=5
+GoStart dt=8 g=105 g_seq=12
+GCMarkAssistEnd dt=7
+HeapAlloc dt=33 heapalloc_value=193919704
+GCMarkAssistBegin dt=13 stack=3
+GCMarkAssistEnd dt=91
+HeapAlloc dt=173 heapalloc_value=194378456
+GCMarkAssistBegin dt=26 stack=3
+GoBlock dt=37 reason_string=13 stack=11
+GoStart dt=33 g=104 g_seq=2
+GCMarkAssistEnd dt=5
+HeapAlloc dt=81 heapalloc_value=194673368
+GoStop dt=2248 reason_string=16 stack=6
+GoStart dt=2855 g=104 g_seq=3
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=27 reason_string=10 stack=18
+GoStart dt=16 g=103 g_seq=5
+GCMarkAssistEnd dt=6
+HeapAlloc dt=6180 heapalloc_value=196655568
+GoStop dt=14 reason_string=16 stack=6
+GoStart dt=146 g=102 g_seq=5
+GCMarkAssistBegin dt=10 stack=3
+HeapAlloc dt=38 heapalloc_value=196663760
+GoBlock dt=16 reason_string=10 stack=18
+ProcStop dt=41
+ProcStart dt=1317 p=19 p_seq=5
+ProcStop dt=24
+ProcStart dt=2117 p=0 p_seq=5
+GoStart dt=5190 g=115 g_seq=10
+GCMarkAssistEnd dt=6
+GCSweepBegin dt=22 stack=27
+GCSweepEnd dt=727 swept_value=71303168 reclaimed_value=1302272
+HeapAlloc dt=37 heapalloc_value=103898784
+HeapAlloc dt=200 heapalloc_value=103947936
+HeapAlloc dt=63 heapalloc_value=103960224
+HeapAlloc dt=27 heapalloc_value=103997088
+HeapAlloc dt=65 heapalloc_value=104103584
+HeapAlloc dt=87 heapalloc_value=104132512
+HeapAlloc dt=63 heapalloc_value=104255392
+HeapAlloc dt=87 heapalloc_value=104267680
+HeapAlloc dt=73 heapalloc_value=104379424
+HeapAlloc dt=79 heapalloc_value=104494112
+GCSweepBegin dt=40 stack=28
+GCSweepEnd dt=7 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=8 heapalloc_value=104526880
+HeapAlloc dt=27 heapalloc_value=104589088
+HeapAlloc dt=42 heapalloc_value=104711968
+HeapAlloc dt=83 heapalloc_value=104821280
+GCSweepBegin dt=21 stack=28
+GCSweepEnd dt=4 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=2 heapalloc_value=104854048
+HeapAlloc dt=105 heapalloc_value=105064992
+GCSweepBegin dt=94 stack=28
+GCSweepEnd dt=9 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=4 heapalloc_value=105250976
+GCSweepBegin dt=29 stack=28
+GCSweepEnd dt=10 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=4 heapalloc_value=105447584
+HeapAlloc dt=30 heapalloc_value=105476256
+HeapAlloc dt=57 heapalloc_value=105566368
+GCSweepBegin dt=74 stack=28
+GCSweepEnd dt=5 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=105741216
+HeapAlloc dt=77 heapalloc_value=105921440
+HeapAlloc dt=76 heapalloc_value=106143904
+HeapAlloc dt=50 heapalloc_value=106274976
+HeapAlloc dt=113 heapalloc_value=106633504
+HeapAlloc dt=110 heapalloc_value=107036320
+HeapAlloc dt=95 heapalloc_value=107351072
+HeapAlloc dt=80 heapalloc_value=107702048
+GCSweepBegin dt=78 stack=28
+GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=2 heapalloc_value=107835936
+HeapAlloc dt=39 heapalloc_value=107904288
+HeapAlloc dt=82 heapalloc_value=108390432
+HeapAlloc dt=230 heapalloc_value=108955808
+HeapAlloc dt=126 heapalloc_value=109421344
+GCSweepBegin dt=131 stack=28
+GCSweepEnd dt=5 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=3 heapalloc_value=109929504
+GCSweepBegin dt=29 stack=28
+GCSweepEnd dt=4 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=3 heapalloc_value=110038816
+HeapAlloc dt=28 heapalloc_value=110109472
+HeapAlloc dt=93 heapalloc_value=110412672
+HeapAlloc dt=33 heapalloc_value=110547840
+HeapAlloc dt=123 heapalloc_value=111070848
+GCSweepBegin dt=155 stack=28
+GCSweepEnd dt=10 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=3 heapalloc_value=111648640
+GCSweepBegin dt=61 stack=28
+GCSweepEnd dt=8 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=111996800
+GCSweepBegin dt=37 stack=28
+GCSweepEnd dt=5 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=8 heapalloc_value=112149760
+HeapAlloc dt=32 heapalloc_value=112342272
+GCSweepBegin dt=75 stack=28
+GCSweepEnd dt=7 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=5 heapalloc_value=112601856
+HeapAlloc dt=61 heapalloc_value=112923264
+HeapAlloc dt=90 heapalloc_value=113262720
+HeapAlloc dt=88 heapalloc_value=113522304
+HeapAlloc dt=119 heapalloc_value=113967488
+HeapAlloc dt=59 heapalloc_value=114201216
+GCSweepBegin dt=130 stack=27
+EventBatch gen=3 m=169431 time=28114950897743 size=407
+ProcStatus dt=2 p=11 pstatus=1
+GoStatus dt=4 g=51 m=169431 gstatus=2
+GoBlock dt=6 reason_string=15 stack=5
+GoUnblock dt=13 g=51 g_seq=1 stack=0
+GoStart dt=6 g=51 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=4143 reason_string=15 stack=5
+GoStatus dt=1425 g=28 m=18446744073709551615 gstatus=4
+GoUnblock dt=2 g=28 g_seq=1 stack=0
+GoStart dt=7 g=28 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=1758 reason_string=15 stack=5
+GoUnblock dt=3904 g=25 g_seq=9 stack=0
+GoStart dt=9 g=25 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=41 reason_string=15 stack=5
+ProcStop dt=1189
+ProcStart dt=16 p=11 p_seq=1
+GoUnblock dt=1157 g=57 g_seq=21 stack=0
+GoStart dt=6 g=57 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=25 reason_string=15 stack=5
+GoUnblock dt=1614 g=52 g_seq=13 stack=0
+GoStart dt=11 g=52 g_seq=14
+GoLabel dt=4 label_string=4
+GoBlock dt=86 reason_string=15 stack=5
+GoUnblock dt=4771 g=22 g_seq=11 stack=0
+GoStart dt=12 g=22 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=1413 reason_string=15 stack=5
+GoUnblock dt=10 g=22 g_seq=13 stack=0
+GoStart dt=4 g=22 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=39 reason_string=15 stack=5
+ProcStop dt=67
+ProcStart dt=2286 p=11 p_seq=2
+ProcStop dt=95
+ProcStart dt=53 p=0 p_seq=2
+GoUnblock dt=9 g=57 g_seq=33 stack=0
+GoStart dt=8 g=57 g_seq=34
+GoLabel dt=1 label_string=4
+GoBlock dt=37 reason_string=15 stack=5
+GoUnblock dt=20 g=22 g_seq=23 stack=0
+GoStart dt=3 g=22 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=1036 reason_string=15 stack=5
+GoUnblock dt=11 g=22 g_seq=25 stack=0
+GoStart dt=6 g=22 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=2130 reason_string=15 stack=5
+GoUnblock dt=11 g=22 g_seq=27 stack=0
+GoStart dt=7 g=22 g_seq=28
+GoLabel dt=2 label_string=2
+GoBlock dt=1227 reason_string=15 stack=5
+GoUnblock dt=12 g=22 g_seq=29 stack=0
+GoStart dt=6 g=22 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=31 reason_string=15 stack=5
+GoUnblock dt=7 g=22 g_seq=31 stack=0
+GoStart dt=2 g=22 g_seq=32
+GoLabel dt=1 label_string=2
+GoBlock dt=2282 reason_string=15 stack=5
+GoUnblock dt=71 g=29 g_seq=33 stack=0
+GoStart dt=4 g=29 g_seq=34
+GoLabel dt=1 label_string=4
+GoBlock dt=1234 reason_string=15 stack=5
+GoUnblock dt=8 g=29 g_seq=35 stack=0
+GoStart dt=8 g=29 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=18 reason_string=15 stack=5
+ProcStop dt=49
+ProcStart dt=10623 p=11 p_seq=5
+ProcStop dt=54
+ProcStart dt=686 p=11 p_seq=6
+GoStart dt=185 g=127 g_seq=5
+GCMarkAssistBegin dt=71 stack=3
+GoStop dt=67 reason_string=20 stack=9
+GoUnblock dt=15 g=53 g_seq=47 stack=0
+GoStart dt=3 g=53 g_seq=48
+GoLabel dt=1 label_string=2
+GoUnblock dt=661 g=121 g_seq=10 stack=12
+GoUnblock dt=7 g=88 g_seq=5 stack=12
+GoUnblock dt=8 g=87 g_seq=4 stack=12
+GoUnblock dt=2751 g=94 g_seq=10 stack=12
+GoUnblock dt=8 g=106 g_seq=7 stack=12
+GoUnblock dt=8 g=98 g_seq=9 stack=12
+GoBlock dt=18 reason_string=15 stack=5
+GoStart dt=17 g=87 g_seq=5
+GCMarkAssistEnd dt=5
+HeapAlloc dt=202 heapalloc_value=194796248
+GoStop dt=7327 reason_string=16 stack=6
+GoStart dt=68 g=84 g_seq=8
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=29 reason_string=13 stack=11
+ProcStop dt=88
+EventBatch gen=3 m=169428 time=28114950899204 size=756
+ProcStatus dt=2 p=31 pstatus=1
+GoStatus dt=5 g=104 m=169428 gstatus=2
+GCMarkAssistActive dt=1 g=104
+GCMarkAssistEnd dt=2
+HeapAlloc dt=37 heapalloc_value=191110592
+GCMarkAssistBegin dt=21 stack=3
+GoBlock dt=2670 reason_string=13 stack=11
+GoStatus dt=1400 g=22 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=22 g_seq=1 stack=0
+GoStart dt=7 g=22 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=43 reason_string=15 stack=5
+GoUnblock dt=2567 g=70 g_seq=3 stack=0
+GoStart dt=9 g=70 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=329 reason_string=15 stack=5
+GoUnblock dt=97 g=70 g_seq=5 stack=0
+GoStart dt=5 g=70 g_seq=6
+GoLabel dt=3 label_string=2
+GoUnblock dt=1728 g=84 g_seq=3 stack=12
+GoBlock dt=3527 reason_string=15 stack=5
+GoStart dt=4132 g=114 g_seq=2
+GoStatus dt=28 g=115 m=18446744073709551615 gstatus=4
+GoUnblock dt=8 g=115 g_seq=1 stack=10
+GCMarkAssistBegin dt=18 stack=3
+GoBlock dt=196 reason_string=13 stack=11
+GoStart dt=14 g=115 g_seq=2
+GoStatus dt=18 g=102 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=102 g_seq=1 stack=10
+GCMarkAssistBegin dt=13 stack=3
+GoBlock dt=371 reason_string=13 stack=11
+GoUnblock dt=9 g=30 g_seq=11 stack=0
+GoStart dt=6 g=30 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=5520 reason_string=15 stack=5
+GoUnblock dt=8 g=30 g_seq=13 stack=0
+GoStart dt=4 g=30 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=28 reason_string=15 stack=5
+GoUnblock dt=10 g=57 g_seq=37 stack=0
+GoStart dt=3 g=57 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=157 reason_string=15 stack=5
+GoUnblock dt=7 g=57 g_seq=39 stack=0
+GoStart dt=4 g=57 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=140 reason_string=15 stack=5
+GoUnblock dt=10 g=53 g_seq=25 stack=0
+GoStart dt=3 g=53 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=90 reason_string=15 stack=5
+GoUnblock dt=62 g=53 g_seq=27 stack=0
+GoStart dt=4 g=53 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=11 reason_string=15 stack=5
+GoUnblock dt=46 g=53 g_seq=29 stack=0
+GoStart dt=7 g=53 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=51 reason_string=15 stack=5
+ProcStop dt=2236
+ProcStart dt=966 p=35 p_seq=2
+GoStart dt=19 g=81 g_seq=5
+GCMarkAssistEnd dt=7
+HeapAlloc dt=67 heapalloc_value=192133920
+GCMarkAssistBegin dt=46 stack=3
+GoBlock dt=32 reason_string=13 stack=11
+ProcStop dt=57
+ProcStart dt=15 p=35 p_seq=3
+GoUnblock dt=2 g=69 g_seq=23 stack=0
+GoStart dt=2 g=69 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=224 reason_string=15 stack=5
+GoUnblock dt=52 g=69 g_seq=25 stack=0
+GoStart dt=3 g=69 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=289 reason_string=15 stack=5
+GoStart dt=23 g=118 g_seq=2
+GCMarkAssistEnd dt=7
+HeapAlloc dt=21 heapalloc_value=192207648
+GCMarkAssistBegin dt=103 stack=3
+GoBlock dt=18 reason_string=13 stack=11
+GoUnblock dt=48 g=29 g_seq=13 stack=0
+GoStart dt=1 g=29 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=19 reason_string=15 stack=5
+GoUnblock dt=44 g=25 g_seq=23 stack=0
+GoStart dt=6 g=25 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=144 reason_string=15 stack=5
+GoUnblock dt=49 g=29 g_seq=17 stack=0
+GoStart dt=1 g=29 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=777 reason_string=15 stack=5
+GoUnblock dt=56 g=52 g_seq=31 stack=0
+GoStart dt=3 g=52 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=27 g=51 g_seq=33 stack=0
+GoStart dt=5 g=51 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=12 reason_string=15 stack=5
+GoUnblock dt=13 g=51 g_seq=35 stack=0
+GoStart dt=4 g=51 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=226 reason_string=15 stack=5
+GoUnblock dt=7 g=51 g_seq=37 stack=0
+GoStart dt=4 g=51 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=3928 reason_string=15 stack=5
+GoUnblock dt=14 g=51 g_seq=39 stack=0
+GoStart dt=3 g=51 g_seq=40
+GoLabel dt=3 label_string=2
+GoBlock dt=214 reason_string=15 stack=5
+GoUnblock dt=5 g=51 g_seq=41 stack=0
+GoStart dt=1 g=51 g_seq=42
+GoLabel dt=1 label_string=2
+GoBlock dt=305 reason_string=15 stack=5
+GoUnblock dt=8 g=51 g_seq=43 stack=0
+GoStart dt=5 g=51 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+ProcStop dt=47
+ProcStart dt=5058 p=35 p_seq=4
+GoUnblock dt=20 g=52 g_seq=51 stack=0
+GoStart dt=188 g=52 g_seq=52
+GoLabel dt=1 label_string=2
+GoBlock dt=33 reason_string=15 stack=5
+GoUnblock dt=9 g=52 g_seq=53 stack=0
+GoStart dt=4 g=52 g_seq=54
+GoLabel dt=1 label_string=2
+GoBlock dt=12 reason_string=15 stack=5
+GoStart dt=14 g=126 g_seq=3
+GCMarkAssistEnd dt=7
+HeapAlloc dt=2068 heapalloc_value=192592600
+GoStop dt=31 reason_string=16 stack=4
+GoUnblock dt=10 g=30 g_seq=39 stack=0
+GoStart dt=4 g=30 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=54 reason_string=15 stack=5
+GoStart dt=708 g=121 g_seq=9
+GoBlock dt=49 reason_string=13 stack=11
+GoStart dt=18 g=90 g_seq=5
+GCMarkAssistBegin dt=12 stack=3
+GoBlock dt=39 reason_string=13 stack=11
+GoUnblock dt=15 g=71 g_seq=31 stack=0
+GoStart dt=4 g=71 g_seq=32
+GoLabel dt=2 label_string=2
+GoBlock dt=1101 reason_string=15 stack=5
+GoUnblock dt=13 g=71 g_seq=33 stack=0
+GoStart dt=4 g=71 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=27 reason_string=15 stack=5
+GoUnblock dt=18 g=14 g_seq=54 stack=0
+GoStart dt=4 g=14 g_seq=55
+GoLabel dt=2 label_string=2
+GoUnblock dt=2171 g=94 g_seq=8 stack=12
+GoBlock dt=28 reason_string=15 stack=5
+GoStart dt=11 g=94 g_seq=9
+GCMarkAssistEnd dt=6
+HeapAlloc dt=42 heapalloc_value=193665752
+GCMarkAssistBegin dt=100 stack=3
+GoBlock dt=30 reason_string=13 stack=11
+GoStart dt=13 g=106 g_seq=6
+HeapAlloc dt=99 heapalloc_value=193977048
+GCMarkAssistBegin dt=21 stack=3
+GoBlock dt=30 reason_string=13 stack=11
+GoStart dt=16 g=92 g_seq=4
+GCMarkAssistEnd dt=6
+HeapAlloc dt=884 heapalloc_value=195205848
+GoStop dt=3270 reason_string=16 stack=4
+GoStart dt=29 g=97 g_seq=6
+GCMarkAssistEnd dt=6
+HeapAlloc dt=42 heapalloc_value=195795408
+GCMarkAssistBegin dt=3026 stack=3
+GoBlock dt=85 reason_string=10 stack=18
+ProcStop dt=99
+EventBatch gen=3 m=169426 time=28114950897488 size=116
+ProcStatus dt=1 p=32 pstatus=1
+GoStatus dt=2 g=90 m=169426 gstatus=2
+GCMarkAssistActive dt=1 g=90
+GCMarkAssistEnd dt=3
+HeapAlloc dt=47 heapalloc_value=190627264
+GCMarkAssistBegin dt=51 stack=3
+GoBlock dt=2393 reason_string=13 stack=11
+GoStart dt=1449 g=125 g_seq=2
+GoStatus dt=26 g=127 m=18446744073709551615 gstatus=4
+GoUnblock dt=16 g=127 g_seq=1 stack=10
+GCMarkAssistBegin dt=17 stack=3
+GoStop dt=6909 reason_string=20 stack=9
+GoStart dt=20 g=125 g_seq=3
+GoBlock dt=2101 reason_string=13 stack=11
+GoUnblock dt=2575 g=71 g_seq=11 stack=0
+GoStart dt=8 g=71 g_seq=12
+GoLabel dt=3 label_string=4
+GoBlock dt=44 reason_string=15 stack=5
+GoStart dt=20 g=82 g_seq=7
+GoBlock dt=367 reason_string=13 stack=11
+GoUnblock dt=11 g=22 g_seq=9 stack=0
+GoStart dt=4 g=22 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=3492 reason_string=15 stack=5
+ProcStop dt=9
+EventBatch gen=3 m=169425 time=28114950900302 size=349
+ProcStatus dt=2 p=10 pstatus=1
+GoStatus dt=2 g=70 m=169425 gstatus=2
+GoBlock dt=8 reason_string=15 stack=5
+GoUnblock dt=15 g=70 g_seq=1 stack=0
+GoStart dt=5 g=70 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=5604 reason_string=15 stack=5
+GoUnblock dt=33 g=29 g_seq=3 stack=0
+GoStart dt=5 g=29 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=1191 reason_string=15 stack=5
+GoUnblock dt=9 g=29 g_seq=5 stack=0
+GoStart dt=5 g=29 g_seq=6
+GoLabel dt=2 label_string=2
+GoBlock dt=1935 reason_string=15 stack=5
+GoUnblock dt=15 g=51 g_seq=11 stack=0
+GoStart dt=5 g=51 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=307 reason_string=15 stack=5
+ProcStop dt=4189
+ProcStart dt=15 p=10 p_seq=1
+GoUnblock dt=10 g=69 g_seq=17 stack=0
+GoStart dt=4 g=69 g_seq=18
+GoLabel dt=1 label_string=2
+GoUnblock dt=780 g=93 g_seq=3 stack=12
+GoBlock dt=6076 reason_string=15 stack=5
+GoUnblock dt=11 g=69 g_seq=19 stack=0
+GoStart dt=4 g=69 g_seq=20
+GoLabel dt=3 label_string=2
+GoUnblock dt=93 g=98 g_seq=5 stack=12
+GoBlock dt=5034 reason_string=15 stack=5
+GoUnblock dt=14 g=58 g_seq=25 stack=0
+GoStart dt=5 g=58 g_seq=26
+GoLabel dt=2 label_string=2
+GoBlock dt=1253 reason_string=15 stack=5
+GoUnblock dt=6 g=58 g_seq=27 stack=0
+GoStart dt=4 g=58 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=1031 reason_string=15 stack=5
+GoUnblock dt=6 g=58 g_seq=29 stack=0
+GoStart dt=4 g=58 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=17 reason_string=15 stack=5
+GoUnblock dt=24 g=52 g_seq=33 stack=0
+GoStart dt=6 g=52 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=321 reason_string=15 stack=5
+GoUnblock dt=75 g=29 g_seq=27 stack=0
+GoStart dt=4 g=29 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=248 reason_string=15 stack=5
+GoUnblock dt=61 g=57 g_seq=47 stack=0
+GoStart dt=4 g=57 g_seq=48
+GoLabel dt=1 label_string=4
+GoBlock dt=794 reason_string=15 stack=5
+ProcStop dt=41
+ProcStart dt=15678 p=21 p_seq=3
+GoStart dt=22 g=88 g_seq=6
+GCMarkAssistEnd dt=9
+HeapAlloc dt=84 heapalloc_value=194730712
+GoStop dt=2177 reason_string=16 stack=6
+GoStart dt=2495 g=88 g_seq=7
+GCMarkAssistBegin dt=19 stack=3
+GoBlock dt=37 reason_string=10 stack=18
+GoStart dt=15 g=126 g_seq=6
+GCMarkAssistEnd dt=5
+HeapAlloc dt=27 heapalloc_value=196114896
+GCMarkAssistBegin dt=18 stack=3
+GoBlock dt=30 reason_string=10 stack=18
+GoStart dt=15 g=98 g_seq=10
+GCMarkAssistEnd dt=6
+HeapAlloc dt=48 heapalloc_value=196155856
+GoStop dt=6168 reason_string=16 stack=6
+GoStart dt=156 g=98 g_seq=11
+GCMarkAssistBegin dt=9 stack=3
+GoBlock dt=27 reason_string=10 stack=18
+GoStart dt=27 g=94 g_seq=12
+GCMarkAssistBegin dt=13 stack=3
+GoBlock dt=35 reason_string=10 stack=18
+ProcStop dt=55
+ProcStart dt=14725 p=13 p_seq=1
+GoStart dt=171 g=112 g_seq=9
+GCMarkAssistEnd dt=6
+GCSweepBegin dt=222 stack=27
+EventBatch gen=3 m=169424 time=28114950894869 size=176
+ProcStatus dt=1 p=23 pstatus=3
+GoStatus dt=2 g=131 m=169424 gstatus=3
+GoSyscallEnd dt=1
+GoBlock dt=64 reason_string=15 stack=2
+GoUnblock dt=2260 g=67 g_seq=1 stack=0
+GoStart dt=6 g=67 g_seq=2
+GoLabel dt=2 label_string=4
+GoBlock dt=530 reason_string=15 stack=5
+GoUnblock dt=12 g=69 g_seq=3 stack=0
+GoStart dt=5 g=69 g_seq=4
+GoLabel dt=1 label_string=2
+GoUnblock dt=2455 g=90 g_seq=1 stack=12
+GoBlock dt=20 reason_string=15 stack=5
+GoUnblock dt=16 g=69 g_seq=5 stack=0
+GoStart dt=7 g=69 g_seq=6
+GoLabel dt=1 label_string=2
+GoUnblock dt=493 g=120 g_seq=2 stack=12
+GoBlock dt=1777 reason_string=15 stack=5
+GoUnblock dt=832 g=69 g_seq=7 stack=0
+GoStart dt=9 g=69 g_seq=8
+GoLabel dt=2 label_string=2
+GoBlock dt=5425 reason_string=15 stack=5
+GoUnblock dt=15 g=69 g_seq=9 stack=0
+GoStart dt=4 g=69 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=1370 reason_string=15 stack=5
+ProcStop dt=2533
+ProcStart dt=11 p=23 p_seq=1
+GoUnblock dt=3354 g=54 g_seq=17 stack=0
+GoStart dt=7 g=54 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=29 reason_string=15 stack=5
+GoUnblock dt=25 g=54 g_seq=19 stack=0
+GoStart dt=5 g=54 g_seq=20
+GoLabel dt=2 label_string=2
+GoBlock dt=232 reason_string=15 stack=5
+GoUnblock dt=11 g=54 g_seq=21 stack=0
+GoStart dt=7 g=54 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=293 reason_string=15 stack=5
+ProcStop dt=11
+EventBatch gen=3 m=169423 time=28114950894865 size=525
+ProcStatus dt=2 p=30 pstatus=1
+GoStatus dt=4 g=87 m=169423 gstatus=2
+GCMarkAssistActive dt=1 g=87
+GCMarkAssistEnd dt=2
+HeapAlloc dt=98 heapalloc_value=189963712
+GoStop dt=56 reason_string=16 stack=6
+GoUnblock dt=20 g=131 g_seq=1 stack=0
+GoStart dt=7 g=131 g_seq=2
+GoSyscallBegin dt=39 p_seq=1 stack=7
+GoSyscallEnd dt=304
+GoSyscallBegin dt=19 p_seq=2 stack=7
+GoSyscallEnd dt=59
+GoSyscallBegin dt=15 p_seq=3 stack=7
+GoSyscallEnd dt=52
+GoSyscallBegin dt=11 p_seq=4 stack=7
+GoSyscallEnd dt=50
+GoSyscallBegin dt=8 p_seq=5 stack=7
+GoSyscallEnd dt=48
+GoSyscallBegin dt=10 p_seq=6 stack=7
+GoSyscallEnd dt=54
+GoSyscallBegin dt=13 p_seq=7 stack=7
+GoSyscallEnd dt=51
+GoSyscallBegin dt=12 p_seq=8 stack=7
+GoSyscallEnd dt=49
+GoSyscallBegin dt=16 p_seq=9 stack=7
+GoSyscallEnd dt=245
+GoSyscallBegin dt=12 p_seq=10 stack=7
+GoSyscallEnd dt=49
+GoSyscallBegin dt=10 p_seq=11 stack=7
+GoSyscallEnd dt=49
+GoSyscallBegin dt=10 p_seq=12 stack=7
+GoSyscallEnd dt=48
+GoSyscallBegin dt=6 p_seq=13 stack=7
+GoSyscallEnd dt=52
+GoStop dt=24 reason_string=16 stack=8
+GoUnblock dt=9 g=14 g_seq=1 stack=0
+GoStart dt=5 g=14 g_seq=2
+GoLabel dt=1 label_string=2
+GoUnblock dt=2948 g=107 g_seq=1 stack=12
+GoBlock dt=2891 reason_string=15 stack=5
+GoUnblock dt=11 g=14 g_seq=3 stack=0
+GoStart dt=5 g=14 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=1138 reason_string=15 stack=5
+GoUnblock dt=22 g=51 g_seq=5 stack=0
+GoStart dt=5 g=51 g_seq=6
+GoLabel dt=1 label_string=2
+GoUnblock dt=451 g=82 g_seq=3 stack=12
+GoBlock dt=460 reason_string=15 stack=5
+GoUnblock dt=4052 g=54 g_seq=5 stack=0
+GoStart dt=11 g=54 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=72 reason_string=15 stack=5
+GoUnblock dt=1333 g=57 g_seq=15 stack=0
+GoStart dt=8 g=57 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=283 reason_string=15 stack=5
+GoUnblock dt=1185 g=57 g_seq=19 stack=0
+GoStart dt=7 g=57 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=134 reason_string=15 stack=5
+GoUnblock dt=1144 g=53 g_seq=11 stack=0
+GoStart dt=6 g=53 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=372 reason_string=15 stack=5
+GoUnblock dt=16 g=53 g_seq=13 stack=0
+GoStart dt=7 g=53 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=8581 reason_string=15 stack=5
+ProcStop dt=76
+ProcStart dt=22 p=30 p_seq=14
+GoUnblock dt=3 g=72 g_seq=31 stack=0
+GoStart dt=7 g=72 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=46 reason_string=15 stack=5
+GoUnblock dt=63 g=23 g_seq=31 stack=0
+GoStart dt=7 g=23 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=34 reason_string=15 stack=5
+GoUnblock dt=14 g=23 g_seq=33 stack=0
+GoStart dt=4 g=23 g_seq=34
+GoLabel dt=2 label_string=2
+GoBlock dt=47 reason_string=15 stack=5
+GoUnblock dt=74 g=53 g_seq=19 stack=0
+GoStart dt=6 g=53 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=154 reason_string=15 stack=5
+GoStatus dt=91 g=56 m=18446744073709551615 gstatus=4
+GoUnblock dt=2 g=56 g_seq=1 stack=0
+GoStart dt=43 g=56 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=45 reason_string=15 stack=5
+GoUnblock dt=65 g=53 g_seq=23 stack=0
+GoStart dt=8 g=53 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=16 reason_string=15 stack=5
+ProcStop dt=2526
+ProcStart dt=208 p=30 p_seq=15
+GoUnblock dt=8 g=53 g_seq=37 stack=0
+GoStart dt=5 g=53 g_seq=38
+GoLabel dt=1 label_string=4
+GoBlock dt=694 reason_string=15 stack=5
+GoUnblock dt=14 g=53 g_seq=39 stack=0
+GoStart dt=4 g=53 g_seq=40
+GoLabel dt=3 label_string=2
+GoBlock dt=336 reason_string=15 stack=5
+GoUnblock dt=52 g=53 g_seq=41 stack=0
+GoStart dt=4 g=53 g_seq=42
+GoLabel dt=1 label_string=4
+GoUnblock dt=449 g=118 g_seq=1 stack=12
+GoBlock dt=17 reason_string=15 stack=5
+GoUnblock dt=65 g=24 g_seq=31 stack=0
+GoStart dt=6 g=24 g_seq=32
+GoLabel dt=2 label_string=4
+GoBlock dt=56 reason_string=15 stack=5
+GoUnblock dt=54 g=24 g_seq=33 stack=0
+GoStart dt=5 g=24 g_seq=34
+GoLabel dt=1 label_string=4
+GoBlock dt=489 reason_string=15 stack=5
+GoUnblock dt=9 g=24 g_seq=35 stack=0
+GoStart dt=4 g=24 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=1307 reason_string=15 stack=5
+ProcStop dt=84
+ProcStart dt=23944 p=15 p_seq=1
+GoStart dt=174 g=108 g_seq=3
+GCMarkAssistBegin dt=25 stack=3
+GoBlock dt=59 reason_string=10 stack=18
+ProcStop dt=71
+EventBatch gen=3 m=169421 time=28114950900230 size=330
+ProcStatus dt=1 p=33 pstatus=1
+GoStatus dt=5 g=81 m=169421 gstatus=2
+GCMarkAssistActive dt=3 g=81
+GoBlock dt=7 reason_string=13 stack=11
+GoStatus dt=1543 g=57 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=57 g_seq=1 stack=0
+GoStart dt=10 g=57 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=123 reason_string=15 stack=5
+GoStatus dt=1345 g=58 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=58 g_seq=1 stack=0
+GoStart dt=5 g=58 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=154 reason_string=15 stack=5
+GoUnblock dt=5938 g=54 g_seq=7 stack=0
+GoStart dt=7 g=54 g_seq=8
+GoLabel dt=1 label_string=4
+GoBlock dt=93 reason_string=15 stack=5
+GoStart dt=1331 g=97 g_seq=2
+GoStatus dt=26 g=93 m=18446744073709551615 gstatus=4
+GoUnblock dt=6 g=93 g_seq=1 stack=10
+GCMarkAssistBegin dt=18 stack=3
+GCMarkAssistEnd dt=1894
+HeapAlloc dt=57 heapalloc_value=191872448
+GCMarkAssistBegin dt=26 stack=3
+GoBlock dt=46 reason_string=13 stack=11
+GoUnblock dt=2442 g=52 g_seq=19 stack=0
+GoStart dt=14 g=52 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=767 reason_string=15 stack=5
+ProcStop dt=2248
+ProcStart dt=24 p=33 p_seq=1
+GoUnblock dt=8 g=72 g_seq=27 stack=0
+GoStart dt=7 g=72 g_seq=28
+GoLabel dt=1 label_string=4
+GoUnblock dt=172 g=119 g_seq=3 stack=12
+GoBlock dt=1629 reason_string=15 stack=5
+GoUnblock dt=71 g=28 g_seq=9 stack=0
+GoStart dt=7 g=28 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=276 reason_string=15 stack=5
+GoUnblock dt=72 g=28 g_seq=11 stack=0
+GoStart dt=4 g=28 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=2016 reason_string=15 stack=5
+GoUnblock dt=16 g=28 g_seq=13 stack=0
+GoStart dt=7 g=28 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=6712 reason_string=15 stack=5
+ProcStop dt=63
+ProcStart dt=20808 p=14 p_seq=1
+GoStart dt=205 g=89 g_seq=7
+GCMarkAssistEnd dt=10
+HeapAlloc dt=64 heapalloc_value=196245968
+GoStop dt=6073 reason_string=16 stack=6
+GoStart dt=21 g=89 g_seq=8
+GCMarkAssistBegin dt=15 stack=3
+GoBlock dt=38 reason_string=10 stack=18
+ProcStop dt=129
+ProcStart dt=13557 p=11 p_seq=7
+GoStart dt=202 g=116 g_seq=12
+GCMarkAssistEnd dt=10
+GCSweepBegin dt=25 stack=28
+GCSweepEnd dt=12 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=114760576
+GCSweepBegin dt=70 stack=28
+GCSweepEnd dt=5 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=1 heapalloc_value=114785152
+GCSweepBegin dt=353 stack=27
+EventBatch gen=3 m=169420 time=28114950896337 size=112
+ProcStatus dt=2 p=17 pstatus=1
+GoStatus dt=1 g=84 m=169420 gstatus=2
+GCMarkAssistActive dt=1 g=84
+GCMarkAssistEnd dt=3
+HeapAlloc dt=20 heapalloc_value=190365120
+GCMarkAssistBegin dt=42 stack=3
+GoStop dt=861 reason_string=20 stack=9
+GoStart dt=142 g=126 g_seq=1
+GoBlock dt=2538 reason_string=13 stack=11
+GoUnblock dt=1653 g=30 g_seq=1 stack=0
+GoStart dt=7 g=30 g_seq=2
+GoLabel dt=2 label_string=4
+GoBlock dt=6064 reason_string=15 stack=5
+GoUnblock dt=1633 g=25 g_seq=11 stack=0
+GoStart dt=8 g=25 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=4927 reason_string=15 stack=5
+GoUnblock dt=3569 g=67 g_seq=11 stack=0
+GoStart dt=7 g=67 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=1289 reason_string=15 stack=5
+GoUnblock dt=73 g=67 g_seq=13 stack=0
+GoStart dt=4 g=67 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=46 reason_string=15 stack=5
+ProcStop dt=52
+EventBatch gen=3 m=169419 time=28114950898971 size=132
+ProcStatus dt=2 p=13 pstatus=1
+GoStatus dt=2 g=30 m=169419 gstatus=2
+GoBlock dt=7 reason_string=15 stack=5
+GoUnblock dt=2697 g=72 g_seq=1 stack=0
+GoStart dt=8 g=72 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=969 reason_string=15 stack=5
+GoStart dt=2978 g=95 g_seq=2
+GoStatus dt=32 g=88 m=18446744073709551615 gstatus=4
+GoUnblock dt=7 g=88 g_seq=1 stack=10
+GCMarkAssistBegin dt=18 stack=3
+GoStop dt=1258 reason_string=20 stack=9
+GoStart dt=17 g=88 g_seq=2
+GoStatus dt=27 g=113 m=18446744073709551615 gstatus=4
+GoUnblock dt=5 g=113 g_seq=1 stack=10
+GCMarkAssistBegin dt=12 stack=3
+GoStop dt=1797 reason_string=20 stack=9
+GoStart dt=18 g=88 g_seq=3
+GoStop dt=2883 reason_string=20 stack=9
+GoUnblock dt=14 g=70 g_seq=7 stack=0
+GoStart dt=5 g=70 g_seq=8
+GoLabel dt=3 label_string=2
+GoBlock dt=5294 reason_string=15 stack=5
+GoStart dt=14 g=123 g_seq=5
+GoBlock dt=18 reason_string=13 stack=11
+ProcStop dt=16
+EventBatch gen=3 m=169418 time=28114950895095 size=398
+ProcStatus dt=1 p=35 pstatus=2
+ProcStart dt=2 p=35 p_seq=1
+GoStart dt=38 g=87 g_seq=1
+HeapAlloc dt=103 heapalloc_value=190086592
+GCMarkAssistBegin dt=64 stack=3
+GCMarkAssistEnd dt=3228
+HeapAlloc dt=76 heapalloc_value=190995904
+GCMarkAssistBegin dt=149 stack=3
+GoBlock dt=3823 reason_string=13 stack=11
+GoStart dt=1406 g=82 g_seq=4
+GCMarkAssistEnd dt=12
+HeapAlloc dt=82 heapalloc_value=191618496
+GCMarkAssistBegin dt=75 stack=3
+GoStop dt=4342 reason_string=20 stack=9
+GoStart dt=17 g=82 g_seq=5
+GoStop dt=987 reason_string=20 stack=9
+GoStart dt=26 g=82 g_seq=6
+GoStop dt=3601 reason_string=20 stack=9
+GoUnblock dt=14 g=58 g_seq=17 stack=0
+GoStart dt=3 g=58 g_seq=18
+GoLabel dt=3 label_string=2
+GoBlock dt=1524 reason_string=15 stack=5
+GoUnblock dt=23 g=25 g_seq=15 stack=0
+GoStart dt=8 g=25 g_seq=16
+GoLabel dt=3 label_string=2
+GoBlock dt=7942 reason_string=15 stack=5
+ProcStop dt=2920
+ProcStart dt=69 p=31 p_seq=1
+GoUnblock dt=7 g=67 g_seq=25 stack=0
+GoStart dt=5 g=67 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=1990 reason_string=15 stack=5
+GoUnblock dt=110 g=67 g_seq=29 stack=0
+GoStart dt=6 g=67 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=39 reason_string=15 stack=5
+GoUnblock dt=64 g=52 g_seq=29 stack=0
+GoStart dt=1 g=52 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=40 reason_string=15 stack=5
+GoUnblock dt=72 g=29 g_seq=19 stack=0
+GoStart dt=7 g=29 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=65 reason_string=15 stack=5
+GoUnblock dt=1007 g=23 g_seq=43 stack=0
+GoStart dt=8 g=23 g_seq=44
+GoLabel dt=1 label_string=4
+GoBlock dt=1633 reason_string=15 stack=5
+GoUnblock dt=7 g=23 g_seq=45 stack=0
+GoStart dt=160 g=23 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=16 reason_string=15 stack=5
+ProcStop dt=31
+ProcStart dt=8279 p=26 p_seq=2
+GoStart dt=216 g=103 g_seq=3
+GCMarkAssistBegin dt=19 stack=3
+GoBlock dt=41 reason_string=13 stack=11
+GoUnblock dt=11 g=25 g_seq=47 stack=0
+GoStart dt=3 g=25 g_seq=48
+GoLabel dt=1 label_string=2
+GoBlock dt=1274 reason_string=15 stack=5
+ProcStop dt=46
+ProcStart dt=1294 p=26 p_seq=3
+GoStart dt=164 g=127 g_seq=6
+GoStop dt=45 reason_string=20 stack=9
+GoStart dt=17 g=127 g_seq=7
+GCMarkAssistEnd dt=1921
+GoStop dt=49 reason_string=16 stack=17
+GoUnblock dt=17 g=22 g_seq=59 stack=0
+GoStart dt=8 g=22 g_seq=60
+GoLabel dt=1 label_string=2
+GoBlock dt=75 reason_string=15 stack=5
+GoStart dt=44 g=83 g_seq=7
+GCMarkAssistEnd dt=4
+GCMarkAssistBegin dt=50 stack=3
+GCMarkAssistEnd dt=27
+HeapAlloc dt=55 heapalloc_value=193551064
+GoStop dt=47 reason_string=16 stack=4
+GoStart dt=30 g=84 g_seq=7
+HeapAlloc dt=82 heapalloc_value=193772248
+HeapAlloc dt=291 heapalloc_value=194239192
+HeapAlloc dt=198 heapalloc_value=194493144
+HeapAlloc dt=7678 heapalloc_value=196524496
+GoStop dt=18 reason_string=16 stack=6
+ProcStop dt=218
+ProcStart dt=2082 p=26 p_seq=4
+ProcStop dt=68
+ProcStart dt=16818 p=14 p_seq=2
+GoStart dt=242 g=118 g_seq=7
+GCMarkAssistEnd dt=8
+GCSweepBegin dt=32 stack=28
+GCSweepEnd dt=11 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=114809728
+GCSweepBegin dt=279 stack=27
+EventBatch gen=3 m=169417 time=28114950894785 size=650
+ProcStatus dt=2 p=18 pstatus=1
+GoStatus dt=2 g=120 m=169417 gstatus=2
+GCMarkAssistActive dt=1 g=120
+GCMarkAssistEnd dt=2
+HeapAlloc dt=26 heapalloc_value=189767104
+GoStop dt=131 reason_string=16 stack=4
+GoStart dt=59 g=120 g_seq=1
+HeapAlloc dt=138 heapalloc_value=190045632
+GCMarkAssistBegin dt=31 stack=3
+GCMarkAssistEnd dt=3339
+HeapAlloc dt=63 heapalloc_value=190938560
+GCMarkAssistBegin dt=150 stack=3
+GoBlock dt=270 reason_string=13 stack=11
+GoUnblock dt=4058 g=57 g_seq=3 stack=0
+GoStart dt=7 g=57 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=902 reason_string=15 stack=5
+GoUnblock dt=4049 g=30 g_seq=3 stack=0
+GoStart dt=8 g=30 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=521 reason_string=15 stack=5
+GoUnblock dt=1581 g=57 g_seq=17 stack=0
+GoStart dt=11 g=57 g_seq=18
+GoLabel dt=3 label_string=4
+GoBlock dt=37 reason_string=15 stack=5
+GoUnblock dt=14 g=69 g_seq=11 stack=0
+GoStart dt=4 g=69 g_seq=12
+GoLabel dt=3 label_string=2
+GoBlock dt=543 reason_string=15 stack=5
+GoUnblock dt=10 g=69 g_seq=13 stack=0
+GoStart dt=6 g=69 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=1813 reason_string=15 stack=5
+ProcStop dt=2875
+ProcStart dt=28 p=18 p_seq=1
+GoUnblock dt=1296 g=54 g_seq=23 stack=0
+GoStart dt=7 g=54 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=1516 reason_string=15 stack=5
+GoUnblock dt=7 g=54 g_seq=25 stack=0
+GoStart dt=5 g=54 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=6851 reason_string=15 stack=5
+GoUnblock dt=71 g=72 g_seq=41 stack=0
+GoStart dt=5 g=72 g_seq=42
+GoLabel dt=1 label_string=4
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=5 g=72 g_seq=43 stack=0
+GoStart dt=3 g=72 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=62 reason_string=15 stack=5
+GoUnblock dt=19 g=72 g_seq=45 stack=0
+GoStart dt=4 g=72 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=3727 reason_string=15 stack=5
+ProcStop dt=69
+ProcStart dt=21 p=18 p_seq=2
+GoUnblock dt=10 g=70 g_seq=15 stack=0
+GoStart dt=3 g=70 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=14 reason_string=15 stack=5
+GoUnblock dt=49 g=70 g_seq=17 stack=0
+GoStart dt=3 g=70 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=2314 reason_string=15 stack=5
+ProcStop dt=46
+ProcStart dt=1398 p=18 p_seq=3
+ProcStop dt=38
+ProcStart dt=4183 p=18 p_seq=4
+GoStart dt=183 g=96 g_seq=4
+GCMarkAssistEnd dt=9
+HeapAlloc dt=36 heapalloc_value=192305952
+GCMarkAssistBegin dt=28 stack=3
+GoBlock dt=1320 reason_string=13 stack=11
+GoUnblock dt=15 g=25 g_seq=45 stack=0
+GoStart dt=7 g=25 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=600 reason_string=15 stack=5
+GoStart dt=13 g=89 g_seq=5
+GCMarkAssistBegin dt=11 stack=3
+GoBlock dt=112 reason_string=13 stack=11
+GoStart dt=14 g=121 g_seq=8
+GoStop dt=1488 reason_string=20 stack=9
+GoUnblock dt=16 g=25 g_seq=49 stack=0
+GoStart dt=7 g=25 g_seq=50
+GoLabel dt=2 label_string=2
+GoUnblock dt=1803 g=115 g_seq=6 stack=12
+GoUnblock dt=5 g=93 g_seq=6 stack=12
+GoUnblock dt=6 g=85 g_seq=5 stack=12
+GoUnblock dt=3 g=104 g_seq=1 stack=12
+GoUnblock dt=6 g=108 g_seq=1 stack=12
+GoUnblock dt=4 g=120 g_seq=4 stack=12
+GoUnblock dt=4 g=126 g_seq=5 stack=12
+GoUnblock dt=7 g=114 g_seq=3 stack=12
+GoUnblock dt=5 g=86 g_seq=4 stack=12
+GoUnblock dt=4 g=110 g_seq=3 stack=12
+GoBlock dt=14 reason_string=15 stack=5
+GoUnblock dt=7 g=25 g_seq=51 stack=0
+GoStart dt=1 g=25 g_seq=52
+GoLabel dt=1 label_string=2
+GoBlock dt=12 reason_string=15 stack=5
+GoStart dt=8 g=115 g_seq=7
+GCMarkAssistEnd dt=6
+HeapAlloc dt=32 heapalloc_value=192838360
+GCMarkAssistBegin dt=55 stack=3
+GoStop dt=1501 reason_string=20 stack=9
+GoUnblock dt=18 g=51 g_seq=51 stack=0
+GoStart dt=6 g=51 g_seq=52
+GoLabel dt=1 label_string=2
+GoUnblock dt=1117 g=105 g_seq=13 stack=12
+GoBlock dt=8 reason_string=15 stack=5
+GoStart dt=8 g=105 g_seq=14
+GCMarkAssistEnd dt=6
+GCMarkAssistBegin dt=27 stack=3
+GoBlock dt=13 reason_string=13 stack=11
+GoStart dt=7 g=86 g_seq=5
+GCMarkAssistEnd dt=6
+HeapAlloc dt=12 heapalloc_value=195148504
+GCMarkAssistBegin dt=65 stack=3
+HeapAlloc dt=22 heapalloc_value=195214040
+GoBlock dt=17 reason_string=10 stack=18
+GoStart dt=2881 g=124 g_seq=5
+HeapAlloc dt=35 heapalloc_value=195517144
+HeapAlloc dt=15 heapalloc_value=195566296
+HeapAlloc dt=61 heapalloc_value=195574224
+HeapAlloc dt=16 heapalloc_value=195631568
+GCMarkAssistBegin dt=23 stack=3
+GoBlock dt=34 reason_string=10 stack=18
+GoStart dt=14 g=90 g_seq=7
+GCMarkAssistEnd dt=5
+HeapAlloc dt=4 heapalloc_value=195697104
+GCMarkAssistBegin dt=58 stack=3
+GoBlock dt=15 reason_string=10 stack=18
+GoStart dt=10 g=96 g_seq=6
+GCMarkAssistEnd dt=3
+GCMarkAssistBegin dt=37 stack=3
+GoBlock dt=16 reason_string=13 stack=11
+GoStart dt=14 g=92 g_seq=5
+GCMarkAssistBegin dt=75 stack=3
+GoBlock dt=25 reason_string=10 stack=18
+GoStart dt=9 g=119 g_seq=6
+GCMarkAssistEnd dt=5
+HeapAlloc dt=20 heapalloc_value=195926480
+GCMarkAssistBegin dt=19 stack=3
+GoBlock dt=14 reason_string=10 stack=18
+GoStart dt=9 g=85 g_seq=6
+GCMarkAssistEnd dt=3
+HeapAlloc dt=38 heapalloc_value=195983824
+GoStop dt=5763 reason_string=16 stack=6
+GoStart dt=15 g=85 g_seq=7
+GCMarkAssistBegin dt=6 stack=3
+GoBlock dt=21 reason_string=10 stack=18
+ProcStop dt=46
+ProcStart dt=17429 p=15 p_seq=2
+GoStart dt=180 g=3 g_seq=2
+EventBatch gen=3 m=169416 time=28114950894874 size=516
+ProcStatus dt=2 p=26 pstatus=1
+GoStatus dt=1 g=98 m=169416 gstatus=2
+GCMarkAssistActive dt=1 g=98
+GCMarkAssistEnd dt=2
+HeapAlloc dt=136 heapalloc_value=190004672
+GoStop dt=29 reason_string=16 stack=4
+GoStart dt=29 g=86 g_seq=1
+GCMarkAssistBegin dt=75 stack=3
+GCMarkAssistEnd dt=8456
+HeapAlloc dt=48 heapalloc_value=191569344
+GoStop dt=32 reason_string=16 stack=4
+GoStart dt=19 g=86 g_seq=2
+GCMarkAssistBegin dt=73 stack=3
+GoStop dt=324 reason_string=20 stack=9
+GoStart dt=11 g=116 g_seq=3
+GoStop dt=270 reason_string=20 stack=9
+GoUnblock dt=14 g=51 g_seq=7 stack=0
+GoStart dt=4 g=51 g_seq=8
+GoLabel dt=3 label_string=2
+GoBlock dt=4139 reason_string=15 stack=5
+GoUnblock dt=9 g=51 g_seq=9 stack=0
+GoStart dt=6 g=51 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=564 reason_string=15 stack=5
+GoUnblock dt=12 g=29 g_seq=7 stack=0
+GoStart dt=4 g=29 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=13475 reason_string=15 stack=5
+ProcStop dt=61
+ProcStart dt=17 p=26 p_seq=1
+GoUnblock dt=6 g=53 g_seq=31 stack=0
+GoStart dt=3 g=53 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=18 reason_string=15 stack=5
+GoUnblock dt=6 g=53 g_seq=33 stack=0
+GoStart dt=4 g=53 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=2291 reason_string=15 stack=5
+GoUnblock dt=8 g=53 g_seq=35 stack=0
+GoStart dt=4 g=53 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=32 reason_string=15 stack=5
+GoUnblock dt=68 g=29 g_seq=9 stack=0
+GoStart dt=4 g=29 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=796 reason_string=15 stack=5
+GoUnblock dt=60 g=29 g_seq=11 stack=0
+GoStart dt=4 g=29 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=643 reason_string=15 stack=5
+GoUnblock dt=61 g=53 g_seq=43 stack=0
+GoStart dt=4 g=53 g_seq=44
+GoLabel dt=1 label_string=4
+GoBlock dt=3485 reason_string=15 stack=5
+GoUnblock dt=10 g=53 g_seq=45 stack=0
+GoStart dt=5 g=53 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=14 reason_string=15 stack=5
+ProcStop dt=38
+ProcStart dt=9443 p=0 p_seq=3
+GoStart dt=226 g=115 g_seq=5
+GoBlock dt=168 reason_string=13 stack=11
+GoUnblock dt=11 g=30 g_seq=37 stack=0
+GoStart dt=6 g=30 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=67 reason_string=15 stack=5
+ProcStop dt=46
+ProcStart dt=1842 p=25 p_seq=6
+GoUnblock dt=12 g=29 g_seq=37 stack=0
+GoStart dt=5 g=29 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=2260 reason_string=15 stack=5
+GoUnblock dt=16 g=29 g_seq=39 stack=0
+GoStart dt=4 g=29 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=19 reason_string=15 stack=5
+GoStart dt=34 g=99 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=55 heapalloc_value=193501912
+GoStop dt=29 reason_string=16 stack=4
+GoUnblock dt=18 g=29 g_seq=41 stack=0
+GoStart dt=7 g=29 g_seq=42
+GoLabel dt=1 label_string=2
+GoBlock dt=10 reason_string=15 stack=5
+GoUnblock dt=14 g=29 g_seq=43 stack=0
+GoStart dt=4 g=29 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=40 reason_string=15 stack=5
+GoStart dt=16 g=111 g_seq=6
+GoBlock dt=37 reason_string=13 stack=11
+GoStart dt=13 g=125 g_seq=6
+GCMarkAssistBegin dt=13 stack=3
+GoBlock dt=34 reason_string=13 stack=11
+GoStart dt=23 g=115 g_seq=8
+GoBlock dt=61 reason_string=13 stack=11
+GoStart dt=27 g=120 g_seq=5
+GCMarkAssistEnd dt=12
+HeapAlloc dt=82 heapalloc_value=194067160
+GoStop dt=22 reason_string=16 stack=4
+GoStart dt=10 g=93 g_seq=7
+GCMarkAssistEnd dt=4
+HeapAlloc dt=663 heapalloc_value=194992856
+GCMarkAssistBegin dt=23 stack=3
+GoBlock dt=12 reason_string=13 stack=11
+GoStart dt=11 g=99 g_seq=7
+GCMarkAssistEnd dt=5
+HeapAlloc dt=4741 heapalloc_value=196180432
+GoStop dt=10 reason_string=16 stack=6
+GoStart dt=19 g=99 g_seq=8
+GCMarkAssistBegin dt=8 stack=3
+GoBlock dt=18 reason_string=10 stack=18
+GoStart dt=9 g=100 g_seq=4
+GCMarkAssistEnd dt=5
+HeapAlloc dt=101 heapalloc_value=196295120
+GoStop dt=6074 reason_string=16 stack=6
+GoStart dt=49 g=100 g_seq=5
+GCMarkAssistBegin dt=10 stack=3
+GoBlock dt=32 reason_string=13 stack=11
+ProcStop dt=67
+ProcStart dt=12947 p=10 p_seq=3
+GoStart dt=200 g=86 g_seq=7
+GoUnblock dt=38 g=124 g_seq=6 stack=30
+GCMarkAssistEnd dt=5
+HeapAlloc dt=90 heapalloc_value=113809792
+HeapAlloc dt=112 heapalloc_value=114160256
+GCSweepBegin dt=694 stack=31
+EventBatch gen=3 m=169415 time=28114950903030 size=633
+ProcStatus dt=1 p=28 pstatus=1
+GoStatus dt=3 g=91 m=169415 gstatus=2
+GCMarkAssistActive dt=1 g=91
+GCMarkAssistEnd dt=2
+HeapAlloc dt=29 heapalloc_value=191479232
+GCMarkAssistBegin dt=84 stack=3
+GoBlock dt=82 reason_string=13 stack=11
+GoStart dt=4920 g=113 g_seq=2
+GoStatus dt=31 g=123 m=18446744073709551615 gstatus=4
+GoUnblock dt=10 g=123 g_seq=1 stack=10
+GCMarkAssistBegin dt=14 stack=3
+GoStop dt=1855 reason_string=20 stack=9
+GoStart dt=15 g=113 g_seq=3
+GoStop dt=352 reason_string=20 stack=9
+GoStart dt=13 g=113 g_seq=4
+GoBlock dt=261 reason_string=13 stack=11
+GoUnblock dt=3404 g=52 g_seq=17 stack=0
+GoStart dt=7 g=52 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=1025 reason_string=15 stack=5
+GoUnblock dt=4703 g=67 g_seq=17 stack=0
+GoStart dt=8 g=67 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=1418 reason_string=15 stack=5
+GoUnblock dt=72 g=23 g_seq=29 stack=0
+GoStart dt=4 g=23 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=307 reason_string=15 stack=5
+GoUnblock dt=85 g=72 g_seq=33 stack=0
+GoStart dt=5 g=72 g_seq=34
+GoLabel dt=3 label_string=4
+GoBlock dt=30 reason_string=15 stack=5
+GoStatus dt=168 g=68 m=18446744073709551615 gstatus=4
+GoUnblock dt=2 g=68 g_seq=1 stack=0
+GoStart dt=64 g=68 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=55 reason_string=15 stack=5
+GoUnblock dt=10 g=68 g_seq=3 stack=0
+GoStart dt=3 g=68 g_seq=4
+GoLabel dt=2 label_string=2
+GoBlock dt=327 reason_string=15 stack=5
+ProcStop dt=80
+ProcStart dt=25 p=28 p_seq=1
+GoUnblock dt=7 g=30 g_seq=17 stack=0
+GoStart dt=4 g=30 g_seq=18
+GoLabel dt=3 label_string=4
+GoBlock dt=2630 reason_string=15 stack=5
+GoUnblock dt=28 g=72 g_seq=39 stack=0
+GoStart dt=12 g=72 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=77 g=30 g_seq=19 stack=0
+GoStart dt=10 g=30 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=3781 reason_string=15 stack=5
+GoUnblock dt=15 g=30 g_seq=21 stack=0
+GoStart dt=5 g=30 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=2537 reason_string=15 stack=5
+GoUnblock dt=55 g=30 g_seq=23 stack=0
+GoStart dt=5 g=30 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=478 reason_string=15 stack=5
+GoUnblock dt=8 g=30 g_seq=25 stack=0
+GoStart dt=4 g=30 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=1039 reason_string=15 stack=5
+GoStart dt=26 g=14 g_seq=37
+GoBlock dt=1631 reason_string=15 stack=5
+GoUnblock dt=22 g=52 g_seq=43 stack=0
+GoStart dt=8 g=52 g_seq=44
+GoLabel dt=3 label_string=2
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=9 g=52 g_seq=45 stack=0
+GoStart dt=3 g=52 g_seq=46
+GoLabel dt=1 label_string=2
+GoBlock dt=17 reason_string=15 stack=5
+GoUnblock dt=6 g=52 g_seq=47 stack=0
+GoStart dt=3 g=52 g_seq=48
+GoLabel dt=1 label_string=2
+GoUnblock dt=217 g=112 g_seq=3 stack=12
+GoBlock dt=298 reason_string=15 stack=5
+GoUnblock dt=8 g=52 g_seq=49 stack=0
+GoStart dt=3 g=52 g_seq=50
+GoLabel dt=1 label_string=2
+GoBlock dt=1919 reason_string=15 stack=5
+GoStart dt=16 g=121 g_seq=6
+GCMarkAssistEnd dt=6
+HeapAlloc dt=1354 heapalloc_value=192363224
+GoStop dt=25 reason_string=16 stack=4
+GoStart dt=16 g=121 g_seq=7
+GCMarkAssistBegin dt=74 stack=3
+GoStop dt=496 reason_string=20 stack=9
+GoUnblock dt=11 g=52 g_seq=55 stack=0
+GoStart dt=4 g=52 g_seq=56
+GoLabel dt=1 label_string=2
+GoUnblock dt=1666 g=94 g_seq=5 stack=12
+GoBlock dt=18 reason_string=15 stack=5
+GoUnblock dt=18 g=30 g_seq=41 stack=0
+GoStart dt=4 g=30 g_seq=42
+GoLabel dt=1 label_string=2
+GoUnblock dt=1362 g=84 g_seq=5 stack=12
+GoUnblock dt=6 g=125 g_seq=4 stack=12
+GoUnblock dt=5 g=118 g_seq=3 stack=12
+GoBlock dt=9 reason_string=15 stack=5
+GoUnblock dt=10 g=30 g_seq=43 stack=0
+GoStart dt=3 g=30 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+GoStart dt=6 g=84 g_seq=6
+GCMarkAssistEnd dt=5
+HeapAlloc dt=24 heapalloc_value=192748248
+GCMarkAssistBegin dt=83 stack=3
+GCMarkAssistEnd dt=1516
+HeapAlloc dt=28 heapalloc_value=193231576
+GoStop dt=27 reason_string=16 stack=6
+GoUnblock dt=14 g=22 g_seq=57 stack=0
+GoStart dt=3 g=22 g_seq=58
+GoLabel dt=1 label_string=2
+GoUnblock dt=16 g=81 g_seq=8 stack=12
+GoBlock dt=10 reason_string=15 stack=5
+GoStart dt=11 g=125 g_seq=5
+GCMarkAssistEnd dt=5
+HeapAlloc dt=16 heapalloc_value=193354456
+GoStop dt=95 reason_string=16 stack=6
+GoUnblock dt=34 g=22 g_seq=61 stack=0
+GoStart dt=1 g=22 g_seq=62
+GoLabel dt=1 label_string=2
+GoUnblock dt=1090 g=99 g_seq=6 stack=12
+GoBlock dt=10 reason_string=15 stack=5
+GoStart dt=8 g=81 g_seq=9
+GCMarkAssistEnd dt=5
+HeapAlloc dt=3528 heapalloc_value=195729872
+GoStop dt=10 reason_string=16 stack=6
+GoStart dt=17 g=81 g_seq=10
+GCMarkAssistBegin dt=9 stack=3
+GoBlock dt=34 reason_string=10 stack=18
+GoStart dt=20 g=121 g_seq=11
+GCMarkAssistEnd dt=4
+HeapAlloc dt=44 heapalloc_value=195852752
+GoStop dt=7425 reason_string=16 stack=6
+ProcStop dt=134
+ProcStart dt=14156 p=12 p_seq=2
+GoStart dt=200 g=84 g_seq=10
+GCMarkAssistEnd dt=6
+GCSweepBegin dt=35 stack=27
+EventBatch gen=3 m=169414 time=28114950903409 size=415
+ProcStatus dt=1 p=19 pstatus=1
+GoStatus dt=1 g=54 m=169414 gstatus=2
+GoBlock dt=7 reason_string=15 stack=5
+GoUnblock dt=2586 g=25 g_seq=5 stack=0
+GoStart dt=8 g=25 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=2605 reason_string=15 stack=5
+GoUnblock dt=1216 g=71 g_seq=3 stack=0
+GoStart dt=7 g=71 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=672 reason_string=15 stack=5
+GoUnblock dt=7231 g=23 g_seq=15 stack=0
+GoStart dt=8 g=23 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=1212 reason_string=15 stack=5
+GoUnblock dt=11 g=23 g_seq=17 stack=0
+GoStart dt=7 g=23 g_seq=18
+GoLabel dt=3 label_string=2
+GoBlock dt=82 reason_string=15 stack=5
+GoUnblock dt=9 g=23 g_seq=19 stack=0
+GoStart dt=6 g=23 g_seq=20
+GoLabel dt=1 label_string=2
+GoBlock dt=162 reason_string=15 stack=5
+ProcStop dt=99
+ProcStart dt=3257 p=19 p_seq=1
+GoUnblock dt=13 g=68 g_seq=5 stack=0
+GoStart dt=10 g=68 g_seq=6
+GoLabel dt=1 label_string=2
+GoBlock dt=43 reason_string=15 stack=5
+GoUnblock dt=12 g=68 g_seq=7 stack=0
+GoStart dt=2 g=68 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=133 reason_string=15 stack=5
+GoUnblock dt=23 g=58 g_seq=23 stack=0
+GoStart dt=6 g=58 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=2822 reason_string=15 stack=5
+GoUnblock dt=11 g=69 g_seq=21 stack=0
+GoStart dt=7 g=69 g_seq=22
+GoLabel dt=2 label_string=2
+GoBlock dt=25 reason_string=15 stack=5
+GoUnblock dt=2937 g=58 g_seq=31 stack=0
+GoStart dt=6 g=58 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=20 reason_string=15 stack=5
+ProcStop dt=60
+ProcStart dt=31 p=19 p_seq=2
+GoUnblock dt=9 g=56 g_seq=7 stack=0
+GoStart dt=6 g=56 g_seq=8
+GoLabel dt=3 label_string=4
+GoBlock dt=949 reason_string=15 stack=5
+ProcStop dt=41
+ProcStart dt=433 p=19 p_seq=3
+ProcStop dt=43
+ProcStart dt=9942 p=11 p_seq=4
+ProcStop dt=50
+ProcStart dt=2351 p=22 p_seq=6
+GoUnblock dt=15 g=30 g_seq=45 stack=0
+GoStart dt=205 g=30 g_seq=46
+GoLabel dt=1 label_string=2
+GoUnblock dt=145 g=113 g_seq=7 stack=12
+GoBlock dt=21 reason_string=15 stack=5
+GoStart dt=10 g=113 g_seq=8
+GCMarkAssistEnd dt=8
+HeapAlloc dt=48 heapalloc_value=192895704
+GCMarkAssistBegin dt=118 stack=3
+GCMarkAssistEnd dt=272
+HeapAlloc dt=20 heapalloc_value=192936664
+HeapAlloc dt=89 heapalloc_value=192953048
+HeapAlloc dt=41 heapalloc_value=192994008
+HeapAlloc dt=92 heapalloc_value=193059544
+HeapAlloc dt=102 heapalloc_value=193108696
+HeapAlloc dt=94 heapalloc_value=193133272
+HeapAlloc dt=42 heapalloc_value=193141464
+HeapAlloc dt=31 heapalloc_value=193207000
+GCMarkAssistBegin dt=142 stack=3
+GoBlock dt=114 reason_string=13 stack=11
+GoStart dt=179 g=109 g_seq=5
+GCMarkAssistEnd dt=8
+GCMarkAssistBegin dt=54 stack=3
+GCMarkAssistEnd dt=720
+HeapAlloc dt=23 heapalloc_value=194427608
+HeapAlloc dt=456 heapalloc_value=195001048
+GCMarkAssistBegin dt=18 stack=3
+GoBlock dt=22 reason_string=13 stack=11
+GoStart dt=23 g=113 g_seq=10
+GCMarkAssistEnd dt=3
+HeapAlloc dt=54 heapalloc_value=195099352
+GoStop dt=6390 reason_string=16 stack=6
+GoStart dt=23 g=113 g_seq=11
+GCMarkAssistBegin dt=6 stack=3
+GoBlock dt=21 reason_string=10 stack=18
+GoStart dt=33 g=101 g_seq=6
+GCMarkAssistEnd dt=6
+HeapAlloc dt=29 heapalloc_value=196409808
+GCMarkAssistBegin dt=22 stack=3
+GoBlock dt=52 reason_string=10 stack=18
+ProcStop dt=102
+EventBatch gen=3 m=169413 time=28114950897164 size=752
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=6 g=67 m=169413 gstatus=2
+GoBlock dt=11 reason_string=15 stack=5
+GoUnblock dt=18 g=25 g_seq=1 stack=0
+GoStart dt=7 g=25 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=1315 reason_string=15 stack=5
+GoUnblock dt=11 g=25 g_seq=3 stack=0
+GoStart dt=6 g=25 g_seq=4
+GoLabel dt=1 label_string=2
+GoUnblock dt=4173 g=106 g_seq=1 stack=12
+GoBlock dt=1258 reason_string=15 stack=5
+GoUnblock dt=4804 g=30 g_seq=5 stack=0
+GoStart dt=7 g=30 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=541 reason_string=15 stack=5
+GoUnblock dt=30 g=30 g_seq=7 stack=0
+GoStart dt=6 g=30 g_seq=8
+GoLabel dt=3 label_string=2
+GoBlock dt=3873 reason_string=15 stack=5
+GoUnblock dt=10 g=30 g_seq=9 stack=0
+GoStart dt=5 g=30 g_seq=10
+GoLabel dt=3 label_string=2
+GoBlock dt=3107 reason_string=15 stack=5
+GoUnblock dt=3672 g=14 g_seq=15 stack=0
+GoStart dt=6 g=14 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=442 reason_string=15 stack=5
+GoStart dt=32 g=83 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=49 heapalloc_value=191962560
+GCMarkAssistBegin dt=108 stack=3
+GoStop dt=885 reason_string=20 stack=9
+GoStart dt=14 g=83 g_seq=5
+GoBlock dt=21 reason_string=13 stack=11
+ProcStop dt=93
+ProcStart dt=38 p=0 p_seq=1
+GoUnblock dt=7 g=53 g_seq=17 stack=0
+GoStart dt=2 g=53 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=31 reason_string=15 stack=5
+ProcStop dt=89
+ProcStart dt=45 p=11 p_seq=3
+GoUnblock dt=6 g=23 g_seq=35 stack=0
+GoStart dt=14 g=23 g_seq=36
+GoLabel dt=3 label_string=4
+GoBlock dt=2881 reason_string=15 stack=5
+GoUnblock dt=72 g=25 g_seq=17 stack=0
+GoStart dt=6 g=25 g_seq=18
+GoLabel dt=1 label_string=4
+GoBlock dt=19 reason_string=15 stack=5
+GoUnblock dt=58 g=25 g_seq=19 stack=0
+GoStart dt=3 g=25 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=13 reason_string=15 stack=5
+GoStart dt=16 g=94 g_seq=4
+GoBlock dt=356 reason_string=13 stack=11
+GoUnblock dt=80 g=52 g_seq=27 stack=0
+GoStart dt=9 g=52 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=2325 reason_string=15 stack=5
+GoUnblock dt=57 g=67 g_seq=31 stack=0
+GoStart dt=4 g=67 g_seq=32
+GoLabel dt=1 label_string=4
+GoBlock dt=2043 reason_string=15 stack=5
+GoUnblock dt=9 g=67 g_seq=33 stack=0
+GoStart dt=171 g=67 g_seq=34
+GoLabel dt=5 label_string=2
+GoBlock dt=21 reason_string=15 stack=5
+ProcStop dt=60
+ProcStart dt=1735 p=25 p_seq=4
+GoUnblock dt=61 g=22 g_seq=39 stack=0
+GoStart dt=178 g=22 g_seq=40
+GoLabel dt=1 label_string=4
+GoBlock dt=66 reason_string=15 stack=5
+GoUnblock dt=8 g=22 g_seq=41 stack=0
+GoStart dt=4 g=22 g_seq=42
+GoLabel dt=1 label_string=2
+GoBlock dt=975 reason_string=15 stack=5
+ProcStop dt=1192
+ProcStart dt=347 p=25 p_seq=5
+GoUnblock dt=11 g=131 g_seq=6 stack=0
+GoStart dt=145 g=131 g_seq=7
+GoBlock dt=21 reason_string=15 stack=2
+GoUnblock dt=30 g=14 g_seq=38 stack=0
+GoStart dt=4 g=14 g_seq=39
+GoLabel dt=1 label_string=2
+GoBlock dt=65 reason_string=15 stack=5
+GoStart dt=26 g=130 g_seq=1
+ProcStatus dt=380 p=38 pstatus=2
+ProcStatus dt=4 p=39 pstatus=2
+ProcStatus dt=4 p=40 pstatus=2
+ProcStatus dt=3 p=41 pstatus=2
+ProcStatus dt=5 p=42 pstatus=2
+ProcStatus dt=5 p=43 pstatus=2
+ProcStatus dt=2 p=44 pstatus=2
+ProcStatus dt=3 p=45 pstatus=2
+ProcStatus dt=4 p=46 pstatus=2
+GoStop dt=1488 reason_string=16 stack=15
+GoUnblock dt=17 g=51 g_seq=45 stack=0
+GoStart dt=3 g=51 g_seq=46
+GoLabel dt=3 label_string=2
+GoBlock dt=1337 reason_string=15 stack=5
+GoStart dt=13 g=81 g_seq=7
+GCMarkAssistEnd dt=6
+GCMarkAssistBegin dt=31 stack=3
+GoBlock dt=20 reason_string=13 stack=11
+GoStart dt=5 g=130 g_seq=2
+HeapAlloc dt=98 heapalloc_value=192314072
+GoBlock dt=348 reason_string=12 stack=16
+GoStart dt=31 g=103 g_seq=2
+GCMarkAssistEnd dt=7
+HeapAlloc dt=53 heapalloc_value=192428760
+GoStop dt=173 reason_string=16 stack=6
+GoUnblock dt=18 g=71 g_seq=29 stack=0
+GoStart dt=4 g=71 g_seq=30
+GoLabel dt=3 label_string=2
+GoBlock dt=1289 reason_string=15 stack=5
+GoStart dt=17 g=126 g_seq=4
+GCMarkAssistBegin dt=125 stack=3
+GoBlock dt=23 reason_string=13 stack=11
+ProcStop dt=76
+ProcStart dt=2523 p=0 p_seq=4
+GoUnblock dt=16 g=30 g_seq=47 stack=0
+GoStart dt=196 g=30 g_seq=48
+GoLabel dt=2 label_string=2
+GoUnblock dt=1834 g=125 g_seq=7 stack=12
+GoBlock dt=17 reason_string=15 stack=5
+GoStart dt=14 g=125 g_seq=8
+GCMarkAssistEnd dt=5
+HeapAlloc dt=69 heapalloc_value=194566872
+GoStop dt=2253 reason_string=16 stack=6
+GoStart dt=2080 g=125 g_seq=9
+GCMarkAssistBegin dt=14 stack=3
+GoBlock dt=41 reason_string=10 stack=18
+GoStart dt=13 g=106 g_seq=8
+GCMarkAssistEnd dt=6
+HeapAlloc dt=53 heapalloc_value=196106704
+GoStop dt=6900 reason_string=16 stack=6
+GoStart dt=57 g=121 g_seq=12
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=47 reason_string=10 stack=18
+ProcStop dt=83
+ProcStart dt=11930 p=7 p_seq=7
+GoStart dt=191 g=96 g_seq=8
+GCMarkAssistEnd dt=10
+HeapAlloc dt=59 heapalloc_value=109727392
+HeapAlloc dt=159 heapalloc_value=110336128
+HeapAlloc dt=109 heapalloc_value=110662528
+GCSweepBegin dt=144 stack=28
+GCSweepEnd dt=18 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=3 heapalloc_value=111288448
+GCSweepBegin dt=49 stack=28
+GCSweepEnd dt=14 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=5 heapalloc_value=111591296
+HeapAlloc dt=65 heapalloc_value=111888256
+HeapAlloc dt=228 heapalloc_value=112797056
+HeapAlloc dt=134 heapalloc_value=113322880
+HeapAlloc dt=83 heapalloc_value=113549696
+GCSweepBegin dt=35 stack=28
+GCSweepEnd dt=16 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=113842560
+HeapAlloc dt=75 heapalloc_value=114080128
+HeapAlloc dt=64 heapalloc_value=114307712
+HeapAlloc dt=134 heapalloc_value=114580608
+HeapAlloc dt=77 heapalloc_value=114670464
+GCSweepBegin dt=33 stack=28
+GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=114727808
+GCSweepBegin dt=90 stack=27
+EventBatch gen=3 m=169412 time=28114950898429 size=583
+ProcStatus dt=1 p=36 pstatus=2
+ProcStart dt=2 p=36 p_seq=1
+GoStart dt=401 g=83 g_seq=2
+GoBlock dt=1477 reason_string=13 stack=11
+GoStart dt=1208 g=81 g_seq=2
+GCMarkAssistEnd dt=9
+HeapAlloc dt=57 heapalloc_value=191348160
+GoStop dt=42 reason_string=16 stack=4
+GoStart dt=25 g=81 g_seq=3
+GCMarkAssistBegin dt=394 stack=3
+GoBlock dt=1177 reason_string=13 stack=11
+GoStart dt=28 g=106 g_seq=2
+GCMarkAssistEnd dt=10
+HeapAlloc dt=52 heapalloc_value=191503808
+GCMarkAssistBegin dt=52 stack=3
+GoStop dt=60 reason_string=20 stack=9
+GoUnblock dt=73 g=58 g_seq=3 stack=0
+GoStart dt=6 g=58 g_seq=4
+GoLabel dt=3 label_string=4
+GoBlock dt=2860 reason_string=15 stack=5
+GoUnblock dt=3777 g=24 g_seq=9 stack=0
+GoStart dt=6 g=24 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=41 reason_string=15 stack=5
+GoUnblock dt=1167 g=71 g_seq=9 stack=0
+GoStart dt=7 g=71 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=1396 reason_string=15 stack=5
+GoUnblock dt=1371 g=57 g_seq=23 stack=0
+GoStart dt=7 g=57 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=584 reason_string=15 stack=5
+GoUnblock dt=4657 g=23 g_seq=23 stack=0
+GoStart dt=7 g=23 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=40 reason_string=15 stack=5
+ProcStop dt=82
+ProcStart dt=1505 p=36 p_seq=2
+ProcStop dt=74
+ProcStart dt=19 p=36 p_seq=3
+GoUnblock dt=7 g=23 g_seq=27 stack=0
+GoStart dt=7 g=23 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=122 reason_string=15 stack=5
+GoUnblock dt=58 g=52 g_seq=25 stack=0
+GoStart dt=6 g=52 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=4034 reason_string=15 stack=5
+GoUnblock dt=75 g=14 g_seq=19 stack=0
+GoStart dt=6 g=14 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=2059 reason_string=15 stack=5
+GoUnblock dt=63 g=14 g_seq=21 stack=0
+GoStart dt=4 g=14 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=56 reason_string=15 stack=5
+ProcStop dt=49
+ProcStart dt=20 p=36 p_seq=4
+GoUnblock dt=6 g=67 g_seq=27 stack=0
+GoStart dt=2 g=67 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=13 reason_string=15 stack=5
+ProcStop dt=1721
+ProcStart dt=20316 p=36 p_seq=5
+GoStart dt=197 g=94 g_seq=11
+GCMarkAssistEnd dt=7
+HeapAlloc dt=6672 heapalloc_value=196598224
+GoStop dt=15 reason_string=16 stack=6
+GoStart dt=54 g=106 g_seq=9
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=32 reason_string=10 stack=18
+GoStart dt=41 g=103 g_seq=6
+GCMarkAssistBegin dt=15 stack=3
+GoBlock dt=84 reason_string=10 stack=18
+ProcStop dt=43
+ProcStart dt=10888 p=5 p_seq=1
+GoStart dt=189 g=120 g_seq=8
+GCMarkAssistEnd dt=7
+HeapAlloc dt=54 heapalloc_value=106433440
+HeapAlloc dt=94 heapalloc_value=106861728
+GCSweepBegin dt=92 stack=28
+GCSweepEnd dt=13 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=4 heapalloc_value=107301920
+HeapAlloc dt=65 heapalloc_value=107394848
+GCSweepBegin dt=32 stack=28
+GCSweepEnd dt=11 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=2 heapalloc_value=107616032
+HeapAlloc dt=60 heapalloc_value=107763488
+HeapAlloc dt=78 heapalloc_value=107953440
+HeapAlloc dt=65 heapalloc_value=108333088
+GCSweepBegin dt=38 stack=28
+GCSweepEnd dt=5 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=1 heapalloc_value=108423200
+GCSweepBegin dt=80 stack=28
+GCSweepEnd dt=9 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=108682656
+GCSweepBegin dt=61 stack=28
+GCSweepEnd dt=10 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=4 heapalloc_value=108816544
+HeapAlloc dt=32 heapalloc_value=108994080
+HeapAlloc dt=50 heapalloc_value=109290272
+HeapAlloc dt=112 heapalloc_value=109566240
+HeapAlloc dt=104 heapalloc_value=109973280
+GCSweepBegin dt=66 stack=29
+GCSweepEnd dt=17 swept_value=8192 reclaimed_value=0
+HeapAlloc dt=3 heapalloc_value=110183040
+HeapAlloc dt=86 heapalloc_value=110506880
+HeapAlloc dt=149 heapalloc_value=111151232
+HeapAlloc dt=24 heapalloc_value=111272064
+HeapAlloc dt=53 heapalloc_value=111368064
+HeapAlloc dt=68 heapalloc_value=111632256
+HeapAlloc dt=103 heapalloc_value=112078720
+GCSweepBegin dt=120 stack=28
+GCSweepEnd dt=7 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=112585472
+HeapAlloc dt=34 heapalloc_value=112616832
+HeapAlloc dt=39 heapalloc_value=112882304
+HeapAlloc dt=141 heapalloc_value=113391232
+HeapAlloc dt=80 heapalloc_value=113664384
+HeapAlloc dt=152 heapalloc_value=114242176
+HeapAlloc dt=104 heapalloc_value=114415616
+HeapAlloc dt=38 heapalloc_value=114527360
+HeapAlloc dt=28 heapalloc_value=114592896
+GCSweepBegin dt=227 stack=27
+EventBatch gen=3 m=169411 time=28114950895719 size=370
+ProcStatus dt=1 p=21 pstatus=1
+GoStatus dt=5 g=85 m=169411 gstatus=2
+GCMarkAssistActive dt=1 g=85
+GCMarkAssistEnd dt=3
+HeapAlloc dt=44 heapalloc_value=190299584
+GoStop dt=38 reason_string=16 stack=4
+GoStart dt=20 g=85 g_seq=1
+GCMarkAssistBegin dt=119 stack=3
+GoStop dt=4468 reason_string=20 stack=9
+GoStart dt=15 g=85 g_seq=2
+GoStop dt=1589 reason_string=20 stack=9
+GoStart dt=8 g=85 g_seq=3
+GCMarkAssistEnd dt=2892
+HeapAlloc dt=33 heapalloc_value=191733184
+GCMarkAssistBegin dt=98 stack=3
+GoStop dt=2309 reason_string=20 stack=9
+GoStart dt=10 g=95 g_seq=3
+GoBlock dt=153 reason_string=13 stack=11
+GoStart dt=5 g=85 g_seq=4
+GoBlock dt=18 reason_string=13 stack=11
+GoUnblock dt=3925 g=58 g_seq=13 stack=0
+GoStart dt=8 g=58 g_seq=14
+GoLabel dt=3 label_string=4
+GoBlock dt=106 reason_string=15 stack=5
+ProcStop dt=1275
+ProcStart dt=21 p=21 p_seq=1
+ProcStop dt=1335
+ProcStart dt=14 p=21 p_seq=2
+GoUnblock dt=1349 g=14 g_seq=9 stack=0
+GoStart dt=8 g=14 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=255 reason_string=15 stack=5
+GoUnblock dt=2226 g=70 g_seq=9 stack=0
+GoStart dt=8 g=70 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=398 reason_string=15 stack=5
+GoUnblock dt=8 g=70 g_seq=11 stack=0
+GoStart dt=6 g=70 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=8210 reason_string=15 stack=5
+GoUnblock dt=12 g=70 g_seq=13 stack=0
+GoStart dt=5 g=70 g_seq=14
+GoLabel dt=2 label_string=2
+GoBlock dt=2354 reason_string=15 stack=5
+GoUnblock dt=93 g=72 g_seq=47 stack=0
+GoStart dt=9 g=72 g_seq=48
+GoLabel dt=1 label_string=4
+GoBlock dt=27 reason_string=15 stack=5
+GoUnblock dt=220 g=72 g_seq=49 stack=0
+GoStart dt=7 g=72 g_seq=50
+GoLabel dt=1 label_string=2
+GoBlock dt=20 reason_string=15 stack=5
+ProcStop dt=61
+ProcStart dt=16474 p=33 p_seq=2
+GoStart dt=3475 g=107 g_seq=4
+GCMarkAssistEnd dt=9
+HeapAlloc dt=52 heapalloc_value=196041168
+GoStop dt=5585 reason_string=16 stack=6
+GoStart dt=15 g=107 g_seq=5
+GCMarkAssistBegin dt=91 stack=3
+GoBlock dt=34 reason_string=10 stack=18
+ProcStop dt=55
+ProcStart dt=1514 p=33 p_seq=3
+ProcStop dt=41
+ProcStart dt=12390 p=8 p_seq=1
+GoStart dt=166 g=100 g_seq=7
+GCMarkAssistEnd dt=5
+HeapAlloc dt=51 heapalloc_value=111353984
+GCSweepBegin dt=133 stack=28
+GCSweepEnd dt=18 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=112029568
+HeapAlloc dt=68 heapalloc_value=112301312
+HeapAlloc dt=120 heapalloc_value=112739712
+HeapAlloc dt=116 heapalloc_value=113221760
+HeapAlloc dt=53 heapalloc_value=113380224
+HeapAlloc dt=115 heapalloc_value=113768832
+HeapAlloc dt=66 heapalloc_value=114026880
+HeapAlloc dt=127 heapalloc_value=114403328
+GCSweepBegin dt=47 stack=28
+GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=114503936
+HeapAlloc dt=67 heapalloc_value=114651264
+GCSweepBegin dt=299 stack=27
+EventBatch gen=3 m=169409 time=28114950894853 size=224
+ProcStatus dt=2 p=29 pstatus=1
+GoStatus dt=3 g=126 m=169409 gstatus=2
+HeapAlloc dt=3 heapalloc_value=189824448
+GCMarkAssistBegin dt=163 stack=3
+GoStop dt=1609 reason_string=20 stack=9
+GoStart dt=26 g=98 g_seq=2
+GCMarkAssistBegin dt=17 stack=3
+GCMarkAssistEnd dt=7751
+HeapAlloc dt=77 heapalloc_value=191675840
+GoStop dt=39 reason_string=16 stack=6
+GoStart dt=20 g=116 g_seq=4
+GoBlock dt=302 reason_string=13 stack=11
+GoUnblock dt=4886 g=51 g_seq=13 stack=0
+GoStart dt=8 g=51 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=2058 reason_string=15 stack=5
+GoUnblock dt=11 g=51 g_seq=15 stack=0
+GoStart dt=6 g=51 g_seq=16
+GoLabel dt=3 label_string=2
+GoBlock dt=2936 reason_string=15 stack=5
+GoUnblock dt=35 g=58 g_seq=21 stack=0
+GoStart dt=6 g=58 g_seq=22
+GoLabel dt=3 label_string=2
+GoBlock dt=7995 reason_string=15 stack=5
+GoUnblock dt=20 g=68 g_seq=9 stack=0
+GoStart dt=6 g=68 g_seq=10
+GoLabel dt=3 label_string=2
+GoBlock dt=92 reason_string=15 stack=5
+GoUnblock dt=8 g=68 g_seq=11 stack=0
+GoStart dt=1 g=68 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=7039 reason_string=15 stack=5
+ProcStop dt=54
+ProcStart dt=14204 p=3 p_seq=1
+GoStart dt=213 g=94 g_seq=7
+GCMarkAssistBegin dt=29 stack=3
+GoBlock dt=62 reason_string=13 stack=11
+GoStart dt=20 g=124 g_seq=4
+GCMarkAssistEnd dt=6
+GCMarkAssistBegin dt=38 stack=3
+GCMarkAssistEnd dt=98
+HeapAlloc dt=118 heapalloc_value=193911512
+HeapAlloc dt=123 heapalloc_value=194116312
+HeapAlloc dt=352 heapalloc_value=194616024
+GoStop dt=3095 reason_string=16 stack=6
+GoStart dt=26 g=110 g_seq=4
+GCMarkAssistEnd dt=6
+HeapAlloc dt=30 heapalloc_value=195508952
+GoStop dt=4300 reason_string=16 stack=6
+GoStart dt=65 g=110 g_seq=5
+GCMarkAssistBegin dt=10 stack=3
+GoBlock dt=46 reason_string=10 stack=18
+ProcStop dt=124
+EventBatch gen=3 m=169408 time=28114950896863 size=856
+ProcStatus dt=1 p=22 pstatus=1
+GoStatus dt=2 g=105 m=169408 gstatus=2
+GCMarkAssistActive dt=1 g=105
+GCMarkAssistEnd dt=2
+HeapAlloc dt=22 heapalloc_value=190512576
+HeapAlloc dt=94 heapalloc_value=190537152
+GCMarkAssistBegin dt=18 stack=3
+GCMarkAssistEnd dt=1243
+HeapAlloc dt=34 heapalloc_value=190741952
+GCMarkAssistBegin dt=36 stack=3
+GCMarkAssistEnd dt=4423
+HeapAlloc dt=22 heapalloc_value=191413696
+GoStop dt=23 reason_string=16 stack=4
+GoStart dt=15 g=105 g_seq=1
+GCMarkAssistBegin dt=57 stack=3
+GoStop dt=662 reason_string=20 stack=9
+GoStart dt=12 g=105 g_seq=2
+GoStop dt=4139 reason_string=20 stack=9
+GoStart dt=11 g=105 g_seq=3
+GoStop dt=4306 reason_string=20 stack=9
+GoStart dt=15 g=105 g_seq=4
+GoBlock dt=21 reason_string=13 stack=11
+GoUnblock dt=2669 g=58 g_seq=19 stack=0
+GoStart dt=5 g=58 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=90 reason_string=15 stack=5
+GoUnblock dt=28 g=51 g_seq=17 stack=0
+GoStart dt=5 g=51 g_seq=18
+GoLabel dt=1 label_string=2
+GoBlock dt=5245 reason_string=15 stack=5
+GoUnblock dt=68 g=51 g_seq=19 stack=0
+GoStart dt=8 g=51 g_seq=20
+GoLabel dt=1 label_string=4
+GoBlock dt=14 reason_string=15 stack=5
+GoUnblock dt=6 g=51 g_seq=21 stack=0
+GoStart dt=1 g=51 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=7035 reason_string=15 stack=5
+GoUnblock dt=13 g=51 g_seq=23 stack=0
+GoStart dt=4 g=51 g_seq=24
+GoLabel dt=2 label_string=2
+GoUnblock dt=188 g=116 g_seq=5 stack=12
+GoBlock dt=65 reason_string=15 stack=5
+GoUnblock dt=9 g=51 g_seq=25 stack=0
+GoStart dt=2 g=51 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=170 reason_string=15 stack=5
+GoUnblock dt=15 g=51 g_seq=27 stack=0
+GoStart dt=6 g=51 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=33 reason_string=15 stack=5
+GoUnblock dt=7 g=51 g_seq=29 stack=0
+GoStart dt=6 g=51 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=159 reason_string=15 stack=5
+GoUnblock dt=8 g=51 g_seq=31 stack=0
+GoStart dt=3 g=51 g_seq=32
+GoLabel dt=1 label_string=2
+GoBlock dt=124 reason_string=15 stack=5
+ProcStop dt=79
+ProcStart dt=18 p=22 p_seq=1
+GoUnblock dt=4 g=29 g_seq=21 stack=0
+GoStart dt=4 g=29 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=28 reason_string=15 stack=5
+ProcStop dt=45
+ProcStart dt=12 p=22 p_seq=2
+GoUnblock dt=2 g=29 g_seq=23 stack=0
+GoStart dt=1 g=29 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=19 reason_string=15 stack=5
+GoUnblock dt=45 g=29 g_seq=25 stack=0
+GoStart dt=1 g=29 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=151 reason_string=15 stack=5
+GoUnblock dt=14 g=52 g_seq=35 stack=0
+GoStart dt=6 g=52 g_seq=36
+GoLabel dt=1 label_string=2
+GoBlock dt=13 reason_string=15 stack=5
+GoUnblock dt=4 g=52 g_seq=37 stack=0
+GoStart dt=3 g=52 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=127 reason_string=15 stack=5
+GoUnblock dt=7 g=52 g_seq=39 stack=0
+GoStart dt=1 g=52 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=11 reason_string=15 stack=5
+GoUnblock dt=6 g=52 g_seq=41 stack=0
+GoStart dt=2 g=52 g_seq=42
+GoLabel dt=1 label_string=2
+GoBlock dt=4594 reason_string=15 stack=5
+ProcStop dt=42
+ProcStart dt=1703 p=27 p_seq=42
+GoUnblock dt=17 g=22 g_seq=45 stack=0
+GoStart dt=283 g=22 g_seq=46
+GoLabel dt=2 label_string=2
+GoUnblock dt=103 g=96 g_seq=3 stack=12
+GoUnblock dt=95 g=121 g_seq=5 stack=12
+GoUnblock dt=5 g=126 g_seq=2 stack=12
+GoUnblock dt=529 g=115 g_seq=3 stack=12
+GoBlock dt=552 reason_string=15 stack=5
+GoUnblock dt=31 g=22 g_seq=47 stack=0
+GoStart dt=4 g=22 g_seq=48
+GoLabel dt=1 label_string=2
+GoUnblock dt=763 g=90 g_seq=3 stack=12
+GoBlock dt=39 reason_string=15 stack=5
+GoUnblock dt=12 g=22 g_seq=49 stack=0
+GoStart dt=4 g=22 g_seq=50
+GoLabel dt=1 label_string=2
+GoBlock dt=806 reason_string=15 stack=5
+GoStart dt=18 g=115 g_seq=4
+GCMarkAssistEnd dt=8
+HeapAlloc dt=834 heapalloc_value=192494296
+GCMarkAssistBegin dt=33 stack=3
+GoStop dt=622 reason_string=20 stack=9
+GoUnblock dt=15 g=14 g_seq=44 stack=0
+GoStart dt=5 g=14 g_seq=45
+GoLabel dt=1 label_string=2
+GoBlock dt=1768 reason_string=15 stack=5
+GoUnblock dt=11 g=14 g_seq=46 stack=0
+GoStart dt=4 g=14 g_seq=47
+GoLabel dt=1 label_string=2
+GoBlock dt=20 reason_string=15 stack=5
+GoUnblock dt=10 g=14 g_seq=48 stack=0
+GoStart dt=636 g=14 g_seq=49
+GoLabel dt=1 label_string=2
+GoBlock dt=55 reason_string=15 stack=5
+GoUnblock dt=18 g=14 g_seq=50 stack=0
+GoStart dt=3 g=14 g_seq=51
+GoLabel dt=1 label_string=2
+GoBlock dt=46 reason_string=15 stack=5
+GoUnblock dt=15 g=14 g_seq=52 stack=0
+GoStart dt=4 g=14 g_seq=53
+GoLabel dt=1 label_string=2
+GoBlock dt=26 reason_string=15 stack=5
+GoUnblock dt=29 g=70 g_seq=23 stack=0
+GoStart dt=5 g=70 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=15 reason_string=15 stack=5
+GoStart dt=30 g=94 g_seq=6
+GCMarkAssistEnd dt=5
+HeapAlloc dt=37 heapalloc_value=192699096
+GoStop dt=34 reason_string=16 stack=6
+GoUnblock dt=9 g=70 g_seq=25 stack=0
+GoStart dt=3 g=70 g_seq=26
+GoLabel dt=1 label_string=2
+GoUnblock dt=190 g=98 g_seq=7 stack=12
+GoUnblock dt=6 g=91 g_seq=1 stack=12
+GoUnblock dt=7 g=123 g_seq=6 stack=12
+GoUnblock dt=5 g=100 g_seq=3 stack=12
+GoUnblock dt=3 g=102 g_seq=3 stack=12
+GoUnblock dt=3 g=103 g_seq=4 stack=12
+GoUnblock dt=5 g=117 g_seq=3 stack=12
+GoBlock dt=45 reason_string=15 stack=5
+GoUnblock dt=8 g=70 g_seq=27 stack=0
+GoStart dt=1 g=70 g_seq=28
+GoLabel dt=1 label_string=2
+GoUnblock dt=1939 g=111 g_seq=7 stack=12
+GoUnblock dt=10 g=101 g_seq=5 stack=12
+GoBlock dt=23 reason_string=15 stack=5
+GoStart dt=15 g=98 g_seq=8
+GCMarkAssistEnd dt=8
+HeapAlloc dt=57 heapalloc_value=193960664
+GCMarkAssistBegin dt=83 stack=3
+GoBlock dt=26 reason_string=13 stack=11
+GoStart dt=7 g=91 g_seq=2
+GCMarkAssistEnd dt=6
+HeapAlloc dt=47 heapalloc_value=194296536
+GCMarkAssistBegin dt=103 stack=3
+GoBlock dt=118 reason_string=13 stack=11
+GoStart dt=20 g=123 g_seq=7
+GCMarkAssistEnd dt=4
+HeapAlloc dt=448 heapalloc_value=195058392
+GoStop dt=6487 reason_string=16 stack=6
+GoStart dt=27 g=123 g_seq=8
+GCMarkAssistBegin dt=10 stack=3
+GoBlock dt=32 reason_string=10 stack=18
+ProcStop dt=78
+ProcStart dt=16845 p=9 p_seq=1
+GoStart dt=21 g=127 g_seq=10
+GCMarkAssistEnd dt=11
+GCSweepBegin dt=37 stack=28
+GCSweepEnd dt=17 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=7 heapalloc_value=110613376
+HeapAlloc dt=77 heapalloc_value=110956160
+HeapAlloc dt=127 heapalloc_value=111501184
+HeapAlloc dt=150 heapalloc_value=112133376
+HeapAlloc dt=103 heapalloc_value=112487168
+HeapAlloc dt=158 heapalloc_value=113166976
+GCSweepBegin dt=50 stack=28
+GCSweepEnd dt=32 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=6 heapalloc_value=113407616
+HeapAlloc dt=173 heapalloc_value=114067840
+HeapAlloc dt=153 heapalloc_value=114430208
+GCSweepBegin dt=35 stack=28
+GCSweepEnd dt=4 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=4 heapalloc_value=114551936
+GCSweepBegin dt=1034 stack=27
+EventBatch gen=3 m=169407 time=28114950901555 size=528
+ProcStatus dt=2 p=4 pstatus=1
+GoStatus dt=1 g=72 m=169407 gstatus=2
+GoBlock dt=7 reason_string=15 stack=5
+GoUnblock dt=1446 g=72 g_seq=3 stack=0
+GoStart dt=9 g=72 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=394 reason_string=15 stack=5
+GoStart dt=26 g=106 g_seq=3
+GoBlock dt=149 reason_string=13 stack=11
+GoUnblock dt=2557 g=72 g_seq=5 stack=0
+GoStart dt=8 g=72 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=44 reason_string=15 stack=5
+GoUnblock dt=13 g=72 g_seq=7 stack=0
+GoStart dt=6 g=72 g_seq=8
+GoLabel dt=5 label_string=2
+GoBlock dt=1622 reason_string=15 stack=5
+GoUnblock dt=9 g=72 g_seq=9 stack=0
+GoStart dt=6 g=72 g_seq=10
+GoLabel dt=1 label_string=2
+GoUnblock dt=165 g=87 g_seq=2 stack=12
+GoBlock dt=854 reason_string=15 stack=5
+GoUnblock dt=9 g=72 g_seq=11 stack=0
+GoStart dt=4 g=72 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=398 reason_string=15 stack=5
+GoUnblock dt=20 g=72 g_seq=13 stack=0
+GoStart dt=5 g=72 g_seq=14
+GoLabel dt=1 label_string=2
+GoBlock dt=1475 reason_string=15 stack=5
+GoStart dt=1158 g=93 g_seq=2
+GoStatus dt=24 g=94 m=18446744073709551615 gstatus=4
+GoUnblock dt=5 g=94 g_seq=1 stack=10
+GCMarkAssistBegin dt=19 stack=3
+GoBlock dt=235 reason_string=13 stack=11
+GoStart dt=9 g=94 g_seq=2
+GoStatus dt=18 g=100 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=100 g_seq=1 stack=10
+GCMarkAssistBegin dt=16 stack=3
+GoStop dt=7669 reason_string=20 stack=9
+GoStart dt=9 g=94 g_seq=3
+GoStop dt=5028 reason_string=20 stack=9
+GoUnblock dt=76 g=23 g_seq=39 stack=0
+GoStart dt=4 g=23 g_seq=40
+GoLabel dt=1 label_string=4
+GoBlock dt=464 reason_string=15 stack=5
+GoUnblock dt=67 g=23 g_seq=41 stack=0
+GoStart dt=151 g=23 g_seq=42
+GoLabel dt=2 label_string=4
+GoBlock dt=3280 reason_string=15 stack=5
+GoStart dt=35 g=113 g_seq=6
+GCMarkAssistEnd dt=7
+GCMarkAssistBegin dt=65 stack=3
+GoBlock dt=63 reason_string=13 stack=11
+ProcStop dt=162
+ProcStart dt=22113 p=24 p_seq=4
+GoStart dt=228 g=111 g_seq=8
+GCMarkAssistEnd dt=11
+HeapAlloc dt=64 heapalloc_value=196401616
+GoStop dt=6120 reason_string=16 stack=6
+GoStart dt=26 g=111 g_seq=9
+GCMarkAssistBegin dt=15 stack=3
+GoBlock dt=35 reason_string=10 stack=18
+ProcStop dt=128
+ProcStart dt=7783 p=1 p_seq=3
+GoStart dt=191 g=87 g_seq=8
+GCMarkAssistEnd dt=9
+GCSweepBegin dt=33 stack=28
+GCSweepEnd dt=16 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=4 heapalloc_value=103833248
+GCSweepBegin dt=56 stack=27
+GCSweepEnd dt=1508 swept_value=4194304 reclaimed_value=3072000
+HeapAlloc dt=33 heapalloc_value=105692064
+HeapAlloc dt=115 heapalloc_value=105976736
+HeapAlloc dt=44 heapalloc_value=106034080
+HeapAlloc dt=109 heapalloc_value=106332320
+HeapAlloc dt=95 heapalloc_value=106715424
+HeapAlloc dt=80 heapalloc_value=106958496
+HeapAlloc dt=97 heapalloc_value=107330592
+HeapAlloc dt=56 heapalloc_value=107460384
+HeapAlloc dt=117 heapalloc_value=107811360
+HeapAlloc dt=62 heapalloc_value=108141856
+HeapAlloc dt=115 heapalloc_value=108472352
+HeapAlloc dt=103 heapalloc_value=108710048
+GCSweepBegin dt=51 stack=28
+GCSweepEnd dt=11 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=4 heapalloc_value=108832928
+HeapAlloc dt=51 heapalloc_value=109134624
+HeapAlloc dt=100 heapalloc_value=109470496
+HeapAlloc dt=98 heapalloc_value=109831200
+HeapAlloc dt=69 heapalloc_value=110087968
+HeapAlloc dt=117 heapalloc_value=110388096
+HeapAlloc dt=150 heapalloc_value=111005312
+HeapAlloc dt=140 heapalloc_value=111509376
+HeapAlloc dt=55 heapalloc_value=111773568
+HeapAlloc dt=105 heapalloc_value=112162048
+GCSweepBegin dt=85 stack=28
+GCSweepEnd dt=8 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=112560896
+HeapAlloc dt=68 heapalloc_value=112816768
+HeapAlloc dt=47 heapalloc_value=112988800
+HeapAlloc dt=122 heapalloc_value=113464960
+HeapAlloc dt=150 heapalloc_value=114008448
+GCSweepBegin dt=885 stack=27
+EventBatch gen=3 m=169406 time=28114950897134 size=117
+ProcStatus dt=3 p=6 pstatus=1
+GoStatus dt=5 g=52 m=169406 gstatus=2
+GoBlock dt=14 reason_string=15 stack=5
+GoUnblock dt=16 g=52 g_seq=1 stack=0
+GoStart dt=5 g=52 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=3752 reason_string=15 stack=5
+GoUnblock dt=21 g=52 g_seq=3 stack=0
+GoStart dt=7 g=52 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=4444 reason_string=15 stack=5
+GoUnblock dt=12 g=52 g_seq=5 stack=0
+GoStart dt=7 g=52 g_seq=6
+GoLabel dt=1 label_string=2
+GoBlock dt=5071 reason_string=15 stack=5
+GoUnblock dt=15 g=52 g_seq=7 stack=0
+GoStart dt=6 g=52 g_seq=8
+GoLabel dt=2 label_string=2
+GoBlock dt=2302 reason_string=15 stack=5
+GoUnblock dt=14 g=52 g_seq=9 stack=0
+GoStart dt=6 g=52 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=32 reason_string=15 stack=5
+GoUnblock dt=9 g=52 g_seq=11 stack=0
+GoStart dt=6 g=52 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=22 reason_string=15 stack=5
+ProcStop dt=35
+EventBatch gen=3 m=169405 time=28114950903578 size=119
+ProcStatus dt=2 p=15 pstatus=1
+GoStatus dt=4 g=53 m=169405 gstatus=2
+GoBlock dt=8 reason_string=15 stack=5
+GoUnblock dt=5238 g=25 g_seq=7 stack=0
+GoStart dt=7 g=25 g_seq=8
+GoLabel dt=1 label_string=4
+GoBlock dt=49 reason_string=15 stack=5
+GoUnblock dt=1111 g=58 g_seq=11 stack=0
+GoStart dt=6 g=58 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=158 reason_string=15 stack=5
+GoStart dt=3143 g=100 g_seq=2
+GoStatus dt=20 g=109 m=18446744073709551615 gstatus=4
+GoUnblock dt=7 g=109 g_seq=1 stack=10
+GCMarkAssistBegin dt=17 stack=3
+GoBlock dt=2307 reason_string=13 stack=11
+GoUnblock dt=2192 g=14 g_seq=13 stack=0
+GoStart dt=4 g=14 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=1366 reason_string=15 stack=5
+GoUnblock dt=68 g=23 g_seq=21 stack=0
+GoStart dt=4 g=23 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=21 reason_string=15 stack=5
+ProcStop dt=3159
+EventBatch gen=3 m=169404 time=28114950896316 size=116
+ProcStatus dt=1 p=5 pstatus=1
+GoStatus dt=2 g=14 m=169404 gstatus=2
+GoBlock dt=5 reason_string=15 stack=5
+GoUnblock dt=1436 g=67 g_seq=3 stack=0
+GoStart dt=217 g=67 g_seq=4
+GoLabel dt=3 label_string=4
+GoBlock dt=1945 reason_string=15 stack=5
+GoStart dt=23 g=121 g_seq=3
+GoStop dt=570 reason_string=20 stack=9
+GoStart dt=14 g=121 g_seq=4
+GoBlock dt=1389 reason_string=13 stack=11
+GoUnblock dt=13 g=51 g_seq=3 stack=0
+GoStart dt=7 g=51 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=1439 reason_string=15 stack=5
+GoUnblock dt=17 g=14 g_seq=5 stack=0
+GoStart dt=5 g=14 g_seq=6
+GoLabel dt=2 label_string=2
+GoBlock dt=11474 reason_string=15 stack=5
+GoStart dt=4166 g=109 g_seq=3
+GoBlock dt=39 reason_string=13 stack=11
+GoStart dt=20 g=119 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=68 heapalloc_value=191921600
+GCMarkAssistBegin dt=69 stack=3
+GoBlock dt=23 reason_string=13 stack=11
+ProcStop dt=59
+EventBatch gen=3 m=169402 time=28114950895074 size=135
+ProcStatus dt=2 p=9 pstatus=1
+GoStatus dt=2 g=25 m=169402 gstatus=2
+GoBlock dt=14 reason_string=15 stack=5
+GoStart dt=54 g=98 g_seq=1
+GCMarkAssistBegin dt=99 stack=3
+GCMarkAssistEnd dt=1187
+HeapAlloc dt=68 heapalloc_value=190463424
+GoStop dt=53 reason_string=16 stack=6
+GoStart dt=10 g=82 g_seq=1
+GCMarkAssistBegin dt=82 stack=3
+GoStop dt=2699 reason_string=20 stack=9
+GoStart dt=13 g=107 g_seq=2
+GCMarkAssistEnd dt=7
+GCMarkAssistBegin dt=49 stack=3
+GoBlock dt=852 reason_string=13 stack=11
+GoStart dt=29 g=90 g_seq=2
+GCMarkAssistEnd dt=3
+HeapAlloc dt=36 heapalloc_value=191233472
+GCMarkAssistBegin dt=825 stack=3
+GoBlock dt=392 reason_string=13 stack=11
+GoUnblock dt=21 g=67 g_seq=5 stack=0
+GoStart dt=5 g=67 g_seq=6
+GoLabel dt=1 label_string=2
+GoBlock dt=8638 reason_string=15 stack=5
+GoUnblock dt=9 g=67 g_seq=7 stack=0
+GoStart dt=4 g=67 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=145 reason_string=15 stack=5
+GoUnblock dt=14 g=67 g_seq=9 stack=0
+GoStart dt=5 g=67 g_seq=10
+GoLabel dt=1 label_string=2
+GoBlock dt=7067 reason_string=15 stack=5
+ProcStop dt=23
+EventBatch gen=3 m=169401 time=28114950894770 size=505
+ProcStatus dt=1 p=8 pstatus=1
+GoStatus dt=1 g=130 m=169401 gstatus=2
+ProcsChange dt=124 procs_value=48 stack=1
+GCActive dt=3 gc_seq=4
+HeapAlloc dt=600 heapalloc_value=190152128
+HeapAlloc dt=16 heapalloc_value=190160320
+HeapAlloc dt=11095 heapalloc_value=191741376
+HeapAlloc dt=179 heapalloc_value=191749568
+HeapAlloc dt=14244 heapalloc_value=192011712
+HeapAlloc dt=292 heapalloc_value=192019904
+HeapAlloc dt=244 heapalloc_value=192028096
+HeapAlloc dt=3225 heapalloc_value=192036288
+HeapAlloc dt=39 heapalloc_value=192044192
+HeapAlloc dt=60 heapalloc_value=192052000
+HeapAlloc dt=462 heapalloc_value=192060192
+HeapAlloc dt=85 heapalloc_value=192068384
+HeapAlloc dt=341 heapalloc_value=192076576
+HeapAlloc dt=314 heapalloc_value=192142112
+GoStop dt=8367 reason_string=16 stack=14
+GoUnblock dt=274 g=30 g_seq=27 stack=0
+GoStart dt=6 g=30 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=312 reason_string=15 stack=5
+GoUnblock dt=403 g=30 g_seq=29 stack=0
+GoStart dt=4 g=30 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=773 reason_string=15 stack=5
+GoUnblock dt=7 g=30 g_seq=31 stack=0
+GoStart dt=3 g=30 g_seq=32
+GoLabel dt=1 label_string=2
+GoBlock dt=8 reason_string=15 stack=5
+GoStart dt=14 g=112 g_seq=4
+GCMarkAssistEnd dt=6
+HeapAlloc dt=45 heapalloc_value=192297760
+GCMarkAssistBegin dt=107 stack=3
+GoStop dt=897 reason_string=20 stack=9
+GoUnblock dt=15 g=70 g_seq=19 stack=0
+GoStart dt=5 g=70 g_seq=20
+GoLabel dt=1 label_string=2
+GoUnblock dt=1479 g=105 g_seq=5 stack=12
+GoBlock dt=2280 reason_string=15 stack=5
+GoUnblock dt=12 g=70 g_seq=21 stack=0
+GoStart dt=5 g=70 g_seq=22
+GoLabel dt=2 label_string=2
+GoBlock dt=1253 reason_string=15 stack=5
+GoUnblock dt=23 g=71 g_seq=35 stack=0
+GoStart dt=8 g=71 g_seq=36
+GoLabel dt=2 label_string=2
+GoBlock dt=26 reason_string=15 stack=5
+GoUnblock dt=6 g=71 g_seq=37 stack=0
+GoStart dt=3 g=71 g_seq=38
+GoLabel dt=1 label_string=2
+GoBlock dt=9 reason_string=15 stack=5
+GoUnblock dt=3 g=71 g_seq=39 stack=0
+GoStart dt=2 g=71 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=3 g=71 g_seq=41 stack=0
+GoStart dt=1 g=71 g_seq=42
+GoLabel dt=1 label_string=2
+GoUnblock dt=82 g=109 g_seq=4 stack=12
+GoUnblock dt=6 g=106 g_seq=4 stack=12
+GoUnblock dt=103 g=111 g_seq=4 stack=12
+GoUnblock dt=5 g=112 g_seq=6 stack=12
+GoUnblock dt=6 g=96 g_seq=5 stack=12
+GoUnblock dt=4 g=119 g_seq=5 stack=12
+GoUnblock dt=6 g=122 g_seq=1 stack=12
+GoUnblock dt=11 g=97 g_seq=5 stack=12
+GoUnblock dt=4 g=107 g_seq=3 stack=12
+GoUnblock dt=106 g=92 g_seq=3 stack=12
+GoUnblock dt=4 g=116 g_seq=9 stack=12
+GoUnblock dt=5 g=82 g_seq=8 stack=12
+GoBlock dt=9 reason_string=15 stack=5
+GoStart dt=12 g=111 g_seq=5
+GCMarkAssistEnd dt=5
+HeapAlloc dt=22 heapalloc_value=192797400
+GCMarkAssistBegin dt=75 stack=3
+GoStop dt=22 reason_string=20 stack=9
+GoUnblock dt=11 g=25 g_seq=53 stack=0
+GoStart dt=4 g=25 g_seq=54
+GoLabel dt=1 label_string=2
+GoUnblock dt=1354 g=95 g_seq=4 stack=12
+GoUnblock dt=9 g=90 g_seq=6 stack=12
+GoUnblock dt=6 g=113 g_seq=9 stack=12
+GoUnblock dt=3 g=89 g_seq=6 stack=12
+GoBlock dt=30 reason_string=15 stack=5
+GoStart dt=10 g=112 g_seq=7
+GCMarkAssistEnd dt=5
+GCMarkAssistBegin dt=28 stack=3
+GoBlock dt=587 reason_string=13 stack=11
+GoStart dt=6 g=116 g_seq=10
+GCMarkAssistEnd dt=5
+HeapAlloc dt=54 heapalloc_value=194337496
+GCMarkAssistBegin dt=51 stack=3
+GoBlock dt=21 reason_string=13 stack=11
+GoStart dt=8 g=82 g_seq=9
+GCMarkAssistEnd dt=6
+HeapAlloc dt=63 heapalloc_value=194525912
+GCMarkAssistBegin dt=51 stack=3
+GoBlock dt=45 reason_string=13 stack=11
+GoStart dt=22 g=95 g_seq=5
+GCMarkAssistEnd dt=6
+HeapAlloc dt=1508 heapalloc_value=195394264
+GoStop dt=6034 reason_string=16 stack=6
+GoStart dt=48 g=95 g_seq=6
+GCMarkAssistBegin dt=18 stack=3
+GoBlock dt=48 reason_string=10 stack=18
+ProcStop dt=85
+ProcStart dt=20619 p=17 p_seq=1
+GoStart dt=1507 g=130 g_seq=7
+EventBatch gen=3 m=169400 time=28114950894819 size=671
+ProcStatus dt=1 p=12 pstatus=1
+GoStatus dt=2 g=112 m=169400 gstatus=2
+GCMarkAssistBegin dt=120 stack=3
+GCMarkAssistEnd dt=3298
+HeapAlloc dt=41 heapalloc_value=190758336
+GCMarkAssistBegin dt=29 stack=3
+GoStop dt=2271 reason_string=20 stack=9
+GoStart dt=14 g=112 g_seq=1
+GoStop dt=569 reason_string=20 stack=9
+GoUnblock dt=2436 g=54 g_seq=1 stack=0
+GoStart dt=18 g=54 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=31 reason_string=15 stack=5
+GoUnblock dt=5090 g=57 g_seq=13 stack=0
+GoStart dt=6 g=57 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=734 reason_string=15 stack=5
+GoUnblock dt=4144 g=71 g_seq=15 stack=0
+GoStart dt=5 g=71 g_seq=16
+GoLabel dt=1 label_string=4
+GoUnblock dt=415 g=111 g_seq=2 stack=12
+GoBlock dt=5674 reason_string=15 stack=5
+GoUnblock dt=9 g=71 g_seq=17 stack=0
+GoStart dt=5 g=71 g_seq=18
+GoLabel dt=1 label_string=2
+GoUnblock dt=693 g=83 g_seq=3 stack=12
+GoBlock dt=4708 reason_string=15 stack=5
+GoUnblock dt=14 g=71 g_seq=19 stack=0
+GoStart dt=6 g=71 g_seq=20
+GoLabel dt=3 label_string=2
+GoBlock dt=1294 reason_string=15 stack=5
+GoUnblock dt=11 g=71 g_seq=21 stack=0
+GoStart dt=4 g=71 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=2434 reason_string=15 stack=5
+GoUnblock dt=8 g=71 g_seq=23 stack=0
+GoStart dt=3 g=71 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=4227 reason_string=15 stack=5
+ProcStop dt=41
+ProcStart dt=3260 p=12 p_seq=1
+GoUnblock dt=16 g=30 g_seq=33 stack=0
+GoStart dt=143 g=30 g_seq=34
+GoLabel dt=1 label_string=2
+GoUnblock dt=553 g=89 g_seq=3 stack=12
+GoUnblock dt=971 g=127 g_seq=3 stack=12
+GoBlock dt=39 reason_string=15 stack=5
+GoStart dt=21 g=89 g_seq=4
+GCMarkAssistEnd dt=10
+HeapAlloc dt=1100 heapalloc_value=192510680
+GoStop dt=24 reason_string=16 stack=6
+GoUnblock dt=12 g=22 g_seq=51 stack=0
+GoStart dt=5 g=22 g_seq=52
+GoLabel dt=3 label_string=2
+GoBlock dt=1678 reason_string=15 stack=5
+GoUnblock dt=13 g=22 g_seq=53 stack=0
+GoStart dt=277 g=22 g_seq=54
+GoLabel dt=3 label_string=2
+GoBlock dt=960 reason_string=15 stack=5
+GoUnblock dt=8 g=22 g_seq=55 stack=0
+GoStart dt=4 g=22 g_seq=56
+GoLabel dt=1 label_string=2
+GoUnblock dt=583 g=99 g_seq=3 stack=12
+GoUnblock dt=5 g=83 g_seq=6 stack=12
+GoUnblock dt=5 g=124 g_seq=3 stack=12
+GoUnblock dt=6 g=105 g_seq=9 stack=12
+GoUnblock dt=1280 g=128 g_seq=3 stack=12
+GoUnblock dt=8 g=101 g_seq=3 stack=12
+GoBlock dt=7 reason_string=15 stack=5
+GoStart dt=11 g=128 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=38 heapalloc_value=193297112
+GCMarkAssistBegin dt=118 stack=3
+GCMarkAssistEnd dt=44
+HeapAlloc dt=21 heapalloc_value=193403608
+GoStop dt=87 reason_string=16 stack=6
+GoStart dt=15 g=101 g_seq=4
+GCMarkAssistEnd dt=5
+HeapAlloc dt=58 heapalloc_value=193608408
+GCMarkAssistBegin dt=92 stack=3
+GoBlock dt=22 reason_string=13 stack=11
+GoStart dt=10 g=128 g_seq=5
+HeapAlloc dt=34 heapalloc_value=193829592
+HeapAlloc dt=166 heapalloc_value=194026200
+HeapAlloc dt=236 heapalloc_value=194419416
+HeapAlloc dt=885 heapalloc_value=195279576
+GoStop dt=6734 reason_string=16 stack=6
+GoUnblock dt=1628 g=130 g_seq=3 stack=0
+GoStart dt=136 g=130 g_seq=4
+HeapAlloc dt=62 heapalloc_value=196532688
+HeapAlloc dt=28 heapalloc_value=196540880
+HeapAlloc dt=22 heapalloc_value=196549072
+HeapAlloc dt=26 heapalloc_value=196557264
+HeapAlloc dt=38 heapalloc_value=196565456
+HeapAlloc dt=51 heapalloc_value=196573648
+GoStop dt=3032 reason_string=16 stack=19
+GoStart dt=10 g=117 g_seq=5
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=51 reason_string=10 stack=18
+ProcStop dt=29
+ProcStart dt=9381 p=4 p_seq=2
+GoStart dt=190 g=105 g_seq=16
+GCMarkAssistEnd dt=4
+HeapAlloc dt=76 heapalloc_value=105214112
+HeapAlloc dt=103 heapalloc_value=105517216
+HeapAlloc dt=84 heapalloc_value=105642912
+HeapAlloc dt=85 heapalloc_value=105864096
+GCSweepBegin dt=188 stack=28
+GCSweepEnd dt=17 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=2 heapalloc_value=106376096
+HeapAlloc dt=43 heapalloc_value=106518816
+HeapAlloc dt=43 heapalloc_value=106756384
+HeapAlloc dt=82 heapalloc_value=106978976
+HeapAlloc dt=42 heapalloc_value=107091616
+GCSweepBegin dt=23 stack=28
+GCSweepEnd dt=8 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=3 heapalloc_value=107310112
+HeapAlloc dt=35 heapalloc_value=107372960
+HeapAlloc dt=65 heapalloc_value=107583264
+HeapAlloc dt=141 heapalloc_value=108018976
+HeapAlloc dt=161 heapalloc_value=108567968
+GCSweepBegin dt=85 stack=28
+GCSweepEnd dt=9 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=4 heapalloc_value=108808352
+HeapAlloc dt=90 heapalloc_value=109241120
+HeapAlloc dt=139 heapalloc_value=109623584
+HeapAlloc dt=162 heapalloc_value=110175008
+HeapAlloc dt=164 heapalloc_value=110769024
+HeapAlloc dt=246 heapalloc_value=111705984
+HeapAlloc dt=187 heapalloc_value=112446208
+HeapAlloc dt=161 heapalloc_value=113148544
+HeapAlloc dt=295 heapalloc_value=114145664
+GCSweepBegin dt=159 stack=28
+GCSweepEnd dt=5 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=7 heapalloc_value=114588800
+GCSweepBegin dt=48 stack=27
+EventBatch gen=3 m=169398 time=28114950899192 size=165
+ProcStatus dt=1 p=37 pstatus=2
+ProcStart dt=2 p=37 p_seq=1
+GoStatus dt=3261 g=29 m=18446744073709551615 gstatus=4
+GoUnblock dt=6 g=29 g_seq=1 stack=0
+GoStart dt=10 g=29 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=1840 reason_string=15 stack=5
+GoStart dt=16 g=86 g_seq=3
+GoBlock dt=1090 reason_string=13 stack=11
+ProcStop dt=1389
+ProcStart dt=16 p=37 p_seq=2
+GoStart dt=1537 g=84 g_seq=4
+GCMarkAssistEnd dt=7
+HeapAlloc dt=55 heapalloc_value=191847872
+GCMarkAssistBegin dt=85 stack=3
+GoBlock dt=249 reason_string=13 stack=11
+GoUnblock dt=1134 g=58 g_seq=9 stack=0
+GoStart dt=7 g=58 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=27 reason_string=15 stack=5
+GoUnblock dt=2190 g=53 g_seq=9 stack=0
+GoStart dt=8 g=53 g_seq=10
+GoLabel dt=1 label_string=4
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=2156 g=25 g_seq=13 stack=0
+GoStart dt=4 g=25 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=20 reason_string=15 stack=5
+GoUnblock dt=1089 g=14 g_seq=7 stack=0
+GoStart dt=4 g=14 g_seq=8
+GoLabel dt=1 label_string=4
+GoBlock dt=107 reason_string=15 stack=5
+GoUnblock dt=1081 g=24 g_seq=15 stack=0
+GoStart dt=6 g=24 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=19 reason_string=15 stack=5
+ProcStop dt=1075
+EventBatch gen=3 m=169397 time=28114950897533 size=734
+ProcStatus dt=1 p=25 pstatus=1
+GoStatus dt=2 g=118 m=169397 gstatus=2
+GCMarkAssistActive dt=1 g=118
+GCMarkAssistEnd dt=2
+HeapAlloc dt=37 heapalloc_value=190684608
+GCMarkAssistBegin dt=79 stack=3
+GoBlock dt=1327 reason_string=13 stack=11
+ProcStop dt=4643
+ProcStart dt=23 p=25 p_seq=1
+GoUnblock dt=20 g=53 g_seq=1 stack=0
+GoStart dt=9 g=53 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=2529 reason_string=15 stack=5
+GoStart dt=3244 g=123 g_seq=2
+GoStatus dt=30 g=97 m=18446744073709551615 gstatus=4
+GoUnblock dt=13 g=97 g_seq=1 stack=10
+GCMarkAssistBegin dt=20 stack=3
+GoStop dt=1976 reason_string=20 stack=9
+GoStart dt=15 g=123 g_seq=3
+GoStop dt=2654 reason_string=20 stack=9
+GoStart dt=12 g=123 g_seq=4
+GoStop dt=2704 reason_string=20 stack=9
+GoUnblock dt=9 g=24 g_seq=17 stack=0
+GoStart dt=4 g=24 g_seq=18
+GoLabel dt=1 label_string=2
+GoBlock dt=4029 reason_string=15 stack=5
+GoUnblock dt=14 g=24 g_seq=19 stack=0
+GoStart dt=4 g=24 g_seq=20
+GoLabel dt=1 label_string=2
+GoBlock dt=534 reason_string=15 stack=5
+GoUnblock dt=4 g=24 g_seq=21 stack=0
+GoStart dt=4 g=24 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=250 reason_string=15 stack=5
+GoUnblock dt=12 g=24 g_seq=23 stack=0
+GoStart dt=4 g=24 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=22 reason_string=15 stack=5
+ProcStop dt=71
+ProcStart dt=244 p=25 p_seq=2
+ProcStop dt=54
+ProcStart dt=25 p=25 p_seq=3
+GoUnblock dt=8 g=53 g_seq=21 stack=0
+GoStart dt=7 g=53 g_seq=22
+GoLabel dt=1 label_string=4
+GoBlock dt=86 reason_string=15 stack=5
+GoUnblock dt=59 g=56 g_seq=3 stack=0
+GoStart dt=4 g=56 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=6219 reason_string=15 stack=5
+GoUnblock dt=52 g=56 g_seq=5 stack=0
+GoStart dt=4 g=56 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=98 reason_string=15 stack=5
+GoUnblock dt=61 g=14 g_seq=27 stack=0
+GoStart dt=4 g=14 g_seq=28
+GoLabel dt=1 label_string=4
+GoBlock dt=32 reason_string=15 stack=5
+GoUnblock dt=13 g=14 g_seq=29 stack=0
+GoStart dt=5 g=14 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=2423 reason_string=15 stack=5
+ProcStop dt=36
+ProcStart dt=7135 p=31 p_seq=2
+GoStart dt=228 g=127 g_seq=4
+GCMarkAssistEnd dt=9
+HeapAlloc dt=2440 heapalloc_value=192666328
+GoStop dt=28 reason_string=16 stack=4
+GoUnblock dt=19 g=52 g_seq=57 stack=0
+GoStart dt=6 g=52 g_seq=58
+GoLabel dt=1 label_string=2
+GoBlock dt=1072 reason_string=15 stack=5
+GoUnblock dt=16 g=52 g_seq=59 stack=0
+GoStart dt=6 g=52 g_seq=60
+GoLabel dt=1 label_string=2
+GoBlock dt=19 reason_string=15 stack=5
+GoUnblock dt=17 g=54 g_seq=39 stack=0
+GoStart dt=4 g=54 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=2352 reason_string=15 stack=5
+GoStart dt=22 g=127 g_seq=8
+GCMarkAssistBegin dt=127 stack=3
+GoBlock dt=42 reason_string=13 stack=11
+GoStart dt=766 g=122 g_seq=2
+GCMarkAssistEnd dt=2
+HeapAlloc dt=19 heapalloc_value=194902744
+GCMarkAssistBegin dt=66 stack=3
+STWBegin dt=12586 kind_string=21 stack=21
+GoUnblock dt=699 g=91 g_seq=3 stack=22
+GoUnblock dt=5 g=127 g_seq=9 stack=22
+GoUnblock dt=3 g=112 g_seq=8 stack=22
+GoUnblock dt=4 g=82 g_seq=10 stack=22
+GoUnblock dt=3 g=116 g_seq=11 stack=22
+GoUnblock dt=3 g=93 g_seq=8 stack=22
+GoUnblock dt=4 g=109 g_seq=6 stack=22
+GoUnblock dt=5 g=115 g_seq=9 stack=22
+GoUnblock dt=7 g=120 g_seq=7 stack=22
+GoUnblock dt=7 g=105 g_seq=15 stack=22
+GoUnblock dt=6 g=96 g_seq=7 stack=22
+GoUnblock dt=3 g=118 g_seq=6 stack=22
+GoUnblock dt=4 g=87 g_seq=7 stack=22
+GoUnblock dt=4 g=84 g_seq=9 stack=22
+GoUnblock dt=6 g=100 g_seq=6 stack=22
+GoUnblock dt=29 g=86 g_seq=6 stack=23
+HeapAlloc dt=53 heapalloc_value=103773088
+GoStatus dt=10 g=3 m=18446744073709551615 gstatus=4
+GoUnblock dt=7 g=3 g_seq=1 stack=24
+GCEnd dt=3 gc_seq=5
+HeapGoal dt=6 heapgoal_value=207987496
+ProcsChange dt=45 procs_value=48 stack=25
+STWEnd dt=399
+GoUnblock dt=5992 g=130 g_seq=6 stack=26
+GCMarkAssistEnd dt=9
+HeapAlloc dt=11 heapalloc_value=103816864
+GCSweepBegin dt=79 stack=27
+GCSweepEnd dt=1631 swept_value=8388608 reclaimed_value=3260416
+HeapAlloc dt=14 heapalloc_value=104810272
+HeapAlloc dt=104 heapalloc_value=105001504
+HeapAlloc dt=107 heapalloc_value=105164960
+HeapAlloc dt=55 heapalloc_value=105308320
+HeapAlloc dt=200 heapalloc_value=105798560
+HeapAlloc dt=119 heapalloc_value=106091424
+HeapAlloc dt=118 heapalloc_value=106359712
+HeapAlloc dt=47 heapalloc_value=106488096
+HeapAlloc dt=44 heapalloc_value=106763424
+HeapAlloc dt=26 heapalloc_value=106820768
+HeapAlloc dt=106 heapalloc_value=107277344
+HeapAlloc dt=131 heapalloc_value=107656992
+HeapAlloc dt=71 heapalloc_value=107790880
+GCSweepBegin dt=42 stack=28
+GCSweepEnd dt=6 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=107860512
+HeapAlloc dt=71 heapalloc_value=108305696
+HeapAlloc dt=113 heapalloc_value=108608928
+HeapAlloc dt=129 heapalloc_value=108890272
+HeapAlloc dt=147 heapalloc_value=109508896
+HeapAlloc dt=88 heapalloc_value=109776544
+HeapAlloc dt=140 heapalloc_value=110286976
+HeapAlloc dt=151 heapalloc_value=110900096
+HeapAlloc dt=152 heapalloc_value=111433600
+HeapAlloc dt=136 heapalloc_value=111931264
+HeapAlloc dt=67 heapalloc_value=112248064
+HeapAlloc dt=209 heapalloc_value=113046144
+HeapAlloc dt=213 heapalloc_value=113949056
+HeapAlloc dt=236 heapalloc_value=114471168
+HeapAlloc dt=90 heapalloc_value=114663552
+GCSweepBegin dt=45 stack=28
+GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=3 heapalloc_value=114703232
+GCSweepBegin dt=54 stack=27
+EventBatch gen=3 m=169396 time=28114950894859 size=148
+ProcStatus dt=2 p=1 pstatus=1
+GoStatus dt=4 g=86 m=169396 gstatus=2
+GCMarkAssistActive dt=2 g=86
+GCMarkAssistEnd dt=2
+HeapAlloc dt=42 heapalloc_value=189889984
+GoStop dt=32 reason_string=16 stack=4
+GoUnblock dt=117 g=69 g_seq=1 stack=0
+GoStart dt=6 g=69 g_seq=2
+GoLabel dt=1 label_string=2
+GoBlock dt=2672 reason_string=15 stack=5
+GoStart dt=16 g=84 g_seq=1
+GoStop dt=2565 reason_string=20 stack=9
+GoStart dt=17 g=84 g_seq=2
+GoBlock dt=886 reason_string=13 stack=11
+ProcStop dt=2581
+ProcStart dt=17 p=1 p_seq=1
+ProcStop dt=4400
+ProcStart dt=16 p=1 p_seq=2
+GoStart dt=24 g=87 g_seq=3
+GCMarkAssistEnd dt=8
+HeapAlloc dt=70 heapalloc_value=191782336
+GCMarkAssistBegin dt=85 stack=3
+GoBlock dt=1055 reason_string=13 stack=11
+GoUnblock dt=20 g=54 g_seq=9 stack=0
+GoStart dt=7 g=54 g_seq=10
+GoLabel dt=3 label_string=2
+GoBlock dt=230 reason_string=15 stack=5
+GoUnblock dt=12 g=54 g_seq=11 stack=0
+GoStart dt=6 g=54 g_seq=12
+GoLabel dt=1 label_string=2
+GoBlock dt=1754 reason_string=15 stack=5
+GoUnblock dt=12 g=54 g_seq=13 stack=0
+GoStart dt=8 g=54 g_seq=14
+GoLabel dt=3 label_string=2
+GoBlock dt=1379 reason_string=15 stack=5
+ProcStop dt=15
+EventBatch gen=3 m=169395 time=28114950898507 size=532
+ProcStatus dt=2 p=14 pstatus=1
+GoStatus dt=2 g=103 m=169395 gstatus=2
+GCMarkAssistActive dt=1 g=103
+GCMarkAssistEnd dt=3
+HeapAlloc dt=40 heapalloc_value=190873024
+HeapAlloc dt=75 heapalloc_value=191036864
+GCMarkAssistBegin dt=65 stack=3
+GoBlock dt=6142 reason_string=13 stack=11
+GoStart dt=19 g=98 g_seq=3
+GCMarkAssistBegin dt=20 stack=3
+GoStop dt=1738 reason_string=20 stack=9
+GoStart dt=16 g=98 g_seq=4
+GoBlock dt=2102 reason_string=13 stack=11
+GoUnblock dt=2317 g=71 g_seq=5 stack=0
+GoStart dt=5 g=71 g_seq=6
+GoLabel dt=2 label_string=4
+GoBlock dt=128 reason_string=15 stack=5
+GoUnblock dt=2283 g=71 g_seq=13 stack=0
+GoStart dt=7 g=71 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=97 reason_string=15 stack=5
+GoUnblock dt=1168 g=24 g_seq=13 stack=0
+GoStart dt=7 g=24 g_seq=14
+GoLabel dt=1 label_string=4
+GoBlock dt=1399 reason_string=15 stack=5
+GoUnblock dt=3752 g=23 g_seq=25 stack=0
+GoStart dt=6 g=23 g_seq=26
+GoLabel dt=3 label_string=4
+GoBlock dt=1167 reason_string=15 stack=5
+GoUnblock dt=99 g=52 g_seq=23 stack=0
+GoStart dt=35 g=52 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=47 reason_string=15 stack=5
+GoUnblock dt=81 g=67 g_seq=19 stack=0
+GoStart dt=8 g=67 g_seq=20
+GoLabel dt=3 label_string=4
+GoBlock dt=3975 reason_string=15 stack=5
+GoUnblock dt=18 g=67 g_seq=21 stack=0
+GoStart dt=6 g=67 g_seq=22
+GoLabel dt=1 label_string=2
+GoBlock dt=80 reason_string=15 stack=5
+GoUnblock dt=18 g=67 g_seq=23 stack=0
+GoStart dt=6 g=67 g_seq=24
+GoLabel dt=1 label_string=2
+GoBlock dt=22 reason_string=15 stack=5
+GoUnblock dt=3174 g=14 g_seq=23 stack=0
+GoStart dt=7 g=14 g_seq=24
+GoLabel dt=1 label_string=4
+GoBlock dt=22 reason_string=15 stack=5
+GoUnblock dt=9 g=14 g_seq=25 stack=0
+GoStart dt=2 g=14 g_seq=26
+GoLabel dt=1 label_string=2
+GoBlock dt=13 reason_string=15 stack=5
+GoUnblock dt=65 g=29 g_seq=29 stack=0
+GoStart dt=8 g=29 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=18 reason_string=15 stack=5
+GoUnblock dt=13 g=29 g_seq=31 stack=0
+GoStart dt=6 g=29 g_seq=32
+GoLabel dt=2 label_string=2
+GoBlock dt=21 reason_string=15 stack=5
+GoUnblock dt=19 g=24 g_seq=37 stack=0
+GoStart dt=4 g=24 g_seq=38
+GoLabel dt=2 label_string=2
+GoBlock dt=33 reason_string=15 stack=5
+GoUnblock dt=8 g=24 g_seq=39 stack=0
+GoStart dt=3 g=24 g_seq=40
+GoLabel dt=1 label_string=2
+GoBlock dt=32 reason_string=15 stack=5
+GoUnblock dt=80 g=25 g_seq=29 stack=0
+GoStart dt=9 g=25 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=20 reason_string=15 stack=5
+GoUnblock dt=27 g=24 g_seq=43 stack=0
+GoStart dt=6 g=24 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=185 reason_string=15 stack=5
+GoUnblock dt=9 g=24 g_seq=45 stack=0
+GoStart dt=6 g=24 g_seq=46
+GoLabel dt=3 label_string=2
+GoBlock dt=10 reason_string=15 stack=5
+GoUnblock dt=6 g=24 g_seq=47 stack=0
+GoStart dt=1 g=24 g_seq=48
+GoLabel dt=1 label_string=2
+GoBlock dt=41 reason_string=15 stack=5
+ProcStop dt=59
+ProcStart dt=21430 p=4 p_seq=1
+GoStart dt=238 g=102 g_seq=4
+GCMarkAssistEnd dt=10
+HeapAlloc dt=38 heapalloc_value=196352464
+GoStop dt=5526 reason_string=16 stack=6
+ProcStop dt=240
+ProcStart dt=11401 p=6 p_seq=1
+GoStart dt=196 g=109 g_seq=7
+GCMarkAssistEnd dt=5
+HeapAlloc dt=54 heapalloc_value=108264736
+HeapAlloc dt=117 heapalloc_value=108527008
+HeapAlloc dt=77 heapalloc_value=108783776
+HeapAlloc dt=90 heapalloc_value=109036320
+HeapAlloc dt=77 heapalloc_value=109355808
+HeapAlloc dt=106 heapalloc_value=109678240
+HeapAlloc dt=70 heapalloc_value=110030624
+HeapAlloc dt=90 heapalloc_value=110205056
+HeapAlloc dt=51 heapalloc_value=110347136
+HeapAlloc dt=63 heapalloc_value=110588800
+HeapAlloc dt=69 heapalloc_value=110912384
+HeapAlloc dt=42 heapalloc_value=111111808
+HeapAlloc dt=105 heapalloc_value=111452032
+HeapAlloc dt=89 heapalloc_value=111822720
+HeapAlloc dt=106 heapalloc_value=112260352
+HeapAlloc dt=55 heapalloc_value=112397056
+HeapAlloc dt=62 heapalloc_value=112682368
+HeapAlloc dt=137 heapalloc_value=113281920
+GCSweepBegin dt=50 stack=28
+GCSweepEnd dt=8 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=4 heapalloc_value=113424000
+HeapAlloc dt=92 heapalloc_value=113908096
+GCSweepBegin dt=145 stack=31
+EventBatch gen=3 m=169394 time=28114950898962 size=373
+ProcStatus dt=1 p=20 pstatus=1
+GoStatus dt=4 g=108 m=169394 gstatus=2
+GCMarkAssistActive dt=1 g=108
+GCMarkAssistEnd dt=2
+HeapAlloc dt=25 heapalloc_value=191102400
+GCMarkAssistBegin dt=104 stack=3
+GCMarkAssistEnd dt=2445
+HeapAlloc dt=47 heapalloc_value=191372736
+GCMarkAssistBegin dt=11 stack=3
+GoBlock dt=1789 reason_string=13 stack=11
+GoUnblock dt=19 g=22 g_seq=3 stack=0
+GoStart dt=7 g=22 g_seq=4
+GoLabel dt=1 label_string=2
+GoBlock dt=3342 reason_string=15 stack=5
+GoUnblock dt=2752 g=71 g_seq=1 stack=0
+GoStart dt=7 g=71 g_seq=2
+GoLabel dt=1 label_string=4
+GoBlock dt=269 reason_string=15 stack=5
+GoStart dt=4308 g=111 g_seq=3
+GCMarkAssistEnd dt=7
+HeapAlloc dt=58 heapalloc_value=191888832
+GCMarkAssistBegin dt=42 stack=3
+GoBlock dt=148 reason_string=13 stack=11
+GoUnblock dt=1120 g=72 g_seq=25 stack=0
+GoStart dt=5 g=72 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=640 reason_string=15 stack=5
+GoStart dt=1105 g=102 g_seq=2
+GoStatus dt=19 g=117 m=18446744073709551615 gstatus=4
+GoUnblock dt=4 g=117 g_seq=1 stack=10
+GCMarkAssistBegin dt=13 stack=3
+GoBlock dt=32 reason_string=13 stack=11
+GoStart dt=8 g=117 g_seq=2
+GoStatus dt=19 g=128 m=18446744073709551615 gstatus=4
+GoUnblock dt=2 g=128 g_seq=1 stack=10
+GCMarkAssistBegin dt=5 stack=3
+GoBlock dt=15 reason_string=13 stack=11
+GoStart dt=5 g=128 g_seq=2
+GoStatus dt=12 g=92 m=18446744073709551615 gstatus=4
+GoUnblock dt=1 g=92 g_seq=1 stack=10
+GCMarkAssistBegin dt=9 stack=3
+GoBlock dt=14 reason_string=13 stack=11
+GoStart dt=7 g=92 g_seq=2
+GoStatus dt=17 g=101 m=18446744073709551615 gstatus=4
+GoUnblock dt=1 g=101 g_seq=1 stack=10
+GCMarkAssistBegin dt=7 stack=3
+GoBlock dt=10 reason_string=13 stack=11
+GoStart dt=5 g=101 g_seq=2
+GoStatus dt=11 g=99 m=18446744073709551615 gstatus=4
+GoUnblock dt=1 g=99 g_seq=1 stack=10
+GCMarkAssistBegin dt=8 stack=3
+GoBlock dt=15 reason_string=13 stack=11
+GoStart dt=6 g=99 g_seq=2
+GoStatus dt=11 g=89 m=18446744073709551615 gstatus=4
+GoUnblock dt=1 g=89 g_seq=1 stack=10
+GCMarkAssistBegin dt=10 stack=3
+GoBlock dt=15 reason_string=13 stack=11
+GoStart dt=4 g=89 g_seq=2
+GoStatus dt=11 g=124 m=18446744073709551615 gstatus=4
+GoUnblock dt=2 g=124 g_seq=1 stack=10
+GCMarkAssistBegin dt=8 stack=3
+GoBlock dt=34 reason_string=13 stack=11
+GoStart dt=5 g=124 g_seq=2
+GoStatus dt=10 g=96 m=18446744073709551615 gstatus=4
+GoUnblock dt=1 g=96 g_seq=1 stack=10
+GCMarkAssistBegin dt=4 stack=3
+GoBlock dt=14 reason_string=13 stack=11
+GoStart dt=4 g=96 g_seq=2
+GCMarkAssistBegin dt=8 stack=3
+GoBlock dt=22 reason_string=13 stack=11
+ProcStop dt=16
+EventBatch gen=3 m=169393 time=28114950894837 size=271
+ProcStatus dt=2 p=16 pstatus=1
+GoStatus dt=2 g=69 m=169393 gstatus=2
+GoBlock dt=122 reason_string=15 stack=5
+GoStatus dt=2224 g=83 m=169393 gstatus=1
+GoStart dt=1 g=83 g_seq=1
+GoStatus dt=33 g=121 m=18446744073709551615 gstatus=4
+GoUnblock dt=10 g=121 g_seq=1 stack=10
+GCMarkAssistBegin dt=16 stack=3
+GoStop dt=620 reason_string=20 stack=9
+GoStart dt=11 g=121 g_seq=2
+GoStatus dt=18 g=110 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=110 g_seq=1 stack=10
+GCMarkAssistBegin dt=12 stack=3
+GoStop dt=1840 reason_string=20 stack=9
+GoStart dt=16 g=110 g_seq=2
+GoStatus dt=19 g=125 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=125 g_seq=1 stack=10
+GCMarkAssistBegin dt=10 stack=3
+GoBlock dt=1799 reason_string=13 stack=11
+GoStart dt=1317 g=127 g_seq=2
+GoStatus dt=21 g=116 m=18446744073709551615 gstatus=4
+GoUnblock dt=9 g=116 g_seq=1 stack=10
+GCMarkAssistBegin dt=16 stack=3
+GoBlock dt=473 reason_string=13 stack=11
+GoStart dt=28 g=116 g_seq=2
+GoStatus dt=14 g=119 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=119 g_seq=1 stack=10
+GCMarkAssistBegin dt=12 stack=3
+GoStop dt=570 reason_string=20 stack=9
+GoStart dt=24 g=119 g_seq=2
+GoStatus dt=18 g=95 m=18446744073709551615 gstatus=4
+GoUnblock dt=3 g=95 g_seq=1 stack=10
+GCMarkAssistBegin dt=11 stack=3
+GoBlock dt=5206 reason_string=13 stack=11
+ProcStop dt=2547
+ProcStart dt=26 p=16 p_seq=1
+GoUnblock dt=87 g=58 g_seq=15 stack=0
+GoStart dt=8 g=58 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=579 reason_string=15 stack=5
+GoUnblock dt=23 g=69 g_seq=15 stack=0
+GoStart dt=5 g=69 g_seq=16
+GoLabel dt=1 label_string=2
+GoBlock dt=1028 reason_string=15 stack=5
+GoUnblock dt=2356 g=14 g_seq=11 stack=0
+GoStart dt=6 g=14 g_seq=12
+GoLabel dt=1 label_string=4
+GoBlock dt=1282 reason_string=15 stack=5
+ProcStop dt=8
+EventBatch gen=3 m=169392 time=28114950898262 size=651
+ProcStatus dt=1 p=3 pstatus=1
+GoStatus dt=1 g=106 m=169392 gstatus=2
+GCMarkAssistActive dt=1 g=106
+GCMarkAssistEnd dt=3
+HeapAlloc dt=34 heapalloc_value=190807488
+HeapAlloc dt=125 heapalloc_value=190832064
+GCMarkAssistBegin dt=46 stack=3
+GoBlock dt=1002 reason_string=13 stack=11
+GoStart dt=28 g=82 g_seq=2
+GoBlock dt=1446 reason_string=13 stack=11
+GoStart dt=34 g=120 g_seq=3
+GCMarkAssistEnd dt=2
+HeapAlloc dt=32 heapalloc_value=191282624
+GCMarkAssistBegin dt=115 stack=3
+GoBlock dt=25 reason_string=13 stack=11
+GoStart dt=17 g=112 g_seq=2
+GoBlock dt=2074 reason_string=13 stack=11
+GoUnblock dt=2604 g=24 g_seq=5 stack=0
+GoStart dt=7 g=24 g_seq=6
+GoLabel dt=2 label_string=4
+GoBlock dt=278 reason_string=15 stack=5
+GoUnblock dt=2267 g=58 g_seq=5 stack=0
+GoStart dt=9 g=58 g_seq=6
+GoLabel dt=1 label_string=4
+GoBlock dt=316 reason_string=15 stack=5
+GoUnblock dt=1167 g=24 g_seq=7 stack=0
+GoStart dt=6 g=24 g_seq=8
+GoLabel dt=1 label_string=4
+GoBlock dt=171 reason_string=15 stack=5
+GoUnblock dt=1155 g=71 g_seq=7 stack=0
+GoStart dt=6 g=71 g_seq=8
+GoLabel dt=1 label_string=4
+GoBlock dt=32 reason_string=15 stack=5
+GoStart dt=3316 g=109 g_seq=2
+GoStatus dt=28 g=114 m=18446744073709551615 gstatus=4
+GoUnblock dt=8 g=114 g_seq=1 stack=10
+GCMarkAssistBegin dt=18 stack=3
+GoStop dt=3860 reason_string=20 stack=9
+GoUnblock dt=14 g=57 g_seq=31 stack=0
+GoStart dt=5 g=57 g_seq=32
+GoLabel dt=3 label_string=2
+GoBlock dt=3324 reason_string=15 stack=5
+GoUnblock dt=97 g=24 g_seq=25 stack=0
+GoStart dt=6 g=24 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=1146 reason_string=15 stack=5
+GoUnblock dt=73 g=24 g_seq=27 stack=0
+GoStart dt=4 g=24 g_seq=28
+GoLabel dt=1 label_string=4
+GoUnblock dt=2655 g=81 g_seq=4 stack=12
+GoBlock dt=402 reason_string=15 stack=5
+GoUnblock dt=9 g=24 g_seq=29 stack=0
+GoStart dt=7 g=24 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=492 reason_string=15 stack=5
+GoUnblock dt=21 g=69 g_seq=27 stack=0
+GoStart dt=6 g=69 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=20 reason_string=15 stack=5
+GoUnblock dt=11 g=69 g_seq=29 stack=0
+GoStart dt=3 g=69 g_seq=30
+GoLabel dt=1 label_string=2
+GoBlock dt=459 reason_string=15 stack=5
+GoStart dt=168 g=116 g_seq=6
+GCMarkAssistEnd dt=8
+HeapAlloc dt=61 heapalloc_value=192232224
+GCMarkAssistBegin dt=39 stack=3
+GoBlock dt=2360 reason_string=13 stack=11
+ProcStop dt=53
+ProcStart dt=14760 p=10 p_seq=2
+GoStart dt=211 g=99 g_seq=5
+GCMarkAssistBegin dt=93 stack=3
+GoBlock dt=33 reason_string=13 stack=11
+GoStart dt=9 g=120 g_seq=6
+GCMarkAssistBegin dt=78 stack=3
+GoBlock dt=102 reason_string=13 stack=11
+GoStart dt=31 g=108 g_seq=2
+GCMarkAssistEnd dt=6
+HeapAlloc dt=307 heapalloc_value=194853592
+GoStop dt=7166 reason_string=16 stack=6
+GoStart dt=86 g=128 g_seq=6
+HeapAlloc dt=4873 heapalloc_value=196688336
+GoStop dt=12 reason_string=16 stack=6
+ProcStop dt=395
+ProcStart dt=8670 p=3 p_seq=2
+GoStart dt=193 g=93 g_seq=9
+GCMarkAssistEnd dt=7
+HeapAlloc dt=78 heapalloc_value=104465440
+HeapAlloc dt=122 heapalloc_value=104583584
+HeapAlloc dt=92 heapalloc_value=104769312
+HeapAlloc dt=127 heapalloc_value=104935968
+GCSweepBegin dt=109 stack=28
+GCSweepEnd dt=9 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=2 heapalloc_value=105138720
+HeapAlloc dt=77 heapalloc_value=105373856
+GCSweepBegin dt=157 stack=28
+GCSweepEnd dt=8 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=3 heapalloc_value=105708448
+GCSweepBegin dt=56 stack=28
+GCSweepEnd dt=11 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=4 heapalloc_value=105880480
+GCSweepBegin dt=48 stack=28
+GCSweepEnd dt=10 swept_value=32768 reclaimed_value=32768
+HeapAlloc dt=4 heapalloc_value=106124192
+GCSweepBegin dt=79 stack=28
+GCSweepEnd dt=7 swept_value=8192 reclaimed_value=8192
+HeapAlloc dt=2 heapalloc_value=106283168
+HeapAlloc dt=98 heapalloc_value=106567968
+HeapAlloc dt=116 heapalloc_value=107070496
+HeapAlloc dt=30 heapalloc_value=107146272
+HeapAlloc dt=105 heapalloc_value=107517728
+HeapAlloc dt=169 heapalloc_value=108084512
+HeapAlloc dt=187 heapalloc_value=108649888
+HeapAlloc dt=158 heapalloc_value=109200160
+HeapAlloc dt=200 heapalloc_value=109872160
+GCSweepBegin dt=116 stack=28
+GCSweepEnd dt=9 swept_value=24576 reclaimed_value=24576
+HeapAlloc dt=3 heapalloc_value=110229632
+HeapAlloc dt=54 heapalloc_value=110441344
+HeapAlloc dt=76 heapalloc_value=110711680
+HeapAlloc dt=100 heapalloc_value=111216768
+HeapAlloc dt=156 heapalloc_value=111708032
+HeapAlloc dt=55 heapalloc_value=111972224
+HeapAlloc dt=122 heapalloc_value=112391424
+HeapAlloc dt=160 heapalloc_value=113099392
+HeapAlloc dt=191 heapalloc_value=113713536
+HeapAlloc dt=158 heapalloc_value=114362368
+GCSweepBegin dt=88 stack=28
+GCSweepEnd dt=14 swept_value=16384 reclaimed_value=16384
+HeapAlloc dt=9 heapalloc_value=114520320
+HeapAlloc dt=56 heapalloc_value=114636672
+GCSweepBegin dt=180 stack=27
+EventBatch gen=3 m=169390 time=28114950895313 size=834
+ProcStatus dt=1 p=27 pstatus=1
+GoStatus dt=3 g=82 m=169390 gstatus=2
+GCMarkAssistActive dt=1 g=82
+GCMarkAssistEnd dt=2
+HeapAlloc dt=28 heapalloc_value=190143936
+HeapAlloc dt=270 heapalloc_value=190201280
+HeapAlloc dt=96 heapalloc_value=190209472
+HeapAlloc dt=29 heapalloc_value=190258624
+HeapAlloc dt=107 heapalloc_value=190356928
+GCMarkAssistBegin dt=57 stack=3
+GCMarkAssistEnd dt=502
+HeapAlloc dt=27 heapalloc_value=190430656
+GoStop dt=26 reason_string=16 stack=4
+GoStart dt=12 g=131 g_seq=3
+GoSyscallBegin dt=17 p_seq=1 stack=7
+GoSyscallEnd dt=205
+GoSyscallBegin dt=19 p_seq=2 stack=7
+GoSyscallEnd dt=2580
+GoSyscallBegin dt=16 p_seq=3 stack=7
+GoSyscallEnd dt=71
+GoSyscallBegin dt=15 p_seq=4 stack=7
+GoSyscallEnd dt=72
+GoSyscallBegin dt=25 p_seq=5 stack=7
+GoSyscallEnd dt=76
+GoSyscallBegin dt=12 p_seq=6 stack=7
+GoSyscallEnd dt=69
+GoSyscallBegin dt=11 p_seq=7 stack=7
+GoSyscallEnd dt=62
+GoSyscallBegin dt=13 p_seq=8 stack=7
+GoSyscallEnd dt=67
+GoSyscallBegin dt=16 p_seq=9 stack=7
+GoSyscallEnd dt=64
+GoSyscallBegin dt=12 p_seq=10 stack=7
+GoSyscallEnd dt=65
+GoSyscallBegin dt=14 p_seq=11 stack=7
+GoSyscallEnd dt=226
+GoSyscallBegin dt=14 p_seq=12 stack=7
+GoSyscallEnd dt=69
+GoSyscallBegin dt=17 p_seq=13 stack=7
+GoSyscallEnd dt=72
+GoSyscallBegin dt=15 p_seq=14 stack=7
+GoSyscallEnd dt=66
+GoSyscallBegin dt=18 p_seq=15 stack=7
+GoSyscallEnd dt=63
+GoSyscallBegin dt=13 p_seq=16 stack=7
+GoSyscallEnd dt=69
+GoSyscallBegin dt=17 p_seq=17 stack=7
+GoSyscallEnd dt=66
+GoSyscallBegin dt=109 p_seq=18 stack=7
+GoSyscallEnd dt=73
+GoSyscallBegin dt=13 p_seq=19 stack=7
+GoSyscallEnd dt=68
+GoSyscallBegin dt=16 p_seq=20 stack=7
+GoSyscallEnd dt=63
+GoSyscallBegin dt=15 p_seq=21 stack=7
+GoSyscallEnd dt=82
+GoSyscallBegin dt=11 p_seq=22 stack=7
+GoSyscallEnd dt=177
+GoSyscallBegin dt=14 p_seq=23 stack=7
+GoSyscallEnd dt=62
+GoSyscallBegin dt=13 p_seq=24 stack=7
+GoSyscallEnd dt=90
+GoSyscallBegin dt=11 p_seq=25 stack=7
+GoSyscallEnd dt=69
+GoSyscallBegin dt=13 p_seq=26 stack=7
+GoSyscallEnd dt=65
+GoSyscallBegin dt=15 p_seq=27 stack=7
+GoSyscallEnd dt=72
+GoSyscallBegin dt=15 p_seq=28 stack=7
+GoSyscallEnd dt=73
+GoSyscallBegin dt=18 p_seq=29 stack=7
+GoSyscallEnd dt=80
+GoSyscallBegin dt=21 p_seq=30 stack=7
+GoSyscallEnd dt=72
+GoSyscallBegin dt=17 p_seq=31 stack=7
+GoSyscallEnd dt=67
+GoSyscallBegin dt=12 p_seq=32 stack=7
+GoSyscallEnd dt=171
+GoSyscallBegin dt=16 p_seq=33 stack=7
+GoSyscallEnd dt=76
+GoSyscallBegin dt=18 p_seq=34 stack=7
+GoSyscallEnd dt=78
+GoSyscallBegin dt=13 p_seq=35 stack=7
+GoSyscallEnd dt=77
+GoSyscallBegin dt=20 p_seq=36 stack=7
+GoSyscallEnd dt=77
+GoBlock dt=16 reason_string=15 stack=2
+GoUnblock dt=1400 g=54 g_seq=3 stack=0
+GoStart dt=8 g=54 g_seq=4
+GoLabel dt=1 label_string=4
+GoBlock dt=2659 reason_string=15 stack=5
+GoUnblock dt=13 g=22 g_seq=5 stack=0
+GoStart dt=5 g=22 g_seq=6
+GoLabel dt=1 label_string=2
+GoBlock dt=2498 reason_string=15 stack=5
+GoUnblock dt=10 g=22 g_seq=7 stack=0
+GoStart dt=7 g=22 g_seq=8
+GoLabel dt=2 label_string=2
+GoBlock dt=4213 reason_string=15 stack=5
+GoUnblock dt=1324 g=57 g_seq=25 stack=0
+GoStart dt=11 g=57 g_seq=26
+GoLabel dt=1 label_string=4
+GoBlock dt=256 reason_string=15 stack=5
+GoUnblock dt=8 g=57 g_seq=27 stack=0
+GoStart dt=5 g=57 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=485 reason_string=15 stack=5
+GoUnblock dt=8 g=57 g_seq=29 stack=0
+GoStart dt=6 g=57 g_seq=30
+GoLabel dt=3 label_string=2
+GoBlock dt=504 reason_string=15 stack=5
+ProcStop dt=3771
+ProcStart dt=29 p=27 p_seq=37
+GoUnblock dt=9 g=22 g_seq=15 stack=0
+GoStart dt=5 g=22 g_seq=16
+GoLabel dt=1 label_string=4
+GoBlock dt=123 reason_string=15 stack=5
+GoUnblock dt=19 g=28 g_seq=7 stack=0
+GoStart dt=2 g=28 g_seq=8
+GoLabel dt=1 label_string=2
+GoBlock dt=67 reason_string=15 stack=5
+GoUnblock dt=73 g=72 g_seq=29 stack=0
+GoStart dt=8 g=72 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=1357 reason_string=15 stack=5
+GoUnblock dt=71 g=53 g_seq=15 stack=0
+GoStart dt=5 g=53 g_seq=16
+GoLabel dt=2 label_string=4
+GoBlock dt=53 reason_string=15 stack=5
+ProcStop dt=61
+ProcStart dt=29 p=27 p_seq=38
+GoUnblock dt=4 g=72 g_seq=35 stack=0
+GoStart dt=4 g=72 g_seq=36
+GoLabel dt=1 label_string=4
+GoBlock dt=775 reason_string=15 stack=5
+GoUnblock dt=11 g=72 g_seq=37 stack=0
+GoStart dt=5 g=72 g_seq=38
+GoLabel dt=3 label_string=2
+GoBlock dt=2553 reason_string=15 stack=5
+GoUnblock dt=23 g=54 g_seq=27 stack=0
+GoStart dt=7 g=54 g_seq=28
+GoLabel dt=1 label_string=2
+GoBlock dt=5185 reason_string=15 stack=5
+ProcStop dt=46
+ProcStart dt=1102 p=27 p_seq=39
+GoUnblock dt=17 g=14 g_seq=31 stack=0
+GoStart dt=191 g=14 g_seq=32
+GoLabel dt=5 label_string=2
+GoBlock dt=26 reason_string=15 stack=5
+GoUnblock dt=7 g=14 g_seq=33 stack=0
+GoStart dt=2 g=14 g_seq=34
+GoLabel dt=1 label_string=2
+GoBlock dt=81 reason_string=15 stack=5
+GoUnblock dt=11 g=14 g_seq=35 stack=0
+GoStart dt=6 g=14 g_seq=36
+GoLabel dt=1 label_string=2
+GoUnblock dt=257 g=97 g_seq=3 stack=12
+GoStop dt=1123 reason_string=16 stack=13
+GoUnblock dt=612 g=131 g_seq=4 stack=0
+GoStart dt=5 g=131 g_seq=5
+GoSyscallBegin dt=23 p_seq=40 stack=7
+GoSyscallEnd dt=200
+GoSyscallBegin dt=13 p_seq=41 stack=7
+GoSyscallEnd dt=179
+GoBlock dt=6 reason_string=15 stack=2
+ProcStop dt=31
+ProcStart dt=1232 p=22 p_seq=3
+GoUnblock dt=16 g=14 g_seq=40 stack=0
+GoStart dt=157 g=14 g_seq=41
+GoLabel dt=2 label_string=2
+GoUnblock dt=343 g=103 g_seq=1 stack=12
+GoBlock dt=2805 reason_string=15 stack=5
+ProcStop dt=68
+ProcStart dt=17 p=22 p_seq=4
+GoUnblock dt=3 g=14 g_seq=42 stack=0
+GoStart dt=4 g=14 g_seq=43
+GoLabel dt=1 label_string=4
+GoUnblock dt=609 g=116 g_seq=7 stack=12
+GoBlock dt=9 reason_string=15 stack=5
+GoStart dt=10 g=116 g_seq=8
+GCMarkAssistEnd dt=7
+HeapAlloc dt=60 heapalloc_value=192527064
+GCMarkAssistBegin dt=41 stack=3
+GoBlock dt=47 reason_string=13 stack=11
+GoUnblock dt=13 g=30 g_seq=35 stack=0
+GoStart dt=4 g=30 g_seq=36
+GoLabel dt=2 label_string=2
+GoBlock dt=266 reason_string=15 stack=5
+GoStart dt=16 g=105 g_seq=8
+GoBlock dt=18 reason_string=13 stack=11
+GoUnblock dt=55 g=54 g_seq=29 stack=0
+GoStart dt=8 g=54 g_seq=30
+GoLabel dt=1 label_string=4
+GoBlock dt=13 reason_string=15 stack=5
+GoUnblock dt=10 g=54 g_seq=31 stack=0
+GoStart dt=1 g=54 g_seq=32
+GoLabel dt=1 label_string=2
+GoBlock dt=46 reason_string=15 stack=5
+ProcStop dt=57
+ProcStart dt=14 p=22 p_seq=5
+GoUnblock dt=4 g=54 g_seq=33 stack=0
+GoStart dt=159 g=54 g_seq=34
+GoLabel dt=1 label_string=4
+GoBlock dt=8 reason_string=15 stack=5
+ProcStop dt=32
+ProcStart dt=3156 p=29 p_seq=1
+GoUnblock dt=15 g=71 g_seq=43 stack=0
+GoStart dt=165 g=71 g_seq=44
+GoLabel dt=1 label_string=2
+GoBlock dt=1463 reason_string=15 stack=5
+GoStart dt=22 g=118 g_seq=4
+GCMarkAssistEnd dt=6
+HeapAlloc dt=903 heapalloc_value=195328728
+GoStop dt=6525 reason_string=16 stack=6
+GoStart dt=46 g=118 g_seq=5
+GCMarkAssistBegin dt=12 stack=3
+GoBlock dt=31 reason_string=13 stack=11
+ProcStop dt=194
+EventBatch gen=3 m=18446744073709551615 time=28114950975784 size=435
+GoStatus dt=1 g=1 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=2 m=18446744073709551615 gstatus=4
+GoStatus dt=6 g=4 m=18446744073709551615 gstatus=4
+GoStatus dt=5 g=5 m=18446744073709551615 gstatus=4
+GoStatus dt=4 g=6 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=7 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=17 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=33 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=8 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=9 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=10 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=18 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=11 m=18446744073709551615 gstatus=4
+GoStatus dt=4 g=34 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=19 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=12 m=18446744073709551615 gstatus=4
+GoStatus dt=2 g=20 m=18446744073709551615 gstatus=4
+GoStatus dt=4 g=35 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=13 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=21 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=36 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=49 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=50 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=15 m=18446744073709551615 gstatus=4
+GoStatus dt=4 g=65 m=18446744073709551615 gstatus=4
+GoStatus dt=2 g=66 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=26 m=18446744073709551615 gstatus=4
+GoStatus dt=4 g=55 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=27 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=37 m=18446744073709551615 gstatus=4
+GoStatus dt=3 g=129 m=18446744073709551615 gstatus=4
+EventBatch gen=3 m=18446744073709551615 time=28114950976078 size=1132
+Stacks
+Stack id=20 nframes=2
+ pc=4540421 func=22 file=23 line=363
+ pc=4546157 func=24 file=23 line=874
+Stack id=21 nframes=5
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=18 nframes=6
+ pc=4296626 func=34 file=35 line=807
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=26 nframes=7
+ pc=4300939 func=36 file=35 line=1196
+ pc=4297301 func=34 file=35 line=926
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=7 nframes=7
+ pc=4709082 func=37 file=38 line=964
+ pc=4738119 func=39 file=40 line=209
+ pc=4738111 func=41 file=42 line=736
+ pc=4737664 func=43 file=42 line=380
+ pc=4739536 func=44 file=45 line=46
+ pc=4739528 func=46 file=47 line=183
+ pc=4803162 func=48 file=49 line=134
+Stack id=10 nframes=4
+ pc=4295522 func=50 file=35 line=627
+ pc=4246870 func=29 file=28 line=1288
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=29 nframes=8
+ pc=4556437 func=51 file=52 line=352
+ pc=4341796 func=53 file=54 line=521
+ pc=4279859 func=55 file=56 line=127
+ pc=4277746 func=57 file=58 line=182
+ pc=4244580 func=59 file=28 line=944
+ pc=4245653 func=29 file=28 line=1116
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=14 nframes=1
+ pc=4546157 func=24 file=23 line=874
+Stack id=17 nframes=1
+ pc=0 func=0 file=0 line=0
+Stack id=19 nframes=2
+ pc=4540420 func=22 file=23 line=353
+ pc=4546157 func=24 file=23 line=874
+Stack id=13 nframes=1
+ pc=0 func=0 file=0 line=0
+Stack id=5 nframes=2
+ pc=4418893 func=60 file=61 line=402
+ pc=4301860 func=62 file=35 line=1297
+Stack id=25 nframes=7
+ pc=4298957 func=36 file=35 line=1087
+ pc=4297301 func=34 file=35 line=926
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=4 nframes=2
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=30 nframes=6
+ pc=4297308 func=34 file=35 line=817
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=11 nframes=6
+ pc=4314276 func=63 file=26 line=749
+ pc=4312530 func=25 file=26 line=589
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=6 nframes=2
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=15 nframes=1
+ pc=4546157 func=24 file=23 line=874
+Stack id=8 nframes=1
+ pc=0 func=0 file=0 line=0
+Stack id=12 nframes=2
+ pc=4614055 func=64 file=65 line=474
+ pc=4302129 func=62 file=35 line=1357
+Stack id=3 nframes=6
+ pc=4556897 func=66 file=52 line=378
+ pc=4312252 func=25 file=26 line=536
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=9 nframes=5
+ pc=4312495 func=25 file=26 line=576
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=24 nframes=8
+ pc=4614055 func=64 file=65 line=474
+ pc=4298031 func=36 file=35 line=964
+ pc=4297301 func=34 file=35 line=926
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=23 nframes=6
+ pc=4297239 func=34 file=35 line=914
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=2 nframes=1
+ pc=4803172 func=48 file=49 line=130
+Stack id=28 nframes=8
+ pc=4556437 func=51 file=52 line=352
+ pc=4341796 func=53 file=54 line=521
+ pc=4280028 func=55 file=56 line=147
+ pc=4277746 func=57 file=58 line=182
+ pc=4244580 func=59 file=28 line=944
+ pc=4246070 func=29 file=28 line=1145
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=27 nframes=5
+ pc=4353658 func=67 file=68 line=958
+ pc=4278148 func=69 file=58 line=234
+ pc=4246244 func=29 file=28 line=1160
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=16 nframes=3
+ pc=4217457 func=70 file=71 line=442
+ pc=4546317 func=72 file=23 line=918
+ pc=4546150 func=24 file=23 line=871
+Stack id=31 nframes=8
+ pc=4353658 func=67 file=68 line=958
+ pc=4280657 func=73 file=56 line=254
+ pc=4280247 func=55 file=56 line=170
+ pc=4277746 func=57 file=58 line=182
+ pc=4244580 func=59 file=28 line=944
+ pc=4246070 func=29 file=28 line=1145
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+Stack id=1 nframes=3
+ pc=4554859 func=74 file=52 line=255
+ pc=4540633 func=22 file=23 line=391
+ pc=4546157 func=24 file=23 line=874
+Stack id=22 nframes=10
+ pc=4558967 func=75 file=76 line=166
+ pc=4558898 func=77 file=52 line=445
+ pc=4447453 func=78 file=61 line=3712
+ pc=4314041 func=79 file=26 line=714
+ pc=4297238 func=34 file=35 line=909
+ pc=4312466 func=25 file=26 line=564
+ pc=4247187 func=27 file=28 line=1333
+ pc=4245160 func=29 file=28 line=1021
+ pc=4502184 func=30 file=31 line=103
+ pc=4804475 func=32 file=33 line=60
+EventBatch gen=3 m=18446744073709551615 time=28114950894688 size=2762
+Strings
+String id=1
+ data="Not worker"
+String id=2
+ data="GC (dedicated)"
+String id=3
+ data="GC (fractional)"
+String id=4
+ data="GC (idle)"
+String id=5
+ data="unspecified"
+String id=6
+ data="forever"
+String id=7
+ data="network"
+String id=8
+ data="select"
+String id=9
+ data="sync.(*Cond).Wait"
+String id=10
+ data="sync"
+String id=11
+ data="chan send"
+String id=12
+ data="chan receive"
+String id=13
+ data="GC mark assist wait for work"
+String id=14
+ data="GC background sweeper wait"
+String id=15
+ data="system goroutine wait"
+String id=16
+ data="preempted"
+String id=17
+ data="wait for debug call"
+String id=18
+ data="wait until GC ends"
+String id=19
+ data="sleep"
+String id=20
+ data="runtime.Gosched"
+String id=21
+ data="GC mark termination"
+String id=22
+ data="runtime.traceAdvance"
+String id=23
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2.go"
+String id=24
+ data="runtime.(*traceAdvancerState).start.func1"
+String id=25
+ data="runtime.gcAssistAlloc"
+String id=26
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgcmark.go"
+String id=27
+ data="runtime.deductAssistCredit"
+String id=28
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/malloc.go"
+String id=29
+ data="runtime.mallocgc"
+String id=30
+ data="runtime.makeslice"
+String id=31
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/slice.go"
+String id=32
+ data="main.main.func1"
+String id=33
+ data="/usr/local/google/home/mknyszek/work/go-1/src/internal/trace/v2/testdata/testprog/gc-stress.go"
+String id=34
+ data="runtime.gcMarkDone"
+String id=35
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgc.go"
+String id=36
+ data="runtime.gcMarkTermination"
+String id=37
+ data="syscall.write"
+String id=38
+ data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/zsyscall_linux_amd64.go"
+String id=39
+ data="syscall.Write"
+String id=40
+ data="/usr/local/google/home/mknyszek/work/go-1/src/syscall/syscall_unix.go"
+String id=41
+ data="internal/poll.ignoringEINTRIO"
+String id=42
+ data="/usr/local/google/home/mknyszek/work/go-1/src/internal/poll/fd_unix.go"
+String id=43
+ data="internal/poll.(*FD).Write"
+String id=44
+ data="os.(*File).write"
+String id=45
+ data="/usr/local/google/home/mknyszek/work/go-1/src/os/file_posix.go"
+String id=46
+ data="os.(*File).Write"
+String id=47
+ data="/usr/local/google/home/mknyszek/work/go-1/src/os/file.go"
+String id=48
+ data="runtime/trace.Start.func1"
+String id=49
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace/trace.go"
+String id=50
+ data="runtime.gcStart"
+String id=51
+ data="runtime.traceLocker.GCSweepSpan"
+String id=52
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2runtime.go"
+String id=53
+ data="runtime.(*sweepLocked).sweep"
+String id=54
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mgcsweep.go"
+String id=55
+ data="runtime.(*mcentral).cacheSpan"
+String id=56
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mcentral.go"
+String id=57
+ data="runtime.(*mcache).refill"
+String id=58
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mcache.go"
+String id=59
+ data="runtime.(*mcache).nextFree"
+String id=60
+ data="runtime.gopark"
+String id=61
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/proc.go"
+String id=62
+ data="runtime.gcBgMarkWorker"
+String id=63
+ data="runtime.gcParkAssist"
+String id=64
+ data="runtime.systemstack_switch"
+String id=65
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/asm_amd64.s"
+String id=66
+ data="runtime.traceLocker.GCMarkAssistStart"
+String id=67
+ data="runtime.(*mheap).alloc"
+String id=68
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/mheap.go"
+String id=69
+ data="runtime.(*mcache).allocLarge"
+String id=70
+ data="runtime.chanrecv1"
+String id=71
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/chan.go"
+String id=72
+ data="runtime.(*wakeableSleep).sleep"
+String id=73
+ data="runtime.(*mcentral).grow"
+String id=74
+ data="runtime.traceLocker.Gomaxprocs"
+String id=75
+ data="runtime.traceLocker.stack"
+String id=76
+ data="/usr/local/google/home/mknyszek/work/go-1/src/runtime/trace2event.go"
+String id=77
+ data="runtime.traceLocker.GoUnpark"
+String id=78
+ data="runtime.injectglist"
+String id=79
+ data="runtime.gcWakeAllAssists"
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-go-create-without-running-g.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-go-create-without-running-g.test
new file mode 100644
index 0000000000000000000000000000000000000000..494c444ca37eb20667f1628e5f21fa28ab94c2f0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-go-create-without-running-g.test
@@ -0,0 +1,17 @@
+-- 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"
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-ambiguous.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-ambiguous.test
new file mode 100644
index 0000000000000000000000000000000000000000..0d88af4d61467d290b604271df6ba3ecedffa586
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-ambiguous.test
@@ -0,0 +1,21 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=21
+ProcStatus dt=0 p=0 pstatus=1
+GoStatus dt=0 g=1 m=0 gstatus=2
+GoSyscallBegin dt=0 p_seq=1 stack=0
+GoSyscallEnd dt=0
+GoSyscallBegin dt=0 p_seq=2 stack=0
+GoSyscallEndBlocked dt=0
+EventBatch gen=1 m=1 time=0 size=14
+ProcStatus dt=0 p=2 pstatus=1
+GoStatus dt=0 g=2 m=1 gstatus=2
+ProcSteal dt=0 p=0 p_seq=3 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test
new file mode 100644
index 0000000000000000000000000000000000000000..bbfc9cc877eee4a3bd584fa8012742ea81800efc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-bare-m.test
@@ -0,0 +1,17 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=11
+ProcStatus dt=1 p=1 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=3
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=9
+ProcStatus dt=1 p=0 pstatus=4
+ProcSteal dt=1 p=0 p_seq=1 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test
new file mode 100644
index 0000000000000000000000000000000000000000..8e291327cf0e27bce70646f56333f50f5b0c376f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc-bare-m.test
@@ -0,0 +1,18 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=15
+GoStatus dt=1 g=1 m=0 gstatus=3
+ProcStatus dt=1 p=1 pstatus=2
+ProcStart dt=1 p=1 p_seq=1
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=9
+ProcStatus dt=1 p=0 pstatus=4
+ProcSteal dt=1 p=0 p_seq=1 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test
new file mode 100644
index 0000000000000000000000000000000000000000..3b26e8f13f5498b3337a56da4133f9222ccd0f8a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary-reacquire-new-proc.test
@@ -0,0 +1,20 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=15
+GoStatus dt=1 g=1 m=0 gstatus=3
+ProcStatus dt=1 p=1 pstatus=2
+ProcStart dt=1 p=1 p_seq=1
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=18
+ProcStatus dt=1 p=2 pstatus=1
+GoStatus dt=1 g=2 m=1 gstatus=2
+ProcStatus dt=1 p=0 pstatus=4
+ProcSteal dt=1 p=0 p_seq=1 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary.test
new file mode 100644
index 0000000000000000000000000000000000000000..133d8a5447c2aaaaa9462ee0fdc093105ba81a31
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-gen-boundary.test
@@ -0,0 +1,19 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=11
+ProcStatus dt=1 p=1 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=3
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=18
+ProcStatus dt=1 p=2 pstatus=1
+GoStatus dt=1 g=2 m=1 gstatus=2
+ProcStatus dt=1 p=0 pstatus=4
+ProcSteal dt=1 p=0 p_seq=1 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test
new file mode 100644
index 0000000000000000000000000000000000000000..fa68c824b91ce402d3d38c87bb62f7563359a04c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc-bare-m.test
@@ -0,0 +1,19 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=23
+ProcStatus dt=1 p=1 pstatus=2
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+GoSyscallBegin dt=1 p_seq=1 stack=0
+ProcStart dt=1 p=1 p_seq=1
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=5
+ProcSteal dt=1 p=0 p_seq=2 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test
new file mode 100644
index 0000000000000000000000000000000000000000..85c19fcf05d021b6b8790c5b0cf9857f41288d2d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-reacquire-new-proc.test
@@ -0,0 +1,21 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=23
+ProcStatus dt=1 p=1 pstatus=2
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+GoSyscallBegin dt=1 p_seq=1 stack=0
+ProcStart dt=1 p=1 p_seq=1
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=14
+ProcStatus dt=1 p=2 pstatus=1
+GoStatus dt=1 g=2 m=1 gstatus=2
+ProcSteal dt=1 p=0 p_seq=2 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-self.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-self.test
new file mode 100644
index 0000000000000000000000000000000000000000..6484eb6d35cca9c1445effb72e1ef91d621d2ca8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-self.test
@@ -0,0 +1,17 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=24
+ProcStatus dt=0 p=0 pstatus=1
+GoStatus dt=0 g=1 m=0 gstatus=2
+GoSyscallBegin dt=0 p_seq=1 stack=0
+ProcSteal dt=0 p=0 p_seq=2 m=0
+ProcStart dt=0 p=0 p_seq=3
+GoSyscallEndBlocked dt=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test
new file mode 100644
index 0000000000000000000000000000000000000000..d33872287d5ed5bcfc3a949255173d2256d9ba54
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple-bare-m.test
@@ -0,0 +1,17 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=15
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+GoSyscallBegin dt=1 p_seq=1 stack=0
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=5
+ProcSteal dt=1 p=0 p_seq=2 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple.test
new file mode 100644
index 0000000000000000000000000000000000000000..a1f9db41d4729f2f6416e793d6309f6e9793b266
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-simple.test
@@ -0,0 +1,19 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=15
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+GoSyscallBegin dt=1 p_seq=1 stack=0
+GoSyscallEndBlocked dt=1
+EventBatch gen=1 m=1 time=0 size=14
+ProcStatus dt=1 p=2 pstatus=1
+GoStatus dt=1 g=2 m=1 gstatus=2
+ProcSteal dt=1 p=0 p_seq=2 m=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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test
new file mode 100644
index 0000000000000000000000000000000000000000..58c41c55491d059354cd11a7392af74fb67069b2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-syscall-steal-proc-sitting-in-syscall.test
@@ -0,0 +1,15 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=9
+ProcStatus dt=1 p=0 pstatus=4
+ProcSteal dt=1 p=0 p_seq=1 m=1
+EventBatch gen=1 m=18446744073709551615 time=0 size=5
+GoStatus dt=1 g=1 m=1 gstatus=3
+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=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-task-across-generations.test b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-task-across-generations.test
new file mode 100644
index 0000000000000000000000000000000000000000..0b8abd7346416b8843e1a4eeecc10124138608d6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testdata/tests/go122-task-across-generations.test
@@ -0,0 +1,26 @@
+-- expect --
+SUCCESS
+-- trace --
+Trace Go1.22
+EventBatch gen=1 m=0 time=0 size=15
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+UserTaskBegin dt=1 task=2 parent_task=0 name_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=11
+Strings
+String id=1
+ data="my task"
+EventBatch gen=2 m=0 time=5 size=13
+ProcStatus dt=1 p=0 pstatus=1
+GoStatus dt=1 g=1 m=0 gstatus=2
+UserTaskEnd dt=1 task=2 stack=0
+EventBatch gen=2 m=18446744073709551615 time=0 size=5
+Frequency freq=15625000
+EventBatch gen=2 m=18446744073709551615 time=0 size=1
+Stacks
+EventBatch gen=2 m=18446744073709551615 time=0 size=1
+Strings
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/expectation.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/expectation.go
new file mode 100644
index 0000000000000000000000000000000000000000..3e5394a7e4e9f95a169191bca3cab9cfe56c4eb5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/expectation.go
@@ -0,0 +1,81 @@
+// 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 testtrace
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// Expectation represents the expected result of some operation.
+type Expectation struct {
+ failure bool
+ errorMatcher *regexp.Regexp
+}
+
+// ExpectSuccess returns an Expectation that trivially expects success.
+func ExpectSuccess() *Expectation {
+ return new(Expectation)
+}
+
+// Check validates whether err conforms to the expectation. Returns
+// an error if it does not conform.
+//
+// Conformance means that if failure is true, then err must be non-nil.
+// If err is non-nil, then it must match errorMatcher.
+func (e *Expectation) Check(err error) error {
+ if !e.failure && err != nil {
+ return fmt.Errorf("unexpected error while reading the trace: %v", err)
+ }
+ if e.failure && err == nil {
+ return fmt.Errorf("expected error while reading the trace: want something matching %q, got none", e.errorMatcher)
+ }
+ if e.failure && err != nil && !e.errorMatcher.MatchString(err.Error()) {
+ return fmt.Errorf("unexpected error while reading the trace: want something matching %q, got %s", e.errorMatcher, err.Error())
+ }
+ return nil
+}
+
+// ParseExpectation parses the serialized form of an Expectation.
+func ParseExpectation(data []byte) (*Expectation, error) {
+ exp := new(Expectation)
+ s := bufio.NewScanner(bytes.NewReader(data))
+ if s.Scan() {
+ c := strings.SplitN(s.Text(), " ", 2)
+ switch c[0] {
+ case "SUCCESS":
+ case "FAILURE":
+ exp.failure = true
+ if len(c) != 2 {
+ return exp, fmt.Errorf("bad header line for FAILURE: %q", s.Text())
+ }
+ matcher, err := parseMatcher(c[1])
+ if err != nil {
+ return exp, err
+ }
+ exp.errorMatcher = matcher
+ default:
+ return exp, fmt.Errorf("bad header line: %q", s.Text())
+ }
+ return exp, nil
+ }
+ return exp, s.Err()
+}
+
+func parseMatcher(quoted string) (*regexp.Regexp, error) {
+ pattern, err := strconv.Unquote(quoted)
+ if err != nil {
+ return nil, fmt.Errorf("malformed pattern: not correctly quoted: %s: %v", quoted, err)
+ }
+ matcher, err := regexp.Compile(pattern)
+ if err != nil {
+ return nil, fmt.Errorf("malformed pattern: not a valid regexp: %s: %v", pattern, err)
+ }
+ return matcher, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/format.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/format.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e2e97530c110265a319d9e6c43916d98ee65f71
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/format.go
@@ -0,0 +1,56 @@
+// 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 testtrace
+
+import (
+ "bytes"
+ "fmt"
+ "internal/trace/v2/raw"
+ "internal/txtar"
+ "io"
+)
+
+// ParseFile parses a test file generated by the testgen package.
+func ParseFile(testPath string) (io.Reader, *Expectation, error) {
+ ar, err := txtar.ParseFile(testPath)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to read test file for %s: %v", testPath, err)
+ }
+ if len(ar.Files) != 2 {
+ return nil, nil, fmt.Errorf("malformed test %s: wrong number of files", testPath)
+ }
+ if ar.Files[0].Name != "expect" {
+ return nil, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[0].Name)
+ }
+ if ar.Files[1].Name != "trace" {
+ return nil, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[1].Name)
+ }
+ tr, err := raw.NewTextReader(bytes.NewReader(ar.Files[1].Data))
+ if err != nil {
+ return nil, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err)
+ }
+ var buf bytes.Buffer
+ tw, err := raw.NewWriter(&buf, tr.Version())
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to create trace byte writer: %v", err)
+ }
+ for {
+ ev, err := tr.ReadEvent()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err)
+ }
+ if err := tw.WriteEvent(ev); err != nil {
+ return nil, nil, fmt.Errorf("internal error during %s: failed to write trace bytes: %v", testPath, err)
+ }
+ }
+ exp, err := ParseExpectation(ar.Files[0].Data)
+ if err != nil {
+ return nil, nil, fmt.Errorf("internal error during %s: failed to parse expectation %q: %v", testPath, string(ar.Files[0].Data), err)
+ }
+ return &buf, exp, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/validation.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/validation.go
new file mode 100644
index 0000000000000000000000000000000000000000..021c7785fdbbac72141ee9453ec33a3871f0e0c7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/testtrace/validation.go
@@ -0,0 +1,361 @@
+// 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 testtrace
+
+import (
+ "errors"
+ "fmt"
+ "internal/trace/v2"
+ "slices"
+ "strings"
+)
+
+// Validator is a type used for validating a stream of trace.Events.
+type Validator struct {
+ lastTs trace.Time
+ gs map[trace.GoID]*goState
+ ps map[trace.ProcID]*procState
+ ms map[trace.ThreadID]*schedContext
+ ranges map[trace.ResourceID][]string
+ tasks map[trace.TaskID]string
+ seenSync bool
+}
+
+type schedContext struct {
+ M trace.ThreadID
+ P trace.ProcID
+ G trace.GoID
+}
+
+type goState struct {
+ state trace.GoState
+ binding *schedContext
+}
+
+type procState struct {
+ state trace.ProcState
+ binding *schedContext
+}
+
+// NewValidator creates a new Validator.
+func NewValidator() *Validator {
+ return &Validator{
+ gs: make(map[trace.GoID]*goState),
+ ps: make(map[trace.ProcID]*procState),
+ ms: make(map[trace.ThreadID]*schedContext),
+ ranges: make(map[trace.ResourceID][]string),
+ tasks: make(map[trace.TaskID]string),
+ }
+}
+
+// Event validates ev as the next event in a stream of trace.Events.
+//
+// Returns an error if validation fails.
+func (v *Validator) Event(ev trace.Event) error {
+ e := new(errAccumulator)
+
+ // Validate timestamp order.
+ if v.lastTs != 0 {
+ if ev.Time() <= v.lastTs {
+ e.Errorf("timestamp out-of-order for %+v", ev)
+ } else {
+ v.lastTs = ev.Time()
+ }
+ } else {
+ v.lastTs = ev.Time()
+ }
+
+ // Validate event stack.
+ checkStack(e, ev.Stack())
+
+ switch ev.Kind() {
+ case trace.EventSync:
+ // Just record that we've seen a Sync at some point.
+ v.seenSync = true
+ case trace.EventMetric:
+ m := ev.Metric()
+ if !strings.Contains(m.Name, ":") {
+ // Should have a ":" as per runtime/metrics convention.
+ e.Errorf("invalid metric name %q", m.Name)
+ }
+ // Make sure the value is OK.
+ if m.Value.Kind() == trace.ValueBad {
+ e.Errorf("invalid value")
+ }
+ switch m.Value.Kind() {
+ case trace.ValueUint64:
+ // Just make sure it doesn't panic.
+ _ = m.Value.Uint64()
+ }
+ case trace.EventLabel:
+ l := ev.Label()
+
+ // Check label.
+ if l.Label == "" {
+ e.Errorf("invalid label %q", l.Label)
+ }
+
+ // Check label resource.
+ if l.Resource.Kind == trace.ResourceNone {
+ e.Errorf("label resource none")
+ }
+ switch l.Resource.Kind {
+ case trace.ResourceGoroutine:
+ id := l.Resource.Goroutine()
+ if _, ok := v.gs[id]; !ok {
+ e.Errorf("label for invalid goroutine %d", id)
+ }
+ case trace.ResourceProc:
+ id := l.Resource.Proc()
+ if _, ok := v.ps[id]; !ok {
+ e.Errorf("label for invalid proc %d", id)
+ }
+ case trace.ResourceThread:
+ id := l.Resource.Thread()
+ if _, ok := v.ms[id]; !ok {
+ e.Errorf("label for invalid thread %d", id)
+ }
+ }
+ case trace.EventStackSample:
+ // Not much to check here. It's basically a sched context and a stack.
+ // The sched context is also not guaranteed to align with other events.
+ // We already checked the stack above.
+ case trace.EventStateTransition:
+ // Validate state transitions.
+ //
+ // TODO(mknyszek): A lot of logic is duplicated between goroutines and procs.
+ // The two are intentionally handled identically; from the perspective of the
+ // API, resources all have the same general properties. Consider making this
+ // code generic over resources and implementing validation just once.
+ tr := ev.StateTransition()
+ checkStack(e, tr.Stack)
+ switch tr.Resource.Kind {
+ case trace.ResourceGoroutine:
+ // Basic state transition validation.
+ id := tr.Resource.Goroutine()
+ old, new := tr.Goroutine()
+ if new == trace.GoUndetermined {
+ e.Errorf("transition to undetermined state for goroutine %d", id)
+ }
+ if v.seenSync && old == trace.GoUndetermined {
+ e.Errorf("undetermined goroutine %d after first global sync", id)
+ }
+ if new == trace.GoNotExist && v.hasAnyRange(trace.MakeResourceID(id)) {
+ e.Errorf("goroutine %d died with active ranges", id)
+ }
+ state, ok := v.gs[id]
+ if ok {
+ if old != state.state {
+ e.Errorf("bad old state for goroutine %d: got %s, want %s", id, old, state.state)
+ }
+ state.state = new
+ } else {
+ if old != trace.GoUndetermined && old != trace.GoNotExist {
+ e.Errorf("bad old state for unregistered goroutine %d: %s", id, old)
+ }
+ state = &goState{state: new}
+ v.gs[id] = state
+ }
+ // Validate sched context.
+ if new.Executing() {
+ ctx := v.getOrCreateThread(e, ev.Thread())
+ if ctx != nil {
+ if ctx.G != trace.NoGoroutine && ctx.G != id {
+ e.Errorf("tried to run goroutine %d when one was already executing (%d) on thread %d", id, ctx.G, ev.Thread())
+ }
+ ctx.G = id
+ state.binding = ctx
+ }
+ } else if old.Executing() && !new.Executing() {
+ if tr.Stack != ev.Stack() {
+ // This is a case where the transition is happening to a goroutine that is also executing, so
+ // these two stacks should always match.
+ e.Errorf("StateTransition.Stack doesn't match Event.Stack")
+ }
+ ctx := state.binding
+ if ctx != nil {
+ if ctx.G != id {
+ e.Errorf("tried to stop goroutine %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.G, ev.Thread())
+ }
+ ctx.G = trace.NoGoroutine
+ state.binding = nil
+ } else {
+ e.Errorf("stopping goroutine %d not bound to any active context", id)
+ }
+ }
+ case trace.ResourceProc:
+ // Basic state transition validation.
+ id := tr.Resource.Proc()
+ old, new := tr.Proc()
+ if new == trace.ProcUndetermined {
+ e.Errorf("transition to undetermined state for proc %d", id)
+ }
+ if v.seenSync && old == trace.ProcUndetermined {
+ e.Errorf("undetermined proc %d after first global sync", id)
+ }
+ if new == trace.ProcNotExist && v.hasAnyRange(trace.MakeResourceID(id)) {
+ e.Errorf("proc %d died with active ranges", id)
+ }
+ state, ok := v.ps[id]
+ if ok {
+ if old != state.state {
+ e.Errorf("bad old state for proc %d: got %s, want %s", id, old, state.state)
+ }
+ state.state = new
+ } else {
+ if old != trace.ProcUndetermined && old != trace.ProcNotExist {
+ e.Errorf("bad old state for unregistered proc %d: %s", id, old)
+ }
+ state = &procState{state: new}
+ v.ps[id] = state
+ }
+ // Validate sched context.
+ if new.Executing() {
+ ctx := v.getOrCreateThread(e, ev.Thread())
+ if ctx != nil {
+ if ctx.P != trace.NoProc && ctx.P != id {
+ e.Errorf("tried to run proc %d when one was already executing (%d) on thread %d", id, ctx.P, ev.Thread())
+ }
+ ctx.P = id
+ state.binding = ctx
+ }
+ } else if old.Executing() && !new.Executing() {
+ ctx := state.binding
+ if ctx != nil {
+ if ctx.P != id {
+ e.Errorf("tried to stop proc %d when it wasn't currently executing (currently executing %d) on thread %d", id, ctx.P, ctx.M)
+ }
+ ctx.P = trace.NoProc
+ state.binding = nil
+ } else {
+ e.Errorf("stopping proc %d not bound to any active context", id)
+ }
+ }
+ }
+ case trace.EventRangeBegin, trace.EventRangeActive, trace.EventRangeEnd:
+ // Validate ranges.
+ r := ev.Range()
+ switch ev.Kind() {
+ case trace.EventRangeBegin:
+ if v.hasRange(r.Scope, r.Name) {
+ e.Errorf("already active range %q on %v begun again", r.Name, r.Scope)
+ }
+ v.addRange(r.Scope, r.Name)
+ case trace.EventRangeActive:
+ if !v.hasRange(r.Scope, r.Name) {
+ v.addRange(r.Scope, r.Name)
+ }
+ case trace.EventRangeEnd:
+ if !v.hasRange(r.Scope, r.Name) {
+ e.Errorf("inactive range %q on %v ended", r.Name, r.Scope)
+ }
+ v.deleteRange(r.Scope, r.Name)
+ }
+ case trace.EventTaskBegin:
+ // Validate task begin.
+ t := ev.Task()
+ if t.ID == trace.NoTask || t.ID == trace.BackgroundTask {
+ // The background task should never have an event emitted for it.
+ e.Errorf("found invalid task ID for task of type %s", t.Type)
+ }
+ if t.Parent == trace.BackgroundTask {
+ // It's not possible for a task to be a subtask of the background task.
+ e.Errorf("found background task as the parent for task of type %s", t.Type)
+ }
+ // N.B. Don't check the task type. Empty string is a valid task type.
+ v.tasks[t.ID] = t.Type
+ case trace.EventTaskEnd:
+ // Validate task end.
+ // We can see a task end without a begin, so ignore a task without information.
+ // Instead, if we've seen the task begin, just make sure the task end lines up.
+ t := ev.Task()
+ if typ, ok := v.tasks[t.ID]; ok {
+ if t.Type != typ {
+ e.Errorf("task end type %q doesn't match task start type %q for task %d", t.Type, typ, t.ID)
+ }
+ delete(v.tasks, t.ID)
+ }
+ case trace.EventLog:
+ // There's really not much here to check, except that we can
+ // generate a Log. The category and message are entirely user-created,
+ // so we can't make any assumptions as to what they are. We also
+ // can't validate the task, because proving the task's existence is very
+ // much best-effort.
+ _ = ev.Log()
+ }
+ return e.Errors()
+}
+
+func (v *Validator) hasRange(r trace.ResourceID, name string) bool {
+ ranges, ok := v.ranges[r]
+ return ok && slices.Contains(ranges, name)
+}
+
+func (v *Validator) addRange(r trace.ResourceID, name string) {
+ ranges, _ := v.ranges[r]
+ ranges = append(ranges, name)
+ v.ranges[r] = ranges
+}
+
+func (v *Validator) hasAnyRange(r trace.ResourceID) bool {
+ ranges, ok := v.ranges[r]
+ return ok && len(ranges) != 0
+}
+
+func (v *Validator) deleteRange(r trace.ResourceID, name string) {
+ ranges, ok := v.ranges[r]
+ if !ok {
+ return
+ }
+ i := slices.Index(ranges, name)
+ if i < 0 {
+ return
+ }
+ v.ranges[r] = slices.Delete(ranges, i, i+1)
+}
+
+func (v *Validator) getOrCreateThread(e *errAccumulator, m trace.ThreadID) *schedContext {
+ if m == trace.NoThread {
+ e.Errorf("must have thread, but thread ID is none")
+ return nil
+ }
+ s, ok := v.ms[m]
+ if !ok {
+ s = &schedContext{M: m, P: trace.NoProc, G: trace.NoGoroutine}
+ v.ms[m] = s
+ return s
+ }
+ return s
+}
+
+func checkStack(e *errAccumulator, stk trace.Stack) {
+ // Check for non-empty values, but we also check for crashes due to incorrect validation.
+ i := 0
+ stk.Frames(func(f trace.StackFrame) bool {
+ if i == 0 {
+ // Allow for one fully zero stack.
+ //
+ // TODO(mknyszek): Investigate why that happens.
+ return true
+ }
+ if f.Func == "" || f.File == "" || f.PC == 0 || f.Line == 0 {
+ e.Errorf("invalid stack frame %#v: missing information", f)
+ }
+ i++
+ return true
+ })
+}
+
+type errAccumulator struct {
+ errs []error
+}
+
+func (e *errAccumulator) Errorf(f string, args ...any) {
+ e.errs = append(e.errs, fmt.Errorf(f, args...))
+}
+
+func (e *errAccumulator) Errors() error {
+ return errors.Join(e.errs...)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/trace_test.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/trace_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7cc7508fe985b952bb3746b9542d0b75d70158e9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/trace_test.go
@@ -0,0 +1,606 @@
+// 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/testenv"
+ "internal/trace/v2"
+ "internal/trace/v2/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", nil)
+}
+
+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 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) {
+ // Run the program and capture the trace, which is always written to stdout.
+ cmd := testenv.Command(t, testenv.GoToolPath(t), "run", testPath)
+ cmd.Env = append(os.Environ(), "GOEXPERIMENT=exectracer2")
+ if stress {
+ // Advance a generation constantly.
+ cmd.Env = append(cmd.Env, "GODEBUG=traceadvanceperiod=0")
+ }
+ // Capture stdout and stderr.
+ //
+ // The protoocol 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 reader stress tests in short mode")
+ }
+ runTest(t, true)
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/value.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/value.go
new file mode 100644
index 0000000000000000000000000000000000000000..bd2cba7878355d6ce45f0bba1a85cfeabee702a9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/value.go
@@ -0,0 +1,53 @@
+// 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 "fmt"
+
+// Value is a dynamically-typed value obtained from a trace.
+type Value struct {
+ kind ValueKind
+ scalar uint64
+}
+
+// ValueKind is the type of a dynamically-typed value from a trace.
+type ValueKind uint8
+
+const (
+ ValueBad ValueKind = iota
+ ValueUint64
+)
+
+// Kind returns the ValueKind of the value.
+//
+// It represents the underlying structure of the value.
+//
+// New ValueKinds may be added in the future. Users of this type must be robust
+// to that possibility.
+func (v Value) Kind() ValueKind {
+ return v.kind
+}
+
+// Uint64 returns the uint64 value for a MetricSampleUint64.
+//
+// Panics if this metric sample's Kind is not MetricSampleUint64.
+func (v Value) Uint64() uint64 {
+ if v.kind != ValueUint64 {
+ panic("Uint64 called on Value of a different Kind")
+ }
+ return v.scalar
+}
+
+// valueAsString produces a debug string value.
+//
+// This isn't just Value.String because we may want to use that to store
+// string values in the future.
+func valueAsString(v Value) string {
+ switch v.Kind() {
+ case ValueUint64:
+ return fmt.Sprintf("Uint64(%d)", v.scalar)
+ }
+ return "Bad"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/trace/v2/version/version.go b/platform/dbops/binaries/go/go/src/internal/trace/v2/version/version.go
new file mode 100644
index 0000000000000000000000000000000000000000..28189f80db85de5340a97e6083614a85300b872b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/trace/v2/version/version.go
@@ -0,0 +1,57 @@
+// 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 version
+
+import (
+ "fmt"
+ "io"
+
+ "internal/trace/v2/event"
+ "internal/trace/v2/event/go122"
+)
+
+// Version represents the version of a trace file.
+type Version uint32
+
+const (
+ Go122 Version = 22
+ Current = Go122
+)
+
+var versions = map[Version][]event.Spec{
+ Go122: go122.Specs(),
+}
+
+// Specs returns the set of event.Specs for this version.
+func (v Version) Specs() []event.Spec {
+ return versions[v]
+}
+
+func (v Version) Valid() bool {
+ _, ok := versions[v]
+ return ok
+}
+
+// headerFmt is the format of the header of all Go execution traces.
+const headerFmt = "go 1.%d trace\x00\x00\x00"
+
+// ReadHeader reads the version of the trace out of the trace file's
+// header, whose prefix must be present in v.
+func ReadHeader(r io.Reader) (Version, error) {
+ var v Version
+ _, err := fmt.Fscanf(r, headerFmt, &v)
+ if err != nil {
+ return v, fmt.Errorf("bad file format: not a Go execution trace?")
+ }
+ if !v.Valid() {
+ return v, fmt.Errorf("unknown or unsupported trace version go 1.%d", v)
+ }
+ return v, nil
+}
+
+// WriteHeader writes a header for a trace version v to w.
+func WriteHeader(w io.Writer, v Version) (int, error) {
+ return fmt.Fprintf(w, headerFmt, v)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/errors/code_string.go b/platform/dbops/binaries/go/go/src/internal/types/errors/code_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..719fc73a5a7672d109fe83bf0b4bfac520a30a16
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/errors/code_string.go
@@ -0,0 +1,199 @@
+// Code generated by "stringer -type Code codes.go"; DO NOT EDIT.
+
+package errors
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidSyntaxTree - -1]
+ _ = x[Test-1]
+ _ = x[BlankPkgName-2]
+ _ = x[MismatchedPkgName-3]
+ _ = x[InvalidPkgUse-4]
+ _ = x[BadImportPath-5]
+ _ = x[BrokenImport-6]
+ _ = x[ImportCRenamed-7]
+ _ = x[UnusedImport-8]
+ _ = x[InvalidInitCycle-9]
+ _ = x[DuplicateDecl-10]
+ _ = x[InvalidDeclCycle-11]
+ _ = x[InvalidTypeCycle-12]
+ _ = x[InvalidConstInit-13]
+ _ = x[InvalidConstVal-14]
+ _ = x[InvalidConstType-15]
+ _ = x[UntypedNilUse-16]
+ _ = x[WrongAssignCount-17]
+ _ = x[UnassignableOperand-18]
+ _ = x[NoNewVar-19]
+ _ = x[MultiValAssignOp-20]
+ _ = x[InvalidIfaceAssign-21]
+ _ = x[InvalidChanAssign-22]
+ _ = x[IncompatibleAssign-23]
+ _ = x[UnaddressableFieldAssign-24]
+ _ = x[NotAType-25]
+ _ = x[InvalidArrayLen-26]
+ _ = x[BlankIfaceMethod-27]
+ _ = x[IncomparableMapKey-28]
+ _ = x[InvalidPtrEmbed-30]
+ _ = x[BadRecv-31]
+ _ = x[InvalidRecv-32]
+ _ = x[DuplicateFieldAndMethod-33]
+ _ = x[DuplicateMethod-34]
+ _ = x[InvalidBlank-35]
+ _ = x[InvalidIota-36]
+ _ = x[MissingInitBody-37]
+ _ = x[InvalidInitSig-38]
+ _ = x[InvalidInitDecl-39]
+ _ = x[InvalidMainDecl-40]
+ _ = x[TooManyValues-41]
+ _ = x[NotAnExpr-42]
+ _ = x[TruncatedFloat-43]
+ _ = x[NumericOverflow-44]
+ _ = x[UndefinedOp-45]
+ _ = x[MismatchedTypes-46]
+ _ = x[DivByZero-47]
+ _ = x[NonNumericIncDec-48]
+ _ = x[UnaddressableOperand-49]
+ _ = x[InvalidIndirection-50]
+ _ = x[NonIndexableOperand-51]
+ _ = x[InvalidIndex-52]
+ _ = x[SwappedSliceIndices-53]
+ _ = x[NonSliceableOperand-54]
+ _ = x[InvalidSliceExpr-55]
+ _ = x[InvalidShiftCount-56]
+ _ = x[InvalidShiftOperand-57]
+ _ = x[InvalidReceive-58]
+ _ = x[InvalidSend-59]
+ _ = x[DuplicateLitKey-60]
+ _ = x[MissingLitKey-61]
+ _ = x[InvalidLitIndex-62]
+ _ = x[OversizeArrayLit-63]
+ _ = x[MixedStructLit-64]
+ _ = x[InvalidStructLit-65]
+ _ = x[MissingLitField-66]
+ _ = x[DuplicateLitField-67]
+ _ = x[UnexportedLitField-68]
+ _ = x[InvalidLitField-69]
+ _ = x[UntypedLit-70]
+ _ = x[InvalidLit-71]
+ _ = x[AmbiguousSelector-72]
+ _ = x[UndeclaredImportedName-73]
+ _ = x[UnexportedName-74]
+ _ = x[UndeclaredName-75]
+ _ = x[MissingFieldOrMethod-76]
+ _ = x[BadDotDotDotSyntax-77]
+ _ = x[NonVariadicDotDotDot-78]
+ _ = x[MisplacedDotDotDot-79]
+ _ = x[InvalidDotDotDot-81]
+ _ = x[UncalledBuiltin-82]
+ _ = x[InvalidAppend-83]
+ _ = x[InvalidCap-84]
+ _ = x[InvalidClose-85]
+ _ = x[InvalidCopy-86]
+ _ = x[InvalidComplex-87]
+ _ = x[InvalidDelete-88]
+ _ = x[InvalidImag-89]
+ _ = x[InvalidLen-90]
+ _ = x[SwappedMakeArgs-91]
+ _ = x[InvalidMake-92]
+ _ = x[InvalidReal-93]
+ _ = x[InvalidAssert-94]
+ _ = x[ImpossibleAssert-95]
+ _ = x[InvalidConversion-96]
+ _ = x[InvalidUntypedConversion-97]
+ _ = x[BadOffsetofSyntax-98]
+ _ = x[InvalidOffsetof-99]
+ _ = x[UnusedExpr-100]
+ _ = x[UnusedVar-101]
+ _ = x[MissingReturn-102]
+ _ = x[WrongResultCount-103]
+ _ = x[OutOfScopeResult-104]
+ _ = x[InvalidCond-105]
+ _ = x[InvalidPostDecl-106]
+ _ = x[InvalidIterVar-108]
+ _ = x[InvalidRangeExpr-109]
+ _ = x[MisplacedBreak-110]
+ _ = x[MisplacedContinue-111]
+ _ = x[MisplacedFallthrough-112]
+ _ = x[DuplicateCase-113]
+ _ = x[DuplicateDefault-114]
+ _ = x[BadTypeKeyword-115]
+ _ = x[InvalidTypeSwitch-116]
+ _ = x[InvalidExprSwitch-117]
+ _ = x[InvalidSelectCase-118]
+ _ = x[UndeclaredLabel-119]
+ _ = x[DuplicateLabel-120]
+ _ = x[MisplacedLabel-121]
+ _ = x[UnusedLabel-122]
+ _ = x[JumpOverDecl-123]
+ _ = x[JumpIntoBlock-124]
+ _ = x[InvalidMethodExpr-125]
+ _ = x[WrongArgCount-126]
+ _ = x[InvalidCall-127]
+ _ = x[UnusedResults-128]
+ _ = x[InvalidDefer-129]
+ _ = x[InvalidGo-130]
+ _ = x[BadDecl-131]
+ _ = x[RepeatedDecl-132]
+ _ = x[InvalidUnsafeAdd-133]
+ _ = x[InvalidUnsafeSlice-134]
+ _ = x[UnsupportedFeature-135]
+ _ = x[NotAGenericType-136]
+ _ = x[WrongTypeArgCount-137]
+ _ = x[CannotInferTypeArgs-138]
+ _ = x[InvalidTypeArg-139]
+ _ = x[InvalidInstanceCycle-140]
+ _ = x[InvalidUnion-141]
+ _ = x[MisplacedConstraintIface-142]
+ _ = x[InvalidMethodTypeParams-143]
+ _ = x[MisplacedTypeParam-144]
+ _ = x[InvalidUnsafeSliceData-145]
+ _ = x[InvalidUnsafeString-146]
+ _ = x[InvalidClear-148]
+ _ = x[TypeTooLarge-149]
+ _ = x[InvalidMinMaxOperand-150]
+}
+
+const (
+ _Code_name_0 = "InvalidSyntaxTree"
+ _Code_name_1 = "TestBlankPkgNameMismatchedPkgNameInvalidPkgUseBadImportPathBrokenImportImportCRenamedUnusedImportInvalidInitCycleDuplicateDeclInvalidDeclCycleInvalidTypeCycleInvalidConstInitInvalidConstValInvalidConstTypeUntypedNilUseWrongAssignCountUnassignableOperandNoNewVarMultiValAssignOpInvalidIfaceAssignInvalidChanAssignIncompatibleAssignUnaddressableFieldAssignNotATypeInvalidArrayLenBlankIfaceMethodIncomparableMapKey"
+ _Code_name_2 = "InvalidPtrEmbedBadRecvInvalidRecvDuplicateFieldAndMethodDuplicateMethodInvalidBlankInvalidIotaMissingInitBodyInvalidInitSigInvalidInitDeclInvalidMainDeclTooManyValuesNotAnExprTruncatedFloatNumericOverflowUndefinedOpMismatchedTypesDivByZeroNonNumericIncDecUnaddressableOperandInvalidIndirectionNonIndexableOperandInvalidIndexSwappedSliceIndicesNonSliceableOperandInvalidSliceExprInvalidShiftCountInvalidShiftOperandInvalidReceiveInvalidSendDuplicateLitKeyMissingLitKeyInvalidLitIndexOversizeArrayLitMixedStructLitInvalidStructLitMissingLitFieldDuplicateLitFieldUnexportedLitFieldInvalidLitFieldUntypedLitInvalidLitAmbiguousSelectorUndeclaredImportedNameUnexportedNameUndeclaredNameMissingFieldOrMethodBadDotDotDotSyntaxNonVariadicDotDotDotMisplacedDotDotDot"
+ _Code_name_3 = "InvalidDotDotDotUncalledBuiltinInvalidAppendInvalidCapInvalidCloseInvalidCopyInvalidComplexInvalidDeleteInvalidImagInvalidLenSwappedMakeArgsInvalidMakeInvalidRealInvalidAssertImpossibleAssertInvalidConversionInvalidUntypedConversionBadOffsetofSyntaxInvalidOffsetofUnusedExprUnusedVarMissingReturnWrongResultCountOutOfScopeResultInvalidCondInvalidPostDecl"
+ _Code_name_4 = "InvalidIterVarInvalidRangeExprMisplacedBreakMisplacedContinueMisplacedFallthroughDuplicateCaseDuplicateDefaultBadTypeKeywordInvalidTypeSwitchInvalidExprSwitchInvalidSelectCaseUndeclaredLabelDuplicateLabelMisplacedLabelUnusedLabelJumpOverDeclJumpIntoBlockInvalidMethodExprWrongArgCountInvalidCallUnusedResultsInvalidDeferInvalidGoBadDeclRepeatedDeclInvalidUnsafeAddInvalidUnsafeSliceUnsupportedFeatureNotAGenericTypeWrongTypeArgCountCannotInferTypeArgsInvalidTypeArgInvalidInstanceCycleInvalidUnionMisplacedConstraintIfaceInvalidMethodTypeParamsMisplacedTypeParamInvalidUnsafeSliceDataInvalidUnsafeString"
+ _Code_name_5 = "InvalidClearTypeTooLargeInvalidMinMaxOperand"
+)
+
+var (
+ _Code_index_1 = [...]uint16{0, 4, 16, 33, 46, 59, 71, 85, 97, 113, 126, 142, 158, 174, 189, 205, 218, 234, 253, 261, 277, 295, 312, 330, 354, 362, 377, 393, 411}
+ _Code_index_2 = [...]uint16{0, 15, 22, 33, 56, 71, 83, 94, 109, 123, 138, 153, 166, 175, 189, 204, 215, 230, 239, 255, 275, 293, 312, 324, 343, 362, 378, 395, 414, 428, 439, 454, 467, 482, 498, 512, 528, 543, 560, 578, 593, 603, 613, 630, 652, 666, 680, 700, 718, 738, 756}
+ _Code_index_3 = [...]uint16{0, 16, 31, 44, 54, 66, 77, 91, 104, 115, 125, 140, 151, 162, 175, 191, 208, 232, 249, 264, 274, 283, 296, 312, 328, 339, 354}
+ _Code_index_4 = [...]uint16{0, 14, 30, 44, 61, 81, 94, 110, 124, 141, 158, 175, 190, 204, 218, 229, 241, 254, 271, 284, 295, 308, 320, 329, 336, 348, 364, 382, 400, 415, 432, 451, 465, 485, 497, 521, 544, 562, 584, 603}
+ _Code_index_5 = [...]uint8{0, 12, 24, 44}
+)
+
+func (i Code) String() string {
+ switch {
+ case i == -1:
+ return _Code_name_0
+ case 1 <= i && i <= 28:
+ i -= 1
+ return _Code_name_1[_Code_index_1[i]:_Code_index_1[i+1]]
+ case 30 <= i && i <= 79:
+ i -= 30
+ return _Code_name_2[_Code_index_2[i]:_Code_index_2[i+1]]
+ case 81 <= i && i <= 106:
+ i -= 81
+ return _Code_name_3[_Code_index_3[i]:_Code_index_3[i+1]]
+ case 108 <= i && i <= 146:
+ i -= 108
+ return _Code_name_4[_Code_index_4[i]:_Code_index_4[i+1]]
+ case 148 <= i && i <= 150:
+ i -= 148
+ return _Code_name_5[_Code_index_5[i]:_Code_index_5[i+1]]
+ default:
+ return "Code(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/errors/codes.go b/platform/dbops/binaries/go/go/src/internal/types/errors/codes.go
new file mode 100644
index 0000000000000000000000000000000000000000..cae688ff874bfca78b42c56d4edda915377f7243
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/errors/codes.go
@@ -0,0 +1,1477 @@
+// 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 errors
+
+//go:generate stringer -type Code codes.go
+
+type Code int
+
+// This file defines the error codes that can be produced during type-checking.
+// Collectively, these codes provide an identifier that may be used to
+// implement special handling for certain types of errors.
+//
+// Error code values should not be changed: add new codes at the end.
+//
+// Error codes should be fine-grained enough that the exact nature of the error
+// can be easily determined, but coarse enough that they are not an
+// implementation detail of the type checking algorithm. As a rule-of-thumb,
+// errors should be considered equivalent if there is a theoretical refactoring
+// of the type checker in which they are emitted in exactly one place. For
+// example, the type checker emits different error messages for "too many
+// arguments" and "too few arguments", but one can imagine an alternative type
+// checker where this check instead just emits a single "wrong number of
+// arguments", so these errors should have the same code.
+//
+// Error code names should be as brief as possible while retaining accuracy and
+// distinctiveness. In most cases names should start with an adjective
+// describing the nature of the error (e.g. "invalid", "unused", "misplaced"),
+// and end with a noun identifying the relevant language object. For example,
+// "_DuplicateDecl" or "_InvalidSliceExpr". For brevity, naming follows the
+// convention that "bad" implies a problem with syntax, and "invalid" implies a
+// problem with types.
+
+const (
+ // InvalidSyntaxTree occurs if an invalid syntax tree is provided
+ // to the type checker. It should never happen.
+ InvalidSyntaxTree Code = -1
+)
+
+const (
+ // The zero Code value indicates an unset (invalid) error code.
+ _ Code = iota
+
+ // Test is reserved for errors that only apply while in self-test mode.
+ Test
+
+ // BlankPkgName occurs when a package name is the blank identifier "_".
+ //
+ // Per the spec:
+ // "The PackageName must not be the blank identifier."
+ //
+ // Example:
+ // package _
+ BlankPkgName
+
+ // MismatchedPkgName occurs when a file's package name doesn't match the
+ // package name already established by other files.
+ MismatchedPkgName
+
+ // InvalidPkgUse occurs when a package identifier is used outside of a
+ // selector expression.
+ //
+ // Example:
+ // import "fmt"
+ //
+ // var _ = fmt
+ InvalidPkgUse
+
+ // BadImportPath occurs when an import path is not valid.
+ BadImportPath
+
+ // BrokenImport occurs when importing a package fails.
+ //
+ // Example:
+ // import "amissingpackage"
+ BrokenImport
+
+ // ImportCRenamed occurs when the special import "C" is renamed. "C" is a
+ // pseudo-package, and must not be renamed.
+ //
+ // Example:
+ // import _ "C"
+ ImportCRenamed
+
+ // UnusedImport occurs when an import is unused.
+ //
+ // Example:
+ // import "fmt"
+ //
+ // func main() {}
+ UnusedImport
+
+ // InvalidInitCycle occurs when an invalid cycle is detected within the
+ // initialization graph.
+ //
+ // Example:
+ // var x int = f()
+ //
+ // func f() int { return x }
+ InvalidInitCycle
+
+ // DuplicateDecl occurs when an identifier is declared multiple times.
+ //
+ // Example:
+ // var x = 1
+ // var x = 2
+ DuplicateDecl
+
+ // InvalidDeclCycle occurs when a declaration cycle is not valid.
+ //
+ // Example:
+ // type S struct {
+ // S
+ // }
+ //
+ InvalidDeclCycle
+
+ // InvalidTypeCycle occurs when a cycle in type definitions results in a
+ // type that is not well-defined.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // type T [unsafe.Sizeof(T{})]int
+ InvalidTypeCycle
+
+ // InvalidConstInit occurs when a const declaration has a non-constant
+ // initializer.
+ //
+ // Example:
+ // var x int
+ // const _ = x
+ InvalidConstInit
+
+ // InvalidConstVal occurs when a const value cannot be converted to its
+ // target type.
+ //
+ // TODO(findleyr): this error code and example are not very clear. Consider
+ // removing it.
+ //
+ // Example:
+ // const _ = 1 << "hello"
+ InvalidConstVal
+
+ // InvalidConstType occurs when the underlying type in a const declaration
+ // is not a valid constant type.
+ //
+ // Example:
+ // const c *int = 4
+ InvalidConstType
+
+ // UntypedNilUse occurs when the predeclared (untyped) value nil is used to
+ // initialize a variable declared without an explicit type.
+ //
+ // Example:
+ // var x = nil
+ UntypedNilUse
+
+ // WrongAssignCount occurs when the number of values on the right-hand side
+ // of an assignment or initialization expression does not match the number
+ // of variables on the left-hand side.
+ //
+ // Example:
+ // var x = 1, 2
+ WrongAssignCount
+
+ // UnassignableOperand occurs when the left-hand side of an assignment is
+ // not assignable.
+ //
+ // Example:
+ // func f() {
+ // const c = 1
+ // c = 2
+ // }
+ UnassignableOperand
+
+ // NoNewVar occurs when a short variable declaration (':=') does not declare
+ // new variables.
+ //
+ // Example:
+ // func f() {
+ // x := 1
+ // x := 2
+ // }
+ NoNewVar
+
+ // MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does
+ // not have single-valued left-hand or right-hand side.
+ //
+ // Per the spec:
+ // "In assignment operations, both the left- and right-hand expression lists
+ // must contain exactly one single-valued expression"
+ //
+ // Example:
+ // func f() int {
+ // x, y := 1, 2
+ // x, y += 1
+ // return x + y
+ // }
+ MultiValAssignOp
+
+ // InvalidIfaceAssign occurs when a value of type T is used as an
+ // interface, but T does not implement a method of the expected interface.
+ //
+ // Example:
+ // type I interface {
+ // f()
+ // }
+ //
+ // type T int
+ //
+ // var x I = T(1)
+ InvalidIfaceAssign
+
+ // InvalidChanAssign occurs when a chan assignment is invalid.
+ //
+ // Per the spec, a value x is assignable to a channel type T if:
+ // "x is a bidirectional channel value, T is a channel type, x's type V and
+ // T have identical element types, and at least one of V or T is not a
+ // defined type."
+ //
+ // Example:
+ // type T1 chan int
+ // type T2 chan int
+ //
+ // var x T1
+ // // Invalid assignment because both types are named
+ // var _ T2 = x
+ InvalidChanAssign
+
+ // IncompatibleAssign occurs when the type of the right-hand side expression
+ // in an assignment cannot be assigned to the type of the variable being
+ // assigned.
+ //
+ // Example:
+ // var x []int
+ // var _ int = x
+ IncompatibleAssign
+
+ // UnaddressableFieldAssign occurs when trying to assign to a struct field
+ // in a map value.
+ //
+ // Example:
+ // func f() {
+ // m := make(map[string]struct{i int})
+ // m["foo"].i = 42
+ // }
+ UnaddressableFieldAssign
+
+ // NotAType occurs when the identifier used as the underlying type in a type
+ // declaration or the right-hand side of a type alias does not denote a type.
+ //
+ // Example:
+ // var S = 2
+ //
+ // type T S
+ NotAType
+
+ // InvalidArrayLen occurs when an array length is not a constant value.
+ //
+ // Example:
+ // var n = 3
+ // var _ = [n]int{}
+ InvalidArrayLen
+
+ // BlankIfaceMethod occurs when a method name is '_'.
+ //
+ // Per the spec:
+ // "The name of each explicitly specified method must be unique and not
+ // blank."
+ //
+ // Example:
+ // type T interface {
+ // _(int)
+ // }
+ BlankIfaceMethod
+
+ // IncomparableMapKey occurs when a map key type does not support the == and
+ // != operators.
+ //
+ // Per the spec:
+ // "The comparison operators == and != must be fully defined for operands of
+ // the key type; thus the key type must not be a function, map, or slice."
+ //
+ // Example:
+ // var x map[T]int
+ //
+ // type T []int
+ IncomparableMapKey
+
+ // InvalidIfaceEmbed occurs when a non-interface type is embedded in an
+ // interface (for go 1.17 or earlier).
+ _ // not used anymore
+
+ // InvalidPtrEmbed occurs when an embedded field is of the pointer form *T,
+ // and T itself is itself a pointer, an unsafe.Pointer, or an interface.
+ //
+ // Per the spec:
+ // "An embedded field must be specified as a type name T or as a pointer to
+ // a non-interface type name *T, and T itself may not be a pointer type."
+ //
+ // Example:
+ // type T *int
+ //
+ // type S struct {
+ // *T
+ // }
+ InvalidPtrEmbed
+
+ // BadRecv occurs when a method declaration does not have exactly one
+ // receiver parameter.
+ //
+ // Example:
+ // func () _() {}
+ BadRecv
+
+ // InvalidRecv occurs when a receiver type expression is not of the form T
+ // or *T, or T is a pointer type.
+ //
+ // Example:
+ // type T struct {}
+ //
+ // func (**T) m() {}
+ InvalidRecv
+
+ // DuplicateFieldAndMethod occurs when an identifier appears as both a field
+ // and method name.
+ //
+ // Example:
+ // type T struct {
+ // m int
+ // }
+ //
+ // func (T) m() {}
+ DuplicateFieldAndMethod
+
+ // DuplicateMethod occurs when two methods on the same receiver type have
+ // the same name.
+ //
+ // Example:
+ // type T struct {}
+ // func (T) m() {}
+ // func (T) m(i int) int { return i }
+ DuplicateMethod
+
+ // InvalidBlank occurs when a blank identifier is used as a value or type.
+ //
+ // Per the spec:
+ // "The blank identifier may appear as an operand only on the left-hand side
+ // of an assignment."
+ //
+ // Example:
+ // var x = _
+ InvalidBlank
+
+ // InvalidIota occurs when the predeclared identifier iota is used outside
+ // of a constant declaration.
+ //
+ // Example:
+ // var x = iota
+ InvalidIota
+
+ // MissingInitBody occurs when an init function is missing its body.
+ //
+ // Example:
+ // func init()
+ MissingInitBody
+
+ // InvalidInitSig occurs when an init function declares parameters or
+ // results.
+ //
+ // Deprecated: no longer emitted by the type checker. _InvalidInitDecl is
+ // used instead.
+ InvalidInitSig
+
+ // InvalidInitDecl occurs when init is declared as anything other than a
+ // function.
+ //
+ // Example:
+ // var init = 1
+ //
+ // Example:
+ // func init() int { return 1 }
+ InvalidInitDecl
+
+ // InvalidMainDecl occurs when main is declared as anything other than a
+ // function, in a main package.
+ InvalidMainDecl
+
+ // TooManyValues occurs when a function returns too many values for the
+ // expression context in which it is used.
+ //
+ // Example:
+ // func ReturnTwo() (int, int) {
+ // return 1, 2
+ // }
+ //
+ // var x = ReturnTwo()
+ TooManyValues
+
+ // NotAnExpr occurs when a type expression is used where a value expression
+ // is expected.
+ //
+ // Example:
+ // type T struct {}
+ //
+ // func f() {
+ // T
+ // }
+ NotAnExpr
+
+ // TruncatedFloat occurs when a float constant is truncated to an integer
+ // value.
+ //
+ // Example:
+ // var _ int = 98.6
+ TruncatedFloat
+
+ // NumericOverflow occurs when a numeric constant overflows its target type.
+ //
+ // Example:
+ // var x int8 = 1000
+ NumericOverflow
+
+ // UndefinedOp occurs when an operator is not defined for the type(s) used
+ // in an operation.
+ //
+ // Example:
+ // var c = "a" - "b"
+ UndefinedOp
+
+ // MismatchedTypes occurs when operand types are incompatible in a binary
+ // operation.
+ //
+ // Example:
+ // var a = "hello"
+ // var b = 1
+ // var c = a - b
+ MismatchedTypes
+
+ // DivByZero occurs when a division operation is provable at compile
+ // time to be a division by zero.
+ //
+ // Example:
+ // const divisor = 0
+ // var x int = 1/divisor
+ DivByZero
+
+ // NonNumericIncDec occurs when an increment or decrement operator is
+ // applied to a non-numeric value.
+ //
+ // Example:
+ // func f() {
+ // var c = "c"
+ // c++
+ // }
+ NonNumericIncDec
+
+ // UnaddressableOperand occurs when the & operator is applied to an
+ // unaddressable expression.
+ //
+ // Example:
+ // var x = &1
+ UnaddressableOperand
+
+ // InvalidIndirection occurs when a non-pointer value is indirected via the
+ // '*' operator.
+ //
+ // Example:
+ // var x int
+ // var y = *x
+ InvalidIndirection
+
+ // NonIndexableOperand occurs when an index operation is applied to a value
+ // that cannot be indexed.
+ //
+ // Example:
+ // var x = 1
+ // var y = x[1]
+ NonIndexableOperand
+
+ // InvalidIndex occurs when an index argument is not of integer type,
+ // negative, or out-of-bounds.
+ //
+ // Example:
+ // var s = [...]int{1,2,3}
+ // var x = s[5]
+ //
+ // Example:
+ // var s = []int{1,2,3}
+ // var _ = s[-1]
+ //
+ // Example:
+ // var s = []int{1,2,3}
+ // var i string
+ // var _ = s[i]
+ InvalidIndex
+
+ // SwappedSliceIndices occurs when constant indices in a slice expression
+ // are decreasing in value.
+ //
+ // Example:
+ // var _ = []int{1,2,3}[2:1]
+ SwappedSliceIndices
+
+ // NonSliceableOperand occurs when a slice operation is applied to a value
+ // whose type is not sliceable, or is unaddressable.
+ //
+ // Example:
+ // var x = [...]int{1, 2, 3}[:1]
+ //
+ // Example:
+ // var x = 1
+ // var y = 1[:1]
+ NonSliceableOperand
+
+ // InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is
+ // applied to a string.
+ //
+ // Example:
+ // var s = "hello"
+ // var x = s[1:2:3]
+ InvalidSliceExpr
+
+ // InvalidShiftCount occurs when the right-hand side of a shift operation is
+ // either non-integer, negative, or too large.
+ //
+ // Example:
+ // var (
+ // x string
+ // y int = 1 << x
+ // )
+ InvalidShiftCount
+
+ // InvalidShiftOperand occurs when the shifted operand is not an integer.
+ //
+ // Example:
+ // var s = "hello"
+ // var x = s << 2
+ InvalidShiftOperand
+
+ // InvalidReceive occurs when there is a channel receive from a value that
+ // is either not a channel, or is a send-only channel.
+ //
+ // Example:
+ // func f() {
+ // var x = 1
+ // <-x
+ // }
+ InvalidReceive
+
+ // InvalidSend occurs when there is a channel send to a value that is not a
+ // channel, or is a receive-only channel.
+ //
+ // Example:
+ // func f() {
+ // var x = 1
+ // x <- "hello!"
+ // }
+ InvalidSend
+
+ // DuplicateLitKey occurs when an index is duplicated in a slice, array, or
+ // map literal.
+ //
+ // Example:
+ // var _ = []int{0:1, 0:2}
+ //
+ // Example:
+ // var _ = map[string]int{"a": 1, "a": 2}
+ DuplicateLitKey
+
+ // MissingLitKey occurs when a map literal is missing a key expression.
+ //
+ // Example:
+ // var _ = map[string]int{1}
+ MissingLitKey
+
+ // InvalidLitIndex occurs when the key in a key-value element of a slice or
+ // array literal is not an integer constant.
+ //
+ // Example:
+ // var i = 0
+ // var x = []string{i: "world"}
+ InvalidLitIndex
+
+ // OversizeArrayLit occurs when an array literal exceeds its length.
+ //
+ // Example:
+ // var _ = [2]int{1,2,3}
+ OversizeArrayLit
+
+ // MixedStructLit occurs when a struct literal contains a mix of positional
+ // and named elements.
+ //
+ // Example:
+ // var _ = struct{i, j int}{i: 1, 2}
+ MixedStructLit
+
+ // InvalidStructLit occurs when a positional struct literal has an incorrect
+ // number of values.
+ //
+ // Example:
+ // var _ = struct{i, j int}{1,2,3}
+ InvalidStructLit
+
+ // MissingLitField occurs when a struct literal refers to a field that does
+ // not exist on the struct type.
+ //
+ // Example:
+ // var _ = struct{i int}{j: 2}
+ MissingLitField
+
+ // DuplicateLitField occurs when a struct literal contains duplicated
+ // fields.
+ //
+ // Example:
+ // var _ = struct{i int}{i: 1, i: 2}
+ DuplicateLitField
+
+ // UnexportedLitField occurs when a positional struct literal implicitly
+ // assigns an unexported field of an imported type.
+ UnexportedLitField
+
+ // InvalidLitField occurs when a field name is not a valid identifier.
+ //
+ // Example:
+ // var _ = struct{i int}{1: 1}
+ InvalidLitField
+
+ // UntypedLit occurs when a composite literal omits a required type
+ // identifier.
+ //
+ // Example:
+ // type outer struct{
+ // inner struct { i int }
+ // }
+ //
+ // var _ = outer{inner: {1}}
+ UntypedLit
+
+ // InvalidLit occurs when a composite literal expression does not match its
+ // type.
+ //
+ // Example:
+ // type P *struct{
+ // x int
+ // }
+ // var _ = P {}
+ InvalidLit
+
+ // AmbiguousSelector occurs when a selector is ambiguous.
+ //
+ // Example:
+ // type E1 struct { i int }
+ // type E2 struct { i int }
+ // type T struct { E1; E2 }
+ //
+ // var x T
+ // var _ = x.i
+ AmbiguousSelector
+
+ // UndeclaredImportedName occurs when a package-qualified identifier is
+ // undeclared by the imported package.
+ //
+ // Example:
+ // import "go/types"
+ //
+ // var _ = types.NotAnActualIdentifier
+ UndeclaredImportedName
+
+ // UnexportedName occurs when a selector refers to an unexported identifier
+ // of an imported package.
+ //
+ // Example:
+ // import "reflect"
+ //
+ // type _ reflect.flag
+ UnexportedName
+
+ // UndeclaredName occurs when an identifier is not declared in the current
+ // scope.
+ //
+ // Example:
+ // var x T
+ UndeclaredName
+
+ // MissingFieldOrMethod occurs when a selector references a field or method
+ // that does not exist.
+ //
+ // Example:
+ // type T struct {}
+ //
+ // var x = T{}.f
+ MissingFieldOrMethod
+
+ // BadDotDotDotSyntax occurs when a "..." occurs in a context where it is
+ // not valid.
+ //
+ // Example:
+ // var _ = map[int][...]int{0: {}}
+ BadDotDotDotSyntax
+
+ // NonVariadicDotDotDot occurs when a "..." is used on the final argument to
+ // a non-variadic function.
+ //
+ // Example:
+ // func printArgs(s []string) {
+ // for _, a := range s {
+ // println(a)
+ // }
+ // }
+ //
+ // func f() {
+ // s := []string{"a", "b", "c"}
+ // printArgs(s...)
+ // }
+ NonVariadicDotDotDot
+
+ // MisplacedDotDotDot occurs when a "..." is used somewhere other than the
+ // final argument in a function declaration.
+ //
+ // Example:
+ // func f(...int, int)
+ MisplacedDotDotDot
+
+ _ // InvalidDotDotDotOperand was removed.
+
+ // InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in
+ // function.
+ //
+ // Example:
+ // var s = []int{1, 2, 3}
+ // var l = len(s...)
+ InvalidDotDotDot
+
+ // UncalledBuiltin occurs when a built-in function is used as a
+ // function-valued expression, instead of being called.
+ //
+ // Per the spec:
+ // "The built-in functions do not have standard Go types, so they can only
+ // appear in call expressions; they cannot be used as function values."
+ //
+ // Example:
+ // var _ = copy
+ UncalledBuiltin
+
+ // InvalidAppend occurs when append is called with a first argument that is
+ // not a slice.
+ //
+ // Example:
+ // var _ = append(1, 2)
+ InvalidAppend
+
+ // InvalidCap occurs when an argument to the cap built-in function is not of
+ // supported type.
+ //
+ // See https://golang.org/ref/spec#Length_and_capacity for information on
+ // which underlying types are supported as arguments to cap and len.
+ //
+ // Example:
+ // var s = 2
+ // var x = cap(s)
+ InvalidCap
+
+ // InvalidClose occurs when close(...) is called with an argument that is
+ // not of channel type, or that is a receive-only channel.
+ //
+ // Example:
+ // func f() {
+ // var x int
+ // close(x)
+ // }
+ InvalidClose
+
+ // InvalidCopy occurs when the arguments are not of slice type or do not
+ // have compatible type.
+ //
+ // See https://golang.org/ref/spec#Appending_and_copying_slices for more
+ // information on the type requirements for the copy built-in.
+ //
+ // Example:
+ // func f() {
+ // var x []int
+ // y := []int64{1,2,3}
+ // copy(x, y)
+ // }
+ InvalidCopy
+
+ // InvalidComplex occurs when the complex built-in function is called with
+ // arguments with incompatible types.
+ //
+ // Example:
+ // var _ = complex(float32(1), float64(2))
+ InvalidComplex
+
+ // InvalidDelete occurs when the delete built-in function is called with a
+ // first argument that is not a map.
+ //
+ // Example:
+ // func f() {
+ // m := "hello"
+ // delete(m, "e")
+ // }
+ InvalidDelete
+
+ // InvalidImag occurs when the imag built-in function is called with an
+ // argument that does not have complex type.
+ //
+ // Example:
+ // var _ = imag(int(1))
+ InvalidImag
+
+ // InvalidLen occurs when an argument to the len built-in function is not of
+ // supported type.
+ //
+ // See https://golang.org/ref/spec#Length_and_capacity for information on
+ // which underlying types are supported as arguments to cap and len.
+ //
+ // Example:
+ // var s = 2
+ // var x = len(s)
+ InvalidLen
+
+ // SwappedMakeArgs occurs when make is called with three arguments, and its
+ // length argument is larger than its capacity argument.
+ //
+ // Example:
+ // var x = make([]int, 3, 2)
+ SwappedMakeArgs
+
+ // InvalidMake occurs when make is called with an unsupported type argument.
+ //
+ // See https://golang.org/ref/spec#Making_slices_maps_and_channels for
+ // information on the types that may be created using make.
+ //
+ // Example:
+ // var x = make(int)
+ InvalidMake
+
+ // InvalidReal occurs when the real built-in function is called with an
+ // argument that does not have complex type.
+ //
+ // Example:
+ // var _ = real(int(1))
+ InvalidReal
+
+ // InvalidAssert occurs when a type assertion is applied to a
+ // value that is not of interface type.
+ //
+ // Example:
+ // var x = 1
+ // var _ = x.(float64)
+ InvalidAssert
+
+ // ImpossibleAssert occurs for a type assertion x.(T) when the value x of
+ // interface cannot have dynamic type T, due to a missing or mismatching
+ // method on T.
+ //
+ // Example:
+ // type T int
+ //
+ // func (t *T) m() int { return int(*t) }
+ //
+ // type I interface { m() int }
+ //
+ // var x I
+ // var _ = x.(T)
+ ImpossibleAssert
+
+ // InvalidConversion occurs when the argument type cannot be converted to the
+ // target.
+ //
+ // See https://golang.org/ref/spec#Conversions for the rules of
+ // convertibility.
+ //
+ // Example:
+ // var x float64
+ // var _ = string(x)
+ InvalidConversion
+
+ // InvalidUntypedConversion occurs when there is no valid implicit
+ // conversion from an untyped value satisfying the type constraints of the
+ // context in which it is used.
+ //
+ // Example:
+ // var _ = 1 + []int{}
+ InvalidUntypedConversion
+
+ // BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument
+ // that is not a selector expression.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.Offsetof(x)
+ BadOffsetofSyntax
+
+ // InvalidOffsetof occurs when unsafe.Offsetof is called with a method
+ // selector, rather than a field selector, or when the field is embedded via
+ // a pointer.
+ //
+ // Per the spec:
+ //
+ // "If f is an embedded field, it must be reachable without pointer
+ // indirections through fields of the struct. "
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // type T struct { f int }
+ // type S struct { *T }
+ // var s S
+ // var _ = unsafe.Offsetof(s.f)
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // type S struct{}
+ //
+ // func (S) m() {}
+ //
+ // var s S
+ // var _ = unsafe.Offsetof(s.m)
+ InvalidOffsetof
+
+ // UnusedExpr occurs when a side-effect free expression is used as a
+ // statement. Such a statement has no effect.
+ //
+ // Example:
+ // func f(i int) {
+ // i*i
+ // }
+ UnusedExpr
+
+ // UnusedVar occurs when a variable is declared but unused.
+ //
+ // Example:
+ // func f() {
+ // x := 1
+ // }
+ UnusedVar
+
+ // MissingReturn occurs when a function with results is missing a return
+ // statement.
+ //
+ // Example:
+ // func f() int {}
+ MissingReturn
+
+ // WrongResultCount occurs when a return statement returns an incorrect
+ // number of values.
+ //
+ // Example:
+ // func ReturnOne() int {
+ // return 1, 2
+ // }
+ WrongResultCount
+
+ // OutOfScopeResult occurs when the name of a value implicitly returned by
+ // an empty return statement is shadowed in a nested scope.
+ //
+ // Example:
+ // func factor(n int) (i int) {
+ // for i := 2; i < n; i++ {
+ // if n%i == 0 {
+ // return
+ // }
+ // }
+ // return 0
+ // }
+ OutOfScopeResult
+
+ // InvalidCond occurs when an if condition is not a boolean expression.
+ //
+ // Example:
+ // func checkReturn(i int) {
+ // if i {
+ // panic("non-zero return")
+ // }
+ // }
+ InvalidCond
+
+ // InvalidPostDecl occurs when there is a declaration in a for-loop post
+ // statement.
+ //
+ // Example:
+ // func f() {
+ // for i := 0; i < 10; j := 0 {}
+ // }
+ InvalidPostDecl
+
+ _ // InvalidChanRange was removed.
+
+ // InvalidIterVar occurs when two iteration variables are used while ranging
+ // over a channel.
+ //
+ // Example:
+ // func f(c chan int) {
+ // for k, v := range c {
+ // println(k, v)
+ // }
+ // }
+ InvalidIterVar
+
+ // InvalidRangeExpr occurs when the type of a range expression is not
+ // a valid type for use with a range loop.
+ //
+ // Example:
+ // func f(f float64) {
+ // for j := range f {
+ // println(j)
+ // }
+ // }
+ InvalidRangeExpr
+
+ // MisplacedBreak occurs when a break statement is not within a for, switch,
+ // or select statement of the innermost function definition.
+ //
+ // Example:
+ // func f() {
+ // break
+ // }
+ MisplacedBreak
+
+ // MisplacedContinue occurs when a continue statement is not within a for
+ // loop of the innermost function definition.
+ //
+ // Example:
+ // func sumeven(n int) int {
+ // proceed := func() {
+ // continue
+ // }
+ // sum := 0
+ // for i := 1; i <= n; i++ {
+ // if i % 2 != 0 {
+ // proceed()
+ // }
+ // sum += i
+ // }
+ // return sum
+ // }
+ MisplacedContinue
+
+ // MisplacedFallthrough occurs when a fallthrough statement is not within an
+ // expression switch.
+ //
+ // Example:
+ // func typename(i interface{}) string {
+ // switch i.(type) {
+ // case int64:
+ // fallthrough
+ // case int:
+ // return "int"
+ // }
+ // return "unsupported"
+ // }
+ MisplacedFallthrough
+
+ // DuplicateCase occurs when a type or expression switch has duplicate
+ // cases.
+ //
+ // Example:
+ // func printInt(i int) {
+ // switch i {
+ // case 1:
+ // println("one")
+ // case 1:
+ // println("One")
+ // }
+ // }
+ DuplicateCase
+
+ // DuplicateDefault occurs when a type or expression switch has multiple
+ // default clauses.
+ //
+ // Example:
+ // func printInt(i int) {
+ // switch i {
+ // case 1:
+ // println("one")
+ // default:
+ // println("One")
+ // default:
+ // println("1")
+ // }
+ // }
+ DuplicateDefault
+
+ // BadTypeKeyword occurs when a .(type) expression is used anywhere other
+ // than a type switch.
+ //
+ // Example:
+ // type I interface {
+ // m()
+ // }
+ // var t I
+ // var _ = t.(type)
+ BadTypeKeyword
+
+ // InvalidTypeSwitch occurs when .(type) is used on an expression that is
+ // not of interface type.
+ //
+ // Example:
+ // func f(i int) {
+ // switch x := i.(type) {}
+ // }
+ InvalidTypeSwitch
+
+ // InvalidExprSwitch occurs when a switch expression is not comparable.
+ //
+ // Example:
+ // func _() {
+ // var a struct{ _ func() }
+ // switch a /* ERROR cannot switch on a */ {
+ // }
+ // }
+ InvalidExprSwitch
+
+ // InvalidSelectCase occurs when a select case is not a channel send or
+ // receive.
+ //
+ // Example:
+ // func checkChan(c <-chan int) bool {
+ // select {
+ // case c:
+ // return true
+ // default:
+ // return false
+ // }
+ // }
+ InvalidSelectCase
+
+ // UndeclaredLabel occurs when an undeclared label is jumped to.
+ //
+ // Example:
+ // func f() {
+ // goto L
+ // }
+ UndeclaredLabel
+
+ // DuplicateLabel occurs when a label is declared more than once.
+ //
+ // Example:
+ // func f() int {
+ // L:
+ // L:
+ // return 1
+ // }
+ DuplicateLabel
+
+ // MisplacedLabel occurs when a break or continue label is not on a for,
+ // switch, or select statement.
+ //
+ // Example:
+ // func f() {
+ // L:
+ // a := []int{1,2,3}
+ // for _, e := range a {
+ // if e > 10 {
+ // break L
+ // }
+ // println(a)
+ // }
+ // }
+ MisplacedLabel
+
+ // UnusedLabel occurs when a label is declared and not used.
+ //
+ // Example:
+ // func f() {
+ // L:
+ // }
+ UnusedLabel
+
+ // JumpOverDecl occurs when a label jumps over a variable declaration.
+ //
+ // Example:
+ // func f() int {
+ // goto L
+ // x := 2
+ // L:
+ // x++
+ // return x
+ // }
+ JumpOverDecl
+
+ // JumpIntoBlock occurs when a forward jump goes to a label inside a nested
+ // block.
+ //
+ // Example:
+ // func f(x int) {
+ // goto L
+ // if x > 0 {
+ // L:
+ // print("inside block")
+ // }
+ // }
+ JumpIntoBlock
+
+ // InvalidMethodExpr occurs when a pointer method is called but the argument
+ // is not addressable.
+ //
+ // Example:
+ // type T struct {}
+ //
+ // func (*T) m() int { return 1 }
+ //
+ // var _ = T.m(T{})
+ InvalidMethodExpr
+
+ // WrongArgCount occurs when too few or too many arguments are passed by a
+ // function call.
+ //
+ // Example:
+ // func f(i int) {}
+ // var x = f()
+ WrongArgCount
+
+ // InvalidCall occurs when an expression is called that is not of function
+ // type.
+ //
+ // Example:
+ // var x = "x"
+ // var y = x()
+ InvalidCall
+
+ // UnusedResults occurs when a restricted expression-only built-in function
+ // is suspended via go or defer. Such a suspension discards the results of
+ // these side-effect free built-in functions, and therefore is ineffectual.
+ //
+ // Example:
+ // func f(a []int) int {
+ // defer len(a)
+ // return i
+ // }
+ UnusedResults
+
+ // InvalidDefer occurs when a deferred expression is not a function call,
+ // for example if the expression is a type conversion.
+ //
+ // Example:
+ // func f(i int) int {
+ // defer int32(i)
+ // return i
+ // }
+ InvalidDefer
+
+ // InvalidGo occurs when a go expression is not a function call, for example
+ // if the expression is a type conversion.
+ //
+ // Example:
+ // func f(i int) int {
+ // go int32(i)
+ // return i
+ // }
+ InvalidGo
+
+ // All codes below were added in Go 1.17.
+
+ // BadDecl occurs when a declaration has invalid syntax.
+ BadDecl
+
+ // RepeatedDecl occurs when an identifier occurs more than once on the left
+ // hand side of a short variable declaration.
+ //
+ // Example:
+ // func _() {
+ // x, y, y := 1, 2, 3
+ // }
+ RepeatedDecl
+
+ // InvalidUnsafeAdd occurs when unsafe.Add is called with a
+ // length argument that is not of integer type.
+ // It also occurs if it is used in a package compiled for a
+ // language version before go1.17.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var p unsafe.Pointer
+ // var _ = unsafe.Add(p, float64(1))
+ InvalidUnsafeAdd
+
+ // InvalidUnsafeSlice occurs when unsafe.Slice is called with a
+ // pointer argument that is not of pointer type or a length argument
+ // that is not of integer type, negative, or out of bounds.
+ // It also occurs if it is used in a package compiled for a language
+ // version before go1.17.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.Slice(x, 1)
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.Slice(&x, float64(1))
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.Slice(&x, -1)
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.Slice(&x, uint64(1) << 63)
+ InvalidUnsafeSlice
+
+ // All codes below were added in Go 1.18.
+
+ // UnsupportedFeature occurs when a language feature is used that is not
+ // supported at this Go version.
+ UnsupportedFeature
+
+ // NotAGenericType occurs when a non-generic type is used where a generic
+ // type is expected: in type or function instantiation.
+ //
+ // Example:
+ // type T int
+ //
+ // var _ T[int]
+ NotAGenericType
+
+ // WrongTypeArgCount occurs when a type or function is instantiated with an
+ // incorrect number of type arguments, including when a generic type or
+ // function is used without instantiation.
+ //
+ // Errors involving failed type inference are assigned other error codes.
+ //
+ // Example:
+ // type T[p any] int
+ //
+ // var _ T[int, string]
+ //
+ // Example:
+ // func f[T any]() {}
+ //
+ // var x = f
+ WrongTypeArgCount
+
+ // CannotInferTypeArgs occurs when type or function type argument inference
+ // fails to infer all type arguments.
+ //
+ // Example:
+ // func f[T any]() {}
+ //
+ // func _() {
+ // f()
+ // }
+ CannotInferTypeArgs
+
+ // InvalidTypeArg occurs when a type argument does not satisfy its
+ // corresponding type parameter constraints.
+ //
+ // Example:
+ // type T[P ~int] struct{}
+ //
+ // var _ T[string]
+ InvalidTypeArg // arguments? InferenceFailed
+
+ // InvalidInstanceCycle occurs when an invalid cycle is detected
+ // within the instantiation graph.
+ //
+ // Example:
+ // func f[T any]() { f[*T]() }
+ InvalidInstanceCycle
+
+ // InvalidUnion occurs when an embedded union or approximation element is
+ // not valid.
+ //
+ // Example:
+ // type _ interface {
+ // ~int | interface{ m() }
+ // }
+ InvalidUnion
+
+ // MisplacedConstraintIface occurs when a constraint-type interface is used
+ // outside of constraint position.
+ //
+ // Example:
+ // type I interface { ~int }
+ //
+ // var _ I
+ MisplacedConstraintIface
+
+ // InvalidMethodTypeParams occurs when methods have type parameters.
+ //
+ // It cannot be encountered with an AST parsed using go/parser.
+ InvalidMethodTypeParams
+
+ // MisplacedTypeParam occurs when a type parameter is used in a place where
+ // it is not permitted.
+ //
+ // Example:
+ // type T[P any] P
+ //
+ // Example:
+ // type T[P any] struct{ *P }
+ MisplacedTypeParam
+
+ // InvalidUnsafeSliceData occurs when unsafe.SliceData is called with
+ // an argument that is not of slice type. It also occurs if it is used
+ // in a package compiled for a language version before go1.20.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var x int
+ // var _ = unsafe.SliceData(x)
+ InvalidUnsafeSliceData
+
+ // InvalidUnsafeString occurs when unsafe.String is called with
+ // a length argument that is not of integer type, negative, or
+ // out of bounds. It also occurs if it is used in a package
+ // compiled for a language version before go1.20.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // var b [10]byte
+ // var _ = unsafe.String(&b[0], -1)
+ InvalidUnsafeString
+
+ // InvalidUnsafeStringData occurs if it is used in a package
+ // compiled for a language version before go1.20.
+ _ // not used anymore
+
+ // InvalidClear occurs when clear is called with an argument
+ // that is not of map or slice type.
+ //
+ // Example:
+ // func _(x int) {
+ // clear(x)
+ // }
+ InvalidClear
+
+ // TypeTooLarge occurs if unsafe.Sizeof or unsafe.Offsetof is
+ // called with an expression whose type is too large.
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // type E [1 << 31 - 1]int
+ // var a [1 << 31]E
+ // var _ = unsafe.Sizeof(a)
+ //
+ // Example:
+ // import "unsafe"
+ //
+ // type E [1 << 31 - 1]int
+ // var s struct {
+ // _ [1 << 31]E
+ // x int
+ // }
+ // var _ = unsafe.Offsetof(s.x)
+ TypeTooLarge
+
+ // InvalidMinMaxOperand occurs if min or max is called
+ // with an operand that cannot be ordered because it
+ // does not support the < operator.
+ //
+ // Example:
+ // const _ = min(true)
+ //
+ // Example:
+ // var s, t []byte
+ // var _ = max(s, t)
+ InvalidMinMaxOperand
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/errors/codes_test.go b/platform/dbops/binaries/go/go/src/internal/types/errors/codes_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2490ade5c369754bb5a879f8cb21de186027d65c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/errors/codes_test.go
@@ -0,0 +1,197 @@
+// 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 errors_test
+
+import (
+ "fmt"
+ "go/ast"
+ "go/constant"
+ "go/importer"
+ "go/parser"
+ "go/token"
+ "internal/testenv"
+ "reflect"
+ "strings"
+ "testing"
+
+ . "go/types"
+)
+
+func TestErrorCodeExamples(t *testing.T) {
+ testenv.MustHaveGoBuild(t) // go command needed to resolve std .a files for importer.Default().
+
+ walkCodes(t, func(name string, value int, spec *ast.ValueSpec) {
+ t.Run(name, func(t *testing.T) {
+ doc := spec.Doc.Text()
+ examples := strings.Split(doc, "Example:")
+ for i := 1; i < len(examples); i++ {
+ example := strings.TrimSpace(examples[i])
+ err := checkExample(t, example)
+ if err == nil {
+ t.Fatalf("no error in example #%d", i)
+ }
+ typerr, ok := err.(Error)
+ if !ok {
+ t.Fatalf("not a types.Error: %v", err)
+ }
+ if got := readCode(typerr); got != value {
+ t.Errorf("%s: example #%d returned code %d (%s), want %d", name, i, got, err, value)
+ }
+ }
+ })
+ })
+}
+
+func walkCodes(t *testing.T, f func(string, int, *ast.ValueSpec)) {
+ t.Helper()
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "codes.go", nil, parser.ParseComments)
+ if err != nil {
+ t.Fatal(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 {
+ t.Fatal(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 {
+ t.Fatalf("bad Code declaration for %q: got %d names, want exactly 1", spec.Names[0].Name, len(spec.Names))
+ }
+ codename := spec.Names[0].Name
+ value := int(constant.Val(obj.(*Const).Val()).(int64))
+ f(codename, value, spec)
+ }
+ }
+ }
+}
+
+func readCode(err Error) int {
+ v := reflect.ValueOf(err)
+ return int(v.FieldByName("go116code").Int())
+}
+
+func checkExample(t *testing.T, example string) error {
+ t.Helper()
+ fset := token.NewFileSet()
+ if !strings.HasPrefix(example, "package") {
+ example = "package p\n\n" + example
+ }
+ file, err := parser.ParseFile(fset, "example.go", example, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conf := Config{
+ FakeImportC: true,
+ Importer: importer.Default(),
+ }
+ _, err = conf.Check("example", fset, []*ast.File{file}, nil)
+ return err
+}
+
+func TestErrorCodeStyle(t *testing.T) {
+ // The set of error codes is large and intended to be self-documenting, so
+ // this test enforces some style conventions.
+ forbiddenInIdent := []string{
+ // use invalid instead
+ "illegal",
+ // words with a common short-form
+ "argument",
+ "assertion",
+ "assignment",
+ "boolean",
+ "channel",
+ "condition",
+ "declaration",
+ "expression",
+ "function",
+ "initial", // use init for initializer, initialization, etc.
+ "integer",
+ "interface",
+ "iterat", // use iter for iterator, iteration, etc.
+ "literal",
+ "operation",
+ "package",
+ "pointer",
+ "receiver",
+ "signature",
+ "statement",
+ "variable",
+ }
+ forbiddenInComment := []string{
+ // lhs and rhs should be spelled-out.
+ "lhs", "rhs",
+ // builtin should be hyphenated.
+ "builtin",
+ // Use dot-dot-dot.
+ "ellipsis",
+ }
+ nameHist := make(map[int]int)
+ longestName := ""
+ maxValue := 0
+
+ walkCodes(t, func(name string, value int, spec *ast.ValueSpec) {
+ if name == "_" {
+ return
+ }
+ nameHist[len(name)]++
+ if value > maxValue {
+ maxValue = value
+ }
+ if len(name) > len(longestName) {
+ longestName = name
+ }
+ if !token.IsExported(name) {
+ t.Errorf("%q is not exported", name)
+ }
+ lower := strings.ToLower(name)
+ for _, bad := range forbiddenInIdent {
+ if strings.Contains(lower, bad) {
+ t.Errorf("%q contains forbidden word %q", name, bad)
+ }
+ }
+ doc := spec.Doc.Text()
+ if doc == "" {
+ t.Errorf("%q is undocumented", name)
+ } else if !strings.HasPrefix(doc, name) {
+ t.Errorf("doc for %q does not start with the error code name", name)
+ }
+ lowerComment := strings.ToLower(strings.TrimPrefix(doc, name))
+ for _, bad := range forbiddenInComment {
+ if strings.Contains(lowerComment, bad) {
+ t.Errorf("doc for %q contains forbidden word %q", name, bad)
+ }
+ }
+ })
+
+ if testing.Verbose() {
+ var totChars, totCount int
+ for chars, count := range nameHist {
+ totChars += chars * count
+ totCount += count
+ }
+ avg := float64(totChars) / float64(totCount)
+ fmt.Println()
+ fmt.Printf("%d error codes\n", totCount)
+ fmt.Printf("average length: %.2f chars\n", avg)
+ fmt.Printf("max length: %d (%s)\n", len(longestName), longestName)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/errors/generrordocs.go b/platform/dbops/binaries/go/go/src/internal/types/errors/generrordocs.go
new file mode 100644
index 0000000000000000000000000000000000000000..46343be3ef08bc45ca445cb54c5487908837a55a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/errors/generrordocs.go
@@ -0,0 +1,117 @@
+//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
+
+//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 ")
+ }
+ 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 <
+ // 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
+---
+
+
+
+
+{{.Description}}
+`
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/blank.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/blank.go
new file mode 100644
index 0000000000000000000000000000000000000000..2bea11f53b7b08a6456e7066195fe90b501d2bf3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/blank.go
@@ -0,0 +1,5 @@
+// Copyright 2014 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 _ /* ERROR "invalid package name" */
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/builtins0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/builtins0.go
new file mode 100644
index 0000000000000000000000000000000000000000..12d8fbfd0e41e6bb0f748f63f8127cba5f3295e3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/builtins0.go
@@ -0,0 +1,1075 @@
+// 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.
+
+// builtin calls
+
+package builtins
+
+import "unsafe"
+
+func f0() {}
+
+func append1() {
+ var b byte
+ var x int
+ var s []byte
+ _ = append() // ERROR "not enough arguments"
+ _ = append("foo" /* ERROR "must be a slice" */ )
+ _ = append(nil /* ERROR "must be a slice" */ , s)
+ _ = append(x /* ERROR "must be a slice" */ , s)
+ _ = append(s)
+ _ = append(s, nil...)
+ append /* ERROR "not used" */ (s)
+
+ _ = append(s, b)
+ _ = append(s, x /* ERROR "cannot use x" */ )
+ _ = append(s, s /* ERROR "cannot use s" */ )
+ _ = append(s...) /* ERROR "not enough arguments" */
+ _ = append(s, b, s /* ERROR "too many arguments" */ ...)
+ _ = append(s, 1, 2, 3)
+ _ = append(s, 1, 2, 3, x /* ERROR "cannot use x" */ , 5, 6, 6)
+ _ = append(s, 1, 2 /* ERROR "too many arguments" */, s...)
+ _ = append([]interface{}(nil), 1, 2, "foo", x, 3.1425, false)
+
+ type S []byte
+ type T string
+ var t T
+ _ = append(s, "foo" /* ERRORx `cannot use .* in argument to append` */ )
+ _ = append(s, "foo"...)
+ _ = append(S(s), "foo" /* ERRORx `cannot use .* in argument to append` */ )
+ _ = append(S(s), "foo"...)
+ _ = append(s, t /* ERROR "cannot use t" */ )
+ _ = append(s, t...)
+ _ = append(s, T("foo")...)
+ _ = append(S(s), t /* ERROR "cannot use t" */ )
+ _ = append(S(s), t...)
+ _ = append(S(s), T("foo")...)
+ _ = append([]string{}, t /* ERROR "cannot use t" */ , "foo")
+ _ = append([]T{}, t, "foo")
+}
+
+// from the spec
+func append2() {
+ s0 := []int{0, 0}
+ s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
+ s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
+ s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
+ s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
+
+ var t []interface{}
+ t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
+
+ var b []byte
+ b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
+
+ _ = s4
+}
+
+func append3() {
+ f1 := func() (s []int) { return }
+ f2 := func() (s []int, x int) { return }
+ f3 := func() (s []int, x, y int) { return }
+ f5 := func() (s []interface{}, x int, y float32, z string, b bool) { return }
+ ff := func() (int, float32) { return 0, 0 }
+ _ = append(f0 /* ERROR "used as value" */ ())
+ _ = append(f1())
+ _ = append(f2())
+ _ = append(f3())
+ _ = append(f5())
+ _ = append(ff /* ERROR "must be a slice" */ ()) // TODO(gri) better error message
+}
+
+func cap1() {
+ var a [10]bool
+ var p *[20]int
+ var c chan string
+ _ = cap() // ERROR "not enough arguments"
+ _ = cap(1, 2) // ERROR "too many arguments"
+ _ = cap(42 /* ERROR "invalid" */)
+ const _3 = cap(a)
+ assert(_3 == 10)
+ const _4 = cap(p)
+ assert(_4 == 20)
+ _ = cap(c)
+ cap /* ERROR "not used" */ (c)
+
+ // issue 4744
+ type T struct{ a [10]int }
+ const _ = cap(((*T)(nil)).a)
+
+ var s [][]byte
+ _ = cap(s)
+ _ = cap(s... /* ERROR "invalid use of ..." */ )
+}
+
+func cap2() {
+ f1a := func() (a [10]int) { return }
+ f1s := func() (s []int) { return }
+ f2 := func() (s []int, x int) { return }
+ _ = cap(f0 /* ERROR "used as value" */ ())
+ _ = cap(f1a())
+ _ = cap(f1s())
+ _ = cap(f2()) // ERROR "too many arguments"
+}
+
+// test cases for issue 7387
+func cap3() {
+ var f = func() int { return 0 }
+ var x = f()
+ const (
+ _ = cap([4]int{})
+ _ = cap([4]int{x})
+ _ = cap /* ERROR "not constant" */ ([4]int{f()})
+ _ = cap /* ERROR "not constant" */ ([4]int{cap([]int{})})
+ _ = cap([4]int{cap([4]int{})})
+ )
+ var y float64
+ var z complex128
+ const (
+ _ = cap([4]float64{})
+ _ = cap([4]float64{y})
+ _ = cap([4]float64{real(2i)})
+ _ = cap /* ERROR "not constant" */ ([4]float64{real(z)})
+ )
+ var ch chan [10]int
+ const (
+ _ = cap /* ERROR "not constant" */ (<-ch)
+ _ = cap /* ERROR "not constant" */ ([4]int{(<-ch)[0]})
+ )
+}
+
+func clear1() {
+ var a [10]int
+ var m map[float64]string
+ var s []byte
+ clear(a /* ERROR "cannot clear a" */)
+ clear(&/* ERROR "cannot clear &a" */a)
+ clear(m)
+ clear(s)
+ clear([]int{})
+}
+
+func close1() {
+ var c chan int
+ var r <-chan int
+ close() // ERROR "not enough arguments"
+ close(1, 2) // ERROR "too many arguments"
+ close(42 /* ERROR "cannot close non-channel" */)
+ close(r /* ERROR "receive-only channel" */)
+ close(c)
+ _ = close /* ERROR "used as value" */ (c)
+
+ var s []chan int
+ close(s... /* ERROR "invalid use of ..." */ )
+}
+
+func close2() {
+ f1 := func() (ch chan int) { return }
+ f2 := func() (ch chan int, x int) { return }
+ close(f0 /* ERROR "used as value" */ ())
+ close(f1())
+ close(f2()) // ERROR "too many arguments"
+}
+
+func complex1() {
+ var i32 int32
+ var f32 float32
+ var f64 float64
+ var c64 complex64
+ var c128 complex128
+ _ = complex() // ERROR "not enough arguments"
+ _ = complex(1) // ERROR "not enough arguments"
+ _ = complex(true /* ERROR "mismatched types" */ , 0)
+ _ = complex(i32 /* ERROR "expected floating-point" */ , 0)
+ _ = complex("foo" /* ERROR "mismatched types" */ , 0)
+ _ = complex(c64 /* ERROR "expected floating-point" */ , 0)
+ _ = complex(0 /* ERROR "mismatched types" */ , true)
+ _ = complex(0 /* ERROR "expected floating-point" */ , i32)
+ _ = complex(0 /* ERROR "mismatched types" */ , "foo")
+ _ = complex(0 /* ERROR "expected floating-point" */ , c64)
+ _ = complex(f32, f32)
+ _ = complex(f32, 1)
+ _ = complex(f32, 1.0)
+ _ = complex(f32, 'a')
+ _ = complex(f64, f64)
+ _ = complex(f64, 1)
+ _ = complex(f64, 1.0)
+ _ = complex(f64, 'a')
+ _ = complex(f32 /* ERROR "mismatched types" */ , f64)
+ _ = complex(f64 /* ERROR "mismatched types" */ , f32)
+ _ = complex(1, 1)
+ _ = complex(1, 1.1)
+ _ = complex(1, 'a')
+ complex /* ERROR "not used" */ (1, 2)
+
+ var _ complex64 = complex(f32, f32)
+ var _ complex64 = complex /* ERRORx `cannot use .* in variable declaration` */ (f64, f64)
+
+ var _ complex128 = complex /* ERRORx `cannot use .* in variable declaration` */ (f32, f32)
+ var _ complex128 = complex(f64, f64)
+
+ // untyped constants
+ const _ int = complex(1, 0)
+ const _ float32 = complex(1, 0)
+ const _ complex64 = complex(1, 0)
+ const _ complex128 = complex(1, 0)
+ const _ = complex(0i, 0i)
+ const _ = complex(0i, 0)
+ const _ int = 1.0 + complex(1, 0i)
+
+ const _ int = complex /* ERROR "int" */ (1.1, 0)
+ const _ float32 = complex /* ERROR "float32" */ (1, 2)
+
+ // untyped values
+ var s uint
+ _ = complex(1 /* ERROR "integer" */ <>8&1 + mi>>16&1 + mi>>32&1)
+ logSizeofUint = uint(mu>>8&1 + mu>>16&1 + mu>>32&1)
+ logSizeofUintptr = uint(mp>>8&1 + mp>>16&1 + mp>>32&1)
+)
+
+const (
+ minInt8 = -1<<(8< 0)
+ _ = assert(smallestFloat64 > 0)
+)
+
+const (
+ maxFloat32 = 1<<127 * (1<<24 - 1) / (1.0<<23)
+ // TODO(gri) The compiler limits integers to 512 bit and thus
+ // we cannot compute the value 1<<1023
+ // without overflow. For now we match the compiler.
+ // See also issue #44057.
+ // maxFloat64 = 1<<1023 * (1<<53 - 1) / (1.0<<52)
+ maxFloat64 = math.MaxFloat64
+)
+
+const (
+ _ int8 = minInt8 /* ERROR "overflows" */ - 1
+ _ int8 = minInt8
+ _ int8 = maxInt8
+ _ int8 = maxInt8 /* ERROR "overflows" */ + 1
+ _ int8 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = int8(minInt8 /* ERROR "overflows" */ - 1)
+ _ = int8(minInt8)
+ _ = int8(maxInt8)
+ _ = int8(maxInt8 /* ERROR "overflows" */ + 1)
+ _ = int8(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ int16 = minInt16 /* ERROR "overflows" */ - 1
+ _ int16 = minInt16
+ _ int16 = maxInt16
+ _ int16 = maxInt16 /* ERROR "overflows" */ + 1
+ _ int16 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = int16(minInt16 /* ERROR "overflows" */ - 1)
+ _ = int16(minInt16)
+ _ = int16(maxInt16)
+ _ = int16(maxInt16 /* ERROR "overflows" */ + 1)
+ _ = int16(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ int32 = minInt32 /* ERROR "overflows" */ - 1
+ _ int32 = minInt32
+ _ int32 = maxInt32
+ _ int32 = maxInt32 /* ERROR "overflows" */ + 1
+ _ int32 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = int32(minInt32 /* ERROR "overflows" */ - 1)
+ _ = int32(minInt32)
+ _ = int32(maxInt32)
+ _ = int32(maxInt32 /* ERROR "overflows" */ + 1)
+ _ = int32(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ int64 = minInt64 /* ERROR "overflows" */ - 1
+ _ int64 = minInt64
+ _ int64 = maxInt64
+ _ int64 = maxInt64 /* ERROR "overflows" */ + 1
+ _ int64 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = int64(minInt64 /* ERROR "overflows" */ - 1)
+ _ = int64(minInt64)
+ _ = int64(maxInt64)
+ _ = int64(maxInt64 /* ERROR "overflows" */ + 1)
+ _ = int64(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ int = minInt /* ERROR "overflows" */ - 1
+ _ int = minInt
+ _ int = maxInt
+ _ int = maxInt /* ERROR "overflows" */ + 1
+ _ int = smallestFloat64 /* ERROR "truncated" */
+
+ _ = int(minInt /* ERROR "overflows" */ - 1)
+ _ = int(minInt)
+ _ = int(maxInt)
+ _ = int(maxInt /* ERROR "overflows" */ + 1)
+ _ = int(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uint8 = 0 /* ERROR "overflows" */ - 1
+ _ uint8 = 0
+ _ uint8 = maxUint8
+ _ uint8 = maxUint8 /* ERROR "overflows" */ + 1
+ _ uint8 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uint8(0 /* ERROR "overflows" */ - 1)
+ _ = uint8(0)
+ _ = uint8(maxUint8)
+ _ = uint8(maxUint8 /* ERROR "overflows" */ + 1)
+ _ = uint8(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uint16 = 0 /* ERROR "overflows" */ - 1
+ _ uint16 = 0
+ _ uint16 = maxUint16
+ _ uint16 = maxUint16 /* ERROR "overflows" */ + 1
+ _ uint16 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uint16(0 /* ERROR "overflows" */ - 1)
+ _ = uint16(0)
+ _ = uint16(maxUint16)
+ _ = uint16(maxUint16 /* ERROR "overflows" */ + 1)
+ _ = uint16(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uint32 = 0 /* ERROR "overflows" */ - 1
+ _ uint32 = 0
+ _ uint32 = maxUint32
+ _ uint32 = maxUint32 /* ERROR "overflows" */ + 1
+ _ uint32 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uint32(0 /* ERROR "overflows" */ - 1)
+ _ = uint32(0)
+ _ = uint32(maxUint32)
+ _ = uint32(maxUint32 /* ERROR "overflows" */ + 1)
+ _ = uint32(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uint64 = 0 /* ERROR "overflows" */ - 1
+ _ uint64 = 0
+ _ uint64 = maxUint64
+ _ uint64 = maxUint64 /* ERROR "overflows" */ + 1
+ _ uint64 = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uint64(0 /* ERROR "overflows" */ - 1)
+ _ = uint64(0)
+ _ = uint64(maxUint64)
+ _ = uint64(maxUint64 /* ERROR "overflows" */ + 1)
+ _ = uint64(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uint = 0 /* ERROR "overflows" */ - 1
+ _ uint = 0
+ _ uint = maxUint
+ _ uint = maxUint /* ERROR "overflows" */ + 1
+ _ uint = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uint(0 /* ERROR "overflows" */ - 1)
+ _ = uint(0)
+ _ = uint(maxUint)
+ _ = uint(maxUint /* ERROR "overflows" */ + 1)
+ _ = uint(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ uintptr = 0 /* ERROR "overflows" */ - 1
+ _ uintptr = 0
+ _ uintptr = maxUintptr
+ _ uintptr = maxUintptr /* ERROR "overflows" */ + 1
+ _ uintptr = smallestFloat64 /* ERROR "truncated" */
+
+ _ = uintptr(0 /* ERROR "overflows" */ - 1)
+ _ = uintptr(0)
+ _ = uintptr(maxUintptr)
+ _ = uintptr(maxUintptr /* ERROR "overflows" */ + 1)
+ _ = uintptr(smallestFloat64 /* ERROR "cannot convert" */)
+)
+
+const (
+ _ float32 = minInt64
+ _ float64 = minInt64
+ _ complex64 = minInt64
+ _ complex128 = minInt64
+
+ _ = float32(minInt64)
+ _ = float64(minInt64)
+ _ = complex64(minInt64)
+ _ = complex128(minInt64)
+)
+
+const (
+ _ float32 = maxUint64
+ _ float64 = maxUint64
+ _ complex64 = maxUint64
+ _ complex128 = maxUint64
+
+ _ = float32(maxUint64)
+ _ = float64(maxUint64)
+ _ = complex64(maxUint64)
+ _ = complex128(maxUint64)
+)
+
+// TODO(gri) find smaller deltas below
+
+const delta32 = maxFloat32/(1 << 23)
+
+const (
+ _ float32 = - /* ERROR "overflow" */ (maxFloat32 + delta32)
+ _ float32 = -maxFloat32
+ _ float32 = maxFloat32
+ _ float32 = maxFloat32 /* ERROR "overflow" */ + delta32
+
+ _ = float32(- /* ERROR "cannot convert" */ (maxFloat32 + delta32))
+ _ = float32(-maxFloat32)
+ _ = float32(maxFloat32)
+ _ = float32(maxFloat32 /* ERROR "cannot convert" */ + delta32)
+
+ _ = assert(float32(smallestFloat32) == smallestFloat32)
+ _ = assert(float32(smallestFloat32/2) == 0)
+ _ = assert(float32(smallestFloat64) == 0)
+ _ = assert(float32(smallestFloat64/2) == 0)
+)
+
+const delta64 = maxFloat64/(1 << 52)
+
+const (
+ _ float64 = - /* ERROR "overflow" */ (maxFloat64 + delta64)
+ _ float64 = -maxFloat64
+ _ float64 = maxFloat64
+ _ float64 = maxFloat64 /* ERROR "overflow" */ + delta64
+
+ _ = float64(- /* ERROR "cannot convert" */ (maxFloat64 + delta64))
+ _ = float64(-maxFloat64)
+ _ = float64(maxFloat64)
+ _ = float64(maxFloat64 /* ERROR "cannot convert" */ + delta64)
+
+ _ = assert(float64(smallestFloat32) == smallestFloat32)
+ _ = assert(float64(smallestFloat32/2) == smallestFloat32/2)
+ _ = assert(float64(smallestFloat64) == smallestFloat64)
+ _ = assert(float64(smallestFloat64/2) == 0)
+)
+
+const (
+ _ complex64 = - /* ERROR "overflow" */ (maxFloat32 + delta32)
+ _ complex64 = -maxFloat32
+ _ complex64 = maxFloat32
+ _ complex64 = maxFloat32 /* ERROR "overflow" */ + delta32
+
+ _ = complex64(- /* ERROR "cannot convert" */ (maxFloat32 + delta32))
+ _ = complex64(-maxFloat32)
+ _ = complex64(maxFloat32)
+ _ = complex64(maxFloat32 /* ERROR "cannot convert" */ + delta32)
+)
+
+const (
+ _ complex128 = - /* ERROR "overflow" */ (maxFloat64 + delta64)
+ _ complex128 = -maxFloat64
+ _ complex128 = maxFloat64
+ _ complex128 = maxFloat64 /* ERROR "overflow" */ + delta64
+
+ _ = complex128(- /* ERROR "cannot convert" */ (maxFloat64 + delta64))
+ _ = complex128(-maxFloat64)
+ _ = complex128(maxFloat64)
+ _ = complex128(maxFloat64 /* ERROR "cannot convert" */ + delta64)
+)
+
+// Initialization of typed constant and conversion are the same:
+const (
+ f32 = 1 + smallestFloat32
+ x32 float32 = f32
+ y32 = float32(f32)
+ _ = assert(x32 - y32 == 0)
+)
+
+const (
+ f64 = 1 + smallestFloat64
+ x64 float64 = f64
+ y64 = float64(f64)
+ _ = assert(x64 - y64 == 0)
+)
+
+const (
+ _ = int8(-1) << 7
+ _ = int8 /* ERROR "overflows" */ (-1) << 8
+
+ _ = uint32(1) << 31
+ _ = uint32 /* ERROR "overflows" */ (1) << 32
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/constdecl.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/constdecl.go
new file mode 100644
index 0000000000000000000000000000000000000000..9ace419a61b1a3984923d5998f1528f65e175ffc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/constdecl.go
@@ -0,0 +1,160 @@
+// 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 constdecl
+
+import "math"
+import "unsafe"
+
+var v int
+
+// Const decls must be initialized by constants.
+const _ = v /* ERROR "not constant" */
+const _ = math /* ERROR "not constant" */ .Sin(0)
+const _ = int /* ERROR "not an expression" */
+
+func _() {
+ const _ = v /* ERROR "not constant" */
+ const _ = math /* ERROR "not constant" */ .Sin(0)
+ const _ = int /* ERROR "not an expression" */
+}
+
+// Identifier and expression arity must match.
+const _ /* ERROR "missing init expr for _" */
+const _ = 1, 2 /* ERROR "extra init expr 2" */
+
+const _ /* ERROR "missing init expr for _" */ int
+const _ int = 1, 2 /* ERROR "extra init expr 2" */
+
+const (
+ _ /* ERROR "missing init expr for _" */
+ _ = 1, 2 /* ERROR "extra init expr 2" */
+
+ _ /* ERROR "missing init expr for _" */ int
+ _ int = 1, 2 /* ERROR "extra init expr 2" */
+)
+
+const (
+ _ = 1
+ _
+ _, _ /* ERROR "missing init expr for _" */
+ _
+)
+
+const (
+ _, _ = 1, 2
+ _, _
+ _ /* ERROR "extra init expr at" */
+ _, _
+ _, _, _ /* ERROR "missing init expr for _" */
+ _, _
+)
+
+func _() {
+ const _ /* ERROR "missing init expr for _" */
+ const _ = 1, 2 /* ERROR "extra init expr 2" */
+
+ const _ /* ERROR "missing init expr for _" */ int
+ const _ int = 1, 2 /* ERROR "extra init expr 2" */
+
+ const (
+ _ /* ERROR "missing init expr for _" */
+ _ = 1, 2 /* ERROR "extra init expr 2" */
+
+ _ /* ERROR "missing init expr for _" */ int
+ _ int = 1, 2 /* ERROR "extra init expr 2" */
+ )
+
+ const (
+ _ = 1
+ _
+ _, _ /* ERROR "missing init expr for _" */
+ _
+ )
+
+ const (
+ _, _ = 1, 2
+ _, _
+ _ /* ERROR "extra init expr at" */
+ _, _
+ _, _, _ /* ERROR "missing init expr for _" */
+ _, _
+ )
+}
+
+// Test case for constant with invalid initialization.
+// Caused panic because the constant value was not set up (gri - 7/8/2014).
+func _() {
+ const (
+ x string = missing /* ERROR "undefined" */
+ y = x + ""
+ )
+}
+
+// Test case for constants depending on function literals (see also #22992).
+const A /* ERROR "initialization cycle" */ = unsafe.Sizeof(func() { _ = A })
+
+func _() {
+ // The function literal below must not see a.
+ const a = unsafe.Sizeof(func() { _ = a /* ERROR "undefined" */ })
+ const b = unsafe.Sizeof(func() { _ = a })
+
+ // The function literal below must not see x, y, or z.
+ const x, y, z = 0, 1, unsafe.Sizeof(func() { _ = x /* ERROR "undefined" */ + y /* ERROR "undefined" */ + z /* ERROR "undefined" */ })
+}
+
+// Test cases for errors in inherited constant initialization expressions.
+// Errors related to inherited initialization expressions must appear at
+// the constant identifier being declared, not at the original expression
+// (issues #42991, #42992).
+const (
+ _ byte = 255 + iota
+ /* some gap */
+ _ // ERROR "overflows"
+ /* some gap */
+ /* some gap */ _ /* ERROR "overflows" */; _ /* ERROR "overflows" */
+ /* some gap */
+ _ = 255 + iota
+ _ = byte /* ERROR "overflows" */ (255) + iota
+ _ /* ERROR "overflows" */
+)
+
+// Test cases from issue.
+const (
+ ok = byte(iota + 253)
+ bad
+ barn
+ bard // ERROR "overflows"
+)
+
+const (
+ c = len([1 - iota]int{})
+ d
+ e // ERROR "invalid array length"
+ f // ERROR "invalid array length"
+)
+
+// Test that identifiers in implicit (omitted) RHS
+// expressions of constant declarations are resolved
+// in the correct context; see issues #49157, #53585.
+const X = 2
+
+func _() {
+ const (
+ A = iota // 0
+ iota = iota // 1
+ B // 1 (iota is declared locally on prev. line)
+ C // 1
+ )
+ assert(A == 0 && B == 1 && C == 1)
+
+ const (
+ X = X + X
+ Y
+ Z = iota
+ )
+ assert(X == 4 && Y == 8 && Z == 1)
+}
+
+// TODO(gri) move extra tests from testdata/const0.src into here
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions0.go
new file mode 100644
index 0000000000000000000000000000000000000000..e1336c0456adf7baada345f46f5da54d89c9b804
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions0.go
@@ -0,0 +1,93 @@
+// 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.
+
+// conversions
+
+package conversions
+
+import "unsafe"
+
+// argument count
+var (
+ _ = int() /* ERROR "missing argument" */
+ _ = int(1, 2 /* ERROR "too many arguments" */ )
+)
+
+// numeric constant conversions are in const1.src.
+
+func string_conversions() {
+ const A = string(65)
+ assert(A == "A")
+ const E = string(-1)
+ assert(E == "\uFFFD")
+ assert(E == string(1234567890))
+
+ type myint int
+ assert(A == string(myint(65)))
+
+ type mystring string
+ const _ mystring = mystring("foo")
+
+ const _ = string(true /* ERROR "cannot convert" */ )
+ const _ = string(1.2 /* ERROR "cannot convert" */ )
+ const _ = string(nil /* ERROR "cannot convert" */ )
+
+ // issues 11357, 11353: argument must be of integer type
+ _ = string(0.0 /* ERROR "cannot convert" */ )
+ _ = string(0i /* ERROR "cannot convert" */ )
+ _ = string(1 /* ERROR "cannot convert" */ + 2i)
+}
+
+func interface_conversions() {
+ type E interface{}
+
+ type I1 interface{
+ m1()
+ }
+
+ type I2 interface{
+ m1()
+ m2(x int)
+ }
+
+ type I3 interface{
+ m1()
+ m2() int
+ }
+
+ var e E
+ var i1 I1
+ var i2 I2
+ var i3 I3
+
+ _ = E(0)
+ _ = E(nil)
+ _ = E(e)
+ _ = E(i1)
+ _ = E(i2)
+
+ _ = I1(0 /* ERROR "cannot convert" */ )
+ _ = I1(nil)
+ _ = I1(i1)
+ _ = I1(e /* ERROR "cannot convert" */ )
+ _ = I1(i2)
+
+ _ = I2(nil)
+ _ = I2(i1 /* ERROR "cannot convert" */ )
+ _ = I2(i2)
+ _ = I2(i3 /* ERROR "cannot convert" */ )
+
+ _ = I3(nil)
+ _ = I3(i1 /* ERROR "cannot convert" */ )
+ _ = I3(i2 /* ERROR "cannot convert" */ )
+ _ = I3(i3)
+
+ // TODO(gri) add more tests, improve error message
+}
+
+func issue6326() {
+ type T unsafe.Pointer
+ var x T
+ _ = uintptr(x) // see issue 6326
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions1.go
new file mode 100644
index 0000000000000000000000000000000000000000..65aabde9105783518f4661f85245bcbd5142150d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/conversions1.go
@@ -0,0 +1,313 @@
+// 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.
+
+// Test various valid and invalid struct assignments and conversions.
+// Does not compile.
+
+package conversions2
+
+type I interface {
+ m()
+}
+
+// conversions between structs
+
+func _() {
+ type S struct{}
+ type T struct{}
+ var s S
+ var t T
+ var u struct{}
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u
+ s = S(s)
+ s = S(t)
+ s = S(u)
+ t = u
+ t = T(u)
+}
+
+func _() {
+ type S struct{ x int }
+ type T struct {
+ x int "foo"
+ }
+ var s S
+ var t T
+ var u struct {
+ x int "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = S(s)
+ s = S(t)
+ s = S(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = T(u)
+}
+
+func _() {
+ type E struct{ x int }
+ type S struct{ x E }
+ type T struct {
+ x E "foo"
+ }
+ var s S
+ var t T
+ var u struct {
+ x E "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = S(s)
+ s = S(t)
+ s = S(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = T(u)
+}
+
+func _() {
+ type S struct {
+ x struct {
+ x int "foo"
+ }
+ }
+ type T struct {
+ x struct {
+ x int "bar"
+ } "foo"
+ }
+ var s S
+ var t T
+ var u struct {
+ x struct {
+ x int "bar"
+ } "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = S(s)
+ s = S(t)
+ s = S(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = T(u)
+}
+
+func _() {
+ type E1 struct {
+ x int "foo"
+ }
+ type E2 struct {
+ x int "bar"
+ }
+ type S struct{ x E1 }
+ type T struct {
+ x E2 "foo"
+ }
+ var s S
+ var t T
+ var u struct {
+ x E2 "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = S(s)
+ s = S(t /* ERROR "cannot convert" */ )
+ s = S(u /* ERROR "cannot convert" */ )
+ t = u // ERRORx `cannot use .* in assignment`
+ t = T(u)
+}
+
+func _() {
+ type E struct{ x int }
+ type S struct {
+ f func(struct {
+ x int "foo"
+ })
+ }
+ type T struct {
+ f func(struct {
+ x int "bar"
+ })
+ }
+ var s S
+ var t T
+ var u struct{ f func(E) }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = S(s)
+ s = S(t)
+ s = S(u /* ERROR "cannot convert" */ )
+ t = u // ERRORx `cannot use .* in assignment`
+ t = T(u /* ERROR "cannot convert" */ )
+}
+
+// conversions between pointers to structs
+
+func _() {
+ type S struct{}
+ type T struct{}
+ var s *S
+ var t *T
+ var u *struct{}
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u)
+}
+
+func _() {
+ type S struct{ x int }
+ type T struct {
+ x int "foo"
+ }
+ var s *S
+ var t *T
+ var u *struct {
+ x int "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u)
+}
+
+func _() {
+ type E struct{ x int }
+ type S struct{ x E }
+ type T struct {
+ x E "foo"
+ }
+ var s *S
+ var t *T
+ var u *struct {
+ x E "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u)
+}
+
+func _() {
+ type S struct {
+ x struct {
+ x int "foo"
+ }
+ }
+ type T struct {
+ x struct {
+ x int "bar"
+ } "foo"
+ }
+ var s *S
+ var t *T
+ var u *struct {
+ x struct {
+ x int "bar"
+ } "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u)
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u)
+}
+
+func _() {
+ type E1 struct {
+ x int "foo"
+ }
+ type E2 struct {
+ x int "bar"
+ }
+ type S struct{ x E1 }
+ type T struct {
+ x E2 "foo"
+ }
+ var s *S
+ var t *T
+ var u *struct {
+ x E2 "bar"
+ }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t /* ERROR "cannot convert" */ )
+ s = (*S)(u /* ERROR "cannot convert" */ )
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u)
+}
+
+func _() {
+ type E struct{ x int }
+ type S struct {
+ f func(struct {
+ x int "foo"
+ })
+ }
+ type T struct {
+ f func(struct {
+ x int "bar"
+ })
+ }
+ var s *S
+ var t *T
+ var u *struct{ f func(E) }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u /* ERROR "cannot convert" */ )
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u /* ERROR "cannot convert" */ )
+}
+
+func _() {
+ type E struct{ x int }
+ type S struct {
+ f func(*struct {
+ x int "foo"
+ })
+ }
+ type T struct {
+ f func(*struct {
+ x int "bar"
+ })
+ }
+ var s *S
+ var t *T
+ var u *struct{ f func(E) }
+ s = s
+ s = t // ERRORx `cannot use .* in assignment`
+ s = u // ERRORx `cannot use .* in assignment`
+ s = (*S)(s)
+ s = (*S)(t)
+ s = (*S)(u /* ERROR "cannot convert" */ )
+ t = u // ERRORx `cannot use .* in assignment`
+ t = (*T)(u /* ERROR "cannot convert" */ )
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles0.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ad7877f946956a74ba9bd088c8f445ef3f6076e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles0.go
@@ -0,0 +1,175 @@
+// 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 cycles
+
+import "unsafe"
+
+type (
+ T0 int
+ T1 /* ERROR "invalid recursive type: T1 refers to itself" */ T1
+ T2 *T2
+
+ T3 /* ERROR "invalid recursive type" */ T4
+ T4 T5
+ T5 T3
+
+ T6 T7
+ T7 *T8
+ T8 T6
+
+ // arrays
+ A0 /* ERROR "invalid recursive type" */ [10]A0
+ A1 [10]*A1
+
+ A2 /* ERROR "invalid recursive type" */ [10]A3
+ A3 [10]A4
+ A4 A2
+
+ A5 [10]A6
+ A6 *A5
+
+ // slices
+ L0 []L0
+
+ // structs
+ S0 /* ERROR "invalid recursive type: S0 refers to itself" */ struct{ _ S0 }
+ S1 /* ERROR "invalid recursive type: S1 refers to itself" */ struct{ S1 }
+ S2 struct{ _ *S2 }
+ S3 struct{ *S3 }
+
+ S4 /* ERROR "invalid recursive type" */ struct{ S5 }
+ S5 struct{ S6 }
+ S6 S4
+
+ // pointers
+ P0 *P0
+ PP *struct{ PP.f /* ERROR "PP.f is not a type" */ }
+
+ // functions
+ F0 func(F0)
+ F1 func() F1
+ F2 func(F2) F2
+
+ // interfaces
+ I0 /* ERROR "invalid recursive type: I0 refers to itself" */ interface{ I0 }
+
+ I1 /* ERROR "invalid recursive type" */ interface{ I2 }
+ I2 interface{ I3 }
+ I3 interface{ I1 }
+
+ I4 interface{ f(I4) }
+
+ // testcase for issue 5090
+ I5 interface{ f(I6) }
+ I6 interface{ I5 }
+
+ // maps
+ M0 map[M0 /* ERROR "invalid map key" */ ]M0
+
+ // channels
+ C0 chan C0
+)
+
+// test case for issue #34771
+type (
+ AA /* ERROR "invalid recursive type" */ B
+ B C
+ C [10]D
+ D E
+ E AA
+)
+
+func _() {
+ type (
+ t1 /* ERROR "invalid recursive type: t1 refers to itself" */ t1
+ t2 *t2
+
+ t3 t4 /* ERROR "undefined" */
+ t4 t5 /* ERROR "undefined" */
+ t5 t3
+
+ // arrays
+ a0 /* ERROR "invalid recursive type: a0 refers to itself" */ [10]a0
+ a1 [10]*a1
+
+ // slices
+ l0 []l0
+
+ // structs
+ s0 /* ERROR "invalid recursive type: s0 refers to itself" */ struct{ _ s0 }
+ s1 /* ERROR "invalid recursive type: s1 refers to itself" */ struct{ s1 }
+ s2 struct{ _ *s2 }
+ s3 struct{ *s3 }
+
+ // pointers
+ p0 *p0
+
+ // functions
+ f0 func(f0)
+ f1 func() f1
+ f2 func(f2) f2
+
+ // interfaces
+ i0 /* ERROR "invalid recursive type: i0 refers to itself" */ interface{ i0 }
+
+ // maps
+ m0 map[m0 /* ERROR "invalid map key" */ ]m0
+
+ // channels
+ c0 chan c0
+ )
+}
+
+// test cases for issue 6667
+
+type A [10]map[A /* ERROR "invalid map key" */ ]bool
+
+type S struct {
+ m map[S /* ERROR "invalid map key" */ ]bool
+}
+
+// test cases for issue 7236
+// (cycle detection must not be dependent on starting point of resolution)
+
+type (
+ P1 *T9
+ T9 /* ERROR "invalid recursive type: T9 refers to itself" */ T9
+
+ T10 /* ERROR "invalid recursive type: T10 refers to itself" */ T10
+ P2 *T10
+)
+
+func (T11) m() {}
+
+type T11 /* ERROR "invalid recursive type: T11 refers to itself" */ struct{ T11 }
+
+type T12 /* ERROR "invalid recursive type: T12 refers to itself" */ struct{ T12 }
+
+func (*T12) m() {}
+
+type (
+ P3 *T13
+ T13 /* ERROR "invalid recursive type" */ T13
+)
+
+// test cases for issue 18643
+// (type cycle detection when non-type expressions are involved)
+type (
+ T14 [len(T14 /* ERROR "invalid recursive type" */ {})]int
+ T15 [][len(T15 /* ERROR "invalid recursive type" */ {})]int
+ T16 map[[len(T16 /* ERROR "invalid recursive type" */ {1:2})]int]int
+ T17 map[int][len(T17 /* ERROR "invalid recursive type" */ {1:2})]int
+)
+
+// Test case for types depending on function literals (see also #22992).
+type T20 chan [unsafe.Sizeof(func(ch T20){ _ = <-ch })]byte
+type T22 = chan [unsafe.Sizeof(func(ch T20){ _ = <-ch })]byte
+
+func _() {
+ type T0 func(T0)
+ type T1 /* ERROR "invalid recursive type" */ = func(T1)
+ type T2 chan [unsafe.Sizeof(func(ch T2){ _ = <-ch })]byte
+ type T3 /* ERROR "invalid recursive type" */ = chan [unsafe.Sizeof(func(ch T3){ _ = <-ch })]byte
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles1.go
new file mode 100644
index 0000000000000000000000000000000000000000..ae2b38ebec21e36d5f2e5bdd360948e8cbba97ce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles1.go
@@ -0,0 +1,77 @@
+// 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 p
+
+type (
+ A interface {
+ a() interface {
+ ABC1
+ }
+ }
+ B interface {
+ b() interface {
+ ABC2
+ }
+ }
+ C interface {
+ c() interface {
+ ABC3
+ }
+ }
+
+ AB interface {
+ A
+ B
+ }
+ BC interface {
+ B
+ C
+ }
+
+ ABC1 interface {
+ A
+ B
+ C
+ }
+ ABC2 interface {
+ AB
+ C
+ }
+ ABC3 interface {
+ A
+ BC
+ }
+)
+
+var (
+ x1 ABC1
+ x2 ABC2
+ x3 ABC3
+)
+
+func _() {
+ // all types have the same method set
+ x1 = x2
+ x2 = x1
+
+ x1 = x3
+ x3 = x1
+
+ x2 = x3
+ x3 = x2
+
+ // all methods return the same type again
+ x1 = x1.a()
+ x1 = x1.b()
+ x1 = x1.c()
+
+ x2 = x2.a()
+ x2 = x2.b()
+ x2 = x2.c()
+
+ x3 = x3.a()
+ x3 = x3.b()
+ x3 = x3.c()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles2.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles2.go
new file mode 100644
index 0000000000000000000000000000000000000000..a932d288b58e3cae9e74753ff7b54ba7cef04669
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles2.go
@@ -0,0 +1,98 @@
+// 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 p
+
+import "unsafe"
+
+// Test case for issue 5090
+
+type t interface {
+ f(u)
+}
+
+type u interface {
+ t
+}
+
+func _() {
+ var t t
+ var u u
+
+ t.f(t)
+ t.f(u)
+
+ u.f(t)
+ u.f(u)
+}
+
+
+// Test case for issues #6589, #33656.
+
+type A interface {
+ a() interface {
+ AB
+ }
+}
+
+type B interface {
+ b() interface {
+ AB
+ }
+}
+
+type AB interface {
+ a() interface {
+ A
+ B
+ }
+ b() interface {
+ A
+ B
+ }
+}
+
+var x AB
+var y interface {
+ A
+ B
+}
+
+var _ = x == y
+
+
+// Test case for issue 6638.
+
+type T interface {
+ m() [T(nil).m /* ERROR "undefined" */ ()[0]]int
+}
+
+// Variations of this test case.
+
+type T1 /* ERROR "invalid recursive type" */ interface {
+ m() [x1.m()[0]]int
+}
+
+var x1 T1
+
+type T2 /* ERROR "invalid recursive type" */ interface {
+ m() [len(x2.m())]int
+}
+
+var x2 T2
+
+type T3 /* ERROR "invalid recursive type" */ interface {
+ m() [unsafe.Sizeof(x3.m)]int
+}
+
+var x3 T3
+
+type T4 /* ERROR "invalid recursive type" */ interface {
+ m() [unsafe.Sizeof(cast4(x4.m))]int // cast is invalid but we have a cycle, so all bets are off
+}
+
+var x4 T4
+var _ = cast4(x4.m)
+
+type cast4 func()
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles3.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles3.go
new file mode 100644
index 0000000000000000000000000000000000000000..3ed999cc3d12a2cf33046353c0051897a3ffe91c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles3.go
@@ -0,0 +1,60 @@
+// 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 p
+
+import "unsafe"
+
+var (
+ _ A = A(nil).a().b().c().d().e().f()
+ _ A = A(nil).b().c().d().e().f()
+ _ A = A(nil).c().d().e().f()
+ _ A = A(nil).d().e().f()
+ _ A = A(nil).e().f()
+ _ A = A(nil).f()
+ _ A = A(nil)
+)
+
+type (
+ A interface {
+ a() B
+ B
+ }
+
+ B interface {
+ b() C
+ C
+ }
+
+ C interface {
+ c() D
+ D
+ }
+
+ D interface {
+ d() E
+ E
+ }
+
+ E interface {
+ e() F
+ F
+ }
+
+ F interface {
+ f() A
+ }
+)
+
+type (
+ U /* ERROR "invalid recursive type" */ interface {
+ V
+ }
+
+ V interface {
+ v() [unsafe.Sizeof(u)]int
+ }
+)
+
+var u U
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles4.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles4.go
new file mode 100644
index 0000000000000000000000000000000000000000..e82300125c8414d5c97c98afe64c4d98e446d271
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles4.go
@@ -0,0 +1,121 @@
+// 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 p
+
+import "unsafe"
+
+// Check that all methods of T are collected before
+// determining the result type of m (which embeds
+// all methods of T).
+
+type T interface {
+ m() interface {T}
+ E
+}
+
+var _ int = T.m(nil).m().e()
+
+type E interface {
+ e() int
+}
+
+// Check that unresolved forward chains are followed
+// (see also comment in resolver.go, checker.typeDecl).
+
+var _ int = C.m(nil).m().e()
+
+type A B
+
+type B interface {
+ m() interface{C}
+ E
+}
+
+type C A
+
+// Check that interface type comparison for identity
+// does not recur endlessly.
+
+type T1 interface {
+ m() interface{T1}
+}
+
+type T2 interface {
+ m() interface{T2}
+}
+
+func _(x T1, y T2) {
+ // Checking for assignability of interfaces must check
+ // if all methods of x are present in y, and that they
+ // have identical signatures. The signatures recur via
+ // the result type, which is an interface that embeds
+ // a single method m that refers to the very interface
+ // that contains it. This requires cycle detection in
+ // identity checks for interface types.
+ x = y
+}
+
+type T3 interface {
+ m() interface{T4}
+}
+
+type T4 interface {
+ m() interface{T3}
+}
+
+func _(x T1, y T3) {
+ x = y
+}
+
+// Check that interfaces are type-checked in order of
+// (embedded interface) dependencies (was issue 7158).
+
+var x1 T5 = T7(nil)
+
+type T5 interface {
+ T6
+}
+
+type T6 interface {
+ m() T7
+}
+type T7 interface {
+ T5
+}
+
+// Actual test case from issue 7158.
+
+func wrapNode() Node {
+ return wrapElement()
+}
+
+func wrapElement() Element {
+ return nil
+}
+
+type EventTarget interface {
+ AddEventListener(Event)
+}
+
+type Node interface {
+ EventTarget
+}
+
+type Element interface {
+ Node
+}
+
+type Event interface {
+ Target() Element
+}
+
+// Check that accessing an interface method too early doesn't lead
+// to follow-on errors due to an incorrectly computed type set.
+
+type T8 interface {
+ m() [unsafe.Sizeof(T8.m /* ERROR "undefined" */ )]int
+}
+
+var _ = T8.m // no error expected here
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5.go
new file mode 100644
index 0000000000000000000000000000000000000000..a6145058bba9a2a72083c6f7e6e742315a174fc7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5.go
@@ -0,0 +1,202 @@
+// -gotypesalias=0
+
+// 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 p
+
+import "unsafe"
+
+// test case from issue #18395
+
+type (
+ A interface { B }
+ B interface { C }
+ C interface { D; F() A }
+ D interface { G() B }
+)
+
+var _ = A(nil).G // G must be found
+
+
+// test case from issue #21804
+
+type sourceBridge interface {
+ listVersions() ([]Version, error)
+}
+
+type Constraint interface {
+ copyTo(*ConstraintMsg)
+}
+
+type ConstraintMsg struct{}
+
+func (m *ConstraintMsg) asUnpairedVersion() UnpairedVersion {
+ return nil
+}
+
+type Version interface {
+ Constraint
+}
+
+type UnpairedVersion interface {
+ Version
+}
+
+var _ Constraint = UnpairedVersion(nil)
+
+
+// derived test case from issue #21804
+
+type (
+ _ interface{ m(B1) }
+ A1 interface{ a(D1) }
+ B1 interface{ A1 }
+ C1 interface{ B1 }
+ D1 interface{ C1 }
+)
+
+var _ A1 = C1(nil)
+
+
+// derived test case from issue #22701
+
+func F(x I4) interface{} {
+ return x.Method()
+}
+
+type Unused interface {
+ RefersToI1(a I1)
+}
+
+type I1 interface {
+ I2
+ I3
+}
+
+type I2 interface {
+ RefersToI4() I4
+}
+
+type I3 interface {
+ Method() interface{}
+}
+
+type I4 interface {
+ I1
+}
+
+
+// check embedding of error interface
+
+type Error interface{ error }
+
+var err Error
+var _ = err.Error()
+
+
+// more esoteric cases
+
+type (
+ T1 interface { T2 }
+ T2 /* ERROR "invalid recursive type" */ T2
+)
+
+type (
+ T3 interface { T4 }
+ T4 /* ERROR "invalid recursive type" */ T5
+ T5 = T6
+ T6 = T7
+ T7 = T4
+)
+
+
+// arbitrary code may appear inside an interface
+
+const n = unsafe.Sizeof(func(){})
+
+type I interface {
+ m([unsafe.Sizeof(func() { I.m(nil, [n]byte{}) })]byte)
+}
+
+
+// test cases for varias alias cycles
+
+type T10 /* ERROR "invalid recursive type" */ = *T10 // issue #25141
+type T11 /* ERROR "invalid recursive type" */ = interface{ f(T11) } // issue #23139
+
+// issue #18640
+type (
+ aa = bb
+ bb struct {
+ *aa
+ }
+)
+
+type (
+ a struct{ *b }
+ b = c
+ c struct{ *b /* ERROR "invalid use of type alias" */ }
+)
+
+// issue #24939
+type (
+ _ interface {
+ M(P)
+ }
+
+ M interface {
+ F() P // ERROR "invalid use of type alias"
+ }
+
+ P = interface {
+ I() M
+ }
+)
+
+// issue #8699
+type T12 /* ERROR "invalid recursive type" */ [len(a12)]int
+var a12 = makeArray()
+func makeArray() (res T12) { return }
+
+// issue #20770
+var r /* ERROR "invalid cycle in declaration of r" */ = newReader()
+func newReader() r
+
+// variations of the theme of #8699 and #20770
+var arr /* ERROR "cycle" */ = f()
+func f() [len(arr)]int
+
+// issue #25790
+func ff(ff /* ERROR "not a type" */ )
+func gg((gg /* ERROR "not a type" */ ))
+
+type T13 /* ERROR "invalid recursive type T13" */ [len(b13)]int
+var b13 T13
+
+func g1() [unsafe.Sizeof(g1)]int
+func g2() [unsafe.Sizeof(x2)]int
+var x2 = g2
+
+// verify that we get the correct sizes for the functions above
+// (note: assert is statically evaluated in go/types test mode)
+func init() {
+ assert(unsafe.Sizeof(g1) == 8)
+ assert(unsafe.Sizeof(x2) == 8)
+}
+
+func h() [h /* ERROR "no value" */ ()[0]]int { panic(0) }
+
+var c14 /* ERROR "cycle" */ T14
+type T14 [uintptr(unsafe.Sizeof(&c14))]byte
+
+// issue #34333
+type T15 /* ERROR "invalid recursive type T15" */ struct {
+ f func() T16
+ b T16
+}
+
+type T16 struct {
+ T15
+}
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5a.go
new file mode 100644
index 0000000000000000000000000000000000000000..ed5853e3f239321581375d7bf315b7968a021e10
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/cycles5a.go
@@ -0,0 +1,202 @@
+// -gotypesalias=1
+
+// 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 p
+
+import "unsafe"
+
+// test case from issue #18395
+
+type (
+ A interface { B }
+ B interface { C }
+ C interface { D; F() A }
+ D interface { G() B }
+)
+
+var _ = A(nil).G // G must be found
+
+
+// test case from issue #21804
+
+type sourceBridge interface {
+ listVersions() ([]Version, error)
+}
+
+type Constraint interface {
+ copyTo(*ConstraintMsg)
+}
+
+type ConstraintMsg struct{}
+
+func (m *ConstraintMsg) asUnpairedVersion() UnpairedVersion {
+ return nil
+}
+
+type Version interface {
+ Constraint
+}
+
+type UnpairedVersion interface {
+ Version
+}
+
+var _ Constraint = UnpairedVersion(nil)
+
+
+// derived test case from issue #21804
+
+type (
+ _ interface{ m(B1) }
+ A1 interface{ a(D1) }
+ B1 interface{ A1 }
+ C1 interface{ B1 }
+ D1 interface{ C1 }
+)
+
+var _ A1 = C1(nil)
+
+
+// derived test case from issue #22701
+
+func F(x I4) interface{} {
+ return x.Method()
+}
+
+type Unused interface {
+ RefersToI1(a I1)
+}
+
+type I1 interface {
+ I2
+ I3
+}
+
+type I2 interface {
+ RefersToI4() I4
+}
+
+type I3 interface {
+ Method() interface{}
+}
+
+type I4 interface {
+ I1
+}
+
+
+// check embedding of error interface
+
+type Error interface{ error }
+
+var err Error
+var _ = err.Error()
+
+
+// more esoteric cases
+
+type (
+ T1 interface { T2 }
+ T2 /* ERROR "invalid recursive type" */ T2
+)
+
+type (
+ T3 interface { T4 }
+ T4 /* ERROR "invalid recursive type" */ T5
+ T5 = T6
+ T6 = T7
+ T7 = T4
+)
+
+
+// arbitrary code may appear inside an interface
+
+const n = unsafe.Sizeof(func(){})
+
+type I interface {
+ m([unsafe.Sizeof(func() { I.m(nil, [n]byte{}) })]byte)
+}
+
+
+// test cases for varias alias cycles
+
+type T10 /* ERROR "invalid recursive type" */ = *T10 // issue #25141
+type T11 /* ERROR "invalid recursive type" */ = interface{ f(T11) } // issue #23139
+
+// issue #18640
+type (
+ aa = bb
+ bb struct {
+ *aa
+ }
+)
+
+type (
+ a struct{ *b }
+ b = c
+ c struct{ *b }
+)
+
+// issue #24939
+type (
+ _ interface {
+ M(P)
+ }
+
+ M interface {
+ F() P
+ }
+
+ P = interface {
+ I() M
+ }
+)
+
+// issue #8699
+type T12 /* ERROR "invalid recursive type" */ [len(a12)]int
+var a12 = makeArray()
+func makeArray() (res T12) { return }
+
+// issue #20770
+var r /* ERROR "invalid cycle in declaration of r" */ = newReader()
+func newReader() r
+
+// variations of the theme of #8699 and #20770
+var arr /* ERROR "cycle" */ = f()
+func f() [len(arr)]int
+
+// issue #25790
+func ff(ff /* ERROR "not a type" */ )
+func gg((gg /* ERROR "not a type" */ ))
+
+type T13 /* ERROR "invalid recursive type T13" */ [len(b13)]int
+var b13 T13
+
+func g1() [unsafe.Sizeof(g1)]int
+func g2() [unsafe.Sizeof(x2)]int
+var x2 = g2
+
+// verify that we get the correct sizes for the functions above
+// (note: assert is statically evaluated in go/types test mode)
+func init() {
+ assert(unsafe.Sizeof(g1) == 8)
+ assert(unsafe.Sizeof(x2) == 8)
+}
+
+func h() [h /* ERROR "no value" */ ()[0]]int { panic(0) }
+
+var c14 /* ERROR "cycle" */ T14
+type T14 [uintptr(unsafe.Sizeof(&c14))]byte
+
+// issue #34333
+type T15 /* ERROR "invalid recursive type T15" */ struct {
+ f func() T16
+ b T16
+}
+
+type T16 struct {
+ T15
+}
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls0.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b99faab19289a1aa7483f3f692b5343922949cd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls0.go
@@ -0,0 +1,210 @@
+// -lang=go1.17
+
+// 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.
+
+// type declarations
+
+package p // don't permit non-interface elements in interfaces
+
+import "unsafe"
+
+const pi = 3.1415
+
+type (
+ N undefined /* ERROR "undefined" */
+ B bool
+ I int32
+ A [10]P
+ T struct {
+ x, y P
+ }
+ P *T
+ R (*R)
+ F func(A) I
+ Y interface {
+ f(A) I
+ }
+ S [](((P)))
+ M map[I]F
+ C chan<- I
+
+ // blank types must be typechecked
+ _ pi /* ERROR "not a type" */
+ _ struct{}
+ _ struct{ pi /* ERROR "not a type" */ }
+)
+
+
+// declarations of init
+const _, init /* ERROR "cannot declare init" */ , _ = 0, 1, 2
+type init /* ERROR "cannot declare init" */ struct{}
+var _, init /* ERROR "cannot declare init" */ int
+
+func init() {}
+func init /* ERROR "missing function body" */ ()
+
+func _() { const init = 0 }
+func _() { type init int }
+func _() { var init int; _ = init }
+
+// invalid array types
+type (
+ iA0 [... /* ERROR "invalid use of [...] array" */ ]byte
+ // The error message below could be better. At the moment
+ // we believe an integer that is too large is not an integer.
+ // But at least we get an error.
+ iA1 [1 /* ERROR "invalid array length" */ <<100]int
+ iA2 [- /* ERROR "invalid array length" */ 1]complex128
+ iA3 ["foo" /* ERROR "must be integer" */ ]string
+ iA4 [float64 /* ERROR "must be integer" */ (0)]int
+)
+
+
+type (
+ p1 pi.foo /* ERROR "pi.foo is not a type" */
+ p2 unsafe.Pointer
+)
+
+
+type (
+ Pi pi /* ERROR "not a type" */
+
+ a /* ERROR "invalid recursive type" */ a
+ a /* ERROR "redeclared" */ int
+
+ b /* ERROR "invalid recursive type" */ c
+ c d
+ d e
+ e b
+
+ t *t
+
+ U V
+ V *W
+ W U
+
+ P1 *S2
+ P2 P1
+
+ S0 struct {
+ }
+ S1 struct {
+ a, b, c int
+ u, v, a /* ERROR "redeclared" */ float32
+ }
+ S2 struct {
+ S0 // embedded field
+ S0 /* ERROR "redeclared" */ int
+ }
+ S3 struct {
+ x S2
+ }
+ S4/* ERROR "invalid recursive type" */ struct {
+ S4
+ }
+ S5 /* ERROR "invalid recursive type" */ struct {
+ S6
+ }
+ S6 struct {
+ field S7
+ }
+ S7 struct {
+ S5
+ }
+
+ L1 []L1
+ L2 []int
+
+ A1 [10.0]int
+ A2 /* ERROR "invalid recursive type" */ [10]A2
+ A3 /* ERROR "invalid recursive type" */ [10]struct {
+ x A4
+ }
+ A4 [10]A3
+
+ F1 func()
+ F2 func(x, y, z float32)
+ F3 func(x, y, x /* ERROR "redeclared" */ float32)
+ F4 func() (x, y, x /* ERROR "redeclared" */ float32)
+ F5 func(x int) (x /* ERROR "redeclared" */ float32)
+ F6 func(x ...int)
+
+ I1 interface{}
+ I2 interface {
+ m1()
+ }
+ I3 interface {
+ m1()
+ m1 /* ERROR "duplicate method" */ ()
+ }
+ I4 interface {
+ m1(x, y, x /* ERROR "redeclared" */ float32)
+ m2() (x, y, x /* ERROR "redeclared" */ float32)
+ m3(x int) (x /* ERROR "redeclared" */ float32)
+ }
+ I5 interface {
+ m1(I5)
+ }
+ I6 interface {
+ S0 /* ERROR "non-interface type S0" */
+ }
+ I7 interface {
+ I1
+ I1
+ }
+ I8 /* ERROR "invalid recursive type" */ interface {
+ I8
+ }
+ I9 /* ERROR "invalid recursive type" */ interface {
+ I10
+ }
+ I10 interface {
+ I11
+ }
+ I11 interface {
+ I9
+ }
+
+ C1 chan int
+ C2 <-chan int
+ C3 chan<- C3
+ C4 chan C5
+ C5 chan C6
+ C6 chan C4
+
+ M1 map[Last]string
+ M2 map[string]M2
+
+ Last int
+)
+
+// cycles in function/method declarations
+// (test cases for issues #5217, #25790 and variants)
+func f1(x f1 /* ERROR "not a type" */ ) {}
+func f2(x *f2 /* ERROR "not a type" */ ) {}
+func f3() (x f3 /* ERROR "not a type" */ ) { return }
+func f4() (x *f4 /* ERROR "not a type" */ ) { return }
+// TODO(#43215) this should be detected as a cycle error
+func f5([unsafe.Sizeof(f5)]int) {}
+
+func (S0) m1 (x S0.m1 /* ERROR "S0.m1 is not a type" */ ) {}
+func (S0) m2 (x *S0.m2 /* ERROR "S0.m2 is not a type" */ ) {}
+func (S0) m3 () (x S0.m3 /* ERROR "S0.m3 is not a type" */ ) { return }
+func (S0) m4 () (x *S0.m4 /* ERROR "S0.m4 is not a type" */ ) { return }
+
+// interfaces may not have any blank methods
+type BlankI interface {
+ _ /* ERROR "methods must have a unique non-blank name" */ ()
+ _ /* ERROR "methods must have a unique non-blank name" */ (float32) int
+ m()
+}
+
+// non-interface types may have multiple blank methods
+type BlankT struct{}
+
+func (BlankT) _() {}
+func (BlankT) _(int) {}
+func (BlankT) _() int { return 0 }
+func (BlankT) _(int) int { return 0}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls1.go
new file mode 100644
index 0000000000000000000000000000000000000000..06f3b2e6cbf8fdd741b71f2ccd299f757e7d3468
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls1.go
@@ -0,0 +1,146 @@
+// 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.
+
+// variable declarations
+
+package decls1
+
+import (
+ "math"
+)
+
+// Global variables without initialization
+var (
+ a, b bool
+ c byte
+ d uint8
+ r rune
+ i int
+ j, k, l int
+ x, y float32
+ xx, yy float64
+ u, v complex64
+ uu, vv complex128
+ s, t string
+ array []byte
+ iface interface{}
+
+ blank _ /* ERROR "cannot use _" */
+)
+
+// Global variables with initialization
+var (
+ s1 = i + j
+ s2 = i /* ERROR "mismatched types" */ + x
+ s3 = c + d
+ s4 = s + t
+ s5 = s /* ERROR "invalid operation" */ / t
+ s6 = array[t1]
+ s7 = array[x /* ERROR "integer" */]
+ s8 = &a
+ s10 = &42 /* ERROR "cannot take address" */
+ s11 = &v
+ s12 = -(u + *t11) / *&v
+ s13 = a /* ERROR "shifted operand" */ << d
+ s14 = i << j
+ s18 = math.Pi * 10.0
+ s19 = s1 /* ERROR "cannot call" */ ()
+ s20 = f0 /* ERROR "no value" */ ()
+ s21 = f6(1, s1, i)
+ s22 = f6(1, s1, uu /* ERRORx `cannot use .* in argument` */ )
+
+ t1 int = i + j
+ t2 int = i /* ERROR "mismatched types" */ + x
+ t3 int = c /* ERRORx `cannot use .* variable declaration` */ + d
+ t4 string = s + t
+ t5 string = s /* ERROR "invalid operation" */ / t
+ t6 byte = array[t1]
+ t7 byte = array[x /* ERROR "must be integer" */]
+ t8 *int = & /* ERRORx `cannot use .* variable declaration` */ a
+ t10 *int = &42 /* ERROR "cannot take address" */
+ t11 *complex64 = &v
+ t12 complex64 = -(u + *t11) / *&v
+ t13 int = a /* ERROR "shifted operand" */ << d
+ t14 int = i << j
+ t15 math /* ERROR "not in selector" */
+ t16 math.xxx /* ERROR "undefined" */
+ t17 math /* ERROR "not a type" */ .Pi
+ t18 float64 = math.Pi * 10.0
+ t19 int = t1 /* ERROR "cannot call" */ ()
+ t20 int = f0 /* ERROR "no value" */ ()
+ t21 int = a /* ERRORx `cannot use .* variable declaration` */
+)
+
+// Various more complex expressions
+var (
+ u1 = x /* ERROR "not an interface" */ .(int)
+ u2 = iface.([]int)
+ u3 = iface.(a /* ERROR "not a type" */ )
+ u4, ok = iface.(int)
+ u5, ok2, ok3 = iface /* ERROR "assignment mismatch" */ .(int)
+)
+
+// Constant expression initializations
+var (
+ v1 = 1 /* ERROR "mismatched types untyped int and untyped string" */ + "foo"
+ v2 = c + 255
+ v3 = c + 256 /* ERROR "overflows" */
+ v4 = r + 2147483647
+ v5 = r + 2147483648 /* ERROR "overflows" */
+ v6 = 42
+ v7 = v6 + 9223372036854775807
+ v8 = v6 + 9223372036854775808 /* ERROR "overflows" */
+ v9 = i + 1 << 10
+ v10 byte = 1024 /* ERROR "overflows" */
+ v11 = xx/yy*yy - xx
+ v12 = true && false
+ v13 = nil /* ERROR "use of untyped nil" */
+ v14 string = 257 // ERRORx `cannot use 257 .* as string value in variable declaration$`
+ v15 int8 = 257 // ERRORx `cannot use 257 .* as int8 value in variable declaration .*overflows`
+)
+
+// Multiple assignment expressions
+var (
+ m1a, m1b = 1, 2
+ m2a, m2b, m2c /* ERROR "missing init expr for m2c" */ = 1, 2
+ m3a, m3b = 1, 2, 3 /* ERROR "extra init expr 3" */
+)
+
+func _() {
+ var (
+ m1a, m1b = 1, 2
+ m2a, m2b, m2c /* ERROR "missing init expr for m2c" */ = 1, 2
+ m3a, m3b = 1, 2, 3 /* ERROR "extra init expr 3" */
+ )
+
+ _, _ = m1a, m1b
+ _, _, _ = m2a, m2b, m2c
+ _, _ = m3a, m3b
+}
+
+// Declaration of parameters and results
+func f0() {}
+func f1(a /* ERROR "not a type" */) {}
+func f2(a, b, c d /* ERROR "not a type" */) {}
+
+func f3() int { return 0 }
+func f4() a /* ERROR "not a type" */ { return 0 }
+func f5() (a, b, c d /* ERROR "not a type" */) { return }
+
+func f6(a, b, c int) complex128 { return 0 }
+
+// Declaration of receivers
+type T struct{}
+
+func (T) m0() {}
+func (*T) m1() {}
+func (x T) m2() {}
+func (x *T) m3() {}
+
+// Initialization functions
+func init() {}
+func init /* ERROR "no arguments and no return values" */ (int) {}
+func init /* ERROR "no arguments and no return values" */ () int { return 0 }
+func init /* ERROR "no arguments and no return values" */ (int) int { return 0 }
+func (T) init(int) int { return 0 }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2a.go
new file mode 100644
index 0000000000000000000000000000000000000000..c2fb421b9611d7fc050db02b38526df64fa99fad
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2a.go
@@ -0,0 +1,111 @@
+// 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.
+
+// method declarations
+
+package decls2
+
+import "time"
+import "unsafe"
+
+// T1 declared before its methods.
+type T1 struct{
+ f int
+}
+
+func (T1) m() {}
+func (T1) m /* ERROR "already declared" */ () {}
+func (x *T1) f /* ERROR "field and method" */ () {}
+
+// Conflict between embedded field and method name,
+// with the embedded field being a basic type.
+type T1b struct {
+ int
+}
+
+func (T1b) int /* ERROR "field and method" */ () {}
+
+type T1c struct {
+ time.Time
+}
+
+func (T1c) Time /* ERROR "field and method" */ () int { return 0 }
+
+// Disabled for now: LookupFieldOrMethod will find Pointer even though
+// it's double-declared (it would cost extra in the common case to verify
+// this). But the MethodSet computation will not find it due to the name
+// collision caused by the double-declaration, leading to an internal
+// inconsistency while we are verifying one computation against the other.
+// var _ = T1c{}.Pointer
+
+// T2's method declared before the type.
+func (*T2) f /* ERROR "field and method" */ () {}
+
+type T2 struct {
+ f int
+}
+
+// Methods declared without a declared type.
+func (undefined /* ERROR "undefined" */) m() {}
+func (x *undefined /* ERROR "undefined" */) m() {}
+
+func (pi /* ERROR "not a type" */) m1() {}
+func (x pi /* ERROR "not a type" */) m2() {}
+func (x *pi /* ERROR "not a type" */ ) m3() {}
+
+// Blank types.
+type _ struct { m int }
+type _ struct { m int }
+
+func (_ /* ERROR "cannot use _" */) m() {}
+func m(_ /* ERROR "cannot use _" */) {}
+
+// Methods with receiver base type declared in another file.
+func (T3) m1() {}
+func (*T3) m2() {}
+func (x T3) m3() {}
+func (x *T3) f /* ERROR "field and method" */ () {}
+
+// Methods of non-struct type.
+type T4 func()
+
+func (self T4) m() func() { return self }
+
+// Methods associated with an interface.
+type T5 interface {
+ m() int
+}
+
+func (T5 /* ERROR "invalid receiver" */ ) m1() {}
+func (T5 /* ERROR "invalid receiver" */ ) m2() {}
+
+// Methods associated with a named pointer type.
+type ptr *int
+func (ptr /* ERROR "invalid receiver" */ ) _() {}
+func (* /* ERROR "invalid receiver" */ ptr) _() {}
+
+// Methods with zero or multiple receivers.
+func ( /* ERROR "method has no receiver" */ ) _() {}
+func (T3, * /* ERROR "method has multiple receivers" */ T3) _() {}
+func (T3, T3, T3 /* ERROR "method has multiple receivers" */ ) _() {}
+func (a, b /* ERROR "method has multiple receivers" */ T3) _() {}
+func (a, b, c /* ERROR "method has multiple receivers" */ T3) _() {}
+
+// Methods associated with non-local or unnamed types.
+func (int /* ERROR "cannot define new methods on non-local type int" */ ) m() {}
+func ([ /* ERROR "invalid receiver" */ ]int) m() {}
+func (time /* ERROR "cannot define new methods on non-local type time.Time" */ .Time) m() {}
+func (* /* ERROR "cannot define new methods on non-local type time.Time" */ time.Time) m() {}
+func (x /* ERROR "invalid receiver" */ interface{}) m() {}
+
+// Unsafe.Pointer is treated like a pointer when used as receiver type.
+type UP unsafe.Pointer
+func (UP /* ERROR "invalid" */ ) m1() {}
+func (* /* ERROR "invalid" */ UP) m2() {}
+
+// Double declarations across package files
+const c_double = 0
+type t_double int
+var v_double int
+func f_double() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2b.go
new file mode 100644
index 0000000000000000000000000000000000000000..dd6cd44d99265b1b8bd80098c9cb5ade14fab0d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls2/decls2b.go
@@ -0,0 +1,75 @@
+// 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.
+
+// method declarations
+
+package decls2
+
+import "io"
+
+const pi = 3.1415
+
+func (T1) m /* ERROR "already declared" */ () {}
+func (T2) m(io.Writer) {}
+
+type T3 struct {
+ f *T3
+}
+
+type T6 struct {
+ x int
+}
+
+func (t *T6) m1() int {
+ return t.x
+}
+
+func f() {
+ var t *T6
+ t.m1()
+}
+
+// Double declarations across package files
+const c_double /* ERROR "redeclared" */ = 0
+type t_double /* ERROR "redeclared" */ int
+var v_double /* ERROR "redeclared" */ int
+func f_double /* ERROR "redeclared" */ () {}
+
+// Blank methods need to be type-checked.
+// Verify by checking that errors are reported.
+func (T /* ERROR "undefined" */ ) _() {}
+func (T1) _(undefined /* ERROR "undefined" */ ) {}
+func (T1) _() int { return "foo" /* ERRORx "cannot use .* in return statement" */ }
+
+// Methods with undefined receiver type can still be checked.
+// Verify by checking that errors are reported.
+func (Foo /* ERROR "undefined" */ ) m() {}
+func (Foo /* ERROR "undefined" */ ) m(undefined /* ERROR "undefined" */ ) {}
+func (Foo /* ERRORx `undefined` */ ) m() int { return "foo" /* ERRORx "cannot use .* in return statement" */ }
+
+func (Foo /* ERROR "undefined" */ ) _() {}
+func (Foo /* ERROR "undefined" */ ) _(undefined /* ERROR "undefined" */ ) {}
+func (Foo /* ERROR "undefined" */ ) _() int { return "foo" /* ERRORx "cannot use .* in return statement" */ }
+
+// Receiver declarations are regular parameter lists;
+// receiver types may use parentheses, and the list
+// may have a trailing comma.
+type T7 struct {}
+
+func (T7) m1() {}
+func ((T7)) m2() {}
+func ((*T7)) m3() {}
+func (x *(T7),) m4() {}
+func (x (*(T7)),) m5() {}
+func (x ((*((T7)))),) m6() {}
+
+// Check that methods with parenthesized receiver are actually present (issue #23130).
+var (
+ _ = T7.m1
+ _ = T7.m2
+ _ = (*T7).m3
+ _ = (*T7).m4
+ _ = (*T7).m5
+ _ = (*T7).m6
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls3.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls3.go
new file mode 100644
index 0000000000000000000000000000000000000000..3d00a580ab922caa9f29c0c92e9637a758e617b9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls3.go
@@ -0,0 +1,309 @@
+// 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.
+
+// embedded types
+
+package decls3
+
+import "unsafe"
+import "fmt"
+
+// fields with the same name at the same level cancel each other out
+
+func _() {
+ type (
+ T1 struct { X int }
+ T2 struct { X int }
+ T3 struct { T1; T2 } // X is embedded twice at the same level via T1->X, T2->X
+ )
+
+ var t T3
+ _ = t.X /* ERROR "ambiguous selector t.X" */
+}
+
+func _() {
+ type (
+ T1 struct { X int }
+ T2 struct { T1 }
+ T3 struct { T1 }
+ T4 struct { T2; T3 } // X is embedded twice at the same level via T2->T1->X, T3->T1->X
+ )
+
+ var t T4
+ _ = t.X /* ERROR "ambiguous selector t.X" */
+}
+
+func issue4355() {
+ type (
+ T1 struct {X int}
+ T2 struct {T1}
+ T3 struct {T2}
+ T4 struct {T2}
+ T5 struct {T3; T4} // X is embedded twice at the same level via T3->T2->T1->X, T4->T2->T1->X
+ )
+
+ var t T5
+ _ = t.X /* ERROR "ambiguous selector t.X" */
+}
+
+func _() {
+ type State int
+ type A struct{ State }
+ type B struct{ fmt.State }
+ type T struct{ A; B }
+
+ var t T
+ _ = t.State /* ERROR "ambiguous selector t.State" */
+}
+
+// Embedded fields can be predeclared types.
+
+func _() {
+ type T0 struct{
+ int
+ float32
+ f int
+ }
+ var x T0
+ _ = x.int
+ _ = x.float32
+ _ = x.f
+
+ type T1 struct{
+ T0
+ }
+ var y T1
+ _ = y.int
+ _ = y.float32
+ _ = y.f
+}
+
+// Restrictions on embedded field types.
+
+func _() {
+ type I1 interface{}
+ type I2 interface{}
+ type P1 *int
+ type P2 *int
+ type UP unsafe.Pointer
+
+ type T1 struct {
+ I1
+ * /* ERROR "cannot be a pointer to an interface" */ I2
+ * /* ERROR "cannot be a pointer to an interface" */ error
+ P1 /* ERROR "cannot be a pointer" */
+ * /* ERROR "cannot be a pointer" */ P2
+ }
+
+ // unsafe.Pointers are treated like regular pointers when embedded
+ type T2 struct {
+ unsafe /* ERROR "cannot be unsafe.Pointer" */ .Pointer
+ */* ERROR "cannot be unsafe.Pointer" */ unsafe.Pointer /* ERROR "Pointer redeclared" */
+ UP /* ERROR "cannot be unsafe.Pointer" */
+ * /* ERROR "cannot be unsafe.Pointer" */ UP /* ERROR "UP redeclared" */
+ }
+}
+
+// Named types that are pointers.
+
+type S struct{ x int }
+func (*S) m() {}
+type P *S
+
+func _() {
+ var s *S
+ _ = s.x
+ _ = s.m
+
+ var p P
+ _ = p.x
+ _ = p.m /* ERROR "no field or method" */
+ _ = P.m /* ERROR "no field or method" */
+}
+
+// Borrowed from the FieldByName test cases in reflect/all_test.go.
+
+type D1 struct {
+ d int
+}
+type D2 struct {
+ d int
+}
+
+type S0 struct {
+ A, B, C int
+ D1
+ D2
+}
+
+type S1 struct {
+ B int
+ S0
+}
+
+type S2 struct {
+ A int
+ *S1
+}
+
+type S1x struct {
+ S1
+}
+
+type S1y struct {
+ S1
+}
+
+type S3 struct {
+ S1x
+ S2
+ D, E int
+ *S1y
+}
+
+type S4 struct {
+ *S4
+ A int
+}
+
+// The X in S6 and S7 annihilate, but they also block the X in S8.S9.
+type S5 struct {
+ S6
+ S7
+ S8
+}
+
+type S6 struct {
+ X int
+}
+
+type S7 S6
+
+type S8 struct {
+ S9
+}
+
+type S9 struct {
+ X int
+ Y int
+}
+
+// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
+type S10 struct {
+ S11
+ S12
+ S13
+}
+
+type S11 struct {
+ S6
+}
+
+type S12 struct {
+ S6
+}
+
+type S13 struct {
+ S8
+}
+
+func _() {
+ _ = struct{}{}.Foo /* ERROR "no field or method" */
+ _ = S0{}.A
+ _ = S0{}.D /* ERROR "no field or method" */
+ _ = S1{}.A
+ _ = S1{}.B
+ _ = S1{}.S0
+ _ = S1{}.C
+ _ = S2{}.A
+ _ = S2{}.S1
+ _ = S2{}.B
+ _ = S2{}.C
+ _ = S2{}.D /* ERROR "no field or method" */
+ _ = S3{}.S1 /* ERROR "ambiguous selector S3{}.S1" */
+ _ = S3{}.A
+ _ = S3{}.B /* ERROR "ambiguous selector S3{}.B" */
+ _ = S3{}.D
+ _ = S3{}.E
+ _ = S4{}.A
+ _ = S4{}.B /* ERROR "no field or method" */
+ _ = S5{}.X /* ERROR "ambiguous selector S5{}.X" */
+ _ = S5{}.Y
+ _ = S10{}.X /* ERROR "ambiguous selector S10{}.X" */
+ _ = S10{}.Y
+}
+
+// Borrowed from the FieldByName benchmark in reflect/all_test.go.
+
+type R0 struct {
+ *R1
+ *R2
+ *R3
+ *R4
+}
+
+type R1 struct {
+ *R5
+ *R6
+ *R7
+ *R8
+}
+
+type R2 R1
+type R3 R1
+type R4 R1
+
+type R5 struct {
+ *R9
+ *R10
+ *R11
+ *R12
+}
+
+type R6 R5
+type R7 R5
+type R8 R5
+
+type R9 struct {
+ *R13
+ *R14
+ *R15
+ *R16
+}
+
+type R10 R9
+type R11 R9
+type R12 R9
+
+type R13 struct {
+ *R17
+ *R18
+ *R19
+ *R20
+}
+
+type R14 R13
+type R15 R13
+type R16 R13
+
+type R17 struct {
+ *R21
+ *R22
+ *R23
+ *R24
+}
+
+type R18 R17
+type R19 R17
+type R20 R17
+
+type R21 struct {
+ X int
+}
+
+type R22 R21
+type R23 R21
+type R24 R21
+
+var _ = R0{}.X /* ERROR "ambiguous selector R0{}.X" */
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls4.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls4.go
new file mode 100644
index 0000000000000000000000000000000000000000..7c063904c8a0d9dec9868e1b4ab23b952790eab7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls4.go
@@ -0,0 +1,199 @@
+// 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.
+
+// type aliases
+
+package decls4
+
+type (
+ T0 [10]int
+ T1 []byte
+ T2 struct {
+ x int
+ }
+ T3 interface{
+ m() T2
+ }
+ T4 func(int, T0) chan T2
+)
+
+type (
+ Ai = int
+ A0 = T0
+ A1 = T1
+ A2 = T2
+ A3 = T3
+ A4 = T4
+
+ A10 = [10]int
+ A11 = []byte
+ A12 = struct {
+ x int
+ }
+ A13 = interface{
+ m() A2
+ }
+ A14 = func(int, A0) chan A2
+)
+
+// check assignment compatibility due to equality of types
+var (
+ xi_ int
+ ai Ai = xi_
+
+ x0 T0
+ a0 A0 = x0
+
+ x1 T1
+ a1 A1 = x1
+
+ x2 T2
+ a2 A2 = x2
+
+ x3 T3
+ a3 A3 = x3
+
+ x4 T4
+ a4 A4 = x4
+)
+
+// alias receiver types
+func (Ai /* ERRORx "cannot define new methods on non-local type (int|Ai)" */) m1() {}
+func (T0) m1() {}
+func (A0) m1 /* ERROR "already declared" */ () {}
+func (A0) m2 () {}
+func (A3 /* ERROR "invalid receiver" */ ) m1 () {}
+func (A10 /* ERROR "invalid receiver" */ ) m1() {}
+
+// x0 has methods m1, m2 declared via receiver type names T0 and A0
+var _ interface{ m1(); m2() } = x0
+
+// alias receiver types (test case for issue #23042)
+type T struct{}
+
+var (
+ _ = T.m
+ _ = T{}.m
+ _ interface{m()} = T{}
+)
+
+var (
+ _ = T.n
+ _ = T{}.n
+ _ interface{m(); n()} = T{}
+)
+
+type U = T
+func (U) m() {}
+
+// alias receiver types (long type declaration chains)
+type (
+ V0 = V1
+ V1 = (V2)
+ V2 = ((V3))
+ V3 = T
+)
+
+func (V0) m /* ERROR "already declared" */ () {}
+func (V1) n() {}
+
+// alias receiver types (invalid due to cycles)
+type (
+ W0 /* ERROR "invalid recursive type" */ = W1
+ W1 = (W2)
+ W2 = ((W0))
+)
+
+func (W0) m() {} // no error expected (due to above cycle error)
+func (W1) n() {}
+
+// alias receiver types (invalid due to builtin underlying type)
+type (
+ B0 = B1
+ B1 = B2
+ B2 = int
+)
+
+func (B0 /* ERRORx "cannot define new methods on non-local type (int|B)" */ ) m() {}
+func (B1 /* ERRORx "cannot define new methods on non-local type (int|B)" */ ) n() {}
+
+// cycles
+type (
+ C2 /* ERROR "invalid recursive type" */ = C2
+ C3 /* ERROR "invalid recursive type" */ = C4
+ C4 = C3
+ C5 struct {
+ f *C6
+ }
+ C6 = C5
+ C7 /* ERROR "invalid recursive type" */ struct {
+ f C8
+ }
+ C8 = C7
+)
+
+// embedded fields
+var (
+ s0 struct { T0 }
+ s1 struct { A0 } = s0 /* ERROR "cannot use" */ // embedded field names are different
+)
+
+// embedding and lookup of fields and methods
+func _(s struct{A0}) { s.A0 = x0 }
+
+type eX struct{xf int}
+
+func (eX) xm()
+
+type eY = struct{eX} // field/method set of eY includes xf, xm
+
+type eZ = *struct{eX} // field/method set of eZ includes xf, xm
+
+type eA struct {
+ eX // eX contributes xf, xm to eA
+}
+
+type eA2 struct {
+ *eX // *eX contributes xf, xm to eA
+}
+
+type eB struct {
+ eY // eY contributes xf, xm to eB
+}
+
+type eB2 struct {
+ *eY // *eY contributes xf, xm to eB
+}
+
+type eC struct {
+ eZ // eZ contributes xf, xm to eC
+}
+
+var (
+ _ = eA{}.xf
+ _ = eA{}.xm
+ _ = eA2{}.xf
+ _ = eA2{}.xm
+ _ = eB{}.xf
+ _ = eB{}.xm
+ _ = eB2{}.xf
+ _ = eB2{}.xm
+ _ = eC{}.xf
+ _ = eC{}.xm
+)
+
+// ambiguous selectors due to embedding via type aliases
+type eD struct {
+ eY
+ eZ
+}
+
+var (
+ _ = eD{}.xf /* ERROR "ambiguous selector eD{}.xf" */
+ _ = eD{}.xm /* ERROR "ambiguous selector eD{}.xm" */
+)
+
+var (
+ _ interface{ xm() } = eD /* ERROR "ambiguous selector eD.xm" */ {}
+)
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls5.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls5.go
new file mode 100644
index 0000000000000000000000000000000000000000..88d31946da44b7c832f84611648c894f31a8d451
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/decls5.go
@@ -0,0 +1,10 @@
+// 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 main
+
+// declarations of main
+const _, main /* ERROR "cannot declare main" */ , _ = 0, 1, 2
+type main /* ERROR "cannot declare main" */ struct{}
+var _, main /* ERROR "cannot declare main" */ int
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/errors.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/errors.go
new file mode 100644
index 0000000000000000000000000000000000000000..10b6a22eb1b880fcdaf5b349999ab56ffd44d08d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/errors.go
@@ -0,0 +1,66 @@
+// 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 errors
+
+// Testing precise operand formatting in error messages
+// (matching messages are regular expressions, hence the \'s).
+func f(x int, m map[string]int) {
+ // no values
+ _ = f /* ERROR "f(0, m) (no value) used as value" */ (0, m)
+
+ // built-ins
+ _ = println // ERROR "println (built-in) must be called"
+
+ // types
+ _ = complex128 // ERROR "complex128 (type) is not an expression"
+
+ // constants
+ const c1 = 991
+ const c2 float32 = 0.5
+ const c3 = "foo"
+ 0 // ERROR "0 (untyped int constant) is not used"
+ 0.5 // ERROR "0.5 (untyped float constant) is not used"
+ "foo" // ERROR `"foo" (untyped string constant) is not used`
+ c1 // ERROR "c1 (untyped int constant 991) is not used"
+ c2 // ERROR "c2 (constant 0.5 of type float32) is not used"
+ c1 /* ERROR "c1 + c2 (constant 991.5 of type float32) is not used" */ + c2
+ c3 // ERROR `c3 (untyped string constant "foo") is not used`
+
+ // variables
+ x // ERROR "x (variable of type int) is not used"
+
+ // values
+ nil // ERROR "nil is not used"
+ ( /* ERROR "(*int)(nil) (value of type *int) is not used" */ *int)(nil)
+ x /* ERROR "x != x (untyped bool value) is not used" */ != x
+ x /* ERROR "x + x (value of type int) is not used" */ + x
+
+ // value, ok's
+ const s = "foo"
+ m /* ERROR "m[s] (map index expression of type int) is not used" */ [s]
+}
+
+// Valid ERROR comments can have a variety of forms.
+func _() {
+ 0 /* ERRORx "0 .* is not used" */
+ 0 /* ERRORx "0 .* is not used" */
+ 0 // ERRORx "0 .* is not used"
+ 0 // ERRORx "0 .* is not used"
+}
+
+// Don't report spurious errors as a consequence of earlier errors.
+// Add more tests as needed.
+func _() {
+ if err := foo /* ERROR "undefined" */ (); err != nil /* "no error here" */ {}
+}
+
+// Use unqualified names for package-local objects.
+type T struct{}
+var _ int = T /* ERROR "value of type T" */ {} // use T in error message rather than errors.T
+
+// Don't report errors containing "invalid type" (issue #24182).
+func _(x *missing /* ERROR "undefined: missing" */ ) {
+ x.m() // there shouldn't be an error here referring to *invalid type
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr0.go
new file mode 100644
index 0000000000000000000000000000000000000000..26dc58958fe7ad858b3f7af8561960e6b1cce90e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr0.go
@@ -0,0 +1,196 @@
+// 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.
+
+// unary expressions
+
+package expr0
+
+type mybool bool
+
+var (
+ // bool
+ b0 = true
+ b1 bool = b0
+ b2 = !true
+ b3 = !b1
+ b4 bool = !true
+ b5 bool = !b4
+ b6 = +b0 /* ERROR "not defined" */
+ b7 = -b0 /* ERROR "not defined" */
+ b8 = ^b0 /* ERROR "not defined" */
+ b9 = *b0 /* ERROR "cannot indirect" */
+ b10 = &true /* ERROR "cannot take address" */
+ b11 = &b0
+ b12 = <-b0 /* ERROR "cannot receive" */
+ b13 = & & /* ERROR "cannot take address" */ b0
+ b14 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ b0
+
+ // byte
+ _ = byte(0)
+ _ = byte(- /* ERROR "overflows" */ 1)
+ _ = - /* ERROR "-byte(1) (constant -1 of type byte) overflows byte" */ byte(1) // test for issue 11367
+ _ = byte /* ERROR "overflows byte" */ (0) - byte(1)
+ _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ byte(0)
+
+ // int
+ i0 = 1
+ i1 int = i0
+ i2 = +1
+ i3 = +i0
+ i4 int = +1
+ i5 int = +i4
+ i6 = -1
+ i7 = -i0
+ i8 int = -1
+ i9 int = -i4
+ i10 = !i0 /* ERROR "not defined" */
+ i11 = ^1
+ i12 = ^i0
+ i13 int = ^1
+ i14 int = ^i4
+ i15 = *i0 /* ERROR "cannot indirect" */
+ i16 = &i0
+ i17 = *i16
+ i18 = <-i16 /* ERROR "cannot receive" */
+ i19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ i0
+
+ // uint
+ u0 = uint(1)
+ u1 uint = u0
+ u2 = +1
+ u3 = +u0
+ u4 uint = +1
+ u5 uint = +u4
+ u6 = -1
+ u7 = -u0
+ u8 uint = - /* ERROR "overflows" */ 1
+ u9 uint = -u4
+ u10 = !u0 /* ERROR "not defined" */
+ u11 = ^1
+ u12 = ^i0
+ u13 uint = ^ /* ERROR "overflows" */ 1
+ u14 uint = ^u4
+ u15 = *u0 /* ERROR "cannot indirect" */
+ u16 = &u0
+ u17 = *u16
+ u18 = <-u16 /* ERROR "cannot receive" */
+ u19 = ^uint(0)
+ u20 = ~ /* ERROR "cannot use ~ outside of interface or type constraint (use ^ for bitwise complement)" */ u0
+
+ // float64
+ f0 = float64(1)
+ f1 float64 = f0
+ f2 = +1
+ f3 = +f0
+ f4 float64 = +1
+ f5 float64 = +f4
+ f6 = -1
+ f7 = -f0
+ f8 float64 = -1
+ f9 float64 = -f4
+ f10 = !f0 /* ERROR "not defined" */
+ f11 = ^1
+ f12 = ^i0
+ f13 float64 = ^1
+ f14 float64 = ^f4 /* ERROR "not defined" */
+ f15 = *f0 /* ERROR "cannot indirect" */
+ f16 = &f0
+ f17 = *u16
+ f18 = <-u16 /* ERROR "cannot receive" */
+ f19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ f0
+
+ // complex128
+ c0 = complex128(1)
+ c1 complex128 = c0
+ c2 = +1
+ c3 = +c0
+ c4 complex128 = +1
+ c5 complex128 = +c4
+ c6 = -1
+ c7 = -c0
+ c8 complex128 = -1
+ c9 complex128 = -c4
+ c10 = !c0 /* ERROR "not defined" */
+ c11 = ^1
+ c12 = ^i0
+ c13 complex128 = ^1
+ c14 complex128 = ^c4 /* ERROR "not defined" */
+ c15 = *c0 /* ERROR "cannot indirect" */
+ c16 = &c0
+ c17 = *u16
+ c18 = <-u16 /* ERROR "cannot receive" */
+ c19 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ c0
+
+ // string
+ s0 = "foo"
+ s1 = +"foo" /* ERROR "not defined" */
+ s2 = -s0 /* ERROR "not defined" */
+ s3 = !s0 /* ERROR "not defined" */
+ s4 = ^s0 /* ERROR "not defined" */
+ s5 = *s4
+ s6 = &s4
+ s7 = *s6
+ s8 = <-s7
+ s9 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ s0
+
+ // channel
+ ch chan int
+ rc <-chan float64
+ sc chan <- string
+ ch0 = +ch /* ERROR "not defined" */
+ ch1 = -ch /* ERROR "not defined" */
+ ch2 = !ch /* ERROR "not defined" */
+ ch3 = ^ch /* ERROR "not defined" */
+ ch4 = *ch /* ERROR "cannot indirect" */
+ ch5 = &ch
+ ch6 = *ch5
+ ch7 = <-ch
+ ch8 = <-rc
+ ch9 = <-sc /* ERROR "cannot receive" */
+ ch10, ok = <-ch
+ // ok is of type bool
+ ch11, myok = <-ch
+ _ mybool = myok /* ERRORx `cannot use .* in variable declaration` */
+ ch12 = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ ch
+
+)
+
+// address of composite literals
+type T struct{x, y int}
+
+func f() T { return T{} }
+
+var (
+ _ = &T{1, 2}
+ _ = &[...]int{}
+ _ = &[]int{}
+ _ = &[]int{}
+ _ = &map[string]T{}
+ _ = &(T{1, 2})
+ _ = &((((T{1, 2}))))
+ _ = &f /* ERROR "cannot take address" */ ()
+)
+
+// recursive pointer types
+type P *P
+
+var (
+ p1 P = new(P)
+ p2 P = *p1
+ p3 P = &p2
+)
+
+func g() (a, b int) { return }
+
+func _() {
+ _ = -g /* ERROR "multiple-value g" */ ()
+ _ = <-g /* ERROR "multiple-value g" */ ()
+}
+
+// ~ is accepted as unary operator only permitted in interface type elements
+var (
+ _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ 0
+ _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ "foo"
+ _ = ~ /* ERROR "cannot use ~ outside of interface or type constraint" */ i0
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr1.go
new file mode 100644
index 0000000000000000000000000000000000000000..1c04c8fb6e8938dae4f9c44b2d7609d218d2d285
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr1.go
@@ -0,0 +1,127 @@
+// 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.
+
+// binary expressions
+
+package expr1
+
+type mybool bool
+
+func _(x, y bool, z mybool) {
+ x = x || y
+ x = x || true
+ x = x || false
+ x = x && y
+ x = x && true
+ x = x && false
+
+ z = z /* ERROR "mismatched types" */ || y
+ z = z || true
+ z = z || false
+ z = z /* ERROR "mismatched types" */ && y
+ z = z && true
+ z = z && false
+}
+
+type myint int
+
+func _(x, y int, z myint) {
+ x = x + 1
+ x = x + 1.0
+ x = x + 1.1 // ERROR "truncated to int"
+ x = x + y
+ x = x - y
+ x = x * y
+ x = x / y
+ x = x % y
+ x = x << y
+ x = x >> y
+
+ z = z + 1
+ z = z + 1.0
+ z = z + 1.1 // ERROR "truncated to int"
+ z = z /* ERROR "mismatched types" */ + y
+ z = z /* ERROR "mismatched types" */ - y
+ z = z /* ERROR "mismatched types" */ * y
+ z = z /* ERROR "mismatched types" */ / y
+ z = z /* ERROR "mismatched types" */ % y
+ z = z << y
+ z = z >> y
+}
+
+type myuint uint
+
+func _(x, y uint, z myuint) {
+ x = x + 1
+ x = x + - /* ERROR "overflows uint" */ 1
+ x = x + 1.0
+ x = x + 1.1 // ERROR "truncated to uint"
+ x = x + y
+ x = x - y
+ x = x * y
+ x = x / y
+ x = x % y
+ x = x << y
+ x = x >> y
+
+ z = z + 1
+ z = x + - /* ERROR "overflows uint" */ 1
+ z = z + 1.0
+ z = z + 1.1 // ERROR "truncated to uint"
+ z = z /* ERROR "mismatched types" */ + y
+ z = z /* ERROR "mismatched types" */ - y
+ z = z /* ERROR "mismatched types" */ * y
+ z = z /* ERROR "mismatched types" */ / y
+ z = z /* ERROR "mismatched types" */ % y
+ z = z << y
+ z = z >> y
+}
+
+type myfloat64 float64
+
+func _(x, y float64, z myfloat64) {
+ x = x + 1
+ x = x + -1
+ x = x + 1.0
+ x = x + 1.1
+ x = x + y
+ x = x - y
+ x = x * y
+ x = x / y
+ x = x /* ERROR "not defined" */ % y
+ x = x /* ERRORx `operand x .* must be integer` */ << y
+ x = x /* ERRORx `operand x .* must be integer` */ >> y
+
+ z = z + 1
+ z = z + -1
+ z = z + 1.0
+ z = z + 1.1
+ z = z /* ERROR "mismatched types" */ + y
+ z = z /* ERROR "mismatched types" */ - y
+ z = z /* ERROR "mismatched types" */ * y
+ z = z /* ERROR "mismatched types" */ / y
+ z = z /* ERROR "mismatched types" */ % y
+ z = z /* ERRORx `operand z .* must be integer` */ << y
+ z = z /* ERRORx `operand z .* must be integer` */ >> y
+}
+
+type mystring string
+
+func _(x, y string, z mystring) {
+ x = x + "foo"
+ x = x /* ERROR "not defined" */ - "foo"
+ x = x /* ERROR "mismatched types string and untyped int" */ + 1
+ x = x + y
+ x = x /* ERROR "not defined" */ - y
+ x = x /* ERROR "mismatched types string and untyped int" */* 10
+}
+
+func f() (a, b int) { return }
+
+func _(x int) {
+ _ = f /* ERROR "multiple-value f" */ () + 1
+ _ = x + f /* ERROR "multiple-value f" */ ()
+ _ = f /* ERROR "multiple-value f" */ () + f
+ _ = f /* ERROR "multiple-value f" */ () + f /* ERROR "multiple-value f" */ ()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr2.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr2.go
new file mode 100644
index 0000000000000000000000000000000000000000..ebb85eb2339d5561893b4fd2523d5349111d0f48
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr2.go
@@ -0,0 +1,260 @@
+// 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.
+
+// comparisons
+
+package expr2
+
+func _bool() {
+ const t = true == true
+ const f = true == false
+ _ = t /* ERRORx `operator .* not defined` */ < f
+ _ = 0 == t /* ERROR "mismatched types untyped int and untyped bool" */
+ var b bool
+ var x, y float32
+ b = x < y
+ _ = b
+ _ = struct{b bool}{x < y}
+}
+
+// corner cases
+var (
+ v0 = nil == nil // ERROR "operator == not defined on untyped nil"
+)
+
+func arrays() {
+ // basics
+ var a, b [10]int
+ _ = a == b
+ _ = a != b
+ _ = a /* ERROR "< not defined" */ < b
+ _ = a == nil /* ERROR "mismatched types" */
+
+ type C [10]int
+ var c C
+ _ = a == c
+
+ type D [10]int
+ var d D
+ _ = c == d /* ERROR "mismatched types" */
+
+ var e [10]func() int
+ _ = e /* ERROR "[10]func() int cannot be compared" */ == e
+}
+
+func structs() {
+ // basics
+ var s, t struct {
+ x int
+ a [10]float32
+ _ bool
+ }
+ _ = s == t
+ _ = s != t
+ _ = s /* ERROR "< not defined" */ < t
+ _ = s == nil /* ERROR "mismatched types" */
+
+ type S struct {
+ x int
+ a [10]float32
+ _ bool
+ }
+ type T struct {
+ x int
+ a [10]float32
+ _ bool
+ }
+ var ss S
+ var tt T
+ _ = s == ss
+ _ = ss == tt /* ERROR "mismatched types" */
+
+ var u struct {
+ x int
+ a [10]map[string]int
+ }
+ _ = u /* ERROR "cannot be compared" */ == u
+}
+
+func pointers() {
+ // nil
+ _ = nil == nil // ERROR "operator == not defined on untyped nil"
+ _ = nil != nil // ERROR "operator != not defined on untyped nil"
+ _ = nil /* ERROR "< not defined" */ < nil
+ _ = nil /* ERROR "<= not defined" */ <= nil
+ _ = nil /* ERROR "> not defined" */ > nil
+ _ = nil /* ERROR ">= not defined" */ >= nil
+
+ // basics
+ var p, q *int
+ _ = p == q
+ _ = p != q
+
+ _ = p == nil
+ _ = p != nil
+ _ = nil == q
+ _ = nil != q
+
+ _ = p /* ERROR "< not defined" */ < q
+ _ = p /* ERROR "<= not defined" */ <= q
+ _ = p /* ERROR "> not defined" */ > q
+ _ = p /* ERROR ">= not defined" */ >= q
+
+ // various element types
+ type (
+ S1 struct{}
+ S2 struct{}
+ P1 *S1
+ P2 *S2
+ )
+ var (
+ ps1 *S1
+ ps2 *S2
+ p1 P1
+ p2 P2
+ )
+ _ = ps1 == ps1
+ _ = ps1 == ps2 /* ERROR "mismatched types" */
+ _ = ps2 == ps1 /* ERROR "mismatched types" */
+
+ _ = p1 == p1
+ _ = p1 == p2 /* ERROR "mismatched types" */
+
+ _ = p1 == ps1
+}
+
+func channels() {
+ // basics
+ var c, d chan int
+ _ = c == d
+ _ = c != d
+ _ = c == nil
+ _ = c /* ERROR "< not defined" */ < d
+
+ // various element types (named types)
+ type (
+ C1 chan int
+ C1r <-chan int
+ C1s chan<- int
+ C2 chan float32
+ )
+ var (
+ c1 C1
+ c1r C1r
+ c1s C1s
+ c1a chan int
+ c2 C2
+ )
+ _ = c1 == c1
+ _ = c1 == c1r /* ERROR "mismatched types" */
+ _ = c1 == c1s /* ERROR "mismatched types" */
+ _ = c1r == c1s /* ERROR "mismatched types" */
+ _ = c1 == c1a
+ _ = c1a == c1
+ _ = c1 == c2 /* ERROR "mismatched types" */
+ _ = c1a == c2 /* ERROR "mismatched types" */
+
+ // various element types (unnamed types)
+ var (
+ d1 chan int
+ d1r <-chan int
+ d1s chan<- int
+ d1a chan<- int
+ d2 chan float32
+ )
+ _ = d1 == d1
+ _ = d1 == d1r
+ _ = d1 == d1s
+ _ = d1r == d1s /* ERROR "mismatched types" */
+ _ = d1 == d1a
+ _ = d1a == d1
+ _ = d1 == d2 /* ERROR "mismatched types" */
+ _ = d1a == d2 /* ERROR "mismatched types" */
+}
+
+// for interfaces test
+type S1 struct{}
+type S11 struct{}
+type S2 struct{}
+func (*S1) m() int
+func (*S11) m() int
+func (*S11) n()
+func (*S2) m() float32
+
+func interfaces() {
+ // basics
+ var i, j interface{ m() int }
+ _ = i == j
+ _ = i != j
+ _ = i == nil
+ _ = i /* ERROR "< not defined" */ < j
+
+ // various interfaces
+ var ii interface { m() int; n() }
+ var k interface { m() float32 }
+ _ = i == ii
+ _ = i == k /* ERROR "mismatched types" */
+
+ // interfaces vs values
+ var s1 S1
+ var s11 S11
+ var s2 S2
+
+ _ = i == 0 /* ERROR "cannot convert" */
+ _ = i == s1 /* ERROR "mismatched types" */
+ _ = i == &s1
+ _ = i == &s11
+
+ _ = i == s2 /* ERROR "mismatched types" */
+ _ = i == & /* ERROR "mismatched types" */ s2
+
+ // issue #28164
+ // testcase from issue
+ _ = interface{}(nil) == [ /* ERROR "slice can only be compared to nil" */ ]int(nil)
+
+ // related cases
+ var e interface{}
+ var s []int
+ var x int
+ _ = e == s // ERROR "slice can only be compared to nil"
+ _ = s /* ERROR "slice can only be compared to nil" */ == e
+ _ = e /* ERROR "operator < not defined on interface" */ < x
+ _ = x < e // ERROR "operator < not defined on interface"
+}
+
+func slices() {
+ // basics
+ var s []int
+ _ = s == nil
+ _ = s != nil
+ _ = s /* ERROR "< not defined" */ < nil
+
+ // slices are not otherwise comparable
+ _ = s /* ERROR "slice can only be compared to nil" */ == s
+ _ = s /* ERROR "< not defined" */ < s
+}
+
+func maps() {
+ // basics
+ var m map[string]int
+ _ = m == nil
+ _ = m != nil
+ _ = m /* ERROR "< not defined" */ < nil
+
+ // maps are not otherwise comparable
+ _ = m /* ERROR "map can only be compared to nil" */ == m
+ _ = m /* ERROR "< not defined" */ < m
+}
+
+func funcs() {
+ // basics
+ var f func(int) float32
+ _ = f == nil
+ _ = f != nil
+ _ = f /* ERROR "< not defined" */ < nil
+
+ // funcs are not otherwise comparable
+ _ = f /* ERROR "func can only be compared to nil" */ == f
+ _ = f /* ERROR "< not defined" */ < f
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr3.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr3.go
new file mode 100644
index 0000000000000000000000000000000000000000..91534cdd629b4007ce0241b7563223eddfdc7332
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/expr3.go
@@ -0,0 +1,564 @@
+// 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 expr3
+
+import "time"
+
+func indexes() {
+ _ = 1 /* ERROR "cannot index" */ [0]
+ _ = indexes /* ERROR "cannot index" */ [0]
+ _ = ( /* ERROR "cannot slice" */ 12 + 3)[1:2]
+
+ var a [10]int
+ _ = a[true /* ERROR "cannot convert" */ ]
+ _ = a["foo" /* ERROR "cannot convert" */ ]
+ _ = a[1.1 /* ERROR "truncated" */ ]
+ _ = a[1.0]
+ _ = a[- /* ERROR "negative" */ 1]
+ _ = a[- /* ERROR "negative" */ 1 :]
+ _ = a[: - /* ERROR "negative" */ 1]
+ _ = a[: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ]
+ _ = a[0: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ]
+ _ = a[0: /* ERROR "middle index required" */ :10]
+ _ = a[:10:10]
+
+ var a0 int
+ a0 = a[0]
+ _ = a0
+ var a1 int32
+ a1 = a /* ERRORx `cannot use .* in assignment` */ [1]
+ _ = a1
+
+ _ = a[9]
+ _ = a[10 /* ERRORx `index .* out of bounds` */ ]
+ _ = a[1 /* ERROR "overflows" */ <<100]
+ _ = a[1<< /* ERROR "constant shift overflow" */ 1000] // no out-of-bounds follow-on error
+ _ = a[10:]
+ _ = a[:10]
+ _ = a[10:10]
+ _ = a[11 /* ERRORx `index .* out of bounds` */ :]
+ _ = a[: 11 /* ERRORx `index .* out of bounds` */ ]
+ _ = a[: 1 /* ERROR "overflows" */ <<100]
+ _ = a[:10:10]
+ _ = a[:11 /* ERRORx `index .* out of bounds` */ :10]
+ _ = a[:10:11 /* ERRORx `index .* out of bounds` */ ]
+ _ = a[10:0 /* ERROR "invalid slice indices" */ :10]
+ _ = a[0:10:0 /* ERROR "invalid slice indices" */ ]
+ _ = a[10:0 /* ERROR "invalid slice indices" */:0]
+ _ = &a /* ERROR "cannot take address" */ [:10]
+
+ pa := &a
+ _ = pa[9]
+ _ = pa[10 /* ERRORx `index .* out of bounds` */ ]
+ _ = pa[1 /* ERROR "overflows" */ <<100]
+ _ = pa[10:]
+ _ = pa[:10]
+ _ = pa[10:10]
+ _ = pa[11 /* ERRORx `index .* out of bounds` */ :]
+ _ = pa[: 11 /* ERRORx `index .* out of bounds` */ ]
+ _ = pa[: 1 /* ERROR "overflows" */ <<100]
+ _ = pa[:10:10]
+ _ = pa[:11 /* ERRORx `index .* out of bounds` */ :10]
+ _ = pa[:10:11 /* ERRORx `index .* out of bounds` */ ]
+ _ = pa[10:0 /* ERROR "invalid slice indices" */ :10]
+ _ = pa[0:10:0 /* ERROR "invalid slice indices" */ ]
+ _ = pa[10:0 /* ERROR "invalid slice indices" */ :0]
+ _ = &pa /* ERROR "cannot take address" */ [:10]
+
+ var b [0]int
+ _ = b[0 /* ERRORx `index .* out of bounds` */ ]
+ _ = b[:]
+ _ = b[0:]
+ _ = b[:0]
+ _ = b[0:0]
+ _ = b[0:0:0]
+ _ = b[1 /* ERRORx `index .* out of bounds` */ :0:0]
+
+ var s []int
+ _ = s[- /* ERROR "negative" */ 1]
+ _ = s[- /* ERROR "negative" */ 1 :]
+ _ = s[: - /* ERROR "negative" */ 1]
+ _ = s[0]
+ _ = s[1:2]
+ _ = s[2:1 /* ERROR "invalid slice indices" */ ]
+ _ = s[2:]
+ _ = s[: 1 /* ERROR "overflows" */ <<100]
+ _ = s[1 /* ERROR "overflows" */ <<100 :]
+ _ = s[1 /* ERROR "overflows" */ <<100 : 1 /* ERROR "overflows" */ <<100]
+ _ = s[: /* ERROR "middle index required" */ : /* ERROR "final index required" */ ]
+ _ = s[:10:10]
+ _ = s[10:0 /* ERROR "invalid slice indices" */ :10]
+ _ = s[0:10:0 /* ERROR "invalid slice indices" */ ]
+ _ = s[10:0 /* ERROR "invalid slice indices" */ :0]
+ _ = &s /* ERROR "cannot take address" */ [:10]
+
+ var m map[string]int
+ _ = m[0 /* ERRORx `cannot use .* in map index` */ ]
+ _ = m /* ERROR "cannot slice" */ ["foo" : "bar"]
+ _ = m["foo"]
+ // ok is of type bool
+ type mybool bool
+ var ok mybool
+ _, ok = m["bar"]
+ _ = ok
+ _ = m/* ERROR "mismatched types int and untyped string" */[0 /* ERROR "cannot use 0" */ ] + "foo"
+
+ var t string
+ _ = t[- /* ERROR "negative" */ 1]
+ _ = t[- /* ERROR "negative" */ 1 :]
+ _ = t[: - /* ERROR "negative" */ 1]
+ _ = t[1:2:3 /* ERROR "3-index slice of string" */ ]
+ _ = "foo"[1:2:3 /* ERROR "3-index slice of string" */ ]
+ var t0 byte
+ t0 = t[0]
+ _ = t0
+ var t1 rune
+ t1 = t /* ERRORx `cannot use .* in assignment` */ [2]
+ _ = t1
+ _ = ("foo" + "bar")[5]
+ _ = ("foo" + "bar")[6 /* ERRORx `index .* out of bounds` */ ]
+
+ const c = "foo"
+ _ = c[- /* ERROR "negative" */ 1]
+ _ = c[- /* ERROR "negative" */ 1 :]
+ _ = c[: - /* ERROR "negative" */ 1]
+ var c0 byte
+ c0 = c[0]
+ _ = c0
+ var c2 float32
+ c2 = c /* ERRORx `cannot use .* in assignment` */ [2]
+ _ = c[3 /* ERRORx `index .* out of bounds` */ ]
+ _ = ""[0 /* ERRORx `index .* out of bounds` */ ]
+ _ = c2
+
+ _ = s[1<<30] // no compile-time error here
+
+ // issue 4913
+ type mystring string
+ var ss string
+ var ms mystring
+ var i, j int
+ ss = "foo"[1:2]
+ ss = "foo"[i:j]
+ ms = "foo" /* ERRORx `cannot use .* in assignment` */ [1:2]
+ ms = "foo" /* ERRORx `cannot use .* in assignment` */ [i:j]
+ _, _ = ss, ms
+}
+
+type T struct {
+ x int
+ y func()
+}
+
+func (*T) m() {}
+
+func method_expressions() {
+ _ = T.a /* ERROR "no field or method" */
+ _ = T.x /* ERROR "has no method" */
+ _ = T.m /* ERROR "invalid method expression T.m (needs pointer receiver (*T).m)" */
+ _ = (*T).m
+
+ var f func(*T) = T.m /* ERROR "invalid method expression T.m (needs pointer receiver (*T).m)" */
+ var g func(*T) = (*T).m
+ _, _ = f, g
+
+ _ = T.y /* ERROR "has no method" */
+ _ = (*T).y /* ERROR "has no method" */
+}
+
+func struct_literals() {
+ type T0 struct {
+ a, b, c int
+ }
+
+ type T1 struct {
+ T0
+ a, b int
+ u float64
+ s string
+ }
+
+ // keyed elements
+ _ = T1{}
+ _ = T1{a: 0, 1 /* ERRORx `mixture of .* elements` */ }
+ _ = T1{aa /* ERROR "unknown field" */ : 0}
+ _ = T1{1 /* ERROR "invalid field name" */ : 0}
+ _ = T1{a: 0, s: "foo", u: 0, a /* ERROR "duplicate field" */: 10}
+ _ = T1{a: "foo" /* ERRORx `cannot use .* in struct literal` */ }
+ _ = T1{c /* ERROR "unknown field" */ : 0}
+ _ = T1{T0: { /* ERROR "missing type" */ }} // struct literal element type may not be elided
+ _ = T1{T0: T0{}}
+ _ = T1{T0 /* ERROR "invalid field name" */ .a: 0}
+
+ // unkeyed elements
+ _ = T0{1, 2, 3}
+ _ = T0{1, b /* ERROR "mixture" */ : 2, 3}
+ _ = T0{1, 2} /* ERROR "too few values" */
+ _ = T0{1, 2, 3, 4 /* ERROR "too many values" */ }
+ _ = T0{1, "foo" /* ERRORx `cannot use .* in struct literal` */, 3.4 /* ERRORx `cannot use .*\(truncated\)` */}
+
+ // invalid type
+ type P *struct{
+ x int
+ }
+ _ = P /* ERROR "invalid composite literal type" */ {}
+
+ // unexported fields
+ _ = time.Time{}
+ _ = time.Time{sec /* ERROR "unknown field" */ : 0}
+ _ = time.Time{
+ 0 /* ERROR "implicit assignment to unexported field wall in struct literal" */,
+ 0 /* ERROR "implicit assignment" */ ,
+ nil /* ERROR "implicit assignment" */ ,
+ }
+}
+
+func array_literals() {
+ type A0 [0]int
+ _ = A0{}
+ _ = A0{0 /* ERRORx `index .* out of bounds` */}
+ _ = A0{0 /* ERRORx `index .* out of bounds` */ : 0}
+
+ type A1 [10]int
+ _ = A1{}
+ _ = A1{0, 1, 2}
+ _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
+ _ = A1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /* ERRORx `index .* out of bounds` */ }
+ _ = A1{- /* ERROR "negative" */ 1: 0}
+ _ = A1{8: 8, 9}
+ _ = A1{8: 8, 9, 10 /* ERRORx `index .* out of bounds` */ }
+ _ = A1{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4}
+ _ = A1{5: 5, 6, 7, 3: 3, 4}
+ _ = A1{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ }
+ _ = A1{10 /* ERRORx `index .* out of bounds` */ : 10, 10 /* ERRORx `index .* out of bounds` */ : 10}
+ _ = A1{5: 5, 6, 7, 3: 3, 1 /* ERROR "overflows" */ <<100: 4, 5 /* ERROR "duplicate index" */ }
+ _ = A1{5: 5, 6, 7, 4: 4, 1 /* ERROR "overflows" */ <<100: 4}
+ _ = A1{2.0}
+ _ = A1{2.1 /* ERROR "truncated" */ }
+ _ = A1{"foo" /* ERRORx `cannot use .* in array or slice literal` */ }
+
+ // indices must be integer constants
+ i := 1
+ const f = 2.1
+ const s = "foo"
+ _ = A1{i /* ERROR "index i must be integer constant" */ : 0}
+ _ = A1{f /* ERROR "truncated" */ : 0}
+ _ = A1{s /* ERROR "cannot convert" */ : 0}
+
+ a0 := [...]int{}
+ assert(len(a0) == 0)
+
+ a1 := [...]int{0, 1, 2}
+ assert(len(a1) == 3)
+ var a13 [3]int
+ var a14 [4]int
+ a13 = a1
+ a14 = a1 /* ERRORx `cannot use .* in assignment` */
+ _, _ = a13, a14
+
+ a2 := [...]int{- /* ERROR "negative" */ 1: 0}
+ _ = a2
+
+ a3 := [...]int{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4}
+ assert(len(a3) == 5) // somewhat arbitrary
+
+ a4 := [...]complex128{0, 1, 2, 1<<10-2: -1i, 1i, 400: 10, 12, 14}
+ assert(len(a4) == 1024)
+
+ // composite literal element types may be elided
+ type T []int
+ _ = [10]T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}}
+ a6 := [...]T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}}
+ assert(len(a6) == 8)
+
+ // recursively so
+ _ = [10][10]T{{}, [10]T{{}}, {{1, 2, 3}}}
+
+ // from the spec
+ type Point struct { x, y float32 }
+ _ = [...]Point{Point{1.5, -3.5}, Point{0, 0}}
+ _ = [...]Point{{1.5, -3.5}, {0, 0}}
+ _ = [][]int{[]int{1, 2, 3}, []int{4, 5}}
+ _ = [][]int{{1, 2, 3}, {4, 5}}
+ _ = [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}}
+ _ = [...]*Point{{1.5, -3.5}, {0, 0}}
+}
+
+func slice_literals() {
+ type S0 []int
+ _ = S0{}
+ _ = S0{0, 1, 2}
+ _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
+ _ = S0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
+ _ = S0{- /* ERROR "negative" */ 1: 0}
+ _ = S0{8: 8, 9}
+ _ = S0{8: 8, 9, 10}
+ _ = S0{0, 1, 2, 0 /* ERROR "duplicate index" */ : 0, 3: 3, 4}
+ _ = S0{5: 5, 6, 7, 3: 3, 4}
+ _ = S0{5: 5, 6, 7, 3: 3, 4, 5 /* ERROR "duplicate index" */ }
+ _ = S0{10: 10, 10 /* ERROR "duplicate index" */ : 10}
+ _ = S0{5: 5, 6, 7, 3: 3, 1 /* ERROR "overflows" */ <<100: 4, 5 /* ERROR "duplicate index" */ }
+ _ = S0{5: 5, 6, 7, 4: 4, 1 /* ERROR "overflows" */ <<100: 4}
+ _ = S0{2.0}
+ _ = S0{2.1 /* ERROR "truncated" */ }
+ _ = S0{"foo" /* ERRORx `cannot use .* in array or slice literal` */ }
+
+ // indices must be resolved correctly
+ const index1 = 1
+ _ = S0{index1: 1}
+ _ = S0{index2: 2}
+ _ = S0{index3 /* ERROR "undefined" */ : 3}
+
+ // indices must be integer constants
+ i := 1
+ const f = 2.1
+ const s = "foo"
+ _ = S0{i /* ERROR "index i must be integer constant" */ : 0}
+ _ = S0{f /* ERROR "truncated" */ : 0}
+ _ = S0{s /* ERROR "cannot convert" */ : 0}
+
+ // composite literal element types may be elided
+ type T []int
+ _ = []T{T{}, {}, 5: T{1, 2, 3}, 7: {1, 2, 3}}
+ _ = [][]int{{1, 2, 3}, {4, 5}}
+
+ // recursively so
+ _ = [][]T{{}, []T{{}}, {{1, 2, 3}}}
+
+ // issue 17954
+ type T0 *struct { s string }
+ _ = []T0{{}}
+ _ = []T0{{"foo"}}
+
+ type T1 *struct{ int }
+ _ = []T1{}
+ _ = []T1{{0}, {1}, {2}}
+
+ type T2 T1
+ _ = []T2{}
+ _ = []T2{{0}, {1}, {2}}
+
+ _ = map[T0]T2{}
+ _ = map[T0]T2{{}: {}}
+}
+
+const index2 int = 2
+
+type N int
+func (N) f() {}
+
+func map_literals() {
+ type M0 map[string]int
+ type M1 map[bool]int
+ type M2 map[*int]int
+
+ _ = M0{}
+ _ = M0{1 /* ERROR "missing key" */ }
+ _ = M0{1 /* ERRORx `cannot use .* in map literal` */ : 2}
+ _ = M0{"foo": "bar" /* ERRORx `cannot use .* in map literal` */ }
+ _ = M0{"foo": 1, "bar": 2, "foo" /* ERROR "duplicate key" */ : 3 }
+
+ _ = map[interface{}]int{2: 1, 2 /* ERROR "duplicate key" */ : 1}
+ _ = map[interface{}]int{int(2): 1, int16(2): 1}
+ _ = map[interface{}]int{int16(2): 1, int16 /* ERROR "duplicate key" */ (2): 1}
+
+ type S string
+
+ _ = map[interface{}]int{"a": 1, "a" /* ERROR "duplicate key" */ : 1}
+ _ = map[interface{}]int{"a": 1, S("a"): 1}
+ _ = map[interface{}]int{S("a"): 1, S /* ERROR "duplicate key" */ ("a"): 1}
+ _ = map[interface{}]int{1.0: 1, 1.0 /* ERROR "duplicate key" */: 1}
+ _ = map[interface{}]int{int64(-1): 1, int64 /* ERROR "duplicate key" */ (-1) : 1}
+ _ = map[interface{}]int{^uint64(0): 1, ^ /* ERROR "duplicate key" */ uint64(0): 1}
+ _ = map[interface{}]int{complex(1,2): 1, complex /* ERROR "duplicate key" */ (1,2) : 1}
+
+ type I interface {
+ f()
+ }
+
+ _ = map[I]int{N(0): 1, N(2): 1}
+ _ = map[I]int{N(2): 1, N /* ERROR "duplicate key" */ (2): 1}
+
+ // map keys must be resolved correctly
+ key1 := "foo"
+ _ = M0{key1: 1}
+ _ = M0{key2: 2}
+ _ = M0{key3 /* ERROR "undefined" */ : 2}
+
+ var value int
+ _ = M1{true: 1, false: 0}
+ _ = M2{nil: 0, &value: 1}
+
+ // composite literal element types may be elided
+ type T [2]int
+ _ = map[int]T{0: T{3, 4}, 1: {5, 6}}
+
+ // recursively so
+ _ = map[int][]T{0: {}, 1: {{}, T{1, 2}}}
+
+ // composite literal key types may be elided
+ _ = map[T]int{T{3, 4}: 0, {5, 6}: 1}
+
+ // recursively so
+ _ = map[[2]T]int{{}: 0, {{}}: 1, [2]T{{}}: 2, {T{1, 2}}: 3}
+
+ // composite literal element and key types may be elided
+ _ = map[T]T{{}: {}, {1, 2}: T{3, 4}, T{4, 5}: {}}
+ _ = map[T]M0{{} : {}, T{1, 2}: M0{"foo": 0}, {1, 3}: {"foo": 1}}
+
+ // recursively so
+ _ = map[[2]T][]T{{}: {}, {{}}: {{}, T{1, 2}}, [2]T{{}}: nil, {T{1, 2}}: {{}, {}}}
+
+ // from the spec
+ type Point struct { x, y float32 }
+ _ = map[string]Point{"orig": {0, 0}}
+ _ = map[*Point]string{{0, 0}: "orig"}
+
+ // issue 17954
+ type T0 *struct{ s string }
+ type T1 *struct{ int }
+ type T2 T1
+
+ _ = map[T0]T2{}
+ _ = map[T0]T2{{}: {}}
+}
+
+var key2 string = "bar"
+
+type I interface {
+ m()
+}
+
+type I2 interface {
+ m(int)
+}
+
+type T1 struct{}
+type T2 struct{}
+
+func (T2) m(int) {}
+
+type mybool bool
+
+func type_asserts() {
+ var x int
+ _ = x /* ERROR "not an interface" */ .(int)
+
+ var e interface{}
+ var ok bool
+ x, ok = e.(int)
+ _ = ok
+
+ // ok value is of type bool
+ var myok mybool
+ _, myok = e.(int)
+ _ = myok
+
+ var t I
+ _ = t /* ERRORx `use of .* outside type switch` */ .(type)
+ _ = t /* ERROR "m has pointer receiver" */ .(T)
+ _ = t.(*T)
+ _ = t /* ERROR "missing method m" */ .(T1)
+ _ = t /* ERROR "wrong type for method m" */ .(T2)
+ _ = t /* STRICT "wrong type for method m" */ .(I2) // only an error in strict mode (issue 8561)
+
+ // e doesn't statically have an m, but may have one dynamically.
+ _ = e.(I2)
+}
+
+func f0() {}
+func f1(x int) {}
+func f2(u float32, s string) {}
+func fs(s []byte) {}
+func fv(x ...int) {}
+func fi(x ... interface{}) {}
+func (T) fm(x ...int)
+
+func g0() {}
+func g1() int { return 0}
+func g2() (u float32, s string) { return }
+func gs() []byte { return nil }
+
+func _calls() {
+ var x int
+ var y float32
+ var s []int
+
+ f0()
+ _ = f0 /* ERROR "used as value" */ ()
+ f0(g0 /* ERROR "too many arguments" */ )
+
+ f1(0)
+ f1(x)
+ f1(10.0)
+ f1() /* ERROR "not enough arguments in call to f1\n\thave ()\n\twant (int)" */
+ f1(x, y /* ERROR "too many arguments in call to f1\n\thave (int, float32)\n\twant (int)" */ )
+ f1(s /* ERRORx `cannot use .* in argument` */ )
+ f1(x ... /* ERROR "cannot use ..." */ )
+ f1(g0 /* ERROR "used as value" */ ())
+ f1(g1())
+ f1(g2 /* ERROR "too many arguments in call to f1\n\thave (float32, string)\n\twant (int)" */ ())
+
+ f2() /* ERROR "not enough arguments in call to f2\n\thave ()\n\twant (float32, string)" */
+ f2(3.14) /* ERROR "not enough arguments in call to f2\n\thave (number)\n\twant (float32, string)" */
+ f2(3.14, "foo")
+ f2(x /* ERRORx `cannot use .* in argument` */ , "foo")
+ f2(g0 /* ERROR "used as value" */ ()) /* ERROR "not enough arguments in call to f2\n\thave (func())\n\twant (float32, string)" */
+ f2(g1()) /* ERROR "not enough arguments in call to f2\n\thave (int)\n\twant (float32, string)" */
+ f2(g2())
+
+ fs() /* ERROR "not enough arguments" */
+ fs(g0 /* ERROR "used as value" */ ())
+ fs(g1 /* ERRORx `cannot use .* in argument` */ ())
+ fs(g2 /* ERROR "too many arguments" */ ())
+ fs(gs())
+
+ fv()
+ fv(1, 2.0, x)
+ fv(s /* ERRORx `cannot use .* in argument` */ )
+ fv(s...)
+ fv(x /* ERROR "cannot use" */ ...)
+ fv(1, s /* ERROR "too many arguments" */ ...)
+ fv(gs /* ERRORx `cannot use .* in argument` */ ())
+ fv(gs /* ERRORx `cannot use .* in argument` */ ()...)
+
+ var t T
+ t.fm()
+ t.fm(1, 2.0, x)
+ t.fm(s /* ERRORx `cannot use .* in argument` */ )
+ t.fm(g1())
+ t.fm(1, s /* ERROR "too many arguments" */ ...)
+ t.fm(gs /* ERRORx `cannot use .* in argument` */ ())
+ t.fm(gs /* ERRORx `cannot use .* in argument` */ ()...)
+
+ T.fm(t, )
+ T.fm(t, 1, 2.0, x)
+ T.fm(t, s /* ERRORx `cannot use .* in argument` */ )
+ T.fm(t, g1())
+ T.fm(t, 1, s /* ERROR "too many arguments" */ ...)
+ T.fm(t, gs /* ERRORx `cannot use .* in argument` */ ())
+ T.fm(t, gs /* ERRORx `cannot use .* in argument` */ ()...)
+
+ var i interface{ fm(x ...int) } = t
+ i.fm()
+ i.fm(1, 2.0, x)
+ i.fm(s /* ERRORx `cannot use .* in argument` */ )
+ i.fm(g1())
+ i.fm(1, s /* ERROR "too many arguments" */ ...)
+ i.fm(gs /* ERRORx `cannot use .* in argument` */ ())
+ i.fm(gs /* ERRORx `cannot use .* in argument` */ ()...)
+
+ fi()
+ fi(1, 2.0, x, 3.14, "foo")
+ fi(g2())
+ fi(0, g2)
+ fi(0, g2 /* ERROR "multiple-value g2" */ ())
+}
+
+func issue6344() {
+ type T []interface{}
+ var x T
+ fi(x...) // ... applies also to named slices
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/funcinference.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/funcinference.go
new file mode 100644
index 0000000000000000000000000000000000000000..e0e978f25a331dcd994dfb2eab6ad4e17055593e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/funcinference.go
@@ -0,0 +1,112 @@
+// 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 funcInference
+
+import "strconv"
+
+type any interface{}
+
+func f0[A any, B interface{*C}, C interface{*D}, D interface{*A}](A, B, C, D) {}
+func _() {
+ f := f0[string]
+ f("a", nil, nil, nil)
+ f0("a", nil, nil, nil)
+}
+
+func f1[A any, B interface{*A}](A, B) {}
+func _() {
+ f := f1[int]
+ f(int(0), new(int))
+ f1(int(0), new(int))
+}
+
+func f2[A any, B interface{[]A}](A, B) {}
+func _() {
+ f := f2[byte]
+ f(byte(0), []byte{})
+ f2(byte(0), []byte{})
+}
+
+// Embedding stand-alone type parameters is not permitted for now. Disabled.
+// func f3[A any, B interface{~C}, C interface{~*A}](A, B, C)
+// func _() {
+// f := f3[int]
+// var x int
+// f(x, &x, &x)
+// f3(x, &x, &x)
+// }
+
+func f4[A any, B interface{[]C}, C interface{*A}](A, B, C) {}
+func _() {
+ f := f4[int]
+ var x int
+ f(x, []*int{}, &x)
+ f4(x, []*int{}, &x)
+}
+
+func f5[A interface{struct{b B; c C}}, B any, C interface{*B}](x B) A { panic(0) }
+func _() {
+ x := f5(1.2)
+ var _ float64 = x.b
+ var _ float64 = *x.c
+}
+
+func f6[A any, B interface{~struct{f []A}}](B) A { panic(0) }
+func _() {
+ x := f6(struct{f []string}{})
+ var _ string = x
+}
+
+func f7[A interface{*B}, B interface{~*A}]() {}
+
+// More realistic examples
+
+func Double[S interface{ ~[]E }, E interface{ ~int | ~int8 | ~int16 | ~int32 | ~int64 }](s S) S {
+ r := make(S, len(s))
+ for i, v := range s {
+ r[i] = v + v
+ }
+ return r
+}
+
+type MySlice []int
+
+var _ = Double(MySlice{1})
+
+// From the draft design.
+
+type Setter[B any] interface {
+ Set(string)
+ *B
+}
+
+func FromStrings[T interface{}, PT Setter[T]](s []string) []T {
+ result := make([]T, len(s))
+ for i, v := range s {
+ // The type of &result[i] is *T which is in the type set
+ // of Setter, so we can convert it to PT.
+ p := PT(&result[i])
+ // PT has a Set method.
+ p.Set(v)
+ }
+ return result
+}
+
+type Settable int
+
+func (p *Settable) Set(s string) {
+ i, _ := strconv.Atoi(s) // real code should not ignore the error
+ *p = Settable(i)
+}
+
+var _ = FromStrings[Settable]([]string{"1", "2"})
+
+// Suitable error message when the type parameter is provided (rather than inferred).
+
+func f8[P, Q any](P, Q) {}
+
+func _(s string) {
+ f8[int](s /* ERROR "cannot use s (variable of type string) as int value in argument to f8[int]" */ , s)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_12.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_12.go
new file mode 100644
index 0000000000000000000000000000000000000000..b47d3de147ad7abbfd6c3f745f312d278ac7bc32
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_12.go
@@ -0,0 +1,36 @@
+// -lang=go1.12
+
+// 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.
+
+// Check Go language version-specific errors.
+
+package p
+
+// numeric literals
+const (
+ _ = 1_000 // ERROR "underscores in numeric literals requires go1.13 or later"
+ _ = 0b111 // ERROR "binary literals requires go1.13 or later"
+ _ = 0o567 // ERROR "0o/0O-style octal literals requires go1.13 or later"
+ _ = 0xabc // ok
+ _ = 0x0p1 // ERROR "hexadecimal floating-point literals requires go1.13 or later"
+
+ _ = 0B111 // ERROR "binary"
+ _ = 0O567 // ERROR "octal"
+ _ = 0Xabc // ok
+ _ = 0X0P1 // ERROR "hexadecimal floating-point"
+
+ _ = 1_000i // ERROR "underscores"
+ _ = 0b111i // ERROR "binary"
+ _ = 0o567i // ERROR "octal"
+ _ = 0xabci // ERROR "hexadecimal floating-point"
+ _ = 0x0p1i // ERROR "hexadecimal floating-point"
+)
+
+// signed shift counts
+var (
+ s int
+ _ = 1 << s // ERROR "invalid operation: signed shift count s (variable of type int) requires go1.13 or later"
+ _ = 1 >> s // ERROR "signed shift count"
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_13.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_13.go
new file mode 100644
index 0000000000000000000000000000000000000000..cc7861d616100222ffddabec24b6cc75d2e4dadc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_13.go
@@ -0,0 +1,23 @@
+// -lang=go1.13
+
+// 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.
+
+// Check Go language version-specific errors.
+
+package p
+
+// interface embedding
+
+type I interface { m() }
+
+type _ interface {
+ m()
+ I // ERROR "duplicate method m"
+}
+
+type _ interface {
+ I
+ I // ERROR "duplicate method m"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_16.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_16.go
new file mode 100644
index 0000000000000000000000000000000000000000..9675b292b627f3a980f8efdd1aa4c47ac433da78
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_16.go
@@ -0,0 +1,15 @@
+// -lang=go1.16
+
+// 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.
+
+// Check Go language version-specific errors.
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (*Array)(s /* ERROR "requires go1.17 or later" */ )
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19.go
new file mode 100644
index 0000000000000000000000000000000000000000..b6cff4f4653071aff0f031a52c64297591862387
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19.go
@@ -0,0 +1,15 @@
+// -lang=go1.19
+
+// 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.
+
+// Check Go language version-specific errors.
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (Array)(s /* ERROR "requires go1.20 or later" */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19_20.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19_20.go
new file mode 100644
index 0000000000000000000000000000000000000000..52e5dfdc4a7786399a30ac299cb4f5f6171c1855
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_19_20.go
@@ -0,0 +1,17 @@
+// -lang=go1.19
+
+// 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.
+
+// Check Go language version-specific errors.
+
+//go:build go1.20
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (Array)(s /* ok */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_20_19.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_20_19.go
new file mode 100644
index 0000000000000000000000000000000000000000..08365a7cfb564d09e7cc5180d38f814bfec40456
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_20_19.go
@@ -0,0 +1,17 @@
+// -lang=go1.20
+
+// 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.
+
+// Check Go language version-specific errors.
+
+//go:build go1.19
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (Array)(s /* ok because Go 1.20 ignored the //go:build go1.19 */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_21_19.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_21_19.go
new file mode 100644
index 0000000000000000000000000000000000000000..2acd25865d4b69a7b88e3ada60b3f62dced43537
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_21_19.go
@@ -0,0 +1,17 @@
+// -lang=go1.21
+
+// 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.
+
+// Check Go language version-specific errors.
+
+//go:build go1.19
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (Array)(s /* ERROR "requires go1.20 or later" */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_8.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_8.go
new file mode 100644
index 0000000000000000000000000000000000000000..6a7e639792aa7eb30d21fbc481aa9ee3fa735f96
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_8.go
@@ -0,0 +1,12 @@
+// -lang=go1.8
+
+// 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.
+
+// Check Go language version-specific errors.
+
+package p
+
+// type alias declarations
+type any = /* ERROR "type aliases requires go1.9 or later" */ interface{}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_xx_19.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_xx_19.go
new file mode 100644
index 0000000000000000000000000000000000000000..01f6b7d2ebb3a23438fa41bc04be9c4dc3f58abe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/go1_xx_19.go
@@ -0,0 +1,15 @@
+// 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.
+
+// Check Go language version-specific errors.
+
+//go:build go1.19
+
+package p
+
+type Slice []byte
+type Array [8]byte
+
+var s Slice
+var p = (Array)(s /* ok because Go 1.X prior to Go 1.21 ignored the //go:build go1.19 */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/gotos.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/gotos.go
new file mode 100644
index 0000000000000000000000000000000000000000..069a94bbbf42f930a972e260702b942ef61bb665
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/gotos.go
@@ -0,0 +1,560 @@
+// 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 is a modified copy of $GOROOT/test/goto.go.
+
+package gotos
+
+var (
+ i, n int
+ x []int
+ c chan int
+ m map[int]int
+ s string
+)
+
+// goto after declaration okay
+func _() {
+ x := 1
+ goto L
+L:
+ _ = x
+}
+
+// goto before declaration okay
+func _() {
+ goto L
+L:
+ x := 1
+ _ = x
+}
+
+// goto across declaration not okay
+func _() {
+ goto L /* ERROR "goto L jumps over variable declaration at line 36" */
+ x := 1
+ _ = x
+L:
+}
+
+// goto across declaration in inner scope okay
+func _() {
+ goto L
+ {
+ x := 1
+ _ = x
+ }
+L:
+}
+
+// goto across declaration after inner scope not okay
+func _() {
+ goto L /* ERROR "goto L jumps over variable declaration at line 58" */
+ {
+ x := 1
+ _ = x
+ }
+ x := 1
+ _ = x
+L:
+}
+
+// goto across declaration in reverse okay
+func _() {
+L:
+ x := 1
+ _ = x
+ goto L
+}
+
+func _() {
+L: L1:
+ x := 1
+ _ = x
+ goto L
+ goto L1
+}
+
+// error shows first offending variable
+func _() {
+ goto L /* ERROR "goto L jumps over variable declaration at line 84" */
+ x := 1
+ _ = x
+ y := 1
+ _ = y
+L:
+}
+
+// goto not okay even if code path is dead
+func _() {
+ goto L /* ERROR "goto L jumps over variable declaration" */
+ x := 1
+ _ = x
+ y := 1
+ _ = y
+ return
+L:
+}
+
+// goto into outer block okay
+func _() {
+ {
+ goto L
+ }
+L:
+}
+
+func _() {
+ {
+ goto L
+ goto L1
+ }
+L: L1:
+}
+
+// goto backward into outer block okay
+func _() {
+L:
+ {
+ goto L
+ }
+}
+
+func _() {
+L: L1:
+ {
+ goto L
+ goto L1
+ }
+}
+
+// goto into inner block not okay
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ {
+ L:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ goto L1 /* ERROR "goto L1 jumps into block" */
+ {
+ L: L1:
+ }
+}
+
+// goto backward into inner block still not okay
+func _() {
+ {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ {
+ L: L1:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+ goto L1 /* ERROR "goto L1 jumps into block" */
+}
+
+// error shows first (outermost) offending block
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ {
+ {
+ {
+ L:
+ }
+ }
+ }
+}
+
+// error prefers block diagnostic over declaration diagnostic
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ x := 1
+ _ = x
+ {
+ L:
+ }
+}
+
+// many kinds of blocks, all invalid to jump into or among,
+// but valid to jump out of
+
+// if
+
+func _() {
+L:
+ if true {
+ goto L
+ }
+}
+
+func _() {
+L:
+ if true {
+ goto L
+ } else {
+ }
+}
+
+func _() {
+L:
+ if false {
+ } else {
+ goto L
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ if true {
+ L:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ if true {
+ L:
+ } else {
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ if true {
+ } else {
+ L:
+ }
+}
+
+func _() {
+ if false {
+ L:
+ } else {
+ goto L /* ERROR "goto L jumps into block" */
+ }
+}
+
+func _() {
+ if true {
+ goto L /* ERROR "goto L jumps into block" */
+ } else {
+ L:
+ }
+}
+
+func _() {
+ if true {
+ goto L /* ERROR "goto L jumps into block" */
+ } else if false {
+ L:
+ }
+}
+
+func _() {
+ if true {
+ goto L /* ERROR "goto L jumps into block" */
+ } else if false {
+ L:
+ } else {
+ }
+}
+
+func _() {
+ if true {
+ goto L /* ERROR "goto L jumps into block" */
+ } else if false {
+ } else {
+ L:
+ }
+}
+
+func _() {
+ if true {
+ goto L /* ERROR "goto L jumps into block" */
+ } else {
+ L:
+ }
+}
+
+func _() {
+ if true {
+ L:
+ } else {
+ goto L /* ERROR "goto L jumps into block" */
+ }
+}
+
+// for
+
+func _() {
+ for {
+ goto L
+ }
+L:
+}
+
+func _() {
+ for {
+ goto L
+ L:
+ }
+}
+
+func _() {
+ for {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for {
+ goto L
+ L1:
+ }
+L:
+ goto L1 /* ERROR "goto L1 jumps into block" */
+}
+
+func _() {
+ for i < n {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for i = 0; i < n; i++ {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for i = range x {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for i = range c {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for i = range m {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+func _() {
+ for i = range s {
+ L:
+ }
+ goto L /* ERROR "goto L jumps into block" */
+}
+
+// switch
+
+func _() {
+L:
+ switch i {
+ case 0:
+ goto L
+ }
+}
+
+func _() {
+L:
+ switch i {
+ case 0:
+
+ default:
+ goto L
+ }
+}
+
+func _() {
+ switch i {
+ case 0:
+
+ default:
+ L:
+ goto L
+ }
+}
+
+func _() {
+ switch i {
+ case 0:
+
+ default:
+ goto L
+ L:
+ }
+}
+
+func _() {
+ switch i {
+ case 0:
+ goto L
+ L:
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ switch i {
+ case 0:
+ L:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ switch i {
+ case 0:
+ L:
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ switch i {
+ case 0:
+ default:
+ L:
+ }
+}
+
+func _() {
+ switch i {
+ default:
+ goto L /* ERROR "goto L jumps into block" */
+ case 0:
+ L:
+ }
+}
+
+func _() {
+ switch i {
+ case 0:
+ L:
+ ;
+ default:
+ goto L /* ERROR "goto L jumps into block" */
+ }
+}
+
+// select
+// different from switch. the statement has no implicit block around it.
+
+func _() {
+L:
+ select {
+ case <-c:
+ goto L
+ }
+}
+
+func _() {
+L:
+ select {
+ case c <- 1:
+
+ default:
+ goto L
+ }
+}
+
+func _() {
+ select {
+ case <-c:
+
+ default:
+ L:
+ goto L
+ }
+}
+
+func _() {
+ select {
+ case c <- 1:
+
+ default:
+ goto L
+ L:
+ }
+}
+
+func _() {
+ select {
+ case <-c:
+ goto L
+ L:
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ select {
+ case c <- 1:
+ L:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ select {
+ case c <- 1:
+ L:
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L /* ERROR "goto L jumps into block" */
+ select {
+ case <-c:
+ default:
+ L:
+ }
+}
+
+func _() {
+ select {
+ default:
+ goto L /* ERROR "goto L jumps into block" */
+ case <-c:
+ L:
+ }
+}
+
+func _() {
+ select {
+ case <-c:
+ L:
+ ;
+ default:
+ goto L /* ERROR "goto L jumps into block" */
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importC.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importC.go
new file mode 100644
index 0000000000000000000000000000000000000000..2cdf383a08840e41c7a6fadc01a801f4d616ed16
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importC.go
@@ -0,0 +1,56 @@
+// -fakeImportC
+
+// 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.
+
+package importC
+
+import "C"
+import _ /* ERROR `cannot rename import "C"` */ "C"
+import foo /* ERROR `cannot rename import "C"` */ "C"
+import . /* ERROR `cannot rename import "C"` */ "C"
+
+// Test cases extracted from issue #22090.
+
+import "unsafe"
+
+const _ C.int = 0xff // no error due to invalid constant type
+
+type T struct {
+ Name string
+ Ordinal int
+}
+
+func _(args []T) {
+ var s string
+ for i, v := range args {
+ cname := C.CString(v.Name)
+ args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s, cname)) // no error due to i not being "used"
+ C.free(unsafe.Pointer(cname))
+ }
+}
+
+type CType C.Type
+
+const _ CType = C.X // no error due to invalid constant type
+const _ = C.X
+
+// Test cases extracted from issue #23712.
+
+func _() {
+ var a [C.ArrayLength]byte
+ _ = a[0] // no index out of bounds error here
+}
+
+// Additional tests to verify fix for #23712.
+
+func _() {
+ var a [C.ArrayLength1]byte
+ _ = 1 / len(a) // no division by zero error here and below
+ _ = 1 / cap(a)
+ _ = uint(unsafe.Sizeof(a)) // must not be negative
+
+ var b [C.ArrayLength2]byte
+ a = b // should be valid
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go
new file mode 100644
index 0000000000000000000000000000000000000000..d514ae4cb70fd23396c6a2dbfaab058aa57269f6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0a.go
@@ -0,0 +1,53 @@
+// 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 importdecl0
+
+import ()
+
+import (
+ // we can have multiple blank imports (was bug)
+ _ "math"
+ _ "net/rpc"
+ init /* ERROR "cannot import package as init" */ "fmt"
+ // reflect defines a type "flag" which shows up in the gc export data
+ "reflect"
+ . /* ERROR "imported and not used" */ "reflect"
+)
+
+import "math" /* ERROR "imported and not used" */
+import m /* ERROR "imported as m and not used" */ "math"
+import _ "math"
+
+import (
+ "math/big" /* ERROR "imported and not used" */
+ b /* ERROR "imported as b and not used" */ "math/big"
+ _ "math/big"
+)
+
+import "fmt"
+import f1 "fmt"
+import f2 "fmt"
+
+// reflect.flag must not be visible in this package
+type flag int
+type _ reflect.flag /* ERROR "not exported" */
+
+// imported package name may conflict with local objects
+type reflect /* ERROR "reflect already declared" */ int
+
+// dot-imported exported objects may conflict with local objects
+type Value /* ERROR "Value already declared through dot-import of package reflect" */ struct{}
+
+var _ = fmt.Println // use "fmt"
+
+func _() {
+ f1.Println() // use "fmt"
+}
+
+func _() {
+ _ = func() {
+ f2.Println() // use "fmt"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go
new file mode 100644
index 0000000000000000000000000000000000000000..99e1d1ebdf7ce82db18b3630c80538880c4215ef
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl0/importdecl0b.go
@@ -0,0 +1,30 @@
+// 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 importdecl0
+
+import "math"
+import m "math"
+
+import . "testing" // declares T in file scope
+import . /* ERRORx `.unsafe. imported and not used` */ "unsafe"
+import . "fmt" // declares Println in file scope
+
+import (
+ "" /* ERROR "invalid import path" */
+ "a!b" /* ERROR "invalid import path" */
+ "abc\xffdef" /* ERROR "invalid import path" */
+)
+
+// using "math" in this file doesn't affect its use in other files
+const Pi0 = math.Pi
+const Pi1 = m.Pi
+
+type _ T // use "testing"
+
+func _() func() interface{} {
+ return func() interface{} {
+ return Println // use "fmt"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go
new file mode 100644
index 0000000000000000000000000000000000000000..d377c01638a534a111d1c93833c2b05cc3627330
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1a.go
@@ -0,0 +1,22 @@
+// Copyright 2014 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 issue 8969.
+
+package importdecl1
+
+import "go/ast"
+import . "unsafe"
+
+var _ Pointer // use dot-imported package unsafe
+
+// Test cases for issue 23914.
+
+type A interface {
+ // Methods m1, m2 must be type-checked in this file scope
+ // even when embedded in an interface in a different
+ // file of the same package.
+ m1() ast.Node
+ m2() Pointer
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go
new file mode 100644
index 0000000000000000000000000000000000000000..49ac2d53e66fd3df3288cdfba10935b4cf931454
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/importdecl1/importdecl1b.go
@@ -0,0 +1,11 @@
+// Copyright 2014 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 importdecl1
+
+import . /* ERRORx ".unsafe. imported and not used" */ "unsafe"
+
+type B interface {
+ A
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init0.go
new file mode 100644
index 0000000000000000000000000000000000000000..ee2175e2c7a96520f86d5b4509679b28c82890c9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init0.go
@@ -0,0 +1,106 @@
+// 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.
+
+// initialization cycles
+
+package init0
+
+// initialization cycles (we don't know the types)
+const (
+ s0 /* ERROR "initialization cycle: s0 refers to itself" */ = s0
+
+ x0 /* ERROR "initialization cycle for x0" */ = y0
+ y0 = x0
+
+ a0 = b0
+ b0 /* ERROR "initialization cycle for b0" */ = c0
+ c0 = d0
+ d0 = b0
+)
+
+var (
+ s1 /* ERROR "initialization cycle: s1 refers to itself" */ = s1
+
+ x1 /* ERROR "initialization cycle for x1" */ = y1
+ y1 = x1
+
+ a1 = b1
+ b1 /* ERROR "initialization cycle for b1" */ = c1
+ c1 = d1
+ d1 = b1
+)
+
+// initialization cycles (we know the types)
+const (
+ s2 /* ERROR "initialization cycle: s2 refers to itself" */ int = s2
+
+ x2 /* ERROR "initialization cycle for x2" */ int = y2
+ y2 = x2
+
+ a2 = b2
+ b2 /* ERROR "initialization cycle for b2" */ int = c2
+ c2 = d2
+ d2 = b2
+)
+
+var (
+ s3 /* ERROR "initialization cycle: s3 refers to itself" */ int = s3
+
+ x3 /* ERROR "initialization cycle for x3" */ int = y3
+ y3 = x3
+
+ a3 = b3
+ b3 /* ERROR "initialization cycle for b3" */ int = c3
+ c3 = d3
+ d3 = b3
+)
+
+// cycles via struct fields
+
+type S1 struct {
+ f int
+}
+const cx3 S1 /* ERROR "invalid constant type" */ = S1{cx3.f}
+var vx3 /* ERROR "initialization cycle: vx3 refers to itself" */ S1 = S1{vx3.f}
+
+// cycles via functions
+
+var x4 = x5
+var x5 /* ERROR "initialization cycle for x5" */ = f1()
+func f1() int { return x5*10 }
+
+var x6, x7 /* ERROR "initialization cycle" */ = f2()
+var x8 = x7
+func f2() (int, int) { return f3() + f3(), 0 }
+func f3() int { return x8 }
+
+// cycles via function literals
+
+var x9 /* ERROR "initialization cycle: x9 refers to itself" */ = func() int { return x9 }()
+
+var x10 /* ERROR "initialization cycle for x10" */ = f4()
+
+func f4() int {
+ _ = func() {
+ _ = x10
+ }
+ return 0
+}
+
+// cycles via method expressions
+
+type T1 struct{}
+
+func (T1) m() bool { _ = x11; return false }
+
+var x11 /* ERROR "initialization cycle for x11" */ = T1.m(T1{})
+
+// cycles via method values
+
+type T2 struct{}
+
+func (T2) m() bool { _ = x12; return false }
+
+var t1 T2
+var x12 /* ERROR "initialization cycle for x12" */ = t1.m
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init1.go
new file mode 100644
index 0000000000000000000000000000000000000000..c89032ad6244c2dbba8633c0ea48202852ccc713
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init1.go
@@ -0,0 +1,97 @@
+// 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.
+
+// initialization cycles
+
+package init1
+
+// issue 6683 (marked as WorkingAsIntended)
+
+type T0 struct{}
+
+func (T0) m() int { return y0 }
+
+var x0 = T0{}
+
+var y0 /* ERROR "initialization cycle" */ = x0.m()
+
+type T1 struct{}
+
+func (T1) m() int { return y1 }
+
+var x1 interface {
+ m() int
+} = T1{}
+
+var y1 = x1.m() // no cycle reported, x1 is of interface type
+
+// issue 6703 (modified)
+
+var x2 /* ERROR "initialization cycle" */ = T2.m
+
+var y2 = x2
+
+type T2 struct{}
+
+func (T2) m() int {
+ _ = y2
+ return 0
+}
+
+var x3 /* ERROR "initialization cycle" */ = T3.m(T3{}) // <<<< added (T3{})
+
+var y3 = x3
+
+type T3 struct{}
+
+func (T3) m() int {
+ _ = y3
+ return 0
+}
+
+var x4 /* ERROR "initialization cycle" */ = T4{}.m // <<<< added {}
+
+var y4 = x4
+
+type T4 struct{}
+
+func (T4) m() int {
+ _ = y4
+ return 0
+}
+
+var x5 /* ERROR "initialization cycle" */ = T5{}.m() // <<<< added ()
+
+var y5 = x5
+
+type T5 struct{}
+
+func (T5) m() int {
+ _ = y5
+ return 0
+}
+
+// issue 4847
+// simplified test case
+
+var x6 = f6
+var y6 /* ERROR "initialization cycle" */ = f6
+func f6() { _ = y6 }
+
+// full test case
+
+type (
+ E int
+ S int
+)
+
+type matcher func(s *S) E
+
+func matchList(s *S) E { return matcher(matchAnyFn)(s) }
+
+var foo = matcher(matchList)
+
+var matchAny /* ERROR "initialization cycle" */ = matcher(matchList)
+
+func matchAnyFn(s *S) (err E) { return matchAny(s) }
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init2.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init2.go
new file mode 100644
index 0000000000000000000000000000000000000000..24e9277122cb922ab76c6d01b904f5336c67d542
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/init2.go
@@ -0,0 +1,139 @@
+// Copyright 2014 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.
+
+// initialization cycles
+
+package init2
+
+// cycles through functions
+
+func f1() int { _ = x1; return 0 }
+var x1 /* ERROR "initialization cycle" */ = f1
+
+func f2() int { _ = x2; return 0 }
+var x2 /* ERROR "initialization cycle" */ = f2()
+
+// cycles through method expressions
+
+type T3 int
+func (T3) m() int { _ = x3; return 0 }
+var x3 /* ERROR "initialization cycle" */ = T3.m
+
+type T4 int
+func (T4) m() int { _ = x4; return 0 }
+var x4 /* ERROR "initialization cycle" */ = T4.m(0)
+
+type T3p int
+func (*T3p) m() int { _ = x3p; return 0 }
+var x3p /* ERROR "initialization cycle" */ = (*T3p).m
+
+type T4p int
+func (*T4p) m() int { _ = x4p; return 0 }
+var x4p /* ERROR "initialization cycle" */ = (*T4p).m(nil)
+
+// cycles through method expressions of embedded methods
+
+type T5 struct { E5 }
+type E5 int
+func (E5) m() int { _ = x5; return 0 }
+var x5 /* ERROR "initialization cycle" */ = T5.m
+
+type T6 struct { E6 }
+type E6 int
+func (E6) m() int { _ = x6; return 0 }
+var x6 /* ERROR "initialization cycle" */ = T6.m(T6{0})
+
+type T5p struct { E5p }
+type E5p int
+func (*E5p) m() int { _ = x5p; return 0 }
+var x5p /* ERROR "initialization cycle" */ = (*T5p).m
+
+type T6p struct { E6p }
+type E6p int
+func (*E6p) m() int { _ = x6p; return 0 }
+var x6p /* ERROR "initialization cycle" */ = (*T6p).m(nil)
+
+// cycles through method values
+
+type T7 int
+func (T7) m() int { _ = x7; return 0 }
+var x7 /* ERROR "initialization cycle" */ = T7(0).m
+
+type T8 int
+func (T8) m() int { _ = x8; return 0 }
+var x8 /* ERROR "initialization cycle" */ = T8(0).m()
+
+type T7p int
+func (*T7p) m() int { _ = x7p; return 0 }
+var x7p /* ERROR "initialization cycle" */ = new(T7p).m
+
+type T8p int
+func (*T8p) m() int { _ = x8p; return 0 }
+var x8p /* ERROR "initialization cycle" */ = new(T8p).m()
+
+type T7v int
+func (T7v) m() int { _ = x7v; return 0 }
+var x7var T7v
+var x7v /* ERROR "initialization cycle" */ = x7var.m
+
+type T8v int
+func (T8v) m() int { _ = x8v; return 0 }
+var x8var T8v
+var x8v /* ERROR "initialization cycle" */ = x8var.m()
+
+type T7pv int
+func (*T7pv) m() int { _ = x7pv; return 0 }
+var x7pvar *T7pv
+var x7pv /* ERROR "initialization cycle" */ = x7pvar.m
+
+type T8pv int
+func (*T8pv) m() int { _ = x8pv; return 0 }
+var x8pvar *T8pv
+var x8pv /* ERROR "initialization cycle" */ = x8pvar.m()
+
+// cycles through method values of embedded methods
+
+type T9 struct { E9 }
+type E9 int
+func (E9) m() int { _ = x9; return 0 }
+var x9 /* ERROR "initialization cycle" */ = T9{0}.m
+
+type T10 struct { E10 }
+type E10 int
+func (E10) m() int { _ = x10; return 0 }
+var x10 /* ERROR "initialization cycle" */ = T10{0}.m()
+
+type T9p struct { E9p }
+type E9p int
+func (*E9p) m() int { _ = x9p; return 0 }
+var x9p /* ERROR "initialization cycle" */ = new(T9p).m
+
+type T10p struct { E10p }
+type E10p int
+func (*E10p) m() int { _ = x10p; return 0 }
+var x10p /* ERROR "initialization cycle" */ = new(T10p).m()
+
+type T9v struct { E9v }
+type E9v int
+func (E9v) m() int { _ = x9v; return 0 }
+var x9var T9v
+var x9v /* ERROR "initialization cycle" */ = x9var.m
+
+type T10v struct { E10v }
+type E10v int
+func (E10v) m() int { _ = x10v; return 0 }
+var x10var T10v
+var x10v /* ERROR "initialization cycle" */ = x10var.m()
+
+type T9pv struct { E9pv }
+type E9pv int
+func (*E9pv) m() int { _ = x9pv; return 0 }
+var x9pvar *T9pv
+var x9pv /* ERROR "initialization cycle" */ = x9pvar.m
+
+type T10pv struct { E10pv }
+type E10pv int
+func (*E10pv) m() int { _ = x10pv; return 0 }
+var x10pvar *T10pv
+var x10pv /* ERROR "initialization cycle" */ = x10pvar.m()
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008a.go
new file mode 100644
index 0000000000000000000000000000000000000000..cf71ca10e48c771f3ed8a931ae45ff33e2d6efbd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008a.go
@@ -0,0 +1,15 @@
+// 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 p
+
+import "io"
+
+type A interface {
+ io.Reader
+}
+
+func f(a A) {
+ a.Read(nil)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008b.go
new file mode 100644
index 0000000000000000000000000000000000000000..f132b7fab3fb348eba2b5ca2046824fb46b0f554
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issue25008/issue25008b.go
@@ -0,0 +1,9 @@
+// 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 p
+
+type B interface {
+ A
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issues0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issues0.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f4d266b8a33ea7c0e29da54d7dab371ea3b46fa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/issues0.go
@@ -0,0 +1,373 @@
+// -lang=go1.17
+
+// Copyright 2014 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 // don't permit non-interface elements in interfaces
+
+import (
+ "fmt"
+ syn "regexp/syntax"
+ t1 "text/template"
+ t2 "html/template"
+)
+
+func issue7035() {
+ type T struct{ X int }
+ _ = func() {
+ fmt.Println() // must refer to imported fmt rather than the fmt below
+ }
+ fmt := new(T)
+ _ = fmt.X
+}
+
+func issue8066() {
+ const (
+ _ = float32(340282356779733661637539395458142568447)
+ _ = float32(340282356779733661637539395458142568448 /* ERROR "cannot convert" */ )
+ )
+}
+
+// Check that a missing identifier doesn't lead to a spurious error cascade.
+func issue8799a() {
+ x, ok := missing /* ERROR "undefined" */ ()
+ _ = !ok
+ _ = x
+}
+
+func issue8799b(x int, ok bool) {
+ x, ok = missing /* ERROR "undefined" */ ()
+ _ = !ok
+ _ = x
+}
+
+func issue9182() {
+ type Point C /* ERROR "undefined" */ .Point
+ // no error for composite literal based on unknown type
+ _ = Point{x: 1, y: 2}
+}
+
+func f0() (a []int) { return }
+func f1() (a []int, b int) { return }
+func f2() (a, b []int) { return }
+
+func append_([]int, ...int) {}
+
+func issue9473(a []int, b ...int) {
+ // variadic builtin function
+ _ = append(f0())
+ _ = append(f0(), f0()...)
+ _ = append(f1())
+ _ = append(f2 /* ERRORx `cannot use .* in argument` */ ())
+ _ = append(f2()... /* ERROR "cannot use ..." */ )
+ _ = append(f0(), f1 /* ERROR "multiple-value f1" */ ())
+ _ = append(f0(), f2 /* ERROR "multiple-value f2" */ ())
+ _ = append(f0(), f1 /* ERROR "multiple-value f1" */ ()...)
+ _ = append(f0(), f2 /* ERROR "multiple-value f2" */ ()...)
+
+ // variadic user-defined function
+ append_(f0())
+ append_(f0(), f0()...)
+ append_(f1())
+ append_(f2 /* ERRORx `cannot use .* in argument` */ ())
+ append_(f2()... /* ERROR "cannot use ..." */ )
+ append_(f0(), f1 /* ERROR "multiple-value f1" */ ())
+ append_(f0(), f2 /* ERROR "multiple-value f2" */ ())
+ append_(f0(), f1 /* ERROR "multiple-value f1" */ ()...)
+ append_(f0(), f2 /* ERROR "multiple-value f2" */ ()...)
+}
+
+// Check that embedding a non-interface type in an interface results in a good error message.
+func issue10979() {
+ type _ interface {
+ int /* ERROR "non-interface type int" */
+ }
+ type T struct{}
+ type _ interface {
+ T /* ERROR "non-interface type T" */
+ }
+ type _ interface {
+ nosuchtype /* ERROR "undefined: nosuchtype" */
+ }
+ type _ interface {
+ fmt.Nosuchtype /* ERROR "undefined: fmt.Nosuchtype" */
+ }
+ type _ interface {
+ nosuchpkg /* ERROR "undefined: nosuchpkg" */ .Nosuchtype
+ }
+ type I interface {
+ I.m /* ERROR "I.m is not a type" */
+ m()
+ }
+}
+
+// issue11347
+// These should not crash.
+var a1, b1 /* ERROR "cycle" */ , c1 /* ERROR "cycle" */ b1 = 0 > 0<<""[""[c1]]>c1
+var a2, b2 /* ERROR "cycle" */ = 0 /* ERROR "assignment mismatch" */ /* ERROR "assignment mismatch" */ > 0<<""[b2]
+var a3, b3 /* ERROR "cycle" */ = int /* ERROR "assignment mismatch" */ /* ERROR "assignment mismatch" */ (1<<""[b3])
+
+// issue10260
+// Check that error messages explain reason for interface assignment failures.
+type (
+ I0 interface{}
+ I1 interface{ foo() }
+ I2 interface{ foo(x int) }
+ T0 struct{}
+ T1 struct{}
+ T2 struct{}
+)
+
+func (*T1) foo() {}
+func (*T2) foo(x int) {}
+
+func issue10260() {
+ var (
+ i0 I0
+ i1 I1
+ i2 I2
+ t0 *T0
+ t1 *T1
+ t2 *T2
+ )
+
+ var x I1
+ x = T1 /* ERRORx `cannot use T1{} .* as I1 value in assignment: T1 does not implement I1 \(method foo has pointer receiver\)` */ {}
+ _ = x /* ERROR "impossible type assertion: x.(T1)\n\tT1 does not implement I1 (method foo has pointer receiver)" */ .(T1)
+
+ T1{}.foo /* ERROR "cannot call pointer method foo on T1" */ ()
+ x.Foo /* ERROR "x.Foo undefined (type I1 has no field or method Foo, but does have foo)" */ ()
+
+ _ = i2 /* ERROR "impossible type assertion: i2.(*T1)\n\t*T1 does not implement I2 (wrong type for method foo)\n\t\thave foo()\n\t\twant foo(int)" */ .(*T1)
+
+ i1 = i0 /* ERRORx `cannot use i0 .* as I1 value in assignment: I0 does not implement I1 \(missing method foo\)` */
+ i1 = t0 /* ERRORx `.* t0 .* as I1 .*: \*T0 does not implement I1 \(missing method foo\)` */
+ i1 = i2 /* ERRORx `.* i2 .* as I1 .*: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */
+ i1 = t2 /* ERRORx `.* t2 .* as I1 .*: \*T2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */
+ i2 = i1 /* ERRORx `.* i1 .* as I2 .*: I1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */
+ i2 = t1 /* ERRORx `.* t1 .* as I2 .*: \*T1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */
+
+ _ = func() I1 { return i0 /* ERRORx `cannot use i0 .* as I1 value in return statement: I0 does not implement I1 \(missing method foo\)` */ }
+ _ = func() I1 { return t0 /* ERRORx `.* t0 .* as I1 .*: \*T0 does not implement I1 \(missing method foo\)` */ }
+ _ = func() I1 { return i2 /* ERRORx `.* i2 .* as I1 .*: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ }
+ _ = func() I1 { return t2 /* ERRORx `.* t2 .* as I1 .*: \*T2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ }
+ _ = func() I2 { return i1 /* ERRORx `.* i1 .* as I2 .*: I1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ }
+ _ = func() I2 { return t1 /* ERRORx `.* t1 .* as I2 .*: \*T1 does not implement I2 \(wrong type for method foo\)\n\t\thave foo\(\)\n\t\twant foo\(int\)` */ }
+
+ // a few more - less exhaustive now
+
+ f := func(I1, I2){}
+ f(i0 /* ERROR "missing method foo" */ , i1 /* ERROR "wrong type for method foo" */ )
+
+ _ = [...]I1{i0 /* ERRORx `cannot use i0 .* as I1 value in array or slice literal: I0 does not implement I1 \(missing method foo\)` */ }
+ _ = [...]I1{i2 /* ERRORx `cannot use i2 .* as I1 value in array or slice literal: I2 does not implement I1 \(wrong type for method foo\)\n\t\thave foo\(int\)\n\t\twant foo\(\)` */ }
+ _ = []I1{i0 /* ERROR "missing method foo" */ }
+ _ = []I1{i2 /* ERROR "wrong type for method foo" */ }
+ _ = map[int]I1{0: i0 /* ERROR "missing method foo" */ }
+ _ = map[int]I1{0: i2 /* ERROR "wrong type for method foo" */ }
+
+ make(chan I1) <- i0 /* ERROR "missing method foo" */
+ make(chan I1) <- i2 /* ERROR "wrong type for method foo" */
+}
+
+// Check that constants representable as integers are in integer form
+// before being used in operations that are only defined on integers.
+func issue14229() {
+ // from the issue
+ const _ = int64(-1<<63) % 1e6
+
+ // related
+ const (
+ a int = 3
+ b = 4.0
+ _ = a / b
+ _ = a % b
+ _ = b / a
+ _ = b % a
+ )
+}
+
+// Check that in a n:1 variable declaration with type and initialization
+// expression the type is distributed to all variables of the lhs before
+// the initialization expression assignment is checked.
+func issue15755() {
+ // from issue
+ var i interface{}
+ type b bool
+ var x, y b = i.(b)
+ _ = x == y
+
+ // related: we should see an error since the result of f1 is ([]int, int)
+ var u, v []int = f1 /* ERROR "cannot use f1" */ ()
+ _ = u
+ _ = v
+}
+
+// Test that we don't get "declared and not used"
+// errors in the context of invalid/C objects.
+func issue20358() {
+ var F C /* ERROR "undefined" */ .F
+ var A C /* ERROR "undefined" */ .A
+ var S C /* ERROR "undefined" */ .S
+ type T C /* ERROR "undefined" */ .T
+ type P C /* ERROR "undefined" */ .P
+
+ // these variables must be "used" even though
+ // the LHS expressions/types below in which
+ // context they are used are unknown/invalid
+ var f, a, s1, s2, s3, t, p int
+
+ _ = F(f)
+ _ = A[a]
+ _ = S[s1:s2:s3]
+ _ = T{t}
+ _ = P{f: p}
+}
+
+// Test that we don't declare lhs variables in short variable
+// declarations before we type-check function literals on the
+// rhs.
+func issue24026() {
+ f := func() int { f(0) /* must refer to outer f */; return 0 }
+ _ = f
+
+ _ = func() {
+ f := func() { _ = f() /* must refer to outer f */ }
+ _ = f
+ }
+
+ // b and c must not be visible inside function literal
+ a := 0
+ a, b, c := func() (int, int, int) {
+ return a, b /* ERROR "undefined" */ , c /* ERROR "undefined" */
+ }()
+ _, _ = b, c
+}
+
+func f(int) {} // for issue24026
+
+// Test that we don't report a "missing return statement" error
+// (due to incorrect context when type-checking interfaces).
+func issue24140(x interface{}) int {
+ switch x.(type) {
+ case interface{}:
+ return 0
+ default:
+ panic(0)
+ }
+}
+
+// Test that we don't crash when the 'if' condition is missing.
+func issue25438() {
+ if { /* ERROR "missing condition" */ }
+ if x := 0; /* ERROR "missing condition" */ { _ = x }
+ if
+ { /* ERROR "missing condition" */ }
+}
+
+// Test that we can embed alias type names in interfaces.
+type issue25301 interface {
+ E
+}
+
+type E = interface {
+ m()
+}
+
+// Test case from issue.
+// cmd/compile reports a cycle as well.
+type issue25301b /* ERROR "invalid recursive type" */ = interface {
+ m() interface{ issue25301b }
+}
+
+type issue25301c interface {
+ notE // ERRORx "non-interface type (struct{}|notE)"
+}
+
+type notE = struct{}
+
+// Test that method declarations don't introduce artificial cycles
+// (issue #26124).
+const CC TT = 1
+type TT int
+func (TT) MM() [CC]TT
+
+// Reduced test case from issue #26124.
+const preloadLimit LNumber = 128
+type LNumber float64
+func (LNumber) assertFunction() *LFunction
+type LFunction struct {
+ GFunction LGFunction
+}
+type LGFunction func(*LState)
+type LState struct {
+ reg *registry
+}
+type registry struct {
+ alloc *allocator
+}
+type allocator struct {
+ _ [int(preloadLimit)]int
+}
+
+// Test that we don't crash when type-checking composite literals
+// containing errors in the type.
+var issue27346 = [][n /* ERROR "undefined" */ ]int{
+ 0: {},
+}
+
+var issue22467 = map[int][... /* ERROR "invalid use of [...] array" */ ]int{0: {}}
+
+// Test that invalid use of ... in parameter lists is recognized
+// (issue #28281).
+func issue28281a(int, int, ...int)
+func issue28281b(a, b int, c ...int)
+func issue28281c(a, b, c ... /* ERROR "can only use ... with final parameter" */ int)
+func issue28281d(... /* ERROR "can only use ... with final parameter" */ int, int)
+func issue28281e(a, b, c ... /* ERROR "can only use ... with final parameter" */ int, d int)
+func issue28281f(... /* ERROR "can only use ... with final parameter" */ int, ... /* ERROR "can only use ... with final parameter" */ int, int)
+func (... /* ERROR "can only use ... with final parameter" */ TT) f()
+func issue28281g() (... /* ERROR "can only use ... with final parameter" */ TT)
+
+// Issue #26234: Make various field/method lookup errors easier to read by matching cmd/compile's output
+func issue26234a(f *syn.Prog) {
+ // The error message below should refer to the actual package name (syntax)
+ // not the local package name (syn).
+ f.foo /* ERROR "f.foo undefined (type *syntax.Prog has no field or method foo)" */
+}
+
+type T struct {
+ x int
+ E1
+ E2
+}
+
+type E1 struct{ f int }
+type E2 struct{ f int }
+
+func issue26234b(x T) {
+ _ = x.f /* ERROR "ambiguous selector x.f" */
+}
+
+func issue26234c() {
+ T.x /* ERROR "T.x undefined (type T has no method x)" */ ()
+}
+
+func issue35895() {
+ // T is defined in this package, don't qualify its name with the package name.
+ var _ T = 0 // ERROR "cannot use 0 (untyped int constant) as T"
+
+ // There is only one package with name syntax imported, only use the (global) package name in error messages.
+ var _ *syn.Prog = 0 // ERROR "cannot use 0 (untyped int constant) as *syntax.Prog"
+
+ // Because both t1 and t2 have the same global package name (template),
+ // qualify packages with full path name in this case.
+ var _ t1.Template = t2 /* ERRORx `cannot use .* \(value of type .html/template.\.Template\) as .text/template.\.Template` */ .Template{}
+}
+
+func issue42989(s uint) {
+ var m map[int]string
+ delete(m, 1< 10:
+ if x == 11 {
+ break L3
+ }
+ if x == 12 {
+ continue L3 /* ERROR "invalid continue label L3" */
+ }
+ goto L3
+ }
+
+L4:
+ if true {
+ if x == 13 {
+ break L4 /* ERROR "invalid break label L4" */
+ }
+ if x == 14 {
+ continue L4 /* ERROR "invalid continue label L4" */
+ }
+ if x == 15 {
+ goto L4
+ }
+ }
+
+L5:
+ f1()
+ if x == 16 {
+ break L5 /* ERROR "invalid break label L5" */
+ }
+ if x == 17 {
+ continue L5 /* ERROR "invalid continue label L5" */
+ }
+ if x == 18 {
+ goto L5
+ }
+
+ for {
+ if x == 19 {
+ break L1 /* ERROR "invalid break label L1" */
+ }
+ if x == 20 {
+ continue L1 /* ERROR "invalid continue label L1" */
+ }
+ if x == 21 {
+ goto L1
+ }
+ }
+}
+
+// Additional tests not in the original files.
+
+func f2() {
+L1 /* ERROR "label L1 declared and not used" */ :
+ if x == 0 {
+ for {
+ continue L1 /* ERROR "invalid continue label L1" */
+ }
+ }
+}
+
+func f3() {
+L1:
+L2:
+L3:
+ for {
+ break L1 /* ERROR "invalid break label L1" */
+ break L2 /* ERROR "invalid break label L2" */
+ break L3
+ continue L1 /* ERROR "invalid continue label L1" */
+ continue L2 /* ERROR "invalid continue label L2" */
+ continue L3
+ goto L1
+ goto L2
+ goto L3
+ }
+}
+
+// Blank labels are never declared.
+
+func f4() {
+_:
+_: // multiple blank labels are ok
+ goto _ /* ERROR "label _ not declared" */
+}
+
+func f5() {
+_:
+ for {
+ break _ /* ERROR "invalid break label _" */
+ continue _ /* ERROR "invalid continue label _" */
+ }
+}
+
+func f6() {
+_:
+ switch {
+ default:
+ break _ /* ERROR "invalid break label _" */
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/linalg.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/linalg.go
new file mode 100644
index 0000000000000000000000000000000000000000..f02e773dbeeeebbafde08ab38ac4cef93f11897a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/linalg.go
@@ -0,0 +1,82 @@
+// 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 linalg
+
+// Numeric is type bound that matches any numeric type.
+// It would likely be in a constraints package in the standard library.
+type Numeric interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
+ ~float32 | ~float64 |
+ ~complex64 | ~complex128
+}
+
+func DotProduct[T Numeric](s1, s2 []T) T {
+ if len(s1) != len(s2) {
+ panic("DotProduct: slices of unequal length")
+ }
+ var r T
+ for i := range s1 {
+ r += s1[i] * s2[i]
+ }
+ return r
+}
+
+// NumericAbs matches numeric types with an Abs method.
+type NumericAbs[T any] interface {
+ Numeric
+
+ Abs() T
+}
+
+// AbsDifference computes the absolute value of the difference of
+// a and b, where the absolute value is determined by the Abs method.
+func AbsDifference[T NumericAbs[T]](a, b T) T {
+ d := a - b
+ return d.Abs()
+}
+
+// OrderedNumeric is a type bound that matches numeric types that support the < operator.
+type OrderedNumeric interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
+ ~float32 | ~float64
+}
+
+// Complex is a type bound that matches the two complex types, which do not have a < operator.
+type Complex interface {
+ ~complex64 | ~complex128
+}
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// // OrderedAbs is a helper type that defines an Abs method for
+// // ordered numeric types.
+// type OrderedAbs[T OrderedNumeric] T
+//
+// func (a OrderedAbs[T]) Abs() OrderedAbs[T] {
+// if a < 0 {
+// return -a
+// }
+// return a
+// }
+//
+// // ComplexAbs is a helper type that defines an Abs method for
+// // complex types.
+// type ComplexAbs[T Complex] T
+//
+// func (a ComplexAbs[T]) Abs() ComplexAbs[T] {
+// r := float64(real(a))
+// i := float64(imag(a))
+// d := math.Sqrt(r * r + i * i)
+// return ComplexAbs[T](complex(d, 0))
+// }
+//
+// func OrderedAbsDifference[T OrderedNumeric](a, b T) T {
+// return T(AbsDifference(OrderedAbs[T](a), OrderedAbs[T](b)))
+// }
+//
+// func ComplexAbsDifference[T Complex](a, b T) T {
+// return T(AbsDifference(ComplexAbs[T](a), ComplexAbs[T](b)))
+// }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/literals.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/literals.go
new file mode 100644
index 0000000000000000000000000000000000000000..494a465f48756717dc04153a2d27d294d60392a0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/literals.go
@@ -0,0 +1,111 @@
+// 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.
+
+// This file tests various representations of literals
+// and compares them with literals or constant expressions
+// of equal values.
+
+package literals
+
+func _() {
+ // 0-octals
+ assert(0_123 == 0123)
+ assert(0123_456 == 0123456)
+
+ // decimals
+ assert(1_234 == 1234)
+ assert(1_234_567 == 1234567)
+
+ // hexadecimals
+ assert(0X_0 == 0)
+ assert(0X_1234 == 0x1234)
+ assert(0X_CAFE_f00d == 0xcafef00d)
+
+ // octals
+ assert(0o0 == 0)
+ assert(0o1234 == 01234)
+ assert(0o01234567 == 01234567)
+
+ assert(0O0 == 0)
+ assert(0O1234 == 01234)
+ assert(0O01234567 == 01234567)
+
+ assert(0o_0 == 0)
+ assert(0o_1234 == 01234)
+ assert(0o0123_4567 == 01234567)
+
+ assert(0O_0 == 0)
+ assert(0O_1234 == 01234)
+ assert(0O0123_4567 == 01234567)
+
+ // binaries
+ assert(0b0 == 0)
+ assert(0b1011 == 0xb)
+ assert(0b00101101 == 0x2d)
+
+ assert(0B0 == 0)
+ assert(0B1011 == 0xb)
+ assert(0B00101101 == 0x2d)
+
+ assert(0b_0 == 0)
+ assert(0b10_11 == 0xb)
+ assert(0b_0010_1101 == 0x2d)
+
+ // decimal floats
+ assert(1_2_3. == 123.)
+ assert(0_123. == 123.)
+
+ assert(0_0e0 == 0.)
+ assert(1_2_3e0 == 123.)
+ assert(0_123e0 == 123.)
+
+ assert(0e-0_0 == 0.)
+ assert(1_2_3E+0 == 123.)
+ assert(0123E1_2_3 == 123e123)
+
+ assert(0.e+1 == 0.)
+ assert(123.E-1_0 == 123e-10)
+ assert(01_23.e123 == 123e123)
+
+ assert(.0e-1 == .0)
+ assert(.123E+10 == .123e10)
+ assert(.0123E123 == .0123e123)
+
+ assert(1_2_3.123 == 123.123)
+ assert(0123.01_23 == 123.0123)
+
+ // hexadecimal floats
+ assert(0x0.p+0 == 0.)
+ assert(0Xdeadcafe.p-10 == 0xdeadcafe/1024.0)
+ assert(0x1234.P84 == 0x1234000000000000000000000)
+
+ assert(0x.1p-0 == 1./16)
+ assert(0X.deadcafep4 == 1.0*0xdeadcafe/0x10000000)
+ assert(0x.1234P+12 == 1.0*0x1234/0x10)
+
+ assert(0x0p0 == 0.)
+ assert(0Xdeadcafep+1 == 0x1bd5b95fc)
+ assert(0x1234P-10 == 0x1234/1024.0)
+
+ assert(0x0.0p0 == 0.)
+ assert(0Xdead.cafep+1 == 1.0*0x1bd5b95fc/0x10000)
+ assert(0x12.34P-10 == 1.0*0x1234/0x40000)
+
+ assert(0Xdead_cafep+1 == 0xdeadcafep+1)
+ assert(0x_1234P-10 == 0x1234p-10)
+
+ assert(0X_dead_cafe.p-10 == 0xdeadcafe.p-10)
+ assert(0x12_34.P1_2_3 == 0x1234.p123)
+
+ assert(1_234i == 1234i)
+ assert(1_234_567i == 1234567i)
+
+ assert(0.i == 0i)
+ assert(123.i == 123i)
+ assert(0123.i == 123i)
+
+ assert(0.e+1i == 0i)
+ assert(123.E-1_0i == 123e-10i)
+ assert(01_23.e123i == 123e123i)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main0.go
new file mode 100644
index 0000000000000000000000000000000000000000..95a8ed1d6d0a2b25e50a94b40889f0dee6b2e66b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main0.go
@@ -0,0 +1,9 @@
+// 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 main
+
+func main()
+func main /* ERROR "no arguments and no return values" */ /* ERROR "redeclared" */ (int)
+func main /* ERROR "no arguments and no return values" */ /* ERROR "redeclared" */ () int
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main1.go
new file mode 100644
index 0000000000000000000000000000000000000000..fb567a07d085a32493b7126995a13b1a0a39962f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/main1.go
@@ -0,0 +1,7 @@
+// 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 main
+
+func main[T /* ERROR "func main must have no type parameters" */ any]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map0.go
new file mode 100644
index 0000000000000000000000000000000000000000..21c989cc9d2c248f10493bcd50089b6ecd015e06
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map0.go
@@ -0,0 +1,113 @@
+// 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 orderedmap provides an ordered map, implemented as a binary tree.
+package orderedmap
+
+// TODO(gri) fix imports for tests
+import "chans" // ERROR "could not import"
+
+// Map is an ordered map.
+type Map[K, V any] struct {
+ root *node[K, V]
+ compare func(K, K) int
+}
+
+// node is the type of a node in the binary tree.
+type node[K, V any] struct {
+ key K
+ val V
+ left, right *node[K, V]
+}
+
+// New returns a new map.
+func New[K, V any](compare func(K, K) int) *Map[K, V] {
+ return &Map[K, V]{compare: compare}
+}
+
+// find looks up key in the map, and returns either a pointer
+// to the node holding key, or a pointer to the location where
+// such a node would go.
+func (m *Map[K, V]) find(key K) **node[K, V] {
+ pn := &m.root
+ for *pn != nil {
+ switch cmp := m.compare(key, (*pn).key); {
+ case cmp < 0:
+ pn = &(*pn).left
+ case cmp > 0:
+ pn = &(*pn).right
+ default:
+ return pn
+ }
+ }
+ return pn
+}
+
+// Insert inserts a new key/value into the map.
+// If the key is already present, the value is replaced.
+// Returns true if this is a new key, false if already present.
+func (m *Map[K, V]) Insert(key K, val V) bool {
+ pn := m.find(key)
+ if *pn != nil {
+ (*pn).val = val
+ return false
+ }
+ *pn = &node[K, V]{key: key, val: val}
+ return true
+}
+
+// Find returns the value associated with a key, or zero if not present.
+// The found result reports whether the key was found.
+func (m *Map[K, V]) Find(key K) (V, bool) {
+ pn := m.find(key)
+ if *pn == nil {
+ var zero V // see the discussion of zero values, above
+ return zero, false
+ }
+ return (*pn).val, true
+}
+
+// keyValue is a pair of key and value used when iterating.
+type keyValue[K, V any] struct {
+ key K
+ val V
+}
+
+// InOrder returns an iterator that does an in-order traversal of the map.
+func (m *Map[K, V]) InOrder() *Iterator[K, V] {
+ sender, receiver := chans.Ranger[keyValue[K, V]]()
+ var f func(*node[K, V]) bool
+ f = func(n *node[K, V]) bool {
+ if n == nil {
+ return true
+ }
+ // Stop sending values if sender.Send returns false,
+ // meaning that nothing is listening at the receiver end.
+ return f(n.left) &&
+ sender.Send(keyValue[K, V]{n.key, n.val}) &&
+ f(n.right)
+ }
+ go func() {
+ f(m.root)
+ sender.Close()
+ }()
+ return &Iterator[K, V]{receiver}
+}
+
+// Iterator is used to iterate over the map.
+type Iterator[K, V any] struct {
+ r *chans.Receiver[keyValue[K, V]]
+}
+
+// Next returns the next key and value pair, and a boolean indicating
+// whether they are valid or whether we have reached the end.
+func (it *Iterator[K, V]) Next() (K, V, bool) {
+ keyval, ok := it.r.Next()
+ if !ok {
+ var zerok K
+ var zerov V
+ return zerok, zerov, false
+ }
+ return keyval.key, keyval.val, true
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map1.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map1.go
new file mode 100644
index 0000000000000000000000000000000000000000..e13bf33feda9edb1f87910f9bda04d4f7908bd9e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/map1.go
@@ -0,0 +1,146 @@
+// 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.
+
+// This file is like map.go2, but instead if importing chans, it contains
+// the necessary functionality at the end of the file.
+
+// Package orderedmap provides an ordered map, implemented as a binary tree.
+package orderedmap
+
+// Map is an ordered map.
+type Map[K, V any] struct {
+ root *node[K, V]
+ compare func(K, K) int
+}
+
+// node is the type of a node in the binary tree.
+type node[K, V any] struct {
+ key K
+ val V
+ left, right *node[K, V]
+}
+
+// New returns a new map.
+func New[K, V any](compare func(K, K) int) *Map[K, V] {
+ return &Map[K, V]{compare: compare}
+}
+
+// find looks up key in the map, and returns either a pointer
+// to the node holding key, or a pointer to the location where
+// such a node would go.
+func (m *Map[K, V]) find(key K) **node[K, V] {
+ pn := &m.root
+ for *pn != nil {
+ switch cmp := m.compare(key, (*pn).key); {
+ case cmp < 0:
+ pn = &(*pn).left
+ case cmp > 0:
+ pn = &(*pn).right
+ default:
+ return pn
+ }
+ }
+ return pn
+}
+
+// Insert inserts a new key/value into the map.
+// If the key is already present, the value is replaced.
+// Returns true if this is a new key, false if already present.
+func (m *Map[K, V]) Insert(key K, val V) bool {
+ pn := m.find(key)
+ if *pn != nil {
+ (*pn).val = val
+ return false
+ }
+ *pn = &node[K, V]{key: key, val: val}
+ return true
+}
+
+// Find returns the value associated with a key, or zero if not present.
+// The found result reports whether the key was found.
+func (m *Map[K, V]) Find(key K) (V, bool) {
+ pn := m.find(key)
+ if *pn == nil {
+ var zero V // see the discussion of zero values, above
+ return zero, false
+ }
+ return (*pn).val, true
+}
+
+// keyValue is a pair of key and value used when iterating.
+type keyValue[K, V any] struct {
+ key K
+ val V
+}
+
+// InOrder returns an iterator that does an in-order traversal of the map.
+func (m *Map[K, V]) InOrder() *Iterator[K, V] {
+ sender, receiver := chans_Ranger[keyValue[K, V]]()
+ var f func(*node[K, V]) bool
+ f = func(n *node[K, V]) bool {
+ if n == nil {
+ return true
+ }
+ // Stop sending values if sender.Send returns false,
+ // meaning that nothing is listening at the receiver end.
+ return f(n.left) &&
+ sender.Send(keyValue[K, V]{n.key, n.val}) &&
+ f(n.right)
+ }
+ go func() {
+ f(m.root)
+ sender.Close()
+ }()
+ return &Iterator[K, V]{receiver}
+}
+
+// Iterator is used to iterate over the map.
+type Iterator[K, V any] struct {
+ r *chans_Receiver[keyValue[K, V]]
+}
+
+// Next returns the next key and value pair, and a boolean indicating
+// whether they are valid or whether we have reached the end.
+func (it *Iterator[K, V]) Next() (K, V, bool) {
+ keyval, ok := it.r.Next()
+ if !ok {
+ var zerok K
+ var zerov V
+ return zerok, zerov, false
+ }
+ return keyval.key, keyval.val, true
+}
+
+// chans
+
+func chans_Ranger[T any]() (*chans_Sender[T], *chans_Receiver[T]) { panic(0) }
+
+// A sender is used to send values to a Receiver.
+type chans_Sender[T any] struct {
+ values chan<- T
+ done <-chan bool
+}
+
+func (s *chans_Sender[T]) Send(v T) bool {
+ select {
+ case s.values <- v:
+ return true
+ case <-s.done:
+ return false
+ }
+}
+
+func (s *chans_Sender[T]) Close() {
+ close(s.values)
+}
+
+type chans_Receiver[T any] struct {
+ values <-chan T
+ done chan<- bool
+}
+
+func (r *chans_Receiver[T]) Next() (T, bool) {
+ v, ok := <-r.values
+ return v, ok
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/methodsets.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/methodsets.go
new file mode 100644
index 0000000000000000000000000000000000000000..5b3e4a296ca8c3b93f29bd80b205b4447babae1b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/methodsets.go
@@ -0,0 +1,214 @@
+// 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 methodsets
+
+type T0 struct {}
+
+func (T0) v0() {}
+func (*T0) p0() {}
+
+type T1 struct {} // like T0 with different method names
+
+func (T1) v1() {}
+func (*T1) p1() {}
+
+type T2 interface {
+ v2()
+ p2()
+}
+
+type T3 struct {
+ T0
+ *T1
+ T2
+}
+
+// Method expressions
+func _() {
+ var (
+ _ func(T0) = T0.v0
+ _ = T0.p0 /* ERROR "invalid method expression T0.p0 (needs pointer receiver (*T0).p0)" */
+
+ _ func (*T0) = (*T0).v0
+ _ func (*T0) = (*T0).p0
+
+ // T1 is like T0
+
+ _ func(T2) = T2.v2
+ _ func(T2) = T2.p2
+
+ _ func(T3) = T3.v0
+ _ func(T3) = T3.p0 /* ERROR "invalid method expression T3.p0 (needs pointer receiver (*T3).p0)" */
+ _ func(T3) = T3.v1
+ _ func(T3) = T3.p1
+ _ func(T3) = T3.v2
+ _ func(T3) = T3.p2
+
+ _ func(*T3) = (*T3).v0
+ _ func(*T3) = (*T3).p0
+ _ func(*T3) = (*T3).v1
+ _ func(*T3) = (*T3).p1
+ _ func(*T3) = (*T3).v2
+ _ func(*T3) = (*T3).p2
+ )
+}
+
+// Method values with addressable receivers
+func _() {
+ var (
+ v0 T0
+ _ func() = v0.v0
+ _ func() = v0.p0
+ )
+
+ var (
+ p0 *T0
+ _ func() = p0.v0
+ _ func() = p0.p0
+ )
+
+ // T1 is like T0
+
+ var (
+ v2 T2
+ _ func() = v2.v2
+ _ func() = v2.p2
+ )
+
+ var (
+ v4 T3
+ _ func() = v4.v0
+ _ func() = v4.p0
+ _ func() = v4.v1
+ _ func() = v4.p1
+ _ func() = v4.v2
+ _ func() = v4.p2
+ )
+
+ var (
+ p4 *T3
+ _ func() = p4.v0
+ _ func() = p4.p0
+ _ func() = p4.v1
+ _ func() = p4.p1
+ _ func() = p4.v2
+ _ func() = p4.p2
+ )
+}
+
+// Method calls with addressable receivers
+func _() {
+ var v0 T0
+ v0.v0()
+ v0.p0()
+
+ var p0 *T0
+ p0.v0()
+ p0.p0()
+
+ // T1 is like T0
+
+ var v2 T2
+ v2.v2()
+ v2.p2()
+
+ var v4 T3
+ v4.v0()
+ v4.p0()
+ v4.v1()
+ v4.p1()
+ v4.v2()
+ v4.p2()
+
+ var p4 *T3
+ p4.v0()
+ p4.p0()
+ p4.v1()
+ p4.p1()
+ p4.v2()
+ p4.p2()
+}
+
+// Method values with value receivers
+func _() {
+ var (
+ _ func() = T0{}.v0
+ _ func() = T0{}.p0 /* ERROR "cannot call pointer method p0 on T0" */
+
+ _ func() = (&T0{}).v0
+ _ func() = (&T0{}).p0
+
+ // T1 is like T0
+
+ // no values for T2
+
+ _ func() = T3{}.v0
+ _ func() = T3{}.p0 /* ERROR "cannot call pointer method p0 on T3" */
+ _ func() = T3{}.v1
+ _ func() = T3{}.p1
+ _ func() = T3{}.v2
+ _ func() = T3{}.p2
+
+ _ func() = (&T3{}).v0
+ _ func() = (&T3{}).p0
+ _ func() = (&T3{}).v1
+ _ func() = (&T3{}).p1
+ _ func() = (&T3{}).v2
+ _ func() = (&T3{}).p2
+ )
+}
+
+// Method calls with value receivers
+func _() {
+ T0{}.v0()
+ T0{}.p0 /* ERROR "cannot call pointer method p0 on T0" */ ()
+
+ (&T0{}).v0()
+ (&T0{}).p0()
+
+ // T1 is like T0
+
+ // no values for T2
+
+ T3{}.v0()
+ T3{}.p0 /* ERROR "cannot call pointer method p0 on T3" */ ()
+ T3{}.v1()
+ T3{}.p1()
+ T3{}.v2()
+ T3{}.p2()
+
+ (&T3{}).v0()
+ (&T3{}).p0()
+ (&T3{}).v1()
+ (&T3{}).p1()
+ (&T3{}).v2()
+ (&T3{}).p2()
+}
+
+// *T has no methods if T is an interface type
+func issue5918() {
+ var (
+ err error
+ _ = err.Error()
+ _ func() string = err.Error
+ _ func(error) string = error.Error
+
+ perr = &err
+ _ = perr.Error /* ERROR "type *error is pointer to interface, not interface" */ ()
+ _ func() string = perr.Error /* ERROR "type *error is pointer to interface, not interface" */
+ _ func(*error) string = (*error).Error /* ERROR "type *error is pointer to interface, not interface" */
+ )
+
+ type T *interface{ m() int }
+ var (
+ x T
+ _ = (*x).m()
+ _ = (*x).m
+
+ _ = x.m /* ERROR "type T is pointer to interface, not interface" */ ()
+ _ = x.m /* ERROR "type T is pointer to interface, not interface" */
+ _ = T.m /* ERROR "type T is pointer to interface, not interface" */
+ )
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/shifts.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/shifts.go
new file mode 100644
index 0000000000000000000000000000000000000000..6ae3985aba4b7bd2197356b29767b92601ef3931
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/shifts.go
@@ -0,0 +1,399 @@
+// 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 shifts
+
+func shifts0() {
+ // basic constant shifts
+ const (
+ s = 10
+ _ = 0<<0
+ _ = 1<> s)
+ _, _, _ = u, v, x
+}
+
+func shifts4() {
+ // shifts in comparisons w/ untyped operands
+ var s uint
+
+ _ = 1<> 1.1 /* ERROR "truncated to uint" */ // example from issue 11325
+ _ = 0 >> 1.1 /* ERROR "truncated to uint" */
+ _ = 0 << 1.1 /* ERROR "truncated to uint" */
+ _ = 0 >> 1.
+ _ = 1 >> 1.1 /* ERROR "truncated to uint" */
+ _ = 1 >> 1.
+ _ = 1. >> 1
+ _ = 1. >> 1.
+ _ = 1.1 /* ERROR "must be integer" */ >> 1
+}
+
+func issue11594() {
+ var _ = complex64 /* ERROR "must be integer" */ (1) << 2 // example from issue 11594
+ _ = float32 /* ERROR "must be integer" */ (0) << 1
+ _ = float64 /* ERROR "must be integer" */ (0) >> 2
+ _ = complex64 /* ERROR "must be integer" */ (0) << 3
+ _ = complex64 /* ERROR "must be integer" */ (0) >> 4
+}
+
+func issue21727() {
+ var s uint
+ var a = make([]int, 1< 255:
+ return 255
+ }
+}
+
+var input = []int{-4, 68954, 7, 44, 0, -555, 6945}
+var limited1 = Map[int, byte](input, limiter)
+var limited2 = Map(input, limiter) // using type inference
+
+func reducer(x float64, y int) float64 {
+ return x + float64(y)
+}
+
+var reduced1 = Reduce[int, float64](input, 0, reducer)
+var reduced2 = Reduce(input, 1i /* ERROR "overflows" */, reducer) // using type inference
+var reduced3 = Reduce(input, 1, reducer) // using type inference
+
+func filter(x int) bool {
+ return x&1 != 0
+}
+
+var filtered1 = Filter[int](input, filter)
+var filtered2 = Filter(input, filter) // using type inference
+
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/stmt0.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/stmt0.go
new file mode 100644
index 0000000000000000000000000000000000000000..d7ae8f8a02bfc36f0febe22c5b8adc55b94cd734
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/stmt0.go
@@ -0,0 +1,994 @@
+// 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.
+
+// statements
+
+package stmt0
+
+func assignments0() (int, int) {
+ var a, b, c int
+ var ch chan int
+ f0 := func() {}
+ f1 := func() int { return 1 }
+ f2 := func() (int, int) { return 1, 2 }
+ f3 := func() (int, int, int) { return 1, 2, 3 }
+
+ a, b, c = 1, 2, 3
+ a, b, c = 1 /* ERROR "assignment mismatch: 3 variables but 2 values" */ , 2
+ a, b, c = 1 /* ERROR "assignment mismatch: 3 variables but 4 values" */ , 2, 3, 4
+ _, _, _ = a, b, c
+
+ a = f0 /* ERROR "used as value" */ ()
+ a = f1()
+ a = f2 /* ERROR "assignment mismatch: 1 variable but f2 returns 2 values" */ ()
+ a, b = f2()
+ a, b, c = f2 /* ERROR "assignment mismatch: 3 variables but f2 returns 2 values" */ ()
+ a, b, c = f3()
+ a, b = f3 /* ERROR "assignment mismatch: 2 variables but f3 returns 3 values" */ ()
+
+ a, b, c = <- /* ERROR "assignment mismatch: 3 variables but 1 value" */ ch
+
+ return /* ERROR "not enough return values\n\thave ()\n\twant (int, int)" */
+ return 1 /* ERROR "not enough return values\n\thave (number)\n\twant (int, int)" */
+ return 1, 2
+ return 1, 2, 3 /* ERROR "too many return values\n\thave (number, number, number)\n\twant (int, int)" */
+}
+
+func assignments1() {
+ b, i, f, c, s := false, 1, 1.0, 1i, "foo"
+ b = i /* ERRORx `cannot use .* in assignment` */
+ i = f /* ERRORx `cannot use .* in assignment` */
+ f = c /* ERRORx `cannot use .* in assignment` */
+ c = s /* ERRORx `cannot use .* in assignment` */
+ s = b /* ERRORx `cannot use .* in assignment` */
+
+ v0, v1, v2 := 1 /* ERROR "assignment mismatch" */ , 2, 3, 4
+ _, _, _ = v0, v1, v2
+
+ b = true
+
+ i += 1
+ i /* ERROR "mismatched types int and untyped string" */+= "foo"
+
+ f -= 1
+ f /= 0
+ f = float32(0)/0 /* ERROR "division by zero" */
+ f /* ERROR "mismatched types float64 and untyped string" */-= "foo"
+
+ c *= 1
+ c /= 0
+
+ s += "bar"
+ s /* ERROR "mismatched types string and untyped int" */+= 1
+
+ var u64 uint64
+ u64 += 1< 0 {
+ return l[0], true
+ }
+ return
+}
+
+// A test case for instantiating types with other types (extracted from map.go2)
+
+type Pair[K any] struct {
+ key K
+}
+
+type Receiver[T any] struct {
+ values T
+}
+
+type Iterator[K any] struct {
+ r Receiver[Pair[K]]
+}
+
+func Values [T any] (r Receiver[T]) T {
+ return r.values
+}
+
+func (it Iterator[K]) Next() K {
+ return Values[Pair[K]](it.r).key
+}
+
+// A more complex test case testing type bounds (extracted from linalg.go2 and reduced to essence)
+
+type NumericAbs[T any] interface {
+ Abs() T
+}
+
+func AbsDifference[T NumericAbs[T]](x T) { panic(0) }
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type OrderedAbs[T any] T
+//
+// func (a OrderedAbs[T]) Abs() OrderedAbs[T]
+//
+// func OrderedAbsDifference[T any](x T) {
+// AbsDifference(OrderedAbs[T](x))
+// }
+
+// same code, reduced to essence
+
+func g[P interface{ m() P }](x P) { panic(0) }
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type T4[P any] P
+//
+// func (_ T4[P]) m() T4[P]
+//
+// func _[Q any](x Q) {
+// g(T4[Q](x))
+// }
+
+// Another test case that caused problems in the past
+
+type T5[_ interface { a() }, _ interface{}] struct{}
+
+type A[P any] struct{ x P }
+
+func (_ A[P]) a() {}
+
+var _ T5[A[int], int]
+
+// Invoking methods with parameterized receiver types uses
+// type inference to determine the actual type arguments matching
+// the receiver type parameters from the actual receiver argument.
+// Go does implicit address-taking and dereferenciation depending
+// on the actual receiver and the method's receiver type. To make
+// type inference work, the type-checker matches "pointer-ness"
+// of the actual receiver and the method's receiver type.
+// The following code tests this mechanism.
+
+type R1[A any] struct{}
+func (_ R1[A]) vm()
+func (_ *R1[A]) pm()
+
+func _[T any](r R1[T], p *R1[T]) {
+ r.vm()
+ r.pm()
+ p.vm()
+ p.pm()
+}
+
+type R2[A, B any] struct{}
+func (_ R2[A, B]) vm()
+func (_ *R2[A, B]) pm()
+
+func _[T any](r R2[T, int], p *R2[string, T]) {
+ r.vm()
+ r.pm()
+ p.vm()
+ p.pm()
+}
+
+// It is ok to have multiple embedded unions.
+type _ interface {
+ m0()
+ ~int | ~string | ~bool
+ ~float32 | ~float64
+ m1()
+ m2()
+ ~complex64 | ~complex128
+ ~rune
+}
+
+// Type sets may contain each type at most once.
+type _ interface {
+ ~int|~ /* ERROR "overlapping terms ~int" */ int
+ ~int|int /* ERROR "overlapping terms int" */
+ int|int /* ERROR "overlapping terms int" */
+}
+
+type _ interface {
+ ~struct{f int} | ~struct{g int} | ~ /* ERROR "overlapping terms" */ struct{f int}
+}
+
+// Interface term lists can contain any type, incl. *Named types.
+// Verify that we use the underlying type(s) of the type(s) in the
+// term list when determining if an operation is permitted.
+
+type MyInt int
+func add1[T interface{MyInt}](x T) T {
+ return x + 1
+}
+
+type MyString string
+func double[T interface{MyInt|MyString}](x T) T {
+ return x + x
+}
+
+// Embedding of interfaces with term lists leads to interfaces
+// with term lists that are the intersection of the embedded
+// term lists.
+
+type E0 interface {
+ ~int | ~bool | ~string
+}
+
+type E1 interface {
+ ~int | ~float64 | ~string
+}
+
+type E2 interface {
+ ~float64
+}
+
+type I0 interface {
+ E0
+}
+
+func f0[T I0]() {}
+var _ = f0[int]
+var _ = f0[bool]
+var _ = f0[string]
+var _ = f0[float64 /* ERROR "does not satisfy I0" */ ]
+
+type I01 interface {
+ E0
+ E1
+}
+
+func f01[T I01]() {}
+var _ = f01[int]
+var _ = f01[bool /* ERROR "does not satisfy I0" */ ]
+var _ = f01[string]
+var _ = f01[float64 /* ERROR "does not satisfy I0" */ ]
+
+type I012 interface {
+ E0
+ E1
+ E2
+}
+
+func f012[T I012]() {}
+var _ = f012[int /* ERRORx `cannot satisfy I012.*empty type set` */ ]
+var _ = f012[bool /* ERRORx `cannot satisfy I012.*empty type set` */ ]
+var _ = f012[string /* ERRORx `cannot satisfy I012.*empty type set` */ ]
+var _ = f012[float64 /* ERRORx `cannot satisfy I012.*empty type set` */ ]
+
+type I12 interface {
+ E1
+ E2
+}
+
+func f12[T I12]() {}
+var _ = f12[int /* ERROR "does not satisfy I12" */ ]
+var _ = f12[bool /* ERROR "does not satisfy I12" */ ]
+var _ = f12[string /* ERROR "does not satisfy I12" */ ]
+var _ = f12[float64]
+
+type I0_ interface {
+ E0
+ ~int
+}
+
+func f0_[T I0_]() {}
+var _ = f0_[int]
+var _ = f0_[bool /* ERROR "does not satisfy I0_" */ ]
+var _ = f0_[string /* ERROR "does not satisfy I0_" */ ]
+var _ = f0_[float64 /* ERROR "does not satisfy I0_" */ ]
+
+// Using a function instance as a type is an error.
+var _ f0 // ERROR "not a type"
+var _ f0 /* ERROR "not a type" */ [int]
+
+// Empty type sets can only be satisfied by empty type sets.
+type none interface {
+ // force an empty type set
+ int
+ string
+}
+
+func ff[T none]() {}
+func gg[T any]() {}
+func hh[T ~int]() {}
+
+func _[T none]() {
+ _ = ff[int /* ERROR "cannot satisfy none (empty type set)" */ ]
+ _ = ff[T] // pathological but ok because T's type set is empty, too
+ _ = gg[int]
+ _ = gg[T]
+ _ = hh[int]
+ _ = hh[T]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeinstcycles.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeinstcycles.go
new file mode 100644
index 0000000000000000000000000000000000000000..74fe19195a8e5e6cc4227c2ba897ff452df56295
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeinstcycles.go
@@ -0,0 +1,11 @@
+// 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
+
+import "unsafe"
+
+func F1[T any](_ [unsafe.Sizeof(F1[int])]T) (res T) { return }
+func F2[T any](_ T) (res [unsafe.Sizeof(F2[string])]int) { return }
+func F3[T any](_ [unsafe.Sizeof(F1[string])]int) {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeparams.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeparams.go
new file mode 100644
index 0000000000000000000000000000000000000000..b002377df79e02b054cce0387067fb6d9a8d8465
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/typeparams.go
@@ -0,0 +1,508 @@
+// 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 p
+
+// import "io" // for type assertion tests
+
+var _ any // ok to use any anywhere
+func _[_ any, _ interface{any}](any) {
+ var _ any
+}
+
+func identity[T any](x T) T { return x }
+
+func _[_ any](x int) int { panic(0) }
+func _[T any](T /* ERROR "redeclared" */ T)() {}
+func _[T, T /* ERROR "redeclared" */ any]() {}
+
+// Constraints (incl. any) may be parenthesized.
+func _[_ (any)]() {}
+func _[_ (interface{})]() {}
+
+func reverse[T any](list []T) []T {
+ rlist := make([]T, len(list))
+ i := len(list)
+ for _, x := range list {
+ i--
+ rlist[i] = x
+ }
+ return rlist
+}
+
+var _ = reverse /* ERROR "cannot use generic function reverse" */
+var _ = reverse[int, float32 /* ERROR "got 2 type arguments" */ ] ([]int{1, 2, 3})
+var _ = reverse[int]([ /* ERROR "cannot use" */ ]float32{1, 2, 3})
+var f = reverse[chan int]
+var _ = f(0 /* ERRORx `cannot use 0 .* as \[\]chan int` */ )
+
+func swap[A, B any](a A, b B) (B, A) { return b, a }
+
+var _ = swap /* ERROR "multiple-value" */ [int, float32](1, 2)
+var f32, i = swap[int, float32](swap[float32, int](1, 2))
+var _ float32 = f32
+var _ int = i
+
+func swapswap[A, B any](a A, b B) (A, B) {
+ return swap[B, A](b, a)
+}
+
+type F[A, B any] func(A, B) (B, A)
+
+func min[T interface{ ~int }](x, y T) T {
+ if x < y {
+ return x
+ }
+ return y
+}
+
+func _[T interface{~int | ~float32}](x, y T) bool { return x < y }
+func _[T any](x, y T) bool { return x /* ERROR "type parameter T is not comparable" */ < y }
+func _[T interface{~int | ~float32 | ~bool}](x, y T) bool { return x /* ERROR "type parameter T is not comparable" */ < y }
+
+func _[T C1[T]](x, y T) bool { return x /* ERROR "type parameter T is not comparable" */ < y }
+func _[T C2[T]](x, y T) bool { return x < y }
+
+type C1[T any] interface{}
+type C2[T any] interface{ ~int | ~float32 }
+
+func new[T any]() *T {
+ var x T
+ return &x
+}
+
+var _ = new /* ERROR "cannot use generic function new" */
+var _ *int = new[int]()
+
+func _[T any](map[T /* ERROR "invalid map key type T (missing comparable constraint)" */]int) {} // w/o constraint we don't know if T is comparable
+
+func f1[T1 any](struct{T1 /* ERRORx `cannot be a .* type parameter` */ }) int { panic(0) }
+var _ = f1[int](struct{T1}{})
+type T1 = int
+
+func f2[t1 any](struct{t1 /* ERRORx `cannot be a .* type parameter` */ ; x float32}) int { panic(0) }
+var _ = f2[t1](struct{t1; x float32}{})
+type t1 = int
+
+
+func f3[A, B, C any](A, struct{x B}, func(A, struct{x B}, *C)) int { panic(0) }
+
+var _ = f3[int, rune, bool](1, struct{x rune}{}, nil)
+
+// indexing
+
+func _[T any] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] }
+func _[T interface{ ~int }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] }
+func _[T interface{ ~string }] (x T, i int) { _ = x[i] }
+func _[T interface{ ~[]int }] (x T, i int) { _ = x[i] }
+func _[T interface{ ~[10]int | ~*[20]int | ~map[int]int }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types
+func _[T interface{ ~string | ~[]byte }] (x T, i int) { _ = x[i] }
+func _[T interface{ ~[]int | ~[1]rune }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] }
+func _[T interface{ ~string | ~[]rune }] (x T, i int) { _ = x /* ERROR "cannot index" */ [i] }
+
+// indexing with various combinations of map types in type sets (see issue #42616)
+func _[T interface{ ~[]E | ~map[int]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types
+func _[T interface{ ~[]E }, E any](x T, i int) { _ = &x[i] }
+func _[T interface{ ~map[int]E }, E any](x T, i int) { _, _ = x[i] } // comma-ok permitted
+func _[T interface{ ~map[int]E }, E any](x T, i int) { _ = &x /* ERROR "cannot take address" */ [i] }
+func _[T interface{ ~map[int]E | ~map[uint]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // different map element types
+func _[T interface{ ~[]E | ~map[string]E }, E any](x T, i int) { _ = x /* ERROR "cannot index" */ [i] } // map and non-map types
+
+// indexing with various combinations of array and other types in type sets
+func _[T interface{ [10]int }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] }
+func _[T interface{ [10]byte | string }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] }
+func _[T interface{ [10]int | *[20]int | []int }](x T, i int) { _ = x[i]; _ = x[9]; _ = x[10 /* ERROR "out of bounds" */ ] }
+
+// indexing with strings and non-variable arrays (assignment not permitted)
+func _[T string](x T) { _ = x[0]; x /* ERROR "cannot assign" */ [0] = 0 }
+func _[T []byte | string](x T) { x /* ERROR "cannot assign" */ [0] = 0 }
+func _[T [10]byte]() { f := func() (x T) { return }; f /* ERROR "cannot assign" */ ()[0] = 0 }
+func _[T [10]byte]() { f := func() (x *T) { return }; f /* ERROR "cannot index" */ ()[0] = 0 }
+func _[T [10]byte]() { f := func() (x *T) { return }; (*f())[0] = 0 }
+func _[T *[10]byte]() { f := func() (x T) { return }; f()[0] = 0 }
+
+// slicing
+
+func _[T interface{ ~[10]E }, E any] (x T, i, j, k int) { var _ []E = x[i:j] }
+func _[T interface{ ~[10]E }, E any] (x T, i, j, k int) { var _ []E = x[i:j:k] }
+func _[T interface{ ~[]byte }] (x T, i, j, k int) { var _ T = x[i:j] }
+func _[T interface{ ~[]byte }] (x T, i, j, k int) { var _ T = x[i:j:k] }
+func _[T interface{ ~string }] (x T, i, j, k int) { var _ T = x[i:j] }
+func _[T interface{ ~string }] (x T, i, j, k int) { var _ T = x[i:j:k /* ERROR "3-index slice of string" */ ] }
+
+type myByte1 []byte
+type myByte2 []byte
+func _[T interface{ []byte | myByte1 | myByte2 }] (x T, i, j, k int) { var _ T = x[i:j:k] }
+func _[T interface{ []byte | myByte1 | []int }] (x T, i, j, k int) { var _ T = x /* ERROR "no core type" */ [i:j:k] }
+
+func _[T interface{ []byte | myByte1 | myByte2 | string }] (x T, i, j, k int) { var _ T = x[i:j] }
+func _[T interface{ []byte | myByte1 | myByte2 | string }] (x T, i, j, k int) { var _ T = x[i:j:k /* ERROR "3-index slice of string" */ ] }
+func _[T interface{ []byte | myByte1 | []int | string }] (x T, i, j, k int) { var _ T = x /* ERROR "no core type" */ [i:j] }
+
+// len/cap built-ins
+
+func _[T any](x T) { _ = len(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~int }](x T) { _ = len(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~string | ~[]byte | ~int }](x T) { _ = len(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~string }](x T) { _ = len(x) }
+func _[T interface{ ~[10]int }](x T) { _ = len(x) }
+func _[T interface{ ~[]byte }](x T) { _ = len(x) }
+func _[T interface{ ~map[int]int }](x T) { _ = len(x) }
+func _[T interface{ ~chan int }](x T) { _ = len(x) }
+func _[T interface{ ~string | ~[]byte | ~chan int }](x T) { _ = len(x) }
+
+func _[T any](x T) { _ = cap(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~string | ~[]byte | ~int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~string }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~[10]int }](x T) { _ = cap(x) }
+func _[T interface{ ~[]byte }](x T) { _ = cap(x) }
+func _[T interface{ ~map[int]int }](x T) { _ = cap(x /* ERROR "invalid argument" */ ) }
+func _[T interface{ ~chan int }](x T) { _ = cap(x) }
+func _[T interface{ ~[]byte | ~chan int }](x T) { _ = cap(x) }
+
+// range iteration
+
+func _[T interface{}](x T) {
+ for range x /* ERROR "cannot range" */ {}
+}
+
+type myString string
+
+func _[
+ B1 interface{ string },
+ B2 interface{ string | myString },
+
+ C1 interface{ chan int },
+ C2 interface{ chan int | <-chan int },
+ C3 interface{ chan<- int },
+
+ S1 interface{ []int },
+ S2 interface{ []int | [10]int },
+
+ A1 interface{ [10]int },
+ A2 interface{ [10]int | []int },
+
+ P1 interface{ *[10]int },
+ P2 interface{ *[10]int | *[]int },
+
+ M1 interface{ map[string]int },
+ M2 interface{ map[string]int | map[string]string },
+]() {
+ var b0 string
+ for range b0 {}
+ for _ = range b0 {}
+ for _, _ = range b0 {}
+
+ var b1 B1
+ for range b1 {}
+ for _ = range b1 {}
+ for _, _ = range b1 {}
+
+ var b2 B2
+ for range b2 {}
+
+ var c0 chan int
+ for range c0 {}
+ for _ = range c0 {}
+ for _, _ /* ERROR "permits only one iteration variable" */ = range c0 {}
+
+ var c1 C1
+ for range c1 {}
+ for _ = range c1 {}
+ for _, _ /* ERROR "permits only one iteration variable" */ = range c1 {}
+
+ var c2 C2
+ for range c2 {}
+
+ var c3 C3
+ for range c3 /* ERROR "receive from send-only channel" */ {}
+
+ var s0 []int
+ for range s0 {}
+ for _ = range s0 {}
+ for _, _ = range s0 {}
+
+ var s1 S1
+ for range s1 {}
+ for _ = range s1 {}
+ for _, _ = range s1 {}
+
+ var s2 S2
+ for range s2 /* ERRORx `cannot range over s2.*no core type` */ {}
+
+ var a0 []int
+ for range a0 {}
+ for _ = range a0 {}
+ for _, _ = range a0 {}
+
+ var a1 A1
+ for range a1 {}
+ for _ = range a1 {}
+ for _, _ = range a1 {}
+
+ var a2 A2
+ for range a2 /* ERRORx `cannot range over a2.*no core type` */ {}
+
+ var p0 *[10]int
+ for range p0 {}
+ for _ = range p0 {}
+ for _, _ = range p0 {}
+
+ var p1 P1
+ for range p1 {}
+ for _ = range p1 {}
+ for _, _ = range p1 {}
+
+ var p2 P2
+ for range p2 /* ERRORx `cannot range over p2.*no core type` */ {}
+
+ var m0 map[string]int
+ for range m0 {}
+ for _ = range m0 {}
+ for _, _ = range m0 {}
+
+ var m1 M1
+ for range m1 {}
+ for _ = range m1 {}
+ for _, _ = range m1 {}
+
+ var m2 M2
+ for range m2 /* ERRORx `cannot range over m2.*no core type` */ {}
+}
+
+// type inference checks
+
+var _ = new /* ERROR "cannot infer T" */ ()
+
+func f4[A, B, C any](A, B) C { panic(0) }
+
+var _ = f4 /* ERROR "cannot infer C" */ (1, 2)
+var _ = f4[int, float32, complex128](1, 2)
+
+func f5[A, B, C any](A, []*B, struct{f []C}) int { panic(0) }
+
+var _ = f5[int, float32, complex128](0, nil, struct{f []complex128}{})
+var _ = f5 /* ERROR "cannot infer" */ (0, nil, struct{f []complex128}{})
+var _ = f5(0, []*float32{new[float32]()}, struct{f []complex128}{})
+
+func f6[A any](A, []A) int { panic(0) }
+
+var _ = f6(0, nil)
+
+func f6nil[A any](A) int { panic(0) }
+
+var _ = f6nil /* ERROR "cannot infer" */ (nil)
+
+// type inference with variadic functions
+
+func f7[T any](...T) T { panic(0) }
+
+var _ int = f7 /* ERROR "cannot infer T" */ ()
+var _ int = f7(1)
+var _ int = f7(1, 2)
+var _ int = f7([]int{}...)
+var _ int = f7 /* ERROR "cannot use" */ ([]float64{}...)
+var _ float64 = f7([]float64{}...)
+var _ = f7[float64](1, 2.3)
+var _ = f7(float64(1), 2.3)
+var _ = f7(1, 2.3)
+var _ = f7(1.2, 3)
+
+func f8[A, B any](A, B, ...B) int { panic(0) }
+
+var _ = f8(1) /* ERROR "not enough arguments" */
+var _ = f8(1, 2.3)
+var _ = f8(1, 2.3, 3.4, 4.5)
+var _ = f8(1, 2.3, 3.4, 4)
+var _ = f8[int, float64](1, 2.3, 3.4, 4)
+
+var _ = f8[int, float64](0, 0, nil...) // test case for #18268
+
+// init functions cannot have type parameters
+
+func init() {}
+func init[_ /* ERROR "func init must have no type parameters" */ any]() {}
+func init[P /* ERROR "func init must have no type parameters" */ any]() {}
+
+type T struct {}
+
+func (T) m1() {}
+func (T) m2[ /* ERROR "method must have no type parameters" */ _ any]() {}
+func (T) m3[ /* ERROR "method must have no type parameters" */ P any]() {}
+
+// type inference across parameterized types
+
+type S1[P any] struct { f P }
+
+func f9[P any](x S1[P]) {}
+
+func _() {
+ f9[int](S1[int]{42})
+ f9(S1[int]{42})
+}
+
+type S2[A, B, C any] struct{}
+
+func f10[X, Y, Z any](a S2[X, int, Z], b S2[X, Y, bool]) {}
+
+func _[P any]() {
+ f10[int, float32, string](S2[int, int, string]{}, S2[int, float32, bool]{})
+ f10(S2[int, int, string]{}, S2[int, float32, bool]{})
+ f10(S2[P, int, P]{}, S2[P, float32, bool]{})
+}
+
+// corner case for type inference
+// (was bug: after instantiating f11, the type-checker didn't mark f11 as non-generic)
+
+func f11[T any]() {}
+
+func _() {
+ f11[int]()
+}
+
+// the previous example was extracted from
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// func f12[T interface{m() T}]() {}
+//
+// type A[T any] T
+//
+// func (a A[T]) m() A[T]
+//
+// func _[T any]() {
+// f12[A[T]]()
+// }
+
+// method expressions
+
+func (_ S1[P]) m()
+
+func _() {
+ m := S1[int].m
+ m(struct { f int }{42})
+}
+
+func _[T any] (x T) {
+ m := S1[T].m
+ m(S1[T]{x})
+}
+
+type I1[A any] interface {
+ m1(A)
+}
+
+var _ I1[int] = r1[int]{}
+
+type r1[T any] struct{}
+
+func (_ r1[T]) m1(T)
+
+type I2[A, B any] interface {
+ m1(A)
+ m2(A) B
+}
+
+var _ I2[int, float32] = R2[int, float32]{}
+
+type R2[P, Q any] struct{}
+
+func (_ R2[X, Y]) m1(X)
+func (_ R2[X, Y]) m2(X) Y
+
+// type assertions and type switches over generic types
+// NOTE: These are currently disabled because it's unclear what the correct
+// approach is, and one can always work around by assigning the variable to
+// an interface first.
+
+// // ReadByte1 corresponds to the ReadByte example in the draft design.
+// func ReadByte1[T io.Reader](r T) (byte, error) {
+// if br, ok := r.(io.ByteReader); ok {
+// return br.ReadByte()
+// }
+// var b [1]byte
+// _, err := r.Read(b[:])
+// return b[0], err
+// }
+//
+// // ReadBytes2 is like ReadByte1 but uses a type switch instead.
+// func ReadByte2[T io.Reader](r T) (byte, error) {
+// switch br := r.(type) {
+// case io.ByteReader:
+// return br.ReadByte()
+// }
+// var b [1]byte
+// _, err := r.Read(b[:])
+// return b[0], err
+// }
+//
+// // type assertions and type switches over generic types are strict
+// type I3 interface {
+// m(int)
+// }
+//
+// type I4 interface {
+// m() int // different signature from I3.m
+// }
+//
+// func _[T I3](x I3, p T) {
+// // type assertions and type switches over interfaces are not strict
+// _ = x.(I4)
+// switch x.(type) {
+// case I4:
+// }
+//
+// // type assertions and type switches over generic types are strict
+// _ = p /* ERROR "cannot have dynamic type I4" */.(I4)
+// switch p.(type) {
+// case I4 /* ERROR "cannot have dynamic type I4" */ :
+// }
+// }
+
+// type assertions and type switches over generic types lead to errors for now
+
+func _[T any](x T) {
+ _ = x /* ERROR "cannot use type assertion" */ .(int)
+ switch x /* ERROR "cannot use type switch" */ .(type) {
+ }
+
+ // work-around
+ var t interface{} = x
+ _ = t.(int)
+ switch t.(type) {
+ }
+}
+
+func _[T interface{~int}](x T) {
+ _ = x /* ERROR "cannot use type assertion" */ .(int)
+ switch x /* ERROR "cannot use type switch" */ .(type) {
+ }
+
+ // work-around
+ var t interface{} = x
+ _ = t.(int)
+ switch t.(type) {
+ }
+}
+
+// error messages related to type bounds mention those bounds
+type C[P any] interface{}
+
+func _[P C[P]] (x P) {
+ x.m /* ERROR "x.m undefined" */ ()
+}
+
+type I interface {}
+
+func _[P I] (x P) {
+ x.m /* ERROR "type P has no field or method m" */ ()
+}
+
+func _[P interface{}] (x P) {
+ x.m /* ERROR "type P has no field or method m" */ ()
+}
+
+func _[P any] (x P) {
+ x.m /* ERROR "type P has no field or method m" */ ()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/unions.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/unions.go
new file mode 100644
index 0000000000000000000000000000000000000000..5a3a9edd356ab64e33b14e05f8bc004c12177f9d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/unions.go
@@ -0,0 +1,66 @@
+// 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.
+
+// Check that overlong unions don't bog down type checking.
+// Disallow them for now.
+
+package p
+
+type t int
+
+type (
+ t00 t; t01 t; t02 t; t03 t; t04 t; t05 t; t06 t; t07 t; t08 t; t09 t
+ t10 t; t11 t; t12 t; t13 t; t14 t; t15 t; t16 t; t17 t; t18 t; t19 t
+ t20 t; t21 t; t22 t; t23 t; t24 t; t25 t; t26 t; t27 t; t28 t; t29 t
+ t30 t; t31 t; t32 t; t33 t; t34 t; t35 t; t36 t; t37 t; t38 t; t39 t
+ t40 t; t41 t; t42 t; t43 t; t44 t; t45 t; t46 t; t47 t; t48 t; t49 t
+ t50 t; t51 t; t52 t; t53 t; t54 t; t55 t; t56 t; t57 t; t58 t; t59 t
+ t60 t; t61 t; t62 t; t63 t; t64 t; t65 t; t66 t; t67 t; t68 t; t69 t
+ t70 t; t71 t; t72 t; t73 t; t74 t; t75 t; t76 t; t77 t; t78 t; t79 t
+ t80 t; t81 t; t82 t; t83 t; t84 t; t85 t; t86 t; t87 t; t88 t; t89 t
+ t90 t; t91 t; t92 t; t93 t; t94 t; t95 t; t96 t; t97 t; t98 t; t99 t
+)
+
+type u99 interface {
+ t00|t01|t02|t03|t04|t05|t06|t07|t08|t09|
+ t10|t11|t12|t13|t14|t15|t16|t17|t18|t19|
+ t20|t21|t22|t23|t24|t25|t26|t27|t28|t29|
+ t30|t31|t32|t33|t34|t35|t36|t37|t38|t39|
+ t40|t41|t42|t43|t44|t45|t46|t47|t48|t49|
+ t50|t51|t52|t53|t54|t55|t56|t57|t58|t59|
+ t60|t61|t62|t63|t64|t65|t66|t67|t68|t69|
+ t70|t71|t72|t73|t74|t75|t76|t77|t78|t79|
+ t80|t81|t82|t83|t84|t85|t86|t87|t88|t89|
+ t90|t91|t92|t93|t94|t95|t96|t97|t98
+}
+
+type u100a interface {
+ u99|float32
+}
+
+type u100b interface {
+ u99|float64
+}
+
+type u101 interface {
+ t00|t01|t02|t03|t04|t05|t06|t07|t08|t09|
+ t10|t11|t12|t13|t14|t15|t16|t17|t18|t19|
+ t20|t21|t22|t23|t24|t25|t26|t27|t28|t29|
+ t30|t31|t32|t33|t34|t35|t36|t37|t38|t39|
+ t40|t41|t42|t43|t44|t45|t46|t47|t48|t49|
+ t50|t51|t52|t53|t54|t55|t56|t57|t58|t59|
+ t60|t61|t62|t63|t64|t65|t66|t67|t68|t69|
+ t70|t71|t72|t73|t74|t75|t76|t77|t78|t79|
+ t80|t81|t82|t83|t84|t85|t86|t87|t88|t89|
+ t90|t91|t92|t93|t94|t95|t96|t97|t98|t99|
+ int // ERROR "cannot handle more than 100 union terms"
+}
+
+type u102 interface {
+ int /* ERROR "cannot handle more than 100 union terms" */ |string|u100a
+}
+
+type u200 interface {
+ u100a /* ERROR "cannot handle more than 100 union terms" */ |u100b
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/check/vardecl.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/vardecl.go
new file mode 100644
index 0000000000000000000000000000000000000000..726b619361fab764755c8a7bc1e5e7a7fb86c21a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/check/vardecl.go
@@ -0,0 +1,215 @@
+// 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 vardecl
+
+// Prerequisites.
+import "math"
+func f() {}
+func g() (x, y int) { return }
+var m map[string]int
+
+// Var decls must have a type or an initializer.
+var _ int
+var _, _ int
+
+var _; /* ERROR "expected type" */
+var _, _; /* ERROR "expected type" */
+var _, _, _; /* ERROR "expected type" */
+
+// The initializer must be an expression.
+var _ = int /* ERROR "not an expression" */
+var _ = f /* ERROR "used as value" */ ()
+
+// Identifier and expression arity must match.
+var _, _ = 1, 2
+var _ = 1, 2 /* ERROR "extra init expr 2" */
+var _, _ = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */
+var _, _, _ /* ERROR "missing init expr for _" */ = 1, 2
+
+var _ = g /* ERROR "multiple-value g" */ ()
+var _, _ = g()
+var _, _, _ = g /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ()
+
+var _ = m["foo"]
+var _, _ = m["foo"]
+var _, _, _ = m /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ["foo"]
+
+var _, _ int = 1, 2
+var _ int = 1, 2 /* ERROR "extra init expr 2" */
+var _, _ int = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */
+var _, _, _ /* ERROR "missing init expr for _" */ int = 1, 2
+
+var (
+ _, _ = 1, 2
+ _ = 1, 2 /* ERROR "extra init expr 2" */
+ _, _ = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */
+ _, _, _ /* ERROR "missing init expr for _" */ = 1, 2
+
+ _ = g /* ERROR "multiple-value g" */ ()
+ _, _ = g()
+ _, _, _ = g /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ()
+
+ _ = m["foo"]
+ _, _ = m["foo"]
+ _, _, _ = m /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ ["foo"]
+
+ _, _ int = 1, 2
+ _ int = 1, 2 /* ERROR "extra init expr 2" */
+ _, _ int = 1 /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */
+ _, _, _ /* ERROR "missing init expr for _" */ int = 1, 2
+)
+
+// Variables declared in function bodies must be 'used'.
+type T struct{}
+func (r T) _(a, b, c int) (u, v, w int) {
+ var x1 /* ERROR "declared and not used" */ int
+ var x2 /* ERROR "declared and not used" */ int
+ x1 = 1
+ (x2) = 2
+
+ y1 /* ERROR "declared and not used" */ := 1
+ y2 /* ERROR "declared and not used" */ := 2
+ y1 = 1
+ (y1) = 2
+
+ {
+ var x1 /* ERROR "declared and not used" */ int
+ var x2 /* ERROR "declared and not used" */ int
+ x1 = 1
+ (x2) = 2
+
+ y1 /* ERROR "declared and not used" */ := 1
+ y2 /* ERROR "declared and not used" */ := 2
+ y1 = 1
+ (y1) = 2
+ }
+
+ if x /* ERROR "declared and not used" */ := 0; a < b {}
+
+ switch x /* ERROR "declared and not used" */, y := 0, 1; a {
+ case 0:
+ _ = y
+ case 1:
+ x /* ERROR "declared and not used" */ := 0
+ }
+
+ var t interface{}
+ switch t /* ERROR "declared and not used" */ := t.(type) {}
+
+ switch t /* ERROR "declared and not used" */ := t.(type) {
+ case int:
+ }
+
+ switch t /* ERROR "declared and not used" */ := t.(type) {
+ case int:
+ case float32, complex64:
+ t = nil
+ }
+
+ switch t := t.(type) {
+ case int:
+ case float32, complex64:
+ _ = t
+ }
+
+ switch t := t.(type) {
+ case int:
+ case float32:
+ case string:
+ _ = func() string {
+ return t
+ }
+ }
+
+ switch t := t; t /* ERROR "declared and not used" */ := t.(type) {}
+
+ var z1 /* ERROR "declared and not used" */ int
+ var z2 int
+ _ = func(a, b, c int) (u, v, w int) {
+ z1 = a
+ (z1) = b
+ a = z2
+ return
+ }
+
+ var s []int
+ var i /* ERROR "declared and not used" */ , j int
+ for i, j = range s {
+ _ = j
+ }
+
+ for i, j /* ERROR "declared and not used" */ := range s {
+ _ = func() int {
+ return i
+ }
+ }
+ return
+}
+
+// Unused variables in function literals must lead to only one error (issue #22524).
+func _() {
+ _ = func() {
+ var x /* ERROR "declared and not used" */ int
+ }
+}
+
+// Invalid variable declarations must not lead to "declared and not used errors".
+// TODO(gri) enable these tests once go/types follows types2 logic for declared and not used variables
+// func _() {
+// var a x // DISABLED_ERROR undefined: x
+// var b = x // DISABLED_ERROR undefined: x
+// var c int = x // DISABLED_ERROR undefined: x
+// var d, e, f x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */
+// var g, h, i = x, x, x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */
+// var j, k, l float32 = x, x, x /* DISABLED_ERROR x */ /* DISABLED_ERROR x */ /* DISABLED_ERROR x */
+// // but no "declared and not used" errors
+// }
+
+// Invalid (unused) expressions must not lead to spurious "declared and not used errors".
+func _() {
+ var a, b, c int
+ var x, y int
+ x, y = a /* ERRORx `assignment mismatch: [1-9]+ variables but.*[1-9]+ value(s)?` */ , b, c
+ _ = x
+ _ = y
+}
+
+func _() {
+ var x int
+ return x /* ERROR "too many return values" */
+ return math /* ERROR "too many return values" */ .Sin(0)
+}
+
+func _() int {
+ var x, y int
+ return x, y /* ERROR "too many return values" */
+}
+
+// Short variable declarations must declare at least one new non-blank variable.
+func _() {
+ _ := /* ERROR "no new variables" */ 0
+ _, a := 0, 1
+ _, a := /* ERROR "no new variables" */ 0, 1
+ _, a, b := 0, 1, 2
+ _, _, _ := /* ERROR "no new variables" */ 0, 1, 2
+
+ _ = a
+ _ = b
+}
+
+// Test case for variables depending on function literals (see also #22992).
+var A /* ERROR "initialization cycle" */ = func() int { return A }()
+
+func _() {
+ // The function literal below must not see a.
+ var a = func() int { return a /* ERROR "undefined" */ }()
+ var _ = func() int { return a }()
+
+ // The function literal below must not see x, y, or z.
+ var x, y, z = 0, 1, func() int { return x /* ERROR "undefined" */ + y /* ERROR "undefined" */ + z /* ERROR "undefined" */ }()
+ _, _, _ = x, y, z
+}
+
+// TODO(gri) consolidate other var decl checks in this file
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/constraints.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/constraints.go
new file mode 100644
index 0000000000000000000000000000000000000000..4c97a400977ced6c06e8344dc397daafc348fbdc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/constraints.go
@@ -0,0 +1,80 @@
+// 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.
+
+// This file shows some examples of generic constraint interfaces.
+
+package p
+
+type MyInt int
+
+type (
+ // Arbitrary types may be embedded like interfaces.
+ _ interface{int}
+ _ interface{~int}
+
+ // Types may be combined into a union.
+ union interface{int|~string}
+
+ // Union terms must describe disjoint (non-overlapping) type sets.
+ _ interface{int|int /* ERROR "overlapping terms int" */ }
+ _ interface{int|~ /* ERROR "overlapping terms ~int" */ int }
+ _ interface{~int|~ /* ERROR "overlapping terms ~int" */ int }
+ _ interface{~int|MyInt /* ERROR "overlapping terms p.MyInt and ~int" */ }
+ _ interface{int|any}
+ _ interface{int|~string|union}
+ _ interface{int|~string|interface{int}}
+ _ interface{union|int} // interfaces (here: union) are ignored when checking for overlap
+ _ interface{union|union} // ditto
+
+ // For now we do not permit interfaces with methods in unions.
+ _ interface{~ /* ERROR "invalid use of ~" */ any}
+ _ interface{int|interface /* ERRORx `cannot use .* in union` */ { m() }}
+)
+
+type (
+ // Tilde is not permitted on defined types or interfaces.
+ foo int
+ bar any
+ _ interface{foo}
+ _ interface{~ /* ERROR "invalid use of ~" */ foo }
+ _ interface{~ /* ERROR "invalid use of ~" */ bar }
+)
+
+// Stand-alone type parameters are not permitted as elements or terms in unions.
+type (
+ _[T interface{ *T } ] struct{} // ok
+ _[T interface{ int | *T } ] struct{} // ok
+ _[T interface{ T /* ERROR "term cannot be a type parameter" */ } ] struct{}
+ _[T interface{ ~T /* ERROR "type in term ~T cannot be a type parameter" */ } ] struct{}
+ _[T interface{ int|T /* ERROR "term cannot be a type parameter" */ }] struct{}
+)
+
+// Multiple embedded union elements are intersected. The order in which they
+// appear in the interface doesn't matter since intersection is a symmetric
+// operation.
+
+type myInt1 int
+type myInt2 int
+
+func _[T interface{ myInt1|myInt2; ~int }]() T { return T(0) }
+func _[T interface{ ~int; myInt1|myInt2 }]() T { return T(0) }
+
+// Here the intersections are empty - there's no type that's in the type set of T.
+func _[T interface{ myInt1|myInt2; int }]() T { return T(0 /* ERROR "cannot convert" */ ) }
+func _[T interface{ int; myInt1|myInt2 }]() T { return T(0 /* ERROR "cannot convert" */ ) }
+
+// Union elements may be interfaces as long as they don't define
+// any methods or embed comparable.
+
+type (
+ Integer interface{ ~int|~int8|~int16|~int32|~int64 }
+ Unsigned interface{ ~uint|~uint8|~uint16|~uint32|~uint64 }
+ Floats interface{ ~float32|~float64 }
+ Complex interface{ ~complex64|~complex128 }
+ Number interface{ Integer|Unsigned|Floats|Complex }
+ Ordered interface{ Integer|Unsigned|Floats|~string }
+
+ _ interface{ Number | error /* ERROR "cannot use error in union" */ }
+ _ interface{ Ordered | comparable /* ERROR "cannot use comparable in union" */ }
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/functions.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/functions.go
new file mode 100644
index 0000000000000000000000000000000000000000..fdc67e7162af555a82c218360b142d434191b3f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/functions.go
@@ -0,0 +1,219 @@
+// 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.
+
+// This file shows some examples of type-parameterized functions.
+
+package p
+
+// Reverse is a generic function that takes a []T argument and
+// reverses that slice in place.
+func Reverse[T any](list []T) {
+ i := 0
+ j := len(list)-1
+ for i < j {
+ list[i], list[j] = list[j], list[i]
+ i++
+ j--
+ }
+}
+
+func _() {
+ // Reverse can be called with an explicit type argument.
+ Reverse[int](nil)
+ Reverse[string]([]string{"foo", "bar"})
+ Reverse[struct{x, y int}]([]struct{x, y int}{{1, 2}, {2, 3}, {3, 4}})
+
+ // Since the type parameter is used for an incoming argument,
+ // it can be inferred from the provided argument's type.
+ Reverse([]string{"foo", "bar"})
+ Reverse([]struct{x, y int}{{1, 2}, {2, 3}, {3, 4}})
+
+ // But the incoming argument must have a type, even if it's a
+ // default type. An untyped nil won't work.
+ // Reverse(nil) // this won't type-check
+
+ // A typed nil will work, though.
+ Reverse([]int(nil))
+}
+
+// Certain functions, such as the built-in `new` could be written using
+// type parameters.
+func new[T any]() *T {
+ var x T
+ return &x
+}
+
+// When calling our own `new`, we need to pass the type parameter
+// explicitly since there is no (value) argument from which the
+// result type could be inferred. We don't try to infer the
+// result type from the assignment to keep things simple and
+// easy to understand.
+var _ = new[int]()
+var _ *float64 = new[float64]() // the result type is indeed *float64
+
+// A function may have multiple type parameters, of course.
+func foo[A, B, C any](a A, b []B, c *C) B {
+ // do something here
+ return b[0]
+}
+
+// As before, we can pass type parameters explicitly.
+var s = foo[int, string, float64](1, []string{"first"}, new[float64]())
+
+// Or we can use type inference.
+var _ float64 = foo(42, []float64{1.0}, &s)
+
+// Type inference works in a straight-forward manner even
+// for variadic functions.
+func variadic[A, B any](A, B, ...B) int { panic(0) }
+
+// var _ = variadic(1) // ERROR "not enough arguments"
+var _ = variadic(1, 2.3)
+var _ = variadic(1, 2.3, 3.4, 4.5)
+var _ = variadic[int, float64](1, 2.3, 3.4, 4)
+
+// Type inference also works in recursive function calls where
+// the inferred type is the type parameter of the caller.
+func f1[T any](x T) {
+ f1(x)
+}
+
+func f2a[T any](x, y T) {
+ f2a(x, y)
+}
+
+func f2b[T any](x, y T) {
+ f2b(y, x)
+}
+
+func g2a[P, Q any](x P, y Q) {
+ g2a(x, y)
+}
+
+func g2b[P, Q any](x P, y Q) {
+ g2b(y, x)
+}
+
+// Here's an example of a recursive function call with variadic
+// arguments and type inference inferring the type parameter of
+// the caller (i.e., itself).
+func max[T interface{ ~int }](x ...T) T {
+ var x0 T
+ if len(x) > 0 {
+ x0 = x[0]
+ }
+ if len(x) > 1 {
+ x1 := max(x[1:]...)
+ if x1 > x0 {
+ return x1
+ }
+ }
+ return x0
+}
+
+// When inferring channel types, the channel direction is ignored
+// for the purpose of type inference. Once the type has been in-
+// fered, the usual parameter passing rules are applied.
+// Thus even if a type can be inferred successfully, the function
+// call may not be valid.
+
+func fboth[T any](chan T) {}
+func frecv[T any](<-chan T) {}
+func fsend[T any](chan<- T) {}
+
+func _() {
+ var both chan int
+ var recv <-chan int
+ var send chan<-int
+
+ fboth(both)
+ fboth(recv /* ERROR "cannot use" */ )
+ fboth(send /* ERROR "cannot use" */ )
+
+ frecv(both)
+ frecv(recv)
+ frecv(send /* ERROR "cannot use" */ )
+
+ fsend(both)
+ fsend(recv /* ERROR "cannot use" */)
+ fsend(send)
+}
+
+func ffboth[T any](func(chan T)) {}
+func ffrecv[T any](func(<-chan T)) {}
+func ffsend[T any](func(chan<- T)) {}
+
+func _() {
+ var both func(chan int)
+ var recv func(<-chan int)
+ var send func(chan<- int)
+
+ ffboth(both)
+ ffboth(recv /* ERROR "does not match" */ )
+ ffboth(send /* ERROR "does not match" */ )
+
+ ffrecv(both /* ERROR "does not match" */ )
+ ffrecv(recv)
+ ffrecv(send /* ERROR "does not match" */ )
+
+ ffsend(both /* ERROR "does not match" */ )
+ ffsend(recv /* ERROR "does not match" */ )
+ ffsend(send)
+}
+
+// When inferring elements of unnamed composite parameter types,
+// if the arguments are defined types, use their underlying types.
+// Even though the matching types are not exactly structurally the
+// same (one is a type literal, the other a named type), because
+// assignment is permitted, parameter passing is permitted as well,
+// so type inference should be able to handle these cases well.
+
+func g1[T any]([]T) {}
+func g2[T any]([]T, T) {}
+func g3[T any](*T, ...T) {}
+
+func _() {
+ type intSlice []int
+ g1([]int{})
+ g1(intSlice{})
+ g2(nil, 0)
+
+ type myString string
+ var s1 string
+ g3(nil, "1", myString("2"), "3")
+ g3(& /* ERROR "cannot use &s1 (value of type *string) as *myString value in argument to g3" */ s1, "1", myString("2"), "3")
+ _ = s1
+
+ type myStruct struct{x int}
+ var s2 myStruct
+ g3(nil, struct{x int}{}, myStruct{})
+ g3(&s2, struct{x int}{}, myStruct{})
+ g3(nil, myStruct{}, struct{x int}{})
+ g3(&s2, myStruct{}, struct{x int}{})
+}
+
+// Here's a realistic example.
+
+func append[T any](s []T, t ...T) []T { panic(0) }
+
+func _() {
+ var f func()
+ type Funcs []func()
+ var funcs Funcs
+ _ = append(funcs, f)
+}
+
+// Generic type declarations cannot have empty type parameter lists
+// (that would indicate a slice type). Thus, generic functions cannot
+// have empty type parameter lists, either. This is a syntax error.
+
+func h[] /* ERROR "empty type parameter list" */ () {}
+
+func _() {
+ h /* ERROR "cannot index" */ [] /* ERROR "operand" */ ()
+}
+
+// Generic functions must have a function body.
+
+func _ /* ERROR "generic function is missing function body" */ [P any]()
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference.go
new file mode 100644
index 0000000000000000000000000000000000000000..0aaaa8278c1478fa472383dfa5dd9ec5badb8ebc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference.go
@@ -0,0 +1,163 @@
+// -lang=go1.20
+
+// 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.
+
+// This file shows some examples of type inference.
+
+package p
+
+type Ordered interface {
+ ~int | ~float64 | ~string
+}
+
+func min[T Ordered](x, y T) T { panic(0) }
+
+func _() {
+ // min can be called with explicit instantiation.
+ _ = min[int](1, 2)
+
+ // Alternatively, the type argument can be inferred from
+ // one of the arguments. Untyped arguments will be considered
+ // last.
+ var x int
+ _ = min(x, x)
+ _ = min(x, 1)
+ _ = min(x, 1.0)
+ _ = min(1, 2)
+ _ = min(1, 2.3)
+
+ var y float64
+ _ = min(1, y)
+ _ = min(1.2, y)
+ _ = min(1.2, 3.4)
+ _ = min(1.2, 3)
+
+ var s string
+ _ = min(s, "foo")
+ _ = min("foo", "bar")
+}
+
+func mixed[T1, T2, T3 any](T1, T2, T3) {}
+
+func _() {
+ // mixed can be called with explicit instantiation.
+ mixed[int, string, bool](0, "", false)
+
+ // Alternatively, partial type arguments may be provided
+ // (from left to right), and the other may be inferred.
+ mixed[int, string](0, "", false)
+ mixed[int](0, "", false)
+ mixed(0, "", false)
+
+ // Provided type arguments always take precedence over
+ // inferred types.
+ mixed[int, string](1.1 /* ERROR "cannot use 1.1" */, "", false)
+}
+
+func related1[Slice interface{ ~[]Elem }, Elem any](s Slice, e Elem) {}
+
+func _() {
+ // related1 can be called with explicit instantiation.
+ var si []int
+ related1[[]int, int](si, 0)
+
+ // Alternatively, the 2nd type argument can be inferred
+ // from the first one through constraint type inference.
+ var ss []string
+ _ = related1[[]string]
+ related1[[]string](ss, "foo")
+
+ // A type argument inferred from another explicitly provided
+ // type argument overrides whatever value argument type is given.
+ related1[[]string](ss, 0 /* ERROR "cannot use 0" */)
+
+ // A type argument may be inferred from a value argument
+ // and then help infer another type argument via constraint
+ // type inference.
+ related1(si, 0)
+ related1(si, "foo" /* ERROR `cannot use "foo"` */)
+}
+
+func related2[Elem any, Slice interface{ []Elem }](e Elem, s Slice) {}
+
+func _() {
+ // related2 can be called with explicit instantiation.
+ var si []int
+ related2[int, []int](0, si)
+
+ // Alternatively, the 2nd type argument can be inferred
+ // from the first one through constraint type inference.
+ var ss []string
+ _ = related2[string]
+ related2[string]("foo", ss)
+
+ // A type argument may be inferred from a value argument
+ // and then help infer another type argument via constraint
+ // type inference. Untyped arguments are always considered
+ // last.
+ related2(1.2, []float64{})
+ related2(1.0, []int{})
+ related2 /* ERROR "Slice (type []int) does not satisfy interface{[]Elem}" */ (float64(1.0), []int{}) // TODO(gri) better error message
+}
+
+type List[P any] []P
+
+func related3[Elem any, Slice []Elem | List[Elem]]() Slice { return nil }
+
+func _() {
+ // related3 can be instantiated explicitly
+ related3[int, []int]()
+ related3[byte, List[byte]]()
+
+ // The 2nd type argument cannot be inferred from the first
+ // one because there's two possible choices: []Elem and
+ // List[Elem].
+ related3 /* ERROR "cannot infer Slice" */ [int]()
+}
+
+func wantsMethods[P interface {
+ m1(Q)
+ m2() R
+}, Q, R any](P) {
+}
+
+type hasMethods1 struct{}
+
+func (hasMethods1) m1(int)
+func (hasMethods1) m2() string
+
+type hasMethods2 struct{}
+
+func (*hasMethods2) m1(int)
+func (*hasMethods2) m2() string
+
+type hasMethods3 interface {
+ m1(float64)
+ m2() complex128
+}
+
+type hasMethods4 interface {
+ m1()
+}
+
+func _() {
+ // wantsMethod can be called with arguments that have the relevant methods
+ // and wantsMethod's type arguments are inferred from those types' method
+ // signatures.
+ wantsMethods(hasMethods1{})
+ wantsMethods(&hasMethods1{})
+ wantsMethods /* ERROR "P (type hasMethods2) does not satisfy interface{m1(Q); m2() R} (method m1 has pointer receiver)" */ (hasMethods2{})
+ wantsMethods(&hasMethods2{})
+ wantsMethods(hasMethods3(nil))
+ wantsMethods /* ERROR "P (type any) does not satisfy interface{m1(Q); m2() R} (missing method m1)" */ (any(nil))
+ wantsMethods /* ERROR "P (type hasMethods4) does not satisfy interface{m1(Q); m2() R} (wrong type for method m1)" */ (hasMethods4(nil))
+}
+
+// "Reverse" type inference is not yet permitted.
+
+func f[P any](P) {}
+
+// This must not crash.
+var _ func(int) = f // ERROR "implicitly instantiated function in assignment requires go1.21 or later"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference2.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference2.go
new file mode 100644
index 0000000000000000000000000000000000000000..91f9df1d840d0460846f9f98f47306f6ce5a6332
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/inference2.go
@@ -0,0 +1,104 @@
+// 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.
+
+// This file shows some examples of "reverse" type inference
+// where the type arguments for generic functions are determined
+// from assigning the functions.
+
+package p
+
+func f1[P any](P) {}
+func f2[P any]() P { var x P; return x }
+func f3[P, Q any](P) Q { var x Q; return x }
+func f4[P any](P, P) {}
+func f5[P any](P) []P { return nil }
+func f6[P any](int) P { var x P; return x }
+func f7[P any](P) string { return "" }
+
+// initialization expressions
+var (
+ v1 = f1 // ERROR "cannot use generic function f1 without instantiation"
+ v2 func(int) = f2 // ERROR "cannot infer P"
+
+ v3 func(int) = f1
+ v4 func() int = f2
+ v5 func(int) int = f3
+ _ func(int) int = f3[int]
+
+ v6 func(int, int) = f4
+ v7 func(int, string) = f4 // ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of v7"
+ v8 func(int) []int = f5
+ v9 func(string) []int = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of v9"
+
+ _, _ func(int) = f1, f1
+ _, _ func(int) = f1, f2 // ERROR "cannot infer P"
+)
+
+// Regular assignments
+func _() {
+ v1 = f1 // no error here because v1 is invalid (we don't know its type) due to the error above
+ var v1_ func() int
+ _ = v1_
+ v1_ = f1 // ERROR "cannot infer P"
+ v2 = f2 // ERROR "cannot infer P"
+
+ v3 = f1
+ v4 = f2
+ v5 = f3
+ v5 = f3[int]
+
+ v6 = f4
+ v7 = f4 // ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of v7"
+ v8 = f5
+ v9 = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of v9"
+
+ // non-trivial LHS
+ var a [2]func(string) []int
+ a[0] = f5 // ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of a[0]"
+}
+
+// Return statements
+func _() func(int) { return f1 }
+func _() func() int { return f2 }
+func _() func(int) int { return f3 }
+func _() func(int) int { return f3[int] }
+
+func _() func(int, int) { return f4 }
+func _() func(int, string) {
+ return f4 /* ERROR "inferred type func(int, int) for func(P, P) does not match type func(int, string) of result variable" */
+}
+func _() func(int) []int { return f5 }
+func _() func(string) []int {
+ return f5 /* ERROR "inferred type func(string) []string for func(P) []P does not match type func(string) []int of result variable" */
+}
+
+func _() (_, _ func(int)) { return f1, f1 }
+func _() (_, _ func(int)) { return f1, f2 /* ERROR "cannot infer P" */ }
+
+// Argument passing
+func g1(func(int)) {}
+func g2(func(int, int)) {}
+func g3(func(int) string) {}
+func g4[P any](func(P) string) {}
+func g5[P, Q any](func(P) string, func(P) Q) {}
+func g6(func(int), func(string)) {}
+
+func _() {
+ g1(f1)
+ g1(f2 /* ERROR "cannot infer P" */)
+ g2(f4)
+ g4(f6)
+ g5(f6, f7)
+ g6(f1, f1)
+}
+
+// Argument passing of partially instantiated functions
+func h(func(int, string), func(string, int)) {}
+
+func p[P, Q any](P, Q) {}
+
+func _() {
+ h(p, p)
+ h(p[int], p[string])
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/methods.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/methods.go
new file mode 100644
index 0000000000000000000000000000000000000000..e92dc5028bb3ae14a48298a2ebf811a1bec5dbf6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/methods.go
@@ -0,0 +1,112 @@
+// 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.
+
+// This file shows some examples of methods on type-parameterized types.
+
+package p
+
+// Parameterized types may have methods.
+type T1[A any] struct{ a A }
+
+// When declaring a method for a parameterized type, the "instantiated"
+// receiver type acts as an implicit declaration of the type parameters
+// for the receiver type. In the example below, method m1 on type T1 has
+// the receiver type T1[A] which declares the type parameter A for use
+// with this method. That is, within the method m1, A stands for the
+// actual type argument provided to an instantiated T1.
+func (t T1[A]) m1() A { return t.a }
+
+// For instance, if T1 is instantiated with the type int, the type
+// parameter A in m1 assumes that type (int) as well and we can write
+// code like this:
+var x T1[int]
+var _ int = x.m1()
+
+// Because the type parameter provided to a parameterized receiver type
+// is declared through that receiver declaration, it must be an identifier.
+// It cannot possibly be some other type because the receiver type is not
+// instantiated with concrete types, it is standing for the parameterized
+// receiver type.
+func (t T1[[ /* ERROR "must be an identifier" */ ]int]) m2() {}
+
+// Note that using what looks like a predeclared identifier, say int,
+// as type parameter in this situation is deceptive and considered bad
+// style. In m3 below, int is the name of the local receiver type parameter
+// and it shadows the predeclared identifier int which then cannot be used
+// anymore as expected.
+// This is no different from locally re-declaring a predeclared identifier
+// and usually should be avoided. There are some notable exceptions; e.g.,
+// sometimes it makes sense to use the identifier "copy" which happens to
+// also be the name of a predeclared built-in function.
+func (t T1[int]) m3() { var _ int = 42 /* ERRORx `cannot use 42 .* as int` */ }
+
+// The names of the type parameters used in a parameterized receiver
+// type don't have to match the type parameter names in the declaration
+// of the type used for the receiver. In our example, even though T1 is
+// declared with type parameter named A, methods using that receiver type
+// are free to use their own name for that type parameter. That is, the
+// name of type parameters is always local to the declaration where they
+// are introduced. In our example we can write a method m2 and use the
+// name X instead of A for the type parameter w/o any difference.
+func (t T1[X]) m4() X { return t.a }
+
+// If the receiver type is parameterized, type parameters must always be
+// provided: this simply follows from the general rule that a parameterized
+// type must be instantiated before it can be used. A method receiver
+// declaration using a parameterized receiver type is no exception. It is
+// simply that such receiver type expressions perform two tasks simultaneously:
+// they declare the (local) type parameters and then use them to instantiate
+// the receiver type. Forgetting to provide a type parameter leads to an error.
+func (t T1 /* ERRORx `generic type .* without instantiation` */ ) m5() {}
+
+// However, sometimes we don't need the type parameter, and thus it is
+// inconvenient to have to choose a name. Since the receiver type expression
+// serves as a declaration for its type parameters, we are free to choose the
+// blank identifier:
+func (t T1[_]) m6() {}
+
+// Naturally, these rules apply to any number of type parameters on the receiver
+// type. Here are some more complex examples.
+type T2[A, B, C any] struct {
+ a A
+ b B
+ c C
+}
+
+// Naming of the type parameters is local and has no semantic impact:
+func (t T2[A, B, C]) m1() (A, B, C) { return t.a, t.b, t.c }
+func (t T2[C, B, A]) m2() (C, B, A) { return t.a, t.b, t.c }
+func (t T2[X, Y, Z]) m3() (X, Y, Z) { return t.a, t.b, t.c }
+
+// Type parameters may be left blank if they are not needed:
+func (t T2[A, _, C]) m4() (A, C) { return t.a, t.c }
+func (t T2[_, _, X]) m5() X { return t.c }
+func (t T2[_, _, _]) m6() {}
+
+// As usual, blank names may be used for any object which we don't care about
+// using later. For instance, we may write an unnamed method with a receiver
+// that cannot be accessed:
+func (_ T2[_, _, _]) _() int { return 42 }
+
+// Because a receiver parameter list is simply a parameter list, we can
+// leave the receiver argument away for receiver types.
+type T0 struct{}
+func (T0) _() {}
+func (T1[A]) _() {}
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// // A generic receiver type may constrain its type parameter such
+// // that it must be a pointer type. Such receiver types are not
+// // permitted.
+// type T3a[P interface{ ~int | ~string | ~float64 }] P
+//
+// func (T3a[_]) m() {} // this is ok
+//
+// type T3b[P interface{ ~unsafe.Pointer }] P
+//
+// func (T3b /* ERROR "invalid receiver" */ [_]) m() {}
+//
+// type T3c[P interface{ *int | *string }] P
+//
+// func (T3c /* ERROR "invalid receiver" */ [_]) m() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/operations.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/operations.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fb95d0b2b05ad14923a8e6a9b1eb286bcbf1774
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/operations.go
@@ -0,0 +1,29 @@
+// 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
+
+// indirection
+
+func _[P any](p P) {
+ _ = *p // ERROR "cannot indirect p"
+}
+
+func _[P interface{ int }](p P) {
+ _ = *p // ERROR "cannot indirect p"
+}
+
+func _[P interface{ *int }](p P) {
+ _ = *p
+}
+
+func _[P interface{ *int | *string }](p P) {
+ _ = *p // ERROR "must have identical base types"
+}
+
+type intPtr *int
+
+func _[P interface{ *int | intPtr } ](p P) {
+ var _ int = *p
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/types.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/types.go
new file mode 100644
index 0000000000000000000000000000000000000000..67f1534be394792d3d77efef763b4a8ad58db488
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/types.go
@@ -0,0 +1,315 @@
+// 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.
+
+// This file shows some examples of generic types.
+
+package p
+
+// List is just what it says - a slice of E elements.
+type List[E any] []E
+
+// A generic (parameterized) type must always be instantiated
+// before it can be used to designate the type of a variable
+// (including a struct field, or function parameter); though
+// for the latter cases, the provided type may be another type
+// parameter. So:
+var _ List[byte] = []byte{}
+
+// A generic binary tree might be declared as follows.
+type Tree[E any] struct {
+ left, right *Tree[E]
+ payload E
+}
+
+// A simple instantiation of Tree:
+var root1 Tree[int]
+
+// The actual type parameter provided may be a generic type itself:
+var root2 Tree[List[int]]
+
+// A couple of more complex examples.
+// We don't need extra parentheses around the element type of the slices on
+// the right (unlike when we use ()'s rather than []'s for type parameters).
+var _ List[List[int]] = []List[int]{}
+var _ List[List[List[Tree[int]]]] = []List[List[Tree[int]]]{}
+
+// Type parameters act like type aliases when used in generic types
+// in the sense that we can "emulate" a specific type instantiation
+// with type aliases.
+type T1[P any] struct {
+ f P
+}
+
+type T2[P any] struct {
+ f struct {
+ g P
+ }
+}
+
+var x1 T1[struct{ g int }]
+var x2 T2[int]
+
+func _() {
+ // This assignment is invalid because the types of x1, x2 are T1(...)
+ // and T2(...) respectively, which are two different defined types.
+ x1 = x2 // ERROR "assignment"
+
+ // This assignment is valid because the types of x1.f and x2.f are
+ // both struct { g int }; the type parameters act like type aliases
+ // and their actual names don't come into play here.
+ x1.f = x2.f
+}
+
+// We can verify this behavior using type aliases instead:
+type T1a struct {
+ f A1
+}
+type A1 = struct { g int }
+
+type T2a struct {
+ f struct {
+ g A2
+ }
+}
+type A2 = int
+
+var x1a T1a
+var x2a T2a
+
+func _() {
+ x1a = x2a // ERROR "assignment"
+ x1a.f = x2a.f
+}
+
+// Another interesting corner case are generic types that don't use
+// their type arguments. For instance:
+type T[P any] struct{}
+
+var xint T[int]
+var xbool T[bool]
+
+// Are these two variables of the same type? After all, their underlying
+// types are identical. We consider them to be different because each type
+// instantiation creates a new named type, in this case T and T
+// even if their underlying types are identical. This is sensible because
+// we might still have methods that have different signatures or behave
+// differently depending on the type arguments, and thus we can't possibly
+// consider such types identical. Consequently:
+func _() {
+ xint = xbool // ERROR "assignment"
+}
+
+// Generic types cannot be used without instantiation.
+var _ T // ERROR "cannot use generic type T"
+var _ = T /* ERROR "cannot use generic type T" */ (0)
+
+// In type context, generic (parameterized) types cannot be parenthesized before
+// being instantiated. See also NOTES entry from 12/4/2019.
+var _ (T /* ERROR "cannot use generic type T" */ )[ /* ERRORx `unexpected \[|expected ';'` */ int]
+
+// All types may be parameterized, including interfaces.
+type I1[T any] interface{
+ m1(T)
+}
+
+// There is no such thing as a variadic generic type.
+type _[T ... /* ERROR "invalid use of '...'" */ any] struct{}
+
+// Generic interfaces may be embedded as one would expect.
+type I2 interface {
+ I1(int) // method!
+ I1[string] // embedded I1
+}
+
+func _() {
+ var x I2
+ x.I1(0)
+ x.m1("foo")
+}
+
+type I0 interface {
+ m0()
+}
+
+type I3 interface {
+ I0
+ I1[bool]
+ m(string)
+}
+
+func _() {
+ var x I3
+ x.m0()
+ x.m1(true)
+ x.m("foo")
+}
+
+type _ struct {
+ ( /* ERROR "cannot parenthesize" */ int8)
+ ( /* ERROR "cannot parenthesize" */ *int16)
+ *( /* ERROR "cannot parenthesize" */ int32)
+ List[int]
+
+ int8 /* ERROR "int8 redeclared" */
+ *int16 /* ERROR "int16 redeclared" */
+ List /* ERROR "List redeclared" */ [int]
+}
+
+// Issue #45639: We don't allow this anymore. Keep this code
+// in case we decide to revisit this decision.
+//
+// It's possible to declare local types whose underlying types
+// are type parameters. As with ordinary type definitions, the
+// types underlying properties are "inherited" but the methods
+// are not.
+// func _[T interface{ m(); ~int }]() {
+// type L T
+// var x L
+//
+// // m is not defined on L (it is not "inherited" from
+// // its underlying type).
+// x.m /* ERROR "x.m undefined" */ ()
+//
+// // But the properties of T, such that as that it supports
+// // the operations of the types given by its type bound,
+// // are also the properties of L.
+// x++
+// _ = x - x
+//
+// // On the other hand, if we define a local alias for T,
+// // that alias stands for T as expected.
+// type A = T
+// var y A
+// y.m()
+// _ = y < 0
+// }
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// // It is not permitted to declare a local type whose underlying
+// // type is a type parameter not declared by that type declaration.
+// func _[T any]() {
+// type _ T // ERROR "cannot use function type parameter T as RHS in type declaration"
+// type _ [_ any] T // ERROR "cannot use function type parameter T as RHS in type declaration"
+// }
+
+// As a special case, an explicit type argument may be omitted
+// from a type parameter bound if the type bound expects exactly
+// one type argument. In that case, the type argument is the
+// respective type parameter to which the type bound applies.
+// Note: We may not permit this syntactic sugar at first.
+// Note: This is now disabled. All examples below are adjusted.
+type Adder[T any] interface {
+ Add(T) T
+}
+
+// We don't need to explicitly instantiate the Adder bound
+// if we have exactly one type parameter.
+func Sum[T Adder[T]](list []T) T {
+ var sum T
+ for _, x := range list {
+ sum = sum.Add(x)
+ }
+ return sum
+}
+
+// Valid and invalid variations.
+type B0 any
+type B1[_ any] any
+type B2[_, _ any] any
+
+func _[T1 B0]() {}
+func _[T1 B1[T1]]() {}
+func _[T1 B2 /* ERRORx `cannot use generic type .* without instantiation` */ ]() {}
+
+func _[T1, T2 B0]() {}
+func _[T1 B1[T1], T2 B1[T2]]() {}
+func _[T1, T2 B2 /* ERRORx `cannot use generic type .* without instantiation` */ ]() {}
+
+func _[T1 B0, T2 B1[T2]]() {} // here B1 applies to T2
+
+// When the type argument is left away, the type bound is
+// instantiated for each type parameter with that type
+// parameter.
+// Note: We may not permit this syntactic sugar at first.
+func _[A Adder[A], B Adder[B], C Adder[A]]() {
+ var a A // A's type bound is Adder[A]
+ a = a.Add(a)
+ var b B // B's type bound is Adder[B]
+ b = b.Add(b)
+ var c C // C's type bound is Adder[A]
+ a = c.Add(a)
+}
+
+// The type of variables (incl. parameters and return values) cannot
+// be an interface with type constraints or be/embed comparable.
+type I interface {
+ ~int
+}
+
+var (
+ _ interface /* ERROR "contains type constraints" */ {~int}
+ _ I /* ERROR "contains type constraints" */
+)
+
+func _(I /* ERROR "contains type constraints" */ )
+func _(x, y, z I /* ERROR "contains type constraints" */ )
+func _() I /* ERROR "contains type constraints" */
+
+func _() {
+ var _ I /* ERROR "contains type constraints" */
+}
+
+type C interface {
+ comparable
+}
+
+var _ comparable /* ERROR "comparable" */
+var _ C /* ERROR "comparable" */
+
+func _(_ comparable /* ERROR "comparable" */ , _ C /* ERROR "comparable" */ )
+
+func _() {
+ var _ comparable /* ERROR "comparable" */
+ var _ C /* ERROR "comparable" */
+}
+
+// Type parameters are never const types, i.e., it's
+// not possible to declare a constant of type parameter type.
+// (If a type set contains just a single const type, we could
+// allow it, but such type sets don't make much sense in the
+// first place.)
+func _[T interface{~int|~float64}]() {
+ // not valid
+ const _ = T /* ERROR "not constant" */ (0)
+ const _ T /* ERROR "invalid constant type T" */ = 1
+
+ // valid
+ var _ = T(0)
+ var _ T = 1
+ _ = T(0)
+}
+
+// It is possible to create composite literals of type parameter
+// type as long as it's possible to create a composite literal
+// of the core type of the type parameter's constraint.
+func _[P interface{ ~[]int }]() P {
+ return P{}
+ return P{1, 2, 3}
+}
+
+func _[P interface{ ~[]E }, E interface{ map[string]P } ]() P {
+ x := P{}
+ return P{{}}
+ return P{E{}}
+ return P{E{"foo": x}}
+ return P{{"foo": x}, {}}
+}
+
+// This is a degenerate case with a singleton type set, but we can create
+// composite literals even if the core type is a defined type.
+type MyInts []int
+
+func _[P MyInts]() P {
+ return P{}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/typesets.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/typesets.go
new file mode 100644
index 0000000000000000000000000000000000000000..93eada730a31ce13c5b87900a6b6c43ff999b9da
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/examples/typesets.go
@@ -0,0 +1,59 @@
+// 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.
+
+// This file shows some examples of constraint literals with elided interfaces.
+// These examples are permitted if proposal issue #48424 is accepted.
+
+package p
+
+// Constraint type sets of the form T, ~T, or A|B may omit the interface.
+type (
+ _[T int] struct{}
+ _[T ~int] struct{}
+ _[T int | string] struct{}
+ _[T ~int | ~string] struct{}
+)
+
+func min[T int | string](x, y T) T {
+ if x < y {
+ return x
+ }
+ return y
+}
+
+func lookup[M ~map[K]V, K comparable, V any](m M, k K) V {
+ return m[k]
+}
+
+func deref[P ~*E, E any](p P) E {
+ return *p
+}
+
+func _() int {
+ p := new(int)
+ return deref(p)
+}
+
+func addrOfCopy[V any, P *V](v V) P {
+ return &v
+}
+
+func _() *int {
+ return addrOfCopy(0)
+}
+
+// A type parameter may not be embedded in an interface;
+// so it can also not be used as a constraint.
+func _[A any, B A /* ERROR "cannot use a type parameter as constraint" */]() {}
+func _[A any, B, C A /* ERROR "cannot use a type parameter as constraint" */]() {}
+
+// Error messages refer to the type constraint as it appears in the source.
+// (No implicit interface should be exposed.)
+func _[T string](x T) T {
+ return x /* ERROR "constrained by string" */ * x
+}
+
+func _[T int | string](x T) T {
+ return x /* ERROR "constrained by int | string" */ * x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue20583.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue20583.go
new file mode 100644
index 0000000000000000000000000000000000000000..55cbd9417562de62f650780daf63e22b5b18b115
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue20583.go
@@ -0,0 +1,14 @@
+// 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 issue20583
+
+const (
+ _ = 6e886451608 /* ERROR "malformed constant" */ /2
+ _ = 6e886451608i /* ERROR "malformed constant" */ /2
+ _ = 0 * 1e+1000000000 // ERROR "malformed constant"
+
+ x = 1e100000000
+ _ = x*x*x*x*x*x* /* ERROR "not representable" */ x
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203a.go
new file mode 100644
index 0000000000000000000000000000000000000000..48cb5889cd90ef1fcf0dfbc6fee261b571c72a0d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203a.go
@@ -0,0 +1,14 @@
+// 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 main
+
+import "unsafe"
+
+type T struct{}
+
+func (T) m1() {}
+func (T) m2([unsafe.Sizeof(T.m1)]int) {}
+
+func main() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203b.go
new file mode 100644
index 0000000000000000000000000000000000000000..638ec6c5ce34c5d0dd974e11fc0655b038f851b0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue23203b.go
@@ -0,0 +1,14 @@
+// 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 main
+
+import "unsafe"
+
+type T struct{}
+
+func (T) m2([unsafe.Sizeof(T.m1)]int) {}
+func (T) m1() {}
+
+func main() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue25838.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue25838.go
new file mode 100644
index 0000000000000000000000000000000000000000..b0ea98ee89609f97bda9d7a0da0a26ccabfb5b72
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue25838.go
@@ -0,0 +1,40 @@
+// 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 p
+
+// examples from the issue
+
+type (
+ e = f
+ f = g
+ g = []h
+ h i
+ i = j
+ j = e
+)
+
+type (
+ e1 = []h1
+ h1 e1
+)
+
+type (
+ P = *T
+ T P
+)
+
+func newA(c funcAlias) A {
+ return A{c: c}
+}
+
+type B struct {
+ a *A
+}
+
+type A struct {
+ c funcAlias
+}
+
+type funcAlias = func(B)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue26390.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue26390.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e0101f5819b9c4fbbee387d56408a7a8f51e073
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue26390.go
@@ -0,0 +1,13 @@
+// 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.
+
+// stand-alone test to ensure case is triggered
+
+package issue26390
+
+type A = T
+
+func (t *T) m() *A { return t }
+
+type T struct{}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue28251.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue28251.go
new file mode 100644
index 0000000000000000000000000000000000000000..71e727e2ac64152ee484586f0b500ed123cc4f71
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue28251.go
@@ -0,0 +1,65 @@
+// 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 contains test cases for various forms of
+// method receiver declarations, per the spec clarification
+// https://golang.org/cl/142757.
+
+package issue28251
+
+// test case from issue28251
+type T struct{}
+
+type T0 = *T
+
+func (T0) m() {}
+
+func _() { (&T{}).m() }
+
+// various alternative forms
+type (
+ T1 = (((T)))
+)
+
+func ((*(T1))) m1() {}
+func _() { (T{}).m2() }
+func _() { (&T{}).m2() }
+
+type (
+ T2 = (((T3)))
+ T3 = T
+)
+
+func (T2) m2() {}
+func _() { (T{}).m2() }
+func _() { (&T{}).m2() }
+
+type (
+ T4 = ((*(T5)))
+ T5 = T
+)
+
+func (T4) m4() {}
+func _() { (T{}).m4 /* ERROR "cannot call pointer method m4 on T" */ () }
+func _() { (&T{}).m4() }
+
+type (
+ T6 = (((T7)))
+ T7 = (*(T8))
+ T8 = T
+)
+
+func (T6) m6() {}
+func _() { (T{}).m6 /* ERROR "cannot call pointer method m6 on T" */ () }
+func _() { (&T{}).m6() }
+
+type (
+ T9 = *T10
+ T10 = *T11
+ T11 = T
+)
+
+func (T9 /* ERRORx `invalid receiver type (\*\*T|T9)` */ ) m9() {}
+func _() { (T{}).m9 /* ERROR "has no field or method m9" */ () }
+func _() { (&T{}).m9 /* ERROR "has no field or method m9" */ () }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue3117.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue3117.go
new file mode 100644
index 0000000000000000000000000000000000000000..16c0afce81d13b8d6b1a2c1e7b80eed1356f59ba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue3117.go
@@ -0,0 +1,13 @@
+// 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 p
+
+type S struct {
+ a [1]int
+}
+
+func _(m map[int]S, key int) {
+ m /* ERROR "cannot assign to m[key].a[0] (neither addressable nor a map index expression)" */ [key].a[0] = 0
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39634.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39634.go
new file mode 100644
index 0000000000000000000000000000000000000000..591b00e40463338e60660cb5079d10f34a1fbe28
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39634.go
@@ -0,0 +1,90 @@
+// 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.
+
+// Examples adjusted to match new [T any] syntax for type parameters.
+// Also, previously permitted empty type parameter lists and instantiations
+// are now syntax errors.
+
+package p
+
+// crash 1
+type nt1[_ any]interface{g /* ERROR "undefined" */ }
+type ph1[e nt1[e],g(d /* ERROR "undefined" */ )]s /* ERROR "undefined" */
+func(*ph1[e,e /* ERROR "redeclared" */ ])h(d /* ERROR "undefined" */ )
+
+// crash 2
+// Disabled: empty []'s are now syntax errors. This example leads to too many follow-on errors.
+// type Numeric2 interface{t2 /* ERROR "not a type" */ }
+// func t2[T Numeric2](s[]T){0 /* ERROR "not a type */ []{s /* ERROR cannot index" */ [0][0]}}
+
+// crash 3
+type t3 *interface{ t3.p /* ERROR "t3.p is not a type" */ }
+
+// crash 4
+type Numeric4 interface{t4 /* ERROR "not a type" */ }
+func t4[T Numeric4](s[]T){if( /* ERROR "non-boolean" */ 0){*s /* ERROR "cannot indirect" */ [0]}}
+
+// crash 7
+type foo7 interface { bar() }
+type x7[A any] struct{ foo7 }
+func main7() { var _ foo7 = x7[int]{} }
+
+// crash 8
+type foo8[A any] interface { ~A /* ERROR "cannot be a type parameter" */ }
+func bar8[A foo8[A]](a A) {}
+
+// crash 9
+type foo9[A any] interface { foo9 /* ERROR "invalid recursive type" */ [A] }
+func _() { var _ = new(foo9[int]) }
+
+// crash 12
+var u /* ERROR "cycle" */ , i [func /* ERROR "used as value" */ /* ERROR "used as value" */ (u, c /* ERROR "undefined" */ /* ERROR "undefined" */ ) {}(0, len /* ERROR "must be called" */ /* ERROR "must be called" */ )]c /* ERROR "undefined" */ /* ERROR "undefined" */
+
+// crash 15
+func y15() { var a /* ERROR "declared and not used" */ interface{ p() } = G15[string]{} }
+type G15[X any] s /* ERROR "undefined" */
+func (G15 /* ERRORx `generic type .* without instantiation` */ ) p()
+
+// crash 16
+type Foo16[T any] r16 /* ERROR "not a type" */
+func r16[T any]() Foo16[Foo16[T]] { panic(0) }
+
+// crash 17
+type Y17 interface{ c() }
+type Z17 interface {
+ c() Y17
+ Y17 /* ERROR "duplicate method" */
+}
+func F17[T Z17](T) {}
+
+// crash 18
+type o18[T any] []func(_ o18[[]_ /* ERROR "cannot use _" */ ])
+
+// crash 19
+type Z19 [][[]Z19{}[0][0]]c19 /* ERROR "undefined" */
+
+// crash 20
+type Z20 /* ERROR "invalid recursive type" */ interface{ Z20 }
+func F20[t Z20]() { F20(t /* ERROR "invalid composite literal type" */ /* ERROR "too many arguments in call to F20\n\thave (unknown type)\n\twant ()" */ {}) }
+
+// crash 21
+type Z21 /* ERROR "invalid recursive type" */ interface{ Z21 }
+func F21[T Z21]() { ( /* ERROR "not used" */ F21[Z21]) }
+
+// crash 24
+type T24[P any] P // ERROR "cannot use a type parameter as RHS in type declaration"
+func (r T24[P]) m() { T24 /* ERROR "without instantiation" */ .m() }
+
+// crash 25
+type T25[A any] int
+func (t T25[A]) m1() {}
+var x T25 /* ERROR "without instantiation" */ .m1
+
+// crash 26
+type T26 = interface{ F26[ /* ERROR "interface method must have no type parameters" */ Z any]() }
+func F26[Z any]() T26 { return F26[] /* ERROR "operand" */ }
+
+// crash 27
+func e27[T any]() interface{ x27 /* ERROR "not a type" */ } { panic(0) }
+func x27() { e27 /* ERROR "cannot infer T" */ () }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39664.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39664.go
new file mode 100644
index 0000000000000000000000000000000000000000..a8148c6e9e3aec342fb4a678ba7541663c0c93c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39664.go
@@ -0,0 +1,15 @@
+// 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 p
+
+type T[_ any] struct {}
+
+func (T /* ERROR "instantiation" */ ) m()
+
+func _() {
+ var x interface { m() }
+ x = T[int]{}
+ _ = x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39680.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39680.go
new file mode 100644
index 0000000000000000000000000000000000000000..e56bc3547582d190f110b6f70a231e9e38012572
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39680.go
@@ -0,0 +1,31 @@
+// 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 p
+
+// Embedding stand-alone type parameters is not permitted for now. Disabled.
+
+/*
+import "fmt"
+
+// Minimal test case.
+func _[T interface{~T}](x T) T{
+ return x
+}
+
+// Test case from issue.
+type constr[T any] interface {
+ ~T
+}
+
+func Print[T constr[T]](s []T) {
+ for _, v := range s {
+ fmt.Print(v)
+ }
+}
+
+func f() {
+ Print([]string{"Hello, ", "playground\n"})
+}
+*/
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39693.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39693.go
new file mode 100644
index 0000000000000000000000000000000000000000..03f27895d8b643d81f14f9ef7544d3928eddda25
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39693.go
@@ -0,0 +1,23 @@
+// 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 p
+
+type Number1 interface {
+ // embedding non-interface types is permitted
+ int
+ float64
+}
+
+func Add1[T Number1](a, b T) T {
+ return a /* ERROR "not defined" */ + b
+}
+
+type Number2 interface {
+ int | float64
+}
+
+func Add2[T Number2](a, b T) T {
+ return a + b
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39699.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39699.go
new file mode 100644
index 0000000000000000000000000000000000000000..73ba0c4cd618d0b554525a947c489f5b905c9dcb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39699.go
@@ -0,0 +1,29 @@
+// 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 p
+
+type T0 interface{
+}
+
+type T1 interface{
+ ~int
+}
+
+type T2 interface{
+ comparable
+}
+
+type T3 interface {
+ T0
+ T1
+ T2
+}
+
+func _() {
+ _ = T0(0)
+ _ = T1 /* ERROR "cannot use interface T1 in conversion" */ (1)
+ _ = T2 /* ERROR "cannot use interface T2 in conversion" */ (2)
+ _ = T3 /* ERROR "cannot use interface T3 in conversion" */ (3)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39711.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39711.go
new file mode 100644
index 0000000000000000000000000000000000000000..d85fa03fc433bc77d34c4e16f4fbb923cfee8d32
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39711.go
@@ -0,0 +1,13 @@
+// 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 p
+
+// Do not report a duplicate type error for this term list.
+// (Check types after interfaces have been completed.)
+type _ interface {
+ // TODO(rfindley) Once we have full type sets we can enable this again.
+ // Fow now we don't permit interfaces in term lists.
+ // type interface{ Error() string }, interface{ String() string }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39723.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39723.go
new file mode 100644
index 0000000000000000000000000000000000000000..19e5e80393987f95976081d28d2d94a4fd9336df
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39723.go
@@ -0,0 +1,9 @@
+// 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 p
+
+// A constraint must be an interface; it cannot
+// be a type parameter, for instance.
+func _[A interface{ ~int }, B A /* ERROR "cannot use a type parameter as constraint" */ ]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39725.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39725.go
new file mode 100644
index 0000000000000000000000000000000000000000..0145667e0de323a45eabde8d3d5c8b903cc83260
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39725.go
@@ -0,0 +1,16 @@
+// 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 p
+
+func f1[T1, T2 any](T1, T2, struct{a T1; b T2}) {}
+func _() {
+ f1(42, string("foo"), struct /* ERROR "does not match inferred type struct{a int; b string}" */ {a, b int}{})
+}
+
+// simplified test case from issue
+func f2[T any](_ []T, _ func(T)) {}
+func _() {
+ f2([]string{}, func /* ERROR "does not match inferred type func(string)" */ (f []byte) {})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39754.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39754.go
new file mode 100644
index 0000000000000000000000000000000000000000..a1bd5bafddae764d9a5908a8f6a3cc46c60d0422
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39754.go
@@ -0,0 +1,21 @@
+// 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 p
+
+type Optional[T any] struct {}
+
+func (_ Optional[T]) Val() (T, bool)
+
+type Box[T any] interface {
+ Val() (T, bool)
+}
+
+func f[V interface{}, A, B Box[V]]() {}
+
+func _() {
+ f[int, Optional[int], Optional[int]]()
+ _ = f[int, Optional[int], Optional /* ERROR "does not satisfy Box" */ [string]]
+ _ = f[int, Optional[int], Optional /* ERRORx "Optional.* does not satisfy Box.*" */ [string]]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39755.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39755.go
new file mode 100644
index 0000000000000000000000000000000000000000..257b73a2fbeff15a934f4daf4798952578bad9d5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39755.go
@@ -0,0 +1,23 @@
+// 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 p
+
+func _[T interface{~map[string]int}](x T) {
+ _ = x == nil
+}
+
+// simplified test case from issue
+
+type PathParamsConstraint interface {
+ ~map[string]string | ~[]struct{key, value string}
+}
+
+type PathParams[T PathParamsConstraint] struct {
+ t T
+}
+
+func (pp *PathParams[T]) IsNil() bool {
+ return pp.t == nil // this must succeed
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39768.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39768.go
new file mode 100644
index 0000000000000000000000000000000000000000..51a417759a27807076f21153bb4e007ceaf0e8cc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39768.go
@@ -0,0 +1,21 @@
+// 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 p
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type T[P any] P
+// type A = T // ERROR "cannot use generic type"
+// var x A[int]
+// var _ A
+//
+// type B = T[int]
+// var y B = x
+// var _ B /* ERROR "not a generic type" */ [int]
+
+// test case from issue
+
+type Vector[T any] []T
+type VectorAlias = Vector // ERROR "cannot use generic type"
+var v Vector[int]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39938.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39938.go
new file mode 100644
index 0000000000000000000000000000000000000000..bd5bdcae07cb4736f9b325619c5493269218b7e8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39938.go
@@ -0,0 +1,54 @@
+// 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 p
+
+// All but E2 and E5 provide an "indirection" and break infinite expansion of a type.
+type E0[P any] []P
+type E1[P any] *P
+type E2[P any] struct{ _ P }
+type E3[P any] struct{ _ *P }
+type E5[P any] struct{ _ [10]P }
+
+type T0 struct {
+ _ E0[T0]
+}
+
+type T0_ struct {
+ E0[T0_]
+}
+
+type T1 struct {
+ _ E1[T1]
+}
+
+type T2 /* ERROR "invalid recursive type" */ struct {
+ _ E2[T2]
+}
+
+type T3 struct {
+ _ E3[T3]
+}
+
+type T4 /* ERROR "invalid recursive type" */ [10]E5[T4]
+
+type T5 struct {
+ _ E0[E2[T5]]
+}
+
+type T6 struct {
+ _ E0[E2[E0[E1[E2[[10]T6]]]]]
+}
+
+type T7 struct {
+ _ E0[[10]E2[E0[E2[E2[T7]]]]]
+}
+
+type T8 struct {
+ _ E0[[]E2[E0[E2[E2[T8]]]]]
+}
+
+type T9 /* ERROR "invalid recursive type" */ [10]E2[E5[E2[T9]]]
+
+type T10 [10]E2[E5[E2[func(T10)]]]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39948.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39948.go
new file mode 100644
index 0000000000000000000000000000000000000000..e4430cfc4af96a0a30815c394a541ced373afb01
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39948.go
@@ -0,0 +1,9 @@
+// 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 p
+
+type T[P any] interface{
+ P // ERROR "term cannot be a type parameter"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39976.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39976.go
new file mode 100644
index 0000000000000000000000000000000000000000..b622cd92874c114e9a42280e2bb5628348db1f2b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39976.go
@@ -0,0 +1,16 @@
+// 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 p
+
+type policy[K, V any] interface{}
+type LRU[K, V any] struct{}
+
+func NewCache[K, V any](p policy[K, V]) {}
+
+func _() {
+ var lru LRU[int, string]
+ NewCache[int, string](&lru)
+ NewCache /* ERROR "cannot infer K" */ (&lru)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39982.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39982.go
new file mode 100644
index 0000000000000000000000000000000000000000..9810b6386a9a9e847617ac0915f28dd42e8374d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue39982.go
@@ -0,0 +1,36 @@
+// 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 p
+
+type (
+ T[_ any] struct{}
+ S[_ any] struct {
+ data T[*T[int]]
+ }
+)
+
+func _() {
+ _ = S[int]{
+ data: T[*T[int]]{},
+ }
+}
+
+// full test case from issue
+
+type (
+ Element[TElem any] struct{}
+
+ entry[K comparable] struct{}
+
+ Cache[K comparable] struct {
+ data map[K]*Element[*entry[K]]
+ }
+)
+
+func _() {
+ _ = Cache[int]{
+ data: make(map[int](*Element[*entry[int]])),
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40038.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40038.go
new file mode 100644
index 0000000000000000000000000000000000000000..5f81fcbfaa7236bfcdd58114ac74847f9e709555
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40038.go
@@ -0,0 +1,15 @@
+// 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 p
+
+type A[T any] int
+
+func (A[T]) m(A[T])
+
+func f[P interface{m(P)}]() {}
+
+func _() {
+ _ = f[A[int]]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40056.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40056.go
new file mode 100644
index 0000000000000000000000000000000000000000..ce882e7f2255e220a41ddf8c750cddea1d31c7dd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40056.go
@@ -0,0 +1,15 @@
+// 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 p
+
+func _() {
+ NewS /* ERROR "cannot infer T" */ ().M()
+}
+
+type S struct {}
+
+func NewS[T any]() *S { panic(0) }
+
+func (_ *S /* ERROR "S is not a generic type" */ [T]) M()
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40057.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40057.go
new file mode 100644
index 0000000000000000000000000000000000000000..2996d398e7d732eae38eae55c6937773bc2ffc4b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40057.go
@@ -0,0 +1,17 @@
+// 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 p
+
+func _() {
+ var x interface{}
+ switch t := x.(type) {
+ case S /* ERROR "cannot use generic type" */ :
+ t.m()
+ }
+}
+
+type S[T any] struct {}
+
+func (_ S[T]) m()
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40301.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40301.go
new file mode 100644
index 0000000000000000000000000000000000000000..c78f9a1fa040892e7ebec27753100db2867752b2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40301.go
@@ -0,0 +1,12 @@
+// 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 p
+
+import "unsafe"
+
+func _[T any](x T) {
+ _ = unsafe.Alignof(x)
+ _ = unsafe.Sizeof(x)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40350.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40350.go
new file mode 100644
index 0000000000000000000000000000000000000000..b7ceb33918e35e59e6eb0f40739c11595122bea2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40350.go
@@ -0,0 +1,16 @@
+// 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 p
+
+type number interface {
+ ~float64 | ~int | ~int32
+ float64 | ~int32
+}
+
+func f[T number]() {}
+
+func _() {
+ _ = f[int /* ERROR "int does not satisfy number (number mentions int, but int is not in the type set of number)" */]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40684.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40684.go
new file mode 100644
index 0000000000000000000000000000000000000000..48051841600df1a688cfce3543dea4600898c679
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40684.go
@@ -0,0 +1,15 @@
+// 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 p
+
+type T[_ any] int
+
+func f[_ any]() {}
+func g[_, _ any]() {}
+
+func _() {
+ _ = f[T /* ERROR "without instantiation" */ ]
+ _ = g[T /* ERROR "without instantiation" */ , T /* ERROR "without instantiation" */ ]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40789.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40789.go
new file mode 100644
index 0000000000000000000000000000000000000000..9eea4ad60a6647380606f70fd998febab618db8c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue40789.go
@@ -0,0 +1,37 @@
+// 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 main
+
+import "fmt"
+
+func main() {
+ m := map[string]int{
+ "a": 6,
+ "b": 7,
+ }
+ fmt.Println(copyMap[map[string]int, string, int](m))
+}
+
+type Map[K comparable, V any] interface {
+ map[K] V
+}
+
+func copyMap[M Map[K, V], K comparable, V any](m M) M {
+ m1 := make(M)
+ for k, v := range m {
+ m1[k] = v
+ }
+ return m1
+}
+
+// simpler test case from the same issue
+
+type A[X comparable] interface {
+ []X
+}
+
+func f[B A[X], X comparable]() B {
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41124.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41124.go
new file mode 100644
index 0000000000000000000000000000000000000000..0f828dc502a5f95254b398a2f24cdf8a59ee91f3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41124.go
@@ -0,0 +1,91 @@
+// 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 p
+
+// Test case from issue.
+
+type Nat /* ERROR "invalid recursive type" */ interface {
+ Zero|Succ
+}
+
+type Zero struct{}
+type Succ struct{
+ Nat // Nat contains type constraints but is invalid, so no error
+}
+
+// Struct tests.
+
+type I1 interface {
+ comparable
+}
+
+type I2 interface {
+ ~int
+}
+
+type I3 interface {
+ I1
+ I2
+}
+
+type _ struct {
+ f I1 // ERRORx `interface is .* comparable`
+}
+
+type _ struct {
+ comparable // ERRORx `interface is .* comparable`
+}
+
+type _ struct{
+ I1 // ERRORx `interface is .* comparable`
+}
+
+type _ struct{
+ I2 // ERROR "interface contains type constraints"
+}
+
+type _ struct{
+ I3 // ERROR "interface contains type constraints"
+}
+
+// General composite types.
+
+type (
+ _ [10]I1 // ERRORx `interface is .* comparable`
+ _ [10]I2 // ERROR "interface contains type constraints"
+
+ _ []I1 // ERRORx `interface is .* comparable`
+ _ []I2 // ERROR "interface contains type constraints"
+
+ _ *I3 // ERROR "interface contains type constraints"
+ _ map[I1 /* ERRORx `interface is .* comparable` */ ]I2 // ERROR "interface contains type constraints"
+ _ chan I3 // ERROR "interface contains type constraints"
+ _ func(I1 /* ERRORx `interface is .* comparable` */ )
+ _ func() I2 // ERROR "interface contains type constraints"
+)
+
+// Other cases.
+
+var _ = [...]I3 /* ERROR "interface contains type constraints" */ {}
+
+func _(x interface{}) {
+ _ = x.(I3 /* ERROR "interface contains type constraints" */ )
+}
+
+type T1[_ any] struct{}
+type T3[_, _, _ any] struct{}
+var _ T1[I2 /* ERROR "interface contains type constraints" */ ]
+var _ T3[int, I2 /* ERROR "interface contains type constraints" */ , float32]
+
+func f1[_ any]() int { panic(0) }
+var _ = f1[I2 /* ERROR "interface contains type constraints" */ ]()
+func f3[_, _, _ any]() int { panic(0) }
+var _ = f3[int, I2 /* ERROR "interface contains type constraints" */ , float32]()
+
+func _(x interface{}) {
+ switch x.(type) {
+ case I2 /* ERROR "interface contains type constraints" */ :
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41176.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41176.go
new file mode 100644
index 0000000000000000000000000000000000000000..755e83a6327464460bf4657ced9368162885780c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue41176.go
@@ -0,0 +1,21 @@
+// 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 p
+
+type S struct{}
+
+func (S) M() byte {
+ return 0
+}
+
+type I[T any] interface {
+ M() T
+}
+
+func f[T any](x I[T]) {}
+
+func _() {
+ f(S{})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42695.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42695.go
new file mode 100644
index 0000000000000000000000000000000000000000..4551e9f03bb3a66c68229b5e07d0eff440450847
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42695.go
@@ -0,0 +1,17 @@
+// 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 issue42695
+
+const _ = 6e5518446744 // ERROR "malformed constant"
+const _ uint8 = 6e5518446744 // ERROR "malformed constant"
+
+var _ = 6e5518446744 // ERROR "malformed constant"
+var _ uint8 = 6e5518446744 // ERROR "malformed constant"
+
+func f(x int) int {
+ return x + 6e5518446744 // ERROR "malformed constant"
+}
+
+var _ = f(6e5518446744 /* ERROR "malformed constant" */ )
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42758.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42758.go
new file mode 100644
index 0000000000000000000000000000000000000000..4e1df340da1d9b2f1851d186e59ddbbb7a8374ce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42758.go
@@ -0,0 +1,33 @@
+// 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 p
+
+func _[T any](x interface{}){
+ switch x.(type) {
+ case T: // ok to use a type parameter
+ case int:
+ }
+
+ switch x.(type) {
+ case T:
+ case T /* ERROR "duplicate case" */ :
+ }
+}
+
+type constraint interface {
+ ~int
+}
+
+func _[T constraint](x interface{}){
+ switch x.(type) {
+ case T: // ok to use a type parameter even if type set contains int
+ case int:
+ }
+}
+
+func _(x constraint /* ERROR "contains type constraints" */ ) {
+ switch x.(type) { // no need to report another error
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42881.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42881.go
new file mode 100644
index 0000000000000000000000000000000000000000..b766b5e5bd3b6c06f685f66f3c43b89b5ab9d816
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42881.go
@@ -0,0 +1,16 @@
+// 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 p
+
+type (
+ T1 interface{ comparable }
+ T2 interface{ int }
+)
+
+var (
+ _ comparable // ERROR "cannot use type comparable outside a type constraint: interface is (or embeds) comparable"
+ _ T1 // ERROR "cannot use type T1 outside a type constraint: interface is (or embeds) comparable"
+ _ T2 // ERROR "cannot use type T2 outside a type constraint: interface contains type constraints"
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42987.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42987.go
new file mode 100644
index 0000000000000000000000000000000000000000..21c14c1fbdd802cf77cb71726994b782b79aa3de
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue42987.go
@@ -0,0 +1,8 @@
+// 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.
+
+// Check that there is only one error (no follow-on errors).
+
+package p
+var _ = [ ... /* ERROR "invalid use of [...] array" */ ]byte("foo")
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43056.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43056.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ff4e7f9b4d8f763d25edbb024ab6dbeeb1e0336
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43056.go
@@ -0,0 +1,31 @@
+// 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 p
+
+// simplified example
+func f[T ~func(T)](a, b T) {}
+
+type F func(F)
+
+func _() {
+ var i F
+ var j func(F)
+
+ f(i, j)
+ f(j, i)
+}
+
+// example from issue
+func g[T interface{ Equal(T) bool }](a, b T) {}
+
+type I interface{ Equal(I) bool }
+
+func _() {
+ var i I
+ var j interface{ Equal(I) bool }
+
+ g(i, j)
+ g(j, i)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43087.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43087.go
new file mode 100644
index 0000000000000000000000000000000000000000..222fac823cdd5253664e0629fb813b4b258206b1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43087.go
@@ -0,0 +1,43 @@
+// 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
+
+func _() {
+ a, b, b /* ERROR "b repeated on left side of :=" */ := 1, 2, 3
+ _ = a
+ _ = b
+}
+
+func _() {
+ a, _, _ := 1, 2, 3 // multiple _'s ok
+ _ = a
+}
+
+func _() {
+ var b int
+ a, b, b /* ERROR "b repeated on left side of :=" */ := 1, 2, 3
+ _ = a
+ _ = b
+}
+
+func _() {
+ var a []int
+ a /* ERRORx `non-name .* on left side of :=` */ [0], b := 1, 2
+ _ = a
+ _ = b
+}
+
+func _() {
+ var a int
+ a, a /* ERROR "a repeated on left side of :=" */ := 1, 2
+ _ = a
+}
+
+func _() {
+ var a, b int
+ a, b := /* ERROR "no new variables on left side of :=" */ 1, 2
+ _ = a
+ _ = b
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43109.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43109.go
new file mode 100644
index 0000000000000000000000000000000000000000..5d21a568dbbe8f6a8db7a31e3ba6576d05bb7d6f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43109.go
@@ -0,0 +1,10 @@
+// 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.
+
+// Ensure there is no "imported and not used" error
+// if a package wasn't imported in the first place.
+
+package p
+
+import . "/foo" // ERROR "could not import /foo"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43110.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43110.go
new file mode 100644
index 0000000000000000000000000000000000000000..1e850226119a4ac3b5bafaae334f3f056a5d5d2f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43110.go
@@ -0,0 +1,43 @@
+// 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 p
+
+type P *struct{}
+
+func _() {
+ // want an error even if the switch is empty
+ var a struct{ _ func() }
+ switch a /* ERROR "cannot switch on a" */ {
+ }
+
+ switch a /* ERROR "cannot switch on a" */ {
+ case a: // no follow-on error here
+ }
+
+ // this is ok because f can be compared to nil
+ var f func()
+ switch f {
+ }
+
+ switch f {
+ case nil:
+ }
+
+ switch (func())(nil) {
+ case nil:
+ }
+
+ switch (func())(nil) {
+ case f /* ERRORx `invalid case f in switch on .* \(func can only be compared to nil\)` */ :
+ }
+
+ switch nil /* ERROR "use of untyped nil in switch expression" */ {
+ }
+
+ // this is ok
+ switch P(nil) {
+ case P(nil):
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43124.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43124.go
new file mode 100644
index 0000000000000000000000000000000000000000..ce26ae1703cc15e08df384ccda1f747106a14bf1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43124.go
@@ -0,0 +1,16 @@
+// 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 p
+
+var _ = int(0 /* ERROR "invalid use of ... in conversion to int" */ ...)
+
+// test case from issue
+
+type M []string
+
+var (
+ x = []string{"a", "b"}
+ _ = M(x /* ERROR "invalid use of ... in conversion to M" */ ...)
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43125.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43125.go
new file mode 100644
index 0000000000000000000000000000000000000000..d0d6feb2a8516c8d766f1fa44b7f52840b574523
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43125.go
@@ -0,0 +1,8 @@
+// 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
+
+var _ = new(- /* ERROR "not a type" */ 1)
+var _ = new(1 /* ERROR "not a type" */ + 1)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43190.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43190.go
new file mode 100644
index 0000000000000000000000000000000000000000..b4d1fa463074310353dcfd908362933667da32ac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43190.go
@@ -0,0 +1,31 @@
+// 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.
+
+// The errors below are produced by the parser, but we check
+// them here for consistency with the types2 tests.
+
+package p
+
+import ; // ERROR "missing import path"
+import "" // ERROR "invalid import path (empty string)"
+import
+var /* ERROR "missing import path" */ _ int
+import .; // ERROR "missing import path"
+import 'x' // ERROR "import path must be a string"
+var _ int
+import /* ERROR "imports must appear before other declarations" */ _ "math"
+
+// Don't repeat previous error for each immediately following import ...
+import ()
+import (.) // ERROR "missing import path"
+import (
+ "fmt"
+ .
+) // ERROR "missing import path"
+
+// ... but remind with error again if we start a new import section after
+// other declarations
+var _ = fmt.Println
+import /* ERROR "imports must appear before other declarations" */ _ "math"
+import _ "math"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43527.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43527.go
new file mode 100644
index 0000000000000000000000000000000000000000..473ab96f56d0bb6304d7ba522624edeb2e84ed1e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43527.go
@@ -0,0 +1,16 @@
+// 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
+
+const L = 10
+
+type (
+ _ [L]struct{}
+ _ [A /* ERROR "undefined array length A or missing type constraint" */ ]struct{}
+ _ [B /* ERROR "invalid array length B" */ ]struct{}
+ _[A any] struct{}
+
+ B int
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43671.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43671.go
new file mode 100644
index 0000000000000000000000000000000000000000..be4c9ee5dd1f5138a1f76f26b66939742b3ba81a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue43671.go
@@ -0,0 +1,58 @@
+// 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
+
+type C0 interface{ int }
+type C1 interface{ chan int }
+type C2 interface{ chan int | <-chan int }
+type C3 interface{ chan int | chan float32 }
+type C4 interface{ chan int | chan<- int }
+type C5[T any] interface{ ~chan T | <-chan T }
+
+func _[T any](ch T) {
+ <-ch // ERRORx `cannot receive from ch .* \(no core type\)`
+}
+
+func _[T C0](ch T) {
+ <-ch // ERROR "cannot receive from non-channel ch"
+}
+
+func _[T C1](ch T) {
+ <-ch
+}
+
+func _[T C2](ch T) {
+ <-ch
+}
+
+func _[T C3](ch T) {
+ <-ch // ERRORx `cannot receive from ch .* \(no core type\)`
+}
+
+func _[T C4](ch T) {
+ <-ch // ERROR "cannot receive from send-only channel"
+}
+
+func _[T C5[X], X any](ch T, x X) {
+ x = <-ch
+}
+
+// test case from issue, slightly modified
+type RecvChan[T any] interface {
+ ~chan T | ~<-chan T
+}
+
+func _[T any, C RecvChan[T]](ch C) T {
+ return <-ch
+}
+
+func f[T any, C interface{ chan T }](ch C) T {
+ return <-ch
+}
+
+func _(ch chan int) {
+ var x int = f(ch) // test constraint type inference for this case
+ _ = x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44688.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44688.go
new file mode 100644
index 0000000000000000000000000000000000000000..512bfcc9223c824c84f960b9de2fb78286bab1d8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44688.go
@@ -0,0 +1,83 @@
+// 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
+
+type A1[T any] struct{}
+
+func (*A1[T]) m1(T) {}
+
+type A2[T any] interface {
+ m2(T)
+}
+
+type B1[T any] struct {
+ filler int
+ *A1[T]
+ A2[T]
+}
+
+type B2[T any] interface {
+ A2[T]
+}
+
+type C[T any] struct {
+ filler1 int
+ filler2 int
+ B1[T]
+}
+
+type D[T any] struct {
+ filler1 int
+ filler2 int
+ filler3 int
+ C[T]
+}
+
+func _() {
+ // calling embedded methods
+ var b1 B1[string]
+
+ b1.A1.m1("")
+ b1.m1("")
+
+ b1.A2.m2("")
+ b1.m2("")
+
+ var b2 B2[string]
+ b2.m2("")
+
+ // a deeper nesting
+ var d D[string]
+ d.m1("")
+ d.m2("")
+
+ // calling method expressions
+ m1x := B1[string].m1
+ m1x(b1, "")
+ m2x := B2[string].m2
+ m2x(b2, "")
+
+ // calling method values
+ m1v := b1.m1
+ m1v("")
+ m2v := b1.m2
+ m2v("")
+ b2v := b2.m2
+ b2v("")
+}
+
+// actual test case from issue
+
+type A[T any] struct{}
+
+func (*A[T]) f(T) {}
+
+type B[T any] struct{ A[T] }
+
+func _() {
+ var b B[string]
+ b.A.f("")
+ b.f("")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44799.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44799.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e528a7475b30e02792def3c31274c37e852e618
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue44799.go
@@ -0,0 +1,19 @@
+// 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 main
+
+func Map[F, T any](s []F, f func(F) T) []T { return nil }
+
+func Reduce[Elem1, Elem2 any](s []Elem1, initializer Elem2, f func(Elem2, Elem1) Elem2) Elem2 { var x Elem2; return x }
+
+func main() {
+ var s []int
+ var f1 func(int) float64
+ var f2 func(float64, int) float64
+ _ = Map[int](s, f1)
+ _ = Map(s, f1)
+ _ = Reduce[int](s, 0, f2)
+ _ = Reduce(s, 0, f2)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45114.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45114.go
new file mode 100644
index 0000000000000000000000000000000000000000..e51b3f711ba19b68ac960d9ebd3ae7d17f5ba594
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45114.go
@@ -0,0 +1,8 @@
+// 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 p
+
+var s uint
+var _ = string(1 /* ERRORx `shifted operand 1 .* must be integer` */ << s)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45548.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45548.go
new file mode 100644
index 0000000000000000000000000000000000000000..01c9672745a600b10d78c9e110437a06460a7d16
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45548.go
@@ -0,0 +1,13 @@
+// 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
+
+func f[F interface{*Q}, G interface{*R}, Q, R any](q Q, r R) {}
+
+func _() {
+ f[*float64, *int](1, 2)
+ f[*float64](1, 2)
+ f(1, 2)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45550.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45550.go
new file mode 100644
index 0000000000000000000000000000000000000000..2ea4ffe3079540a0588bc14cf806f418b788b2a0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45550.go
@@ -0,0 +1,10 @@
+// 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
+
+type Builder /* ERROR "invalid recursive type" */ [T interface{ struct{ Builder[T] } }] struct{}
+type myBuilder struct {
+ Builder[myBuilder]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45635.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45635.go
new file mode 100644
index 0000000000000000000000000000000000000000..b83d4774fe935126b8ae53fc9afcf3e54fe7fb03
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45635.go
@@ -0,0 +1,31 @@
+// 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 main
+
+func main() {
+ some /* ERROR "undefined" */ [int, int]()
+}
+
+type N[T any] struct{}
+
+var _ N [] // ERROR "expected type argument list"
+
+type I interface {
+ ~[]int
+}
+
+func _[T I](i, j int) {
+ var m map[int]int
+ _ = m[i, j /* ERROR "more than one index" */ ]
+
+ var a [3]int
+ _ = a[i, j /* ERROR "more than one index" */ ]
+
+ var s []int
+ _ = s[i, j /* ERROR "more than one index" */ ]
+
+ var t T
+ _ = t[i, j /* ERROR "more than one index" */ ]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45639.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45639.go
new file mode 100644
index 0000000000000000000000000000000000000000..a224aedcb68e10d056c35ad04c450fcf70a9ac86
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45639.go
@@ -0,0 +1,13 @@
+// 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
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// // It is not permitted to declare a local type whose underlying
+// // type is a type parameters not declared by that type declaration.
+// func _[T any]() {
+// type _ T // ERROR "cannot use function type parameter T as RHS in type declaration"
+// type _ [_ any] T // ERROR "cannot use function type parameter T as RHS in type declaration"
+// }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45920.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45920.go
new file mode 100644
index 0000000000000000000000000000000000000000..716abb17680d5e787f01da34ee41d3ff1cf693e7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45920.go
@@ -0,0 +1,17 @@
+// 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
+
+func f1[T any, C chan T | <-chan T](ch C) {}
+
+func _(ch chan int) { f1(ch) }
+func _(ch <-chan int) { f1(ch) }
+func _(ch chan<- int) { f1 /* ERROR "chan<- int does not satisfy chan int | <-chan int" */ (ch) }
+
+func f2[T any, C chan T | chan<- T](ch C) {}
+
+func _(ch chan int) { f2(ch) }
+func _(ch <-chan int) { f2 /* ERROR "<-chan int does not satisfy chan int | chan<- int" */ (ch) }
+func _(ch chan<- int) { f2(ch) }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45985.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45985.go
new file mode 100644
index 0000000000000000000000000000000000000000..c486150cb39f24c8a3e8083f28d17d8c46baae52
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue45985.go
@@ -0,0 +1,13 @@
+// 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 issue45985
+
+func app[S interface{ ~[]T }, T any](s S, e T) S {
+ return append(s, e)
+}
+
+func _() {
+ _ = app /* ERROR "S (type int) does not satisfy interface{~[]T}" */ [int] // TODO(gri) better error message
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46090.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46090.go
new file mode 100644
index 0000000000000000000000000000000000000000..59670da7fa416cb2b60c295e84a0c2e1778a436d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46090.go
@@ -0,0 +1,11 @@
+// -lang=go1.17
+
+// 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.
+
+// The predeclared type comparable is not visible before Go 1.18.
+
+package p
+
+type _ comparable // ERROR "predeclared comparable"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46275.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46275.go
new file mode 100644
index 0000000000000000000000000000000000000000..0862d5bb5a0ef6dac4311b39757ef8b952d8d5fe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46275.go
@@ -0,0 +1,26 @@
+// 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 issue46275
+
+type N[T any] struct {
+ *N[T]
+ t T
+}
+
+func (n *N[T]) Elem() T {
+ return n.t
+}
+
+type I interface {
+ Elem() string
+}
+
+func _() {
+ var n1 *N[string]
+ var _ I = n1
+ type NS N[string]
+ var n2 *NS
+ var _ I = n2
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46403.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46403.go
new file mode 100644
index 0000000000000000000000000000000000000000..fc60340a2102cf132f9f2e1d569217ca3e840fa9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46403.go
@@ -0,0 +1,11 @@
+// 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 issue46403
+
+func _() {
+ // a should be used, despite the parser error below.
+ var a []int
+ var _ = a[] // ERROR "expected operand"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46404.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46404.go
new file mode 100644
index 0000000000000000000000000000000000000000..e3c93f66a85938999e65dbdd0d80be83533aa75b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46404.go
@@ -0,0 +1,10 @@
+// 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 issue46404
+
+// TODO(gri) re-enable this test with matching errors
+// between go/types and types2
+// Check that we don't type check t[_] as an instantiation.
+// type t [t /* type parameters must be named */ /* not a generic type */ [_]]_ // cannot use
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461.go
new file mode 100644
index 0000000000000000000000000000000000000000..e823013f9951676daabe94e76ed63db2b9c5482a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461.go
@@ -0,0 +1,22 @@
+// -gotypesalias=0
+
+// 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 case 1
+type T /* ERROR "invalid recursive type" */ [U interface{ M() T[U] }] int
+
+type X int
+
+func (X) M() T[X] { return 0 }
+
+// test case 2
+type A /* ERROR "invalid recursive type" */ [T interface{ A[T] }] interface{}
+
+// test case 3
+type A2 /* ERROR "invalid recursive type" */ [U interface{ A2[U] }] interface{ M() A2[U] }
+
+type I interface{ A2[I]; M() A2[I] }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461a.go
new file mode 100644
index 0000000000000000000000000000000000000000..e4b8e1a240a973f62ed89669f3b1a8babe9376c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46461a.go
@@ -0,0 +1,23 @@
+// -gotypesalias=1
+
+// 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 case 1
+type T /* ERROR "invalid recursive type" */ [U interface{ M() T[U] }] int
+
+type X int
+
+func (X) M() T[X] { return 0 }
+
+// test case 2
+type A /* ERROR "invalid recursive type" */ [T interface{ A[T] }] interface{}
+
+// test case 3
+// TODO(gri) should report error only once
+type A2 /* ERROR "invalid recursive type" */ /* ERROR "invalid recursive type" */ [U interface{ A2[U] }] interface{ M() A2[U] }
+
+type I interface{ A2[I]; M() A2[I] }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46583.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46583.go
new file mode 100644
index 0000000000000000000000000000000000000000..1901bff31e8f323885fb6ff784c9d6eeae149073
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue46583.go
@@ -0,0 +1,28 @@
+// 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
+
+type T1 struct{}
+func (t T1) m(int) {}
+var f1 func(T1)
+
+type T2 struct{}
+func (t T2) m(x int) {}
+var f2 func(T2)
+
+type T3 struct{}
+func (T3) m(int) {}
+var f3 func(T3)
+
+type T4 struct{}
+func (T4) m(x int) {}
+var f4 func(T4)
+
+func _() {
+ f1 = T1 /* ERROR "func(T1, int)" */ .m
+ f2 = T2 /* ERROR "func(t T2, x int)" */ .m
+ f3 = T3 /* ERROR "func(T3, int)" */ .m
+ f4 = T4 /* ERROR "func(_ T4, x int)" */ .m
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47031.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47031.go
new file mode 100644
index 0000000000000000000000000000000000000000..23a9c55a1106883e18643c128c87d16adacbab67
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47031.go
@@ -0,0 +1,20 @@
+// 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
+
+type Mer interface { M() }
+
+func F[T Mer](p *T) {
+ p.M /* ERROR "p.M undefined" */ ()
+}
+
+type MyMer int
+
+func (MyMer) M() {}
+
+func _() {
+ F(new(MyMer))
+ F[Mer](nil)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47115.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47115.go
new file mode 100644
index 0000000000000000000000000000000000000000..2d2be34104216efba3e896f2928d209b4d5d14d8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47115.go
@@ -0,0 +1,40 @@
+// 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
+
+type C0 interface{ int }
+type C1 interface{ chan int }
+type C2 interface{ chan int | <-chan int }
+type C3 interface{ chan int | chan float32 }
+type C4 interface{ chan int | chan<- int }
+type C5[T any] interface{ ~chan T | chan<- T }
+
+func _[T any](ch T) {
+ ch <- /* ERRORx `cannot send to ch .* no core type` */ 0
+}
+
+func _[T C0](ch T) {
+ ch <- /* ERROR "cannot send to non-channel" */ 0
+}
+
+func _[T C1](ch T) {
+ ch <- 0
+}
+
+func _[T C2](ch T) {
+ ch <-/* ERROR "cannot send to receive-only channel" */ 0
+}
+
+func _[T C3](ch T) {
+ ch <- /* ERRORx `cannot send to ch .* no core type` */ 0
+}
+
+func _[T C4](ch T) {
+ ch <- 0
+}
+
+func _[T C5[X], X any](ch T, x X) {
+ ch <- x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47127.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47127.go
new file mode 100644
index 0000000000000000000000000000000000000000..b6639387ea460e46d480bbe2f6b64e376d3c62fd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47127.go
@@ -0,0 +1,37 @@
+// 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.
+
+// Embedding of stand-alone type parameters is not permitted.
+
+package p
+
+type (
+ _[P any] interface{ *P | []P | chan P | map[string]P }
+ _[P any] interface{ P /* ERROR "term cannot be a type parameter" */ }
+ _[P any] interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+ _[P any] interface{ int | P /* ERROR "term cannot be a type parameter" */ }
+ _[P any] interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+)
+
+func _[P any]() {
+ type (
+ _[P any] interface{ *P | []P | chan P | map[string]P }
+ _[P any] interface{ P /* ERROR "term cannot be a type parameter" */ }
+ _[P any] interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+ _[P any] interface{ int | P /* ERROR "term cannot be a type parameter" */ }
+ _[P any] interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+
+ _ interface{ *P | []P | chan P | map[string]P }
+ _ interface{ P /* ERROR "term cannot be a type parameter" */ }
+ _ interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+ _ interface{ int | P /* ERROR "term cannot be a type parameter" */ }
+ _ interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ }
+ )
+}
+
+func _[P any, Q interface{ *P | []P | chan P | map[string]P }]() {}
+func _[P any, Q interface{ P /* ERROR "term cannot be a type parameter" */ }]() {}
+func _[P any, Q interface{ ~P /* ERROR "type in term ~P cannot be a type parameter" */ }]() {}
+func _[P any, Q interface{ int | P /* ERROR "term cannot be a type parameter" */ }]() {}
+func _[P any, Q interface{ int | ~P /* ERROR "type in term ~P cannot be a type parameter" */ }]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47411.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47411.go
new file mode 100644
index 0000000000000000000000000000000000000000..97b5942ff05ed1ef3e9a6ec976ed0d2f88a3faa5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47411.go
@@ -0,0 +1,26 @@
+// 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
+
+func f[_ comparable]() {}
+func g[_ interface{interface{comparable; ~int|~string}}]() {}
+
+func _[P comparable,
+ Q interface{ comparable; ~int|~string },
+ R any, // not comparable
+ S interface{ comparable; ~func() }, // not comparable
+]() {
+ _ = f[int]
+ _ = f[P]
+ _ = f[Q]
+ _ = f[func /* ERROR "does not satisfy comparable" */ ()]
+ _ = f[R /* ERROR "R does not satisfy comparable" */ ]
+
+ _ = g[int]
+ _ = g[P /* ERROR "P does not satisfy interface{interface{comparable; ~int | ~string}" */ ]
+ _ = g[Q]
+ _ = g[func /* ERROR "func() does not satisfy interface{interface{comparable; ~int | ~string}}" */ ()]
+ _ = g[R /* ERROR "R does not satisfy interface{interface{comparable; ~int | ~string}" */ ]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47747.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47747.go
new file mode 100644
index 0000000000000000000000000000000000000000..34c78d3b49c02f6629982c047d289eb55c5510f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47747.go
@@ -0,0 +1,71 @@
+// 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
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type T1[P any] P
+//
+// func (T1[_]) m() {}
+//
+// func _[P any](x *T1[P]) {
+// // x.m exists because x is of type *T1 where T1 is a defined type
+// // (even though under(T1) is a type parameter)
+// x.m()
+// }
+
+
+func _[P interface{ m() }](x P) {
+ x.m()
+ // (&x).m doesn't exist because &x is of type *P
+ // and pointers to type parameters don't have methods
+ (&x).m /* ERROR "type *P is pointer to type parameter, not type parameter" */ ()
+}
+
+
+type T2 interface{ m() }
+
+func _(x *T2) {
+ // x.m doesn't exists because x is of type *T2
+ // and pointers to interfaces don't have methods
+ x.m /* ERROR "type *T2 is pointer to interface, not interface" */()
+}
+
+// Test case 1 from issue
+
+type Fooer1[t any] interface {
+ Foo(Barer[t])
+}
+type Barer[t any] interface {
+ Bar(t)
+}
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type Foo1[t any] t
+// type Bar[t any] t
+//
+// func (l Foo1[t]) Foo(v Barer[t]) { v.Bar(t(l)) }
+// func (b *Bar[t]) Bar(l t) { *b = Bar[t](l) }
+//
+// func _[t any](f Fooer1[t]) t {
+// var b Bar[t]
+// f.Foo(&b)
+// return t(b)
+// }
+
+// Test case 2 from issue
+
+// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
+// type Fooer2[t any] interface {
+// Foo()
+// }
+//
+// type Foo2[t any] t
+//
+// func (f *Foo2[t]) Foo() {}
+//
+// func _[t any](v t) {
+// var f = Foo2[t](v)
+// _ = Fooer2[t](&f)
+// }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47796.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47796.go
new file mode 100644
index 0000000000000000000000000000000000000000..7f719ff6745eaa15adb84398befcfad945c92fce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47796.go
@@ -0,0 +1,33 @@
+// 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
+
+// parameterized types with self-recursive constraints
+type (
+ T1 /* ERROR "invalid recursive type" */ [P T1[P]] interface{}
+ T2 /* ERROR "invalid recursive type" */ [P, Q T2[P, Q]] interface{}
+ T3[P T2[P, Q], Q interface{ ~string }] interface{}
+
+ T4a /* ERROR "invalid recursive type" */ [P T4a[P]] interface{ ~int }
+ T4b /* ERROR "invalid recursive type" */ [P T4b[int]] interface{ ~int }
+ T4c /* ERROR "invalid recursive type" */ [P T4c[string]] interface{ ~int }
+
+ // mutually recursive constraints
+ T5 /* ERROR "invalid recursive type" */ [P T6[P]] interface{ int }
+ T6[P T5[P]] interface{ int }
+)
+
+// verify that constraints are checked as expected
+var (
+ _ T1[int]
+ _ T2[int, string]
+ _ T3[int, string]
+)
+
+// test case from issue
+
+type Eq /* ERROR "invalid recursive type" */ [a Eq[a]] interface {
+ Equal(that a) bool
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47818.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47818.go
new file mode 100644
index 0000000000000000000000000000000000000000..21c85392ab6bfe01c871fdc29ccb5580b216de4e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47818.go
@@ -0,0 +1,61 @@
+// -lang=go1.17
+
+// 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.
+
+// Parser accepts type parameters but the type checker
+// needs to report any operations that are not permitted
+// before Go 1.18.
+
+package p
+
+type T[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */] struct{}
+
+// for init (and main, but we're not in package main) we should only get one error
+func init[P /* ERROR "func init must have no type parameters" */ any /* ERROR "predeclared any requires go1.18 or later" */]() {
+}
+func main[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */]() {
+}
+
+func f[P /* ERROR "type parameter requires go1.18 or later" */ any /* ERROR "predeclared any requires go1.18 or later" */](x P) {
+ var _ T[ /* ERROR "type instantiation requires go1.18 or later" */ int]
+ var _ (T[ /* ERROR "type instantiation requires go1.18 or later" */ int])
+ _ = T[ /* ERROR "type instantiation requires go1.18 or later" */ int]{}
+ _ = T[ /* ERROR "type instantiation requires go1.18 or later" */ int](struct{}{})
+}
+
+func (T[ /* ERROR "type instantiation requires go1.18 or later" */ P]) g(x int) {
+ f[ /* ERROR "function instantiation requires go1.18 or later" */ int](0) // explicit instantiation
+ (f[ /* ERROR "function instantiation requires go1.18 or later" */ int])(0) // parentheses (different code path)
+ f( /* ERROR "implicit function instantiation requires go1.18 or later" */ x) // implicit instantiation
+}
+
+type C1 interface {
+ comparable // ERROR "predeclared comparable requires go1.18 or later"
+}
+
+type C2 interface {
+ comparable // ERROR "predeclared comparable requires go1.18 or later"
+ int // ERROR "embedding non-interface type int requires go1.18 or later"
+ ~ /* ERROR "embedding interface element ~int requires go1.18 or later" */ int
+ int /* ERROR "embedding interface element int | ~string requires go1.18 or later" */ | ~string
+}
+
+type _ interface {
+ // errors for these were reported with their declaration
+ C1
+ C2
+}
+
+type (
+ _ comparable // ERROR "predeclared comparable requires go1.18 or later"
+ // errors for these were reported with their declaration
+ _ C1
+ _ C2
+
+ _ = comparable // ERROR "predeclared comparable requires go1.18 or later"
+ // errors for these were reported with their declaration
+ _ = C1
+ _ = C2
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47887.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47887.go
new file mode 100644
index 0000000000000000000000000000000000000000..4c4fc2fda8f8a3140ae9f9b540eb5b7a0781f2e2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47887.go
@@ -0,0 +1,28 @@
+// 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
+
+type Fooer[t any] interface {
+ foo(Barer[t])
+}
+type Barer[t any] interface {
+ bar(Bazer[t])
+}
+type Bazer[t any] interface {
+ Fooer[t]
+ baz(t)
+}
+
+type Int int
+
+func (n Int) baz(int) {}
+func (n Int) foo(b Barer[int]) { b.bar(n) }
+
+type F[t any] interface { f(G[t]) }
+type G[t any] interface { g(H[t]) }
+type H[t any] interface { F[t] }
+
+type T struct{}
+func (n T) f(b G[T]) { b.g(n) }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47968.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47968.go
new file mode 100644
index 0000000000000000000000000000000000000000..83a1786133f297415b83320f4899b63072a972c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue47968.go
@@ -0,0 +1,21 @@
+// 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
+
+type T[P any] struct{}
+
+func (T[P]) m1()
+
+type A1 = T // ERROR "cannot use generic type"
+
+func (A1[P]) m2() {}
+
+type A2 = T[int]
+
+func (A2 /* ERRORx `cannot define new methods on instantiated type (T\[int\]|A2)` */) m3() {}
+func (_ /* ERRORx `cannot define new methods on instantiated type (T\[int\]|A2)` */ A2) m4() {}
+
+func (T[int]) m5() {} // int is the type parameter name, not an instantiation
+func (T[* /* ERROR "must be an identifier" */ int]) m6() {} // syntax error
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48008.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48008.go
new file mode 100644
index 0000000000000000000000000000000000000000..8d0c640c3cecd1f88022489e9f3cb70646031641
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48008.go
@@ -0,0 +1,60 @@
+// 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
+
+type T[P any] struct{}
+
+func _(x interface{}) {
+ switch x.(type) {
+ case nil:
+ case int:
+
+ case T[int]:
+ case []T[int]:
+ case [10]T[int]:
+ case struct{T[int]}:
+ case *T[int]:
+ case func(T[int]):
+ case interface{m(T[int])}:
+ case map[T[int]] string:
+ case chan T[int]:
+
+ case T /* ERROR "cannot use generic type T[P any] without instantiation" */ :
+ case []T /* ERROR "cannot use generic type" */ :
+ case [10]T /* ERROR "cannot use generic type" */ :
+ case struct{T /* ERROR "cannot use generic type" */ }:
+ case *T /* ERROR "cannot use generic type" */ :
+ case func(T /* ERROR "cannot use generic type" */ ):
+ case interface{m(T /* ERROR "cannot use generic type" */ )}:
+ case map[T /* ERROR "cannot use generic type" */ ] string:
+ case chan T /* ERROR "cannot use generic type" */ :
+
+ case T /* ERROR "cannot use generic type" */ , *T /* ERROR "cannot use generic type" */ :
+ }
+}
+
+// Make sure a parenthesized nil is ok.
+
+func _(x interface{}) {
+ switch x.(type) {
+ case ((nil)), int:
+ }
+}
+
+// Make sure we look for the predeclared nil.
+
+func _(x interface{}) {
+ type nil int
+ switch x.(type) {
+ case nil: // ok - this is the type nil
+ }
+}
+
+func _(x interface{}) {
+ var nil int
+ switch x.(type) {
+ case nil /* ERROR "not a type" */ : // not ok - this is the variable nil
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48018.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48018.go
new file mode 100644
index 0000000000000000000000000000000000000000..3df908acb58ab817235adc893b95e546d10d1b91
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48018.go
@@ -0,0 +1,20 @@
+// 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 main
+
+type Box[A any] struct {
+ value A
+}
+
+func Nest[A /* ERROR "instantiation cycle" */ any](b Box[A], n int) interface{} {
+ if n == 0 {
+ return b
+ }
+ return Nest(Box[Box[A]]{b}, n-1)
+}
+
+func main() {
+ Nest(Box[int]{0}, 10)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48048.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48048.go
new file mode 100644
index 0000000000000000000000000000000000000000..98a03eabdf0c82ee9cf3d47c7d18df27f7998ab9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48048.go
@@ -0,0 +1,15 @@
+// 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
+
+type T[P any] struct{}
+
+func (T[_]) A() {}
+
+var _ = (T[int]).A
+var _ = (*T[int]).A
+
+var _ = (T /* ERROR "cannot use generic type" */).A
+var _ = (*T /* ERROR "cannot use generic type" */).A
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48082.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48082.go
new file mode 100644
index 0000000000000000000000000000000000000000..648c512ea22ae2c4d91ad239137254d4f9c9f3e7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48082.go
@@ -0,0 +1,7 @@
+// 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 issue48082
+
+import "init" /* ERROR "init must be a func" */ /* ERROR "could not import init" */
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48083.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48083.go
new file mode 100644
index 0000000000000000000000000000000000000000..15e9b70d1d9d5eb2d1fa90988928798b78a86e62
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48083.go
@@ -0,0 +1,9 @@
+// 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
+
+type T[P any] struct{}
+
+type _ interface{ int | T /* ERROR "cannot use generic type" */ }
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48136.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48136.go
new file mode 100644
index 0000000000000000000000000000000000000000..b76322e8554ac2c904f730352699e86a5cbd7519
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48136.go
@@ -0,0 +1,36 @@
+// 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
+
+func f1[P interface{ *P }]() {}
+func f2[P interface{ func(P) }]() {}
+func f3[P, Q interface{ func(Q) P }]() {}
+func f4[P interface{ *Q }, Q interface{ func(P) }]() {}
+func f5[P interface{ func(P) }]() {}
+func f6[P interface { *Tree[P] }, Q any ]() {}
+
+func _() {
+ f1 /* ERROR "cannot infer P" */ ()
+ f2 /* ERROR "cannot infer P" */ ()
+ f3 /* ERROR "cannot infer P" */ ()
+ f4 /* ERROR "cannot infer P" */ ()
+ f5 /* ERROR "cannot infer P" */ ()
+ f6 /* ERROR "cannot infer P" */ ()
+}
+
+type Tree[P any] struct {
+ left, right *Tree[P]
+ data P
+}
+
+// test case from issue
+
+func foo[Src interface { func() Src }]() Src {
+ return foo[Src]
+}
+
+func _() {
+ foo /* ERROR "cannot infer Src" */ ()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48234.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48234.go
new file mode 100644
index 0000000000000000000000000000000000000000..e069930c42d99c3caa36a9acff90d60cf6031fa4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48234.go
@@ -0,0 +1,10 @@
+// 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
+
+var _ = interface{
+ m()
+ m /* ERROR "duplicate method" */ ()
+}(nil)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48312.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48312.go
new file mode 100644
index 0000000000000000000000000000000000000000..708201b415fe07d4e9ada1c16cb13c8e8a4ff25c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48312.go
@@ -0,0 +1,20 @@
+// 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 p
+
+type T interface{ m() }
+type P *T
+
+func _(p *T) {
+ p.m /* ERROR "type *T is pointer to interface, not interface" */ ()
+}
+
+func _(p P) {
+ p.m /* ERROR "type P is pointer to interface, not interface" */ ()
+}
+
+func _[P T](p *P) {
+ p.m /* ERROR "type *P is pointer to type parameter, not type parameter" */ ()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48472.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48472.go
new file mode 100644
index 0000000000000000000000000000000000000000..169ab0da9e054c6e4ebc34def9371b8a6428ad7f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48472.go
@@ -0,0 +1,16 @@
+// 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
+
+func g() {
+ var s string
+ var i int
+ _ = s /* ERROR "invalid operation: s + i (mismatched types string and int)" */ + i
+}
+
+func f(i int) int {
+ i /* ERROR `invalid operation: i += "1" (mismatched types int and untyped string)` */ += "1"
+ return i
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48529.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48529.go
new file mode 100644
index 0000000000000000000000000000000000000000..bcc5e3536d3457558fd2adc8d08fb2766412f2a1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48529.go
@@ -0,0 +1,11 @@
+// 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
+
+type T /* ERROR "invalid recursive type" */ [U interface{ M() T[U, int] }] int
+
+type X int
+
+func (X) M() T[X] { return 0 }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48582.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48582.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ffcd5a8c2e02a65cdca0c2194cce93298f23ca7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48582.go
@@ -0,0 +1,29 @@
+// 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
+
+type N /* ERROR "invalid recursive type" */ interface {
+ int | N
+}
+
+type A /* ERROR "invalid recursive type" */ interface {
+ int | B
+}
+
+type B interface {
+ int | A
+}
+
+type S /* ERROR "invalid recursive type" */ struct {
+ I // ERROR "interface contains type constraints"
+}
+
+type I interface {
+ int | S
+}
+
+type P interface {
+ *P // ERROR "interface contains type constraints"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48619.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48619.go
new file mode 100644
index 0000000000000000000000000000000000000000..fc5dce0ad5620f3856e19d46b77df23fa6d43645
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48619.go
@@ -0,0 +1,22 @@
+// 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
+
+func f[P any](a, _ P) {
+ var x int
+ // TODO(gri) these error messages, while correct, could be better
+ f(a, x /* ERROR "type int of x does not match inferred type P for P" */)
+ f(x, a /* ERROR "type P of a does not match inferred type int for P" */)
+}
+
+func g[P any](a, b P) {
+ g(a, b)
+ g(&a, &b)
+ g([]P{}, []P{})
+
+ // work-around: provide type argument explicitly
+ g[*P](&a, &b)
+ g[[]P]([]P{}, []P{})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48656.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48656.go
new file mode 100644
index 0000000000000000000000000000000000000000..f77e08a4c116a33559c66a6fe2e7542305cf1a45
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48656.go
@@ -0,0 +1,13 @@
+// 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
+
+func f[P *Q, Q any](P, Q) {
+ _ = f[P]
+}
+
+func f2[P /* ERROR "instantiation cycle" */ *Q, Q any](P, Q) {
+ _ = f2[*P]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48695.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48695.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f4a76851d5dad0ec983630cbb97abf263011f88
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48695.go
@@ -0,0 +1,14 @@
+// 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
+
+func g[P ~func(T) P, T any](P) {}
+
+func _() {
+ type F func(int) F
+ var f F
+ g(f)
+ _ = g[F]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48703.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48703.go
new file mode 100644
index 0000000000000000000000000000000000000000..89c667b2e9ca7744982605d41cdb18f3faa8fab6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48703.go
@@ -0,0 +1,27 @@
+// 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
+
+import "unsafe"
+
+// The actual example from the issue.
+type List[P any] struct{}
+
+func (_ List[P]) m() (_ List[List[P]]) { return }
+
+// Other types of recursion through methods.
+type R[P any] int
+
+func (*R[R /* ERROR "must be an identifier" */ [int]]) m0() {}
+func (R[P]) m1(R[R[P]]) {}
+func (R[P]) m2(R[*P]) {}
+func (R[P]) m3([unsafe.Sizeof(new(R[P]))]int) {}
+func (R[P]) m4([unsafe.Sizeof(new(R[R[P]]))]int) {}
+
+// Mutual recursion
+type M[P any] int
+
+func (R[P]) m5(M[M[P]]) {}
+func (M[P]) m(R[R[P]]) {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48712.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48712.go
new file mode 100644
index 0000000000000000000000000000000000000000..76ad16cd8feea906c6019cb3786c5b8a89a38b51
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48712.go
@@ -0,0 +1,41 @@
+// 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 p
+
+func _[P comparable](x, y P) {
+ _ = x == x
+ _ = x == y
+ _ = y == x
+ _ = y == y
+
+ _ = x /* ERROR "type parameter P is not comparable with <" */ < y
+}
+
+func _[P comparable](x P, y any) {
+ _ = x == x
+ _ = x == y
+ _ = y == x
+ _ = y == y
+
+ _ = x /* ERROR "type parameter P is not comparable with <" */ < y
+}
+
+func _[P any](x, y P) {
+ _ = x /* ERROR "incomparable types in type set" */ == x
+ _ = x /* ERROR "incomparable types in type set" */ == y
+ _ = y /* ERROR "incomparable types in type set" */ == x
+ _ = y /* ERROR "incomparable types in type set" */ == y
+
+ _ = x /* ERROR "type parameter P is not comparable with <" */ < y
+}
+
+func _[P any](x P, y any) {
+ _ = x /* ERROR "incomparable types in type set" */ == x
+ _ = x /* ERROR "incomparable types in type set" */ == y
+ _ = y == x // ERROR "incomparable types in type set"
+ _ = y == y
+
+ _ = x /* ERROR "type parameter P is not comparable with <" */ < y
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48819.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48819.go
new file mode 100644
index 0000000000000000000000000000000000000000..916faaffef5496c172587e4d7b1928213ce50835
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48819.go
@@ -0,0 +1,15 @@
+// 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
+
+import "unsafe"
+
+type T /* ERROR "invalid recursive type: T refers to itself" */ struct {
+ T
+}
+
+func _(t T) {
+ _ = unsafe.Sizeof(t) // should not go into infinite recursion here
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48827.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48827.go
new file mode 100644
index 0000000000000000000000000000000000000000..bd08835e9159614698a684b47527dcbbbeba90ff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48827.go
@@ -0,0 +1,19 @@
+// 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
+
+type G[P any] int
+
+type (
+ _ G[int]
+ _ G[G /* ERRORx `cannot use.*without instantiation` */]
+ _ bool /* ERROR "invalid operation: bool[int] (bool is not a generic type)" */ [int]
+ _ bool /* ERROR "invalid operation: bool[G] (bool is not a generic type)" */[G]
+)
+
+// The example from the issue.
+func _() {
+ _ = &([10]bool /* ERRORx `invalid operation.*bool is not a generic type` */ [1 /* ERROR "expected type" */ ]{})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48951.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48951.go
new file mode 100644
index 0000000000000000000000000000000000000000..8d6f8500e4259638a2c8739218f78853a229c015
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48951.go
@@ -0,0 +1,21 @@
+// 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 p
+
+type (
+ A1[P any] [10]A1 /* ERROR "invalid recursive type" */ [P]
+ A2[P any] [10]A2 /* ERROR "invalid recursive type" */ [*P]
+ A3[P any] [10]*A3[P]
+
+ L1[P any] []L1[P]
+
+ S1[P any] struct{ f S1 /* ERROR "invalid recursive type" */ [P] }
+ S2[P any] struct{ f S2 /* ERROR "invalid recursive type" */ [*P] } // like example in issue
+ S3[P any] struct{ f *S3[P] }
+
+ I1[P any] interface{ I1 /* ERROR "invalid recursive type" */ [P] }
+ I2[P any] interface{ I2 /* ERROR "invalid recursive type" */ [*P] }
+ I3[P any] interface{ *I3 /* ERROR "interface contains type constraints" */ [P] }
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48962.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48962.go
new file mode 100644
index 0000000000000000000000000000000000000000..4294cf08619ee211943be2bd5bd5f4b5553d6853
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48962.go
@@ -0,0 +1,13 @@
+// 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 p
+
+type T0[P any] struct {
+ f P
+}
+
+type T1 /* ERROR "invalid recursive type" */ struct {
+ _ T0[T1]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48974.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48974.go
new file mode 100644
index 0000000000000000000000000000000000000000..08d8656a061c036000bdaa802f54292eb28e68e4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue48974.go
@@ -0,0 +1,22 @@
+// 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
+
+type Fooer interface {
+ Foo()
+}
+
+type Fooable[F /* ERROR "instantiation cycle" */ Fooer] struct {
+ ptr F
+}
+
+func (f *Fooable[F]) Adapter() *Fooable[*FooerImpl[F]] {
+ return &Fooable[*FooerImpl[F]]{&FooerImpl[F]{}}
+}
+
+type FooerImpl[F Fooer] struct {
+}
+
+func (fi *FooerImpl[F]) Foo() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49003.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49003.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf2e6c4d113cb0bb9e40a6d13987c5eba7c9edab
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49003.go
@@ -0,0 +1,10 @@
+// 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
+
+func f(s string) int {
+ for range s {
+ }
+} // ERROR "missing return"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49005.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49005.go
new file mode 100644
index 0000000000000000000000000000000000000000..d91c2078730baa35f5faca996d3c9a4a1b81d506
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49005.go
@@ -0,0 +1,31 @@
+// 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
+
+type T1 interface{ M() }
+
+func F1() T1
+
+var _ = F1().(*X1 /* ERROR "undefined: X1" */)
+
+func _() {
+ switch F1().(type) {
+ case *X1 /* ERROR "undefined: X1" */ :
+ }
+}
+
+type T2 interface{ M() }
+
+func F2() T2
+
+var _ = F2 /* ERROR "impossible type assertion: F2().(*X2)\n\t*X2 does not implement T2 (missing method M)" */ ().(*X2)
+
+type X2 struct{}
+
+func _() {
+ switch F2().(type) {
+ case * /* ERROR "impossible type switch case: *X2\n\tF2() (value of type T2) cannot have dynamic type *X2 (missing method M)" */ X2:
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49043.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49043.go
new file mode 100644
index 0000000000000000000000000000000000000000..7594b3277cbce5e1341e945e99766f36e979f7c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49043.go
@@ -0,0 +1,24 @@
+// 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
+
+// The example from the issue.
+type (
+ N[P any] M /* ERROR "invalid recursive type" */ [P]
+ M[P any] N[P]
+)
+
+// A slightly more complicated case.
+type (
+ A[P any] B /* ERROR "invalid recursive type" */ [P]
+ B[P any] C[P]
+ C[P any] A[P]
+)
+
+// Confusing but valid (note that `type T *T` is valid).
+type (
+ N1[P any] *M1[P]
+ M1[P any] *N1[P]
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49112.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49112.go
new file mode 100644
index 0000000000000000000000000000000000000000..e87d1c07dcfb4dc774fe060dd43a5a9b56433a02
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49112.go
@@ -0,0 +1,15 @@
+// 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
+
+func f[P int](P) {}
+
+func _() {
+ _ = f[int]
+ _ = f[[ /* ERROR "[]int does not satisfy int ([]int missing in int)" */ ]int]
+
+ f(0)
+ f /* ERROR "P (type []int) does not satisfy int" */ ([]int{}) // TODO(gri) better error message
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49179.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49179.go
new file mode 100644
index 0000000000000000000000000000000000000000..1f8da295959207d768665f321f651ade4769beb7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49179.go
@@ -0,0 +1,37 @@
+// 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
+
+func f1[P int | string]() {}
+func f2[P ~int | string | float64]() {}
+func f3[P int](x P) {}
+
+type myInt int
+type myFloat float64
+
+func _() {
+ _ = f1[int]
+ _ = f1[myInt /* ERROR "possibly missing ~ for int in int | string" */]
+ _ = f2[myInt]
+ _ = f2[myFloat /* ERROR "possibly missing ~ for float64 in ~int | string | float64" */]
+ var x myInt
+ f3 /* ERROR "myInt does not satisfy int (possibly missing ~ for int in int)" */ (x)
+}
+
+// test case from the issue
+
+type SliceConstraint[T any] interface {
+ []T
+}
+
+func Map[S SliceConstraint[E], E any](s S, f func(E) E) S {
+ return s
+}
+
+type MySlice []int
+
+func f(s MySlice) {
+ Map[MySlice /* ERROR "MySlice does not satisfy SliceConstraint[int] (possibly missing ~ for []int in SliceConstraint[int])" */, int](s, nil)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49242.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49242.go
new file mode 100644
index 0000000000000000000000000000000000000000..0415bf692ea3b92f729dfeb3754b806f11b3f3fd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49242.go
@@ -0,0 +1,27 @@
+// 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
+
+func _[P int](x P) int {
+ return x // ERRORx `cannot use x .* as int value in return statement`
+}
+
+func _[P int]() int {
+ return P /* ERRORx `cannot use P\(1\) .* as int value in return statement` */ (1)
+}
+
+func _[P int](x int) P {
+ return x // ERRORx `cannot use x .* as P value in return statement`
+}
+
+func _[P, Q any](x P) Q {
+ return x // ERRORx `cannot use x .* as Q value in return statement`
+}
+
+// test case from issue
+func F[G interface{ uint }]() int {
+ f := func(uint) int { return 0 }
+ return f(G /* ERRORx `cannot use G\(1\) .* as uint value in argument to f` */ (1))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49247.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49247.go
new file mode 100644
index 0000000000000000000000000000000000000000..0ad2e29d9c5f8114487b72e2c860d87231c19ef8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49247.go
@@ -0,0 +1,20 @@
+// 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
+
+type integer interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
+}
+
+func Add1024[T integer](s []T) {
+ for i, v := range s {
+ s[i] = v + 1024 // ERROR "cannot convert 1024 (untyped int constant) to type T"
+ }
+}
+
+func f[T interface{ int8 }]() {
+ println(T(1024 /* ERROR "cannot convert 1024 (untyped int value) to type T" */))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49276.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49276.go
new file mode 100644
index 0000000000000000000000000000000000000000..bdfb42f407fa603ec70f7d293b82baf04bc9f87e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49276.go
@@ -0,0 +1,46 @@
+// 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
+
+import "unsafe"
+
+type S /* ERROR "invalid recursive type S" */ struct {
+ _ [unsafe.Sizeof(s)]byte
+}
+
+var s S
+
+// Since f is a pointer, this case could be valid.
+// But it's pathological and not worth the expense.
+type T struct {
+ f *[unsafe.Sizeof(T /* ERROR "invalid recursive type" */ {})]int
+}
+
+// a mutually recursive case using unsafe.Sizeof
+type (
+ A1 struct {
+ _ [unsafe.Sizeof(B1{})]int
+ }
+
+ B1 struct {
+ _ [unsafe.Sizeof(A1 /* ERROR "invalid recursive type" */ {})]int
+ }
+)
+
+// a mutually recursive case using len
+type (
+ A2 struct {
+ f [len(B2{}.f)]int
+ }
+
+ B2 struct {
+ f [len(A2 /* ERROR "invalid recursive type" */ {}.f)]int
+ }
+)
+
+// test case from issue
+type a struct {
+ _ [42 - unsafe.Sizeof(a /* ERROR "invalid recursive type" */ {})]byte
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49296.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49296.go
new file mode 100644
index 0000000000000000000000000000000000000000..c8c520873676b99ba9696597b55b020e5205fc4c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49296.go
@@ -0,0 +1,20 @@
+// 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
+
+func _[
+ T0 any,
+ T1 []int,
+ T2 ~float64 | ~complex128 | chan int,
+]() {
+ _ = T0(nil /* ERROR "cannot convert nil to type T0" */ )
+ _ = T1(1 /* ERRORx `cannot convert 1 .* to type T1` */ )
+ _ = T2(2 /* ERRORx `cannot convert 2 .* to type T2` */ )
+}
+
+// test case from issue
+func f[T interface{[]int}]() {
+ _ = T(1 /* ERROR "cannot convert" */ )
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49439.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49439.go
new file mode 100644
index 0000000000000000000000000000000000000000..3852f160948913888f4bce28f7a28cc3dc89d549
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49439.go
@@ -0,0 +1,26 @@
+// 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
+
+import "unsafe"
+
+type T0 /* ERROR "invalid recursive type" */ [P T0[P]] struct{}
+
+type T1 /* ERROR "invalid recursive type" */ [P T2[P]] struct{}
+type T2[P T1[P]] struct{}
+
+type T3 /* ERROR "invalid recursive type" */ [P interface{ ~struct{ f T3[int] } }] struct{}
+
+// valid cycle in M
+type N[P M[P]] struct{}
+type M[Q any] struct { F *M[Q] }
+
+// "crazy" case
+type TC[P [unsafe.Sizeof(func() {
+ type T [P [unsafe.Sizeof(func(){})]byte] struct{}
+})]byte] struct{}
+
+// test case from issue
+type X /* ERROR "invalid recursive type" */ [T any, PT X[T]] interface{}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49482.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49482.go
new file mode 100644
index 0000000000000000000000000000000000000000..7139baebc0cb66abc6e5944717e6fca45158c218
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49482.go
@@ -0,0 +1,26 @@
+// 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 p
+
+// The following is OK, per the special handling for type literals discussed in issue #49482.
+type _[P *struct{}] struct{}
+type _[P *int,] int
+type _[P (*int),] int
+
+const P = 2 // declare P to avoid noisy 'undefined' errors below.
+
+// The following parse as invalid array types due to parsing ambiguitiues.
+type _ [P *int /* ERROR "int (type) is not an expression" */ ]int
+type _ [P /* ERROR "non-function P" */ (*int)]int
+
+// Adding a trailing comma or an enclosing interface resolves the ambiguity.
+type _[P *int,] int
+type _[P (*int),] int
+type _[P interface{*int}] int
+type _[P interface{(*int)}] int
+
+// The following parse correctly as valid generic types.
+type _[P *struct{} | int] struct{}
+type _[P *struct{} | ~int] struct{}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49541.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49541.go
new file mode 100644
index 0000000000000000000000000000000000000000..665ed1da7c7a1f17f5c764fcc082843476c859cf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49541.go
@@ -0,0 +1,45 @@
+// 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 p
+
+type S[A, B any] struct {
+ f int
+}
+
+func (S[A, B]) m() {}
+
+// TODO(gri): with type-type inference enabled we should only report one error
+// below. See issue #50588.
+
+func _[A any](s S /* ERROR "not enough type arguments for type S: have 1, want 2" */ [A]) {
+ // we should see no follow-on errors below
+ s.f = 1
+ s.m()
+}
+
+// another test case from the issue
+
+func _() {
+ X /* ERROR "cannot infer Q" */ (Interface[*F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [string]](Impl{}))
+}
+
+func X[Q Qer](fs Interface[Q]) {
+}
+
+type Impl struct{}
+
+func (Impl) M() {}
+
+type Interface[Q Qer] interface {
+ M()
+}
+
+type Qer interface {
+ Q()
+}
+
+type F[A, B any] struct{}
+
+func (f *F[A, B]) Q() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49579.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49579.go
new file mode 100644
index 0000000000000000000000000000000000000000..780859c50962ba3b0670f4d9abe0dc03194a83e6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49579.go
@@ -0,0 +1,17 @@
+// 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
+
+type I[F any] interface {
+ Q(*F)
+}
+
+func G[F any]() I[any] {
+ return g /* ERRORx `cannot use g\[F\]{} .* as I\[any\] value in return statement: g\[F\] does not implement I\[any\] \(method Q has pointer receiver\)` */ [F]{}
+}
+
+type g[F any] struct{}
+
+func (*g[F]) Q(*any) {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49592.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49592.go
new file mode 100644
index 0000000000000000000000000000000000000000..846deaa89aac62bf1d7b404ca8e78d01965587f9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49592.go
@@ -0,0 +1,11 @@
+// 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
+
+func _() {
+ var x *interface{}
+ var y interface{}
+ _ = x == y
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49602.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49602.go
new file mode 100644
index 0000000000000000000000000000000000000000..09cc96963ba311fd65ea38ea303b10684e8dd7a6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49602.go
@@ -0,0 +1,19 @@
+// 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
+
+type M interface {
+ m()
+}
+
+type C interface {
+ comparable
+}
+
+type _ interface {
+ int | M // ERROR "cannot use p.M in union (p.M contains methods)"
+ int | comparable // ERROR "cannot use comparable in union"
+ int | C // ERROR "cannot use p.C in union (p.C embeds comparable)"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49705.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49705.go
new file mode 100644
index 0000000000000000000000000000000000000000..5b5fba2a1dc661a76f1f0fe1b98174cb28896ed2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49705.go
@@ -0,0 +1,14 @@
+// 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
+
+type Integer interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
+}
+
+func shl[I Integer](n int) I {
+ return 1 << n
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49735.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49735.go
new file mode 100644
index 0000000000000000000000000000000000000000..0fcc778a066529bd7edfe0fb71dad17a5a3a298f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49735.go
@@ -0,0 +1,11 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+func _[P1 any, P2 ~byte](s1 P1, s2 P2) {
+ _ = append(nil /* ERROR "first argument to append must be a slice; have untyped nil" */ , 0)
+ _ = append(s1 /* ERRORx `s1 .* has no core type` */ , 0)
+ _ = append(s2 /* ERRORx `s2 .* has core type byte` */ , 0)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49739.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49739.go
new file mode 100644
index 0000000000000000000000000000000000000000..73825f440dd41505a6857ea10d95db39b8945409
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49739.go
@@ -0,0 +1,23 @@
+// 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.
+
+// Verify that we get an empty type set (not just an error)
+// when using an invalid ~A.
+
+package p
+
+type A int
+type C interface {
+ ~ /* ERROR "invalid use of ~" */ A
+}
+
+func f[_ C]() {}
+func g[_ interface{ C }]() {}
+func h[_ C | int]() {}
+
+func _() {
+ _ = f[int /* ERROR "cannot satisfy C (empty type set)" */]
+ _ = g[int /* ERROR "cannot satisfy interface{C} (empty type set)" */]
+ _ = h[int]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49864.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49864.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ccd77cfea07bb97e4b913e7f07efbc23dde49a2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue49864.go
@@ -0,0 +1,9 @@
+// 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
+
+func _[P ~int, Q any](p P) {
+ _ = Q(p /* ERROR "cannot convert" */ )
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50259.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50259.go
new file mode 100644
index 0000000000000000000000000000000000000000..6df8c64524324c68f800d3a412374bad6f4b7d18
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50259.go
@@ -0,0 +1,18 @@
+// 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 p
+
+var x T[B]
+
+type T[_ any] struct{}
+type A T[B]
+type B = T[A]
+
+// test case from issue
+
+var v Box[Step]
+type Box[T any] struct{}
+type Step = Box[StepBox]
+type StepBox Box[Step]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50276.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50276.go
new file mode 100644
index 0000000000000000000000000000000000000000..97e477e6fa32108152e3658e0708fa2c537520d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50276.go
@@ -0,0 +1,39 @@
+// 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 p
+
+// simplified test case
+
+type transform[T any] struct{}
+type pair[S any] struct {}
+
+var _ transform[step]
+
+type box transform[step]
+type step = pair[box]
+
+// test case from issue
+
+type Transform[T any] struct{ hold T }
+type Pair[S, T any] struct {
+ First S
+ Second T
+}
+
+var first Transform[Step]
+
+// This line doesn't use the Step alias, and it compiles fine if you uncomment it.
+var second Transform[Pair[Box, interface{}]]
+
+type Box *Transform[Step]
+
+// This line is the same as the `first` line, but it comes after the Box declaration and
+// does not break the compile.
+var third Transform[Step]
+
+type Step = Pair[Box, interface{}]
+
+// This line also does not break the compile
+var fourth Transform[Step]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50281.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50281.go
new file mode 100644
index 0000000000000000000000000000000000000000..f333e81a7054f8105224001ef30d7b443aaa7445
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50281.go
@@ -0,0 +1,26 @@
+// 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 p
+
+func _[S string | []byte](s S) {
+ var buf []byte
+ _ = append(buf, s...)
+}
+
+func _[S ~string | ~[]byte](s S) {
+ var buf []byte
+ _ = append(buf, s...)
+}
+
+// test case from issue
+
+type byteseq interface {
+ string | []byte
+}
+
+// This should allow to eliminate the two functions above.
+func AppendByteString[source byteseq](buf []byte, s source) []byte {
+ return append(buf, s[1:6]...)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50321.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50321.go
new file mode 100644
index 0000000000000000000000000000000000000000..ab2a31b7ebdbb5630758baf87f71b0c58999b3ed
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50321.go
@@ -0,0 +1,8 @@
+// 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
+
+func Ln[A A /* ERROR "cannot use a type parameter as constraint" */ ](p A) {
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50372.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50372.go
new file mode 100644
index 0000000000000000000000000000000000000000..10d2a24a28cb9df5c5f270d1fbf8fe37439fa4a6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50372.go
@@ -0,0 +1,27 @@
+// 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
+
+func _(s []int) {
+ var i, j, k, l int
+ _, _, _, _ = i, j, k, l
+
+ for range s {}
+ for i = range s {}
+ for i, j = range s {}
+ for i, j, k /* ERRORx "range clause permits at most two iteration variables|at most 2 expressions" */ = range s {}
+ for i, j, k, l /* ERRORx "range clause permits at most two iteration variables|at most 2 expressions" */ = range s {}
+}
+
+func _(s chan int) {
+ var i, j, k, l int
+ _, _, _, _ = i, j, k, l
+
+ for range s {}
+ for i = range s {}
+ for i, j /* ERRORx `range over .* permits only one iteration variable` */ = range s {}
+ for i, j, k /* ERRORx `range over .* permits only one iteration variable|at most 2 expressions` */ = range s {}
+ for i, j, k, l /* ERRORx `range over .* permits only one iteration variable|at most 2 expressions` */ = range s {}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50417.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50417.go
new file mode 100644
index 0000000000000000000000000000000000000000..c70898e2a87bf21b4463cf4d5c30e7d67c7456f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50417.go
@@ -0,0 +1,68 @@
+// 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.
+
+// Field accesses through type parameters are disabled
+// until we have a more thorough understanding of the
+// implications on the spec. See issue #51576.
+
+package p
+
+type Sf struct {
+ f int
+}
+
+func f0[P Sf](p P) {
+ _ = p.f // ERROR "p.f undefined"
+ p.f /* ERROR "p.f undefined" */ = 0
+}
+
+func f0t[P ~struct{f int}](p P) {
+ _ = p.f // ERROR "p.f undefined"
+ p.f /* ERROR "p.f undefined" */ = 0
+}
+
+var _ = f0[Sf]
+var _ = f0t[Sf]
+
+var _ = f0[Sm /* ERROR "does not satisfy" */ ]
+var _ = f0t[Sm /* ERROR "does not satisfy" */ ]
+
+func f1[P interface{ Sf; m() }](p P) {
+ _ = p.f // ERROR "p.f undefined"
+ p.f /* ERROR "p.f undefined" */ = 0
+ p.m()
+}
+
+var _ = f1[Sf /* ERROR "missing method m" */ ]
+var _ = f1[Sm /* ERROR "does not satisfy" */ ]
+
+type Sm struct {}
+
+func (Sm) m() {}
+
+type Sfm struct {
+ f int
+}
+
+func (Sfm) m() {}
+
+func f2[P interface{ Sfm; m() }](p P) {
+ _ = p.f // ERROR "p.f undefined"
+ p.f /* ERROR "p.f undefined" */ = 0
+ p.m()
+}
+
+var _ = f2[Sfm]
+
+// special case: core type is a named pointer type
+
+type PSfm *Sfm
+
+func f3[P interface{ PSfm }](p P) {
+ _ = p.f // ERROR "p.f undefined"
+ p.f /* ERROR "p.f undefined" */ = 0
+ p.m /* ERROR "type P has no field or method m" */ ()
+}
+
+var _ = f3[PSfm]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50426.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50426.go
new file mode 100644
index 0000000000000000000000000000000000000000..17ec0ce529688bae5e8c27ce7a1024fe4d3388ed
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50426.go
@@ -0,0 +1,44 @@
+// 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 p
+
+type A1 [2]uint64
+type A2 [2]uint64
+
+func (a A1) m() A1 { return a }
+func (a A2) m() A2 { return a }
+
+func f[B any, T interface {
+ A1 | A2
+ m() T
+}](v T) {
+}
+
+func _() {
+ var v A2
+ // Use function type inference to infer type A2 for T.
+ // Don't use constraint type inference before function
+ // type inference for typed arguments, otherwise it would
+ // infer type [2]uint64 for T which doesn't have method m
+ // (was the bug).
+ f[int](v)
+}
+
+// Keep using constraint type inference before function type
+// inference for untyped arguments so we infer type float64
+// for E below, and not int (which would not work).
+func g[S ~[]E, E any](S, E) {}
+
+func _() {
+ var s []float64
+ g[[]float64](s, 0)
+}
+
+// Keep using constraint type inference after function
+// type inference for untyped arguments so we infer
+// missing type arguments for which we only have the
+// untyped arguments as starting point.
+func h[E any, R []E](v E) R { return R{v} }
+func _() []int { return h(0) }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50427.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50427.go
new file mode 100644
index 0000000000000000000000000000000000000000..d89d63e3087d966361570416ddc52101651c9730
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50427.go
@@ -0,0 +1,23 @@
+// 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 p
+
+// The parser no longer parses type parameters for methods.
+// In the past, type checking the code below led to a crash (#50427).
+
+type T interface{ m[ /* ERROR "must have no type parameters" */ P any]() }
+
+func _(t T) {
+ var _ interface{ m[ /* ERROR "must have no type parameters" */ P any](); n() } = t /* ERROR "does not implement" */
+}
+
+type S struct{}
+
+func (S) m[ /* ERROR "must have no type parameters" */ P any]() {}
+
+func _(s S) {
+ var _ interface{ m[ /* ERROR "must have no type parameters" */ P any](); n() } = s /* ERROR "does not implement" */
+
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50450.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50450.go
new file mode 100644
index 0000000000000000000000000000000000000000..bae311157860558829538bd5ff5719c7a633068e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50450.go
@@ -0,0 +1,11 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+type S struct{}
+
+func f[P S]() {}
+
+var _ = f[S]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50516.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50516.go
new file mode 100644
index 0000000000000000000000000000000000000000..fcaefedc45a18eec372816ec854cf2a98d22292d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50516.go
@@ -0,0 +1,13 @@
+// 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 p
+
+func _[P struct{ f int }](x P) {
+ _ = x.g // ERROR "type P has no field or method g"
+}
+
+func _[P struct{ f int } | struct{ g int }](x P) {
+ _ = x.g // ERROR "type P has no field or method g"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50646.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50646.go
new file mode 100644
index 0000000000000000000000000000000000000000..2c16cfcda46f012f17622975c6edef55338fe582
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50646.go
@@ -0,0 +1,26 @@
+// 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 p
+
+func f1[_ comparable]() {}
+func f2[_ interface{ comparable }]() {}
+
+type T interface{ m() }
+
+func _[P comparable, Q ~int, R any]() {
+ _ = f1[int]
+ _ = f1[T]
+ _ = f1[any]
+ _ = f1[P]
+ _ = f1[Q]
+ _ = f1[R /* ERROR "R does not satisfy comparable" */]
+
+ _ = f2[int]
+ _ = f2[T]
+ _ = f2[any]
+ _ = f2[P]
+ _ = f2[Q]
+ _ = f2[R /* ERROR "R does not satisfy comparable" */]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729.go
new file mode 100644
index 0000000000000000000000000000000000000000..fe19fdfa6884630a8299c145d18e6fd707366513
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729.go
@@ -0,0 +1,19 @@
+// 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 p
+
+// version 1
+var x1 T1[B1]
+
+type T1[_ any] struct{}
+type A1 T1[B1]
+type B1 = T1[A1]
+
+// version 2
+type T2[_ any] struct{}
+type A2 T2[B2]
+type B2 = T2[A2]
+
+var x2 T2[B2]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729b.go
new file mode 100644
index 0000000000000000000000000000000000000000..bc1f4406e5227f5f621e27f1507acda87d3e1533
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50729b.go
@@ -0,0 +1,15 @@
+// -gotypesalias=1
+
+// 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 p
+
+type d[T any] struct{}
+type (
+ b d[a]
+)
+
+type a = func(c)
+type c struct{ a }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50755.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50755.go
new file mode 100644
index 0000000000000000000000000000000000000000..afc7b2414cb37ca8fe633fc8058bb3d7541cebc5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50755.go
@@ -0,0 +1,47 @@
+// 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 p
+
+// The core type of M2 unifies with the type of m1
+// during function argument type inference.
+// M2's constraint is unnamed.
+func f1[K1 comparable, E1 any](m1 map[K1]E1) {}
+
+func f2[M2 map[string]int](m2 M2) {
+ f1(m2)
+}
+
+// The core type of M3 unifies with the type of m1
+// during function argument type inference.
+// M3's constraint is named.
+type Map3 map[string]int
+
+func f3[M3 Map3](m3 M3) {
+ f1(m3)
+}
+
+// The core type of M5 unifies with the core type of M4
+// during constraint type inference.
+func f4[M4 map[K4]int, K4 comparable](m4 M4) {}
+
+func f5[M5 map[K5]int, K5 comparable](m5 M5) {
+ f4(m5)
+}
+
+// test case from issue
+
+func Copy[MC ~map[KC]VC, KC comparable, VC any](dst, src MC) {
+ for k, v := range src {
+ dst[k] = v
+ }
+}
+
+func Merge[MM ~map[KM]VM, KM comparable, VM any](ms ...MM) MM {
+ result := MM{}
+ for _, m := range ms {
+ Copy(result, m)
+ }
+ return result
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779.go
new file mode 100644
index 0000000000000000000000000000000000000000..59c0f2d6a015750eb73237450dcf459c06374c27
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779.go
@@ -0,0 +1,25 @@
+// -gotypesalias=0
+
+// 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 p
+
+type AC interface {
+ C
+}
+
+type ST []int
+
+type R[S any, P any] struct{}
+
+type SR = R[SS, ST]
+
+type SS interface {
+ NSR(any) *SR // ERROR "invalid use of type alias SR in recursive type"
+}
+
+type C interface {
+ NSR(any) *SR
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779a.go
new file mode 100644
index 0000000000000000000000000000000000000000..d0e99058b7ede98bdf6a3d5d0d6252290b2ee4eb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50779a.go
@@ -0,0 +1,25 @@
+// -gotypesalias=1
+
+// 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 p
+
+type AC interface {
+ C
+}
+
+type ST []int
+
+type R[S any, P any] struct{}
+
+type SR = R[SS, ST]
+
+type SS interface {
+ NSR(any) *SR
+}
+
+type C interface {
+ NSR(any) *SR
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50782.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50782.go
new file mode 100644
index 0000000000000000000000000000000000000000..97e8f6cdff4db34b4e741ab5f089b4421f884583
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50782.go
@@ -0,0 +1,47 @@
+// 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.
+
+// Field accesses through type parameters are disabled
+// until we have a more thorough understanding of the
+// implications on the spec. See issue #51576.
+
+package p
+
+// The first example from the issue.
+type Numeric interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64
+}
+
+// numericAbs matches numeric types with an Abs method.
+type numericAbs[T Numeric] interface {
+ ~struct{ Value T }
+ Abs() T
+}
+
+// AbsDifference computes the absolute value of the difference of
+// a and b, where the absolute value is determined by the Abs method.
+func absDifference[T numericAbs[T /* ERROR "T does not satisfy Numeric" */]](a, b T) T {
+ // Field accesses are not permitted for now. Keep an error so
+ // we can find and fix this code once the situation changes.
+ return a.Value // ERROR "a.Value undefined"
+ // TODO: The error below should probably be positioned on the '-'.
+ // d := a /* ERROR "invalid operation: operator - not defined" */ .Value - b.Value
+ // return d.Abs()
+}
+
+// The second example from the issue.
+type T[P int] struct{ f P }
+
+func _[P T[P /* ERROR "P does not satisfy int" */ ]]() {}
+
+// Additional tests
+func _[P T[T /* ERROR "T[P] does not satisfy int" */ [P /* ERROR "P does not satisfy int" */ ]]]() {}
+func _[P T[Q /* ERROR "Q does not satisfy int" */ ], Q T[P /* ERROR "P does not satisfy int" */ ]]() {}
+func _[P T[Q], Q int]() {}
+
+type C[P comparable] struct{ f P }
+func _[P C[C[P]]]() {}
+func _[P C[C /* ERROR "C[Q] does not satisfy comparable" */ [Q /* ERROR "Q does not satisfy comparable" */]], Q func()]() {}
+func _[P [10]C[P]]() {}
+func _[P struct{ f C[C[P]]}]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50816.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50816.go
new file mode 100644
index 0000000000000000000000000000000000000000..b7c28cdffd824104e103899898ba8dbc01fe7e86
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50816.go
@@ -0,0 +1,23 @@
+// 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 pkg
+
+type I interface {
+ Foo()
+}
+
+type T1 struct{}
+
+func (T1) foo() {}
+
+type T2 struct{}
+
+func (T2) foo() string { return "" }
+
+func _() {
+ var i I
+ _ = i /* ERROR "impossible type assertion: i.(T1)\n\tT1 does not implement I (missing method Foo)\n\t\thave foo()\n\t\twant Foo()" */ .(T1)
+ _ = i /* ERROR "impossible type assertion: i.(T2)\n\tT2 does not implement I (missing method Foo)\n\t\thave foo() string\n\t\twant Foo()" */ .(T2)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50833.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50833.go
new file mode 100644
index 0000000000000000000000000000000000000000..e912e4d67dfe8a46049b495374ce28db354db08e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50833.go
@@ -0,0 +1,16 @@
+// 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 p
+
+type (
+ S struct{ f int }
+ PS *S
+)
+
+func a() []*S { return []*S{{f: 1}} }
+func b() []PS { return []PS{{f: 1}} }
+
+func c[P *S]() []P { return []P{{f: 1}} }
+func d[P PS]() []P { return []P{{f: 1}} }
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50912.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50912.go
new file mode 100644
index 0000000000000000000000000000000000000000..a99fa7bfeaeb49c6681920736ce0ce1ebcc0be84
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50912.go
@@ -0,0 +1,19 @@
+// 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 p
+
+func Real[P ~complex128](x P) {
+ _ = real(x /* ERROR "not supported" */ )
+}
+
+func Imag[P ~complex128](x P) {
+ _ = imag(x /* ERROR "not supported" */ )
+}
+
+func Complex[P ~float64](x P) {
+ _ = complex(x /* ERROR "not supported" */ , 0)
+ _ = complex(0 /* ERROR "not supported" */ , x)
+ _ = complex(x /* ERROR "not supported" */ , x)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50918.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50918.go
new file mode 100644
index 0000000000000000000000000000000000000000..5744fa810d34eebf91558a1aeed42f777643ad2c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50918.go
@@ -0,0 +1,21 @@
+// 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 p
+
+type thing1 struct {
+ things []string
+}
+
+type thing2 struct {
+ things []thing1
+}
+
+func _() {
+ var a1, b1 thing1
+ _ = a1 /* ERROR "struct containing []string cannot be compared" */ == b1
+
+ var a2, b2 thing2
+ _ = a2 /* ERROR "struct containing []thing1 cannot be compared" */ == b2
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50929.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50929.go
new file mode 100644
index 0000000000000000000000000000000000000000..a665e229be0627d1e14bd7bc8fd4ff46a7bcd792
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50929.go
@@ -0,0 +1,68 @@
+// 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.
+
+// This file is tested when running "go test -run Manual"
+// without source arguments. Use for one-off debugging.
+
+package p
+
+import "fmt"
+
+type F[A, B any] int
+
+func G[A, B any](F[A, B]) {
+}
+
+func _() {
+ // TODO(gri) only report one error below (issue #50932)
+ var x F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [int]
+ G(x /* ERROR "does not match" */)
+}
+
+// test case from issue
+// (lots of errors but doesn't crash anymore)
+
+type RC[G any, RG any] interface {
+ ~[]RG
+}
+
+type RG[G any] struct{}
+
+type RSC[G any] []*RG[G]
+
+type M[Rc RC[G, RG], G any, RG any] struct {
+ Fn func(Rc)
+}
+
+type NFn[Rc RC[G, RG], G any, RG any] func(Rc)
+
+func NC[Rc RC[G, RG], G any, RG any](nFn NFn[Rc, G, RG]) {
+ var empty Rc
+ nFn(empty)
+}
+
+func NSG[G any](c RSC[G]) {
+ fmt.Println(c)
+}
+
+func MMD[Rc RC /* ERROR "not enough type arguments for type RC: have 1, want 2" */ [RG], RG any, G any]() M /* ERROR "not enough type arguments for type" */ [Rc, RG] {
+
+ var nFn NFn /* ERROR "not enough type arguments for type NFn: have 2, want 3" */ [Rc, RG]
+
+ var empty Rc
+ switch any(empty).(type) {
+ case BC /* ERROR "undefined: BC" */ :
+
+ case RSC[G]:
+ nFn = NSG /* ERROR "cannot use NSG[G]" */ [G]
+ }
+
+ return M /* ERROR "not enough type arguments for type M: have 2, want 3" */ [Rc, RG]{
+ Fn: func(rc Rc) {
+ NC(nFn /* ERROR "does not match" */)
+ },
+ }
+
+ return M /* ERROR "not enough type arguments for type M: have 2, want 3" */ [Rc, RG]{}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50965.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50965.go
new file mode 100644
index 0000000000000000000000000000000000000000..79059e96731dd55f6c36350c70e7bdc2f566d87f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue50965.go
@@ -0,0 +1,17 @@
+// 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 p
+
+func _(x int, c string) {
+ switch x {
+ case c /* ERROR "invalid case c in switch on x (mismatched types string and int)" */ :
+ }
+}
+
+func _(x, c []int) {
+ switch x {
+ case c /* ERROR "invalid case c in switch on x (slice can only be compared to nil)" */ :
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51025.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51025.go
new file mode 100644
index 0000000000000000000000000000000000000000..caaabd583eabf8c579ea02689444b76551ec0a26
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51025.go
@@ -0,0 +1,38 @@
+// 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 p
+
+var _ interface{ m() } = struct /* ERROR "m is a field, not a method" */ {
+ m func()
+}{}
+
+var _ interface{ m() } = & /* ERROR "m is a field, not a method" */ struct {
+ m func()
+}{}
+
+var _ interface{ M() } = struct /* ERROR "missing method M" */ {
+ m func()
+}{}
+
+var _ interface{ M() } = & /* ERROR "missing method M" */ struct {
+ m func()
+}{}
+
+// test case from issue
+type I interface{ m() }
+type T struct{ m func() }
+type M struct{}
+
+func (M) m() {}
+
+func _() {
+ var t T
+ var m M
+ var i I
+
+ i = m
+ i = t // ERROR "m is a field, not a method"
+ _ = i
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51048.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51048.go
new file mode 100644
index 0000000000000000000000000000000000000000..58308370ea54b75c07798c43846c7962942115bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51048.go
@@ -0,0 +1,11 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+func _[P int]() {
+ _ = f[P]
+}
+
+func f[T int]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51139.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51139.go
new file mode 100644
index 0000000000000000000000000000000000000000..4c460d4ff8ee9110215f3affb895bbf3fded1f77
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51139.go
@@ -0,0 +1,26 @@
+// 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 p
+
+func f[S []T, T any](S, T) {}
+
+func _() {
+ type L chan int
+ f([]L{}, make(chan int))
+ f([]L{}, make(L))
+ f([]chan int{}, make(chan int))
+ f /* ERROR "[]chan int does not satisfy []L ([]chan int missing in []p.L)" */ ([]chan int{}, make(L))
+}
+
+// test case from issue
+
+func Append[S ~[]T, T any](s S, x ...T) S { /* implementation of append */ return s }
+
+func _() {
+ type MyPtr *int
+ var x []MyPtr
+ _ = append(x, new(int))
+ _ = Append(x, new(int))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51145.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51145.go
new file mode 100644
index 0000000000000000000000000000000000000000..1f970d9bb07476c3bccd86ee759c54d24b9fe85a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51145.go
@@ -0,0 +1,18 @@
+// 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 p
+
+import "fmt"
+
+type (
+ _ [fmt /* ERROR "invalid array length fmt" */ ]int
+ _ [float64 /* ERROR "invalid array length float64" */ ]int
+ _ [f /* ERROR "invalid array length f" */ ]int
+ _ [nil /* ERROR "invalid array length nil" */ ]int
+)
+
+func f()
+
+var _ fmt.Stringer // use fmt
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51158.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51158.go
new file mode 100644
index 0000000000000000000000000000000000000000..3edc50538206ed45562af0ada88abf9db88a15af
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51158.go
@@ -0,0 +1,18 @@
+// 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 p
+
+// Type checking the following code should not cause an infinite recursion.
+func f[M map[K]int, K comparable](m M) {
+ f(m)
+}
+
+// Equivalent code using mutual recursion.
+func f1[M map[K]int, K comparable](m M) {
+ f2(m)
+}
+func f2[M map[K]int, K comparable](m M) {
+ f1(m)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51229.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51229.go
new file mode 100644
index 0000000000000000000000000000000000000000..22a91135dfd9b6769999bc4154256074beac226c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51229.go
@@ -0,0 +1,164 @@
+// 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 p
+
+// Constraint type inference should be independent of the
+// ordering of the type parameter declarations. Try all
+// permutations in the test case below.
+// Permutations produced by https://go.dev/play/p/PHcZNGJTEBZ.
+
+func f00[S1 ~[]E1, S2 ~[]E2, E1 ~byte, E2 ~byte](S1, S2) {}
+func f01[S2 ~[]E2, S1 ~[]E1, E1 ~byte, E2 ~byte](S1, S2) {}
+func f02[E1 ~byte, S1 ~[]E1, S2 ~[]E2, E2 ~byte](S1, S2) {}
+func f03[S1 ~[]E1, E1 ~byte, S2 ~[]E2, E2 ~byte](S1, S2) {}
+func f04[S2 ~[]E2, E1 ~byte, S1 ~[]E1, E2 ~byte](S1, S2) {}
+func f05[E1 ~byte, S2 ~[]E2, S1 ~[]E1, E2 ~byte](S1, S2) {}
+func f06[E2 ~byte, S2 ~[]E2, S1 ~[]E1, E1 ~byte](S1, S2) {}
+func f07[S2 ~[]E2, E2 ~byte, S1 ~[]E1, E1 ~byte](S1, S2) {}
+func f08[S1 ~[]E1, E2 ~byte, S2 ~[]E2, E1 ~byte](S1, S2) {}
+func f09[E2 ~byte, S1 ~[]E1, S2 ~[]E2, E1 ~byte](S1, S2) {}
+func f10[S2 ~[]E2, S1 ~[]E1, E2 ~byte, E1 ~byte](S1, S2) {}
+func f11[S1 ~[]E1, S2 ~[]E2, E2 ~byte, E1 ~byte](S1, S2) {}
+func f12[S1 ~[]E1, E1 ~byte, E2 ~byte, S2 ~[]E2](S1, S2) {}
+func f13[E1 ~byte, S1 ~[]E1, E2 ~byte, S2 ~[]E2](S1, S2) {}
+func f14[E2 ~byte, S1 ~[]E1, E1 ~byte, S2 ~[]E2](S1, S2) {}
+func f15[S1 ~[]E1, E2 ~byte, E1 ~byte, S2 ~[]E2](S1, S2) {}
+func f16[E1 ~byte, E2 ~byte, S1 ~[]E1, S2 ~[]E2](S1, S2) {}
+func f17[E2 ~byte, E1 ~byte, S1 ~[]E1, S2 ~[]E2](S1, S2) {}
+func f18[E2 ~byte, E1 ~byte, S2 ~[]E2, S1 ~[]E1](S1, S2) {}
+func f19[E1 ~byte, E2 ~byte, S2 ~[]E2, S1 ~[]E1](S1, S2) {}
+func f20[S2 ~[]E2, E2 ~byte, E1 ~byte, S1 ~[]E1](S1, S2) {}
+func f21[E2 ~byte, S2 ~[]E2, E1 ~byte, S1 ~[]E1](S1, S2) {}
+func f22[E1 ~byte, S2 ~[]E2, E2 ~byte, S1 ~[]E1](S1, S2) {}
+func f23[S2 ~[]E2, E1 ~byte, E2 ~byte, S1 ~[]E1](S1, S2) {}
+
+type myByte byte
+
+func _(a []byte, b []myByte) {
+ f00(a, b)
+ f01(a, b)
+ f02(a, b)
+ f03(a, b)
+ f04(a, b)
+ f05(a, b)
+ f06(a, b)
+ f07(a, b)
+ f08(a, b)
+ f09(a, b)
+ f10(a, b)
+ f11(a, b)
+ f12(a, b)
+ f13(a, b)
+ f14(a, b)
+ f15(a, b)
+ f16(a, b)
+ f17(a, b)
+ f18(a, b)
+ f19(a, b)
+ f20(a, b)
+ f21(a, b)
+ f22(a, b)
+ f23(a, b)
+}
+
+// Constraint type inference may have to iterate.
+// Again, the order of the type parameters shouldn't matter.
+
+func g0[S ~[]E, M ~map[string]S, E any](m M) {}
+func g1[M ~map[string]S, S ~[]E, E any](m M) {}
+func g2[E any, S ~[]E, M ~map[string]S](m M) {}
+func g3[S ~[]E, E any, M ~map[string]S](m M) {}
+func g4[M ~map[string]S, E any, S ~[]E](m M) {}
+func g5[E any, M ~map[string]S, S ~[]E](m M) {}
+
+func _(m map[string][]byte) {
+ g0(m)
+ g1(m)
+ g2(m)
+ g3(m)
+ g4(m)
+ g5(m)
+}
+
+// Worst-case scenario.
+// There are 10 unknown type parameters. In each iteration of
+// constraint type inference we infer one more, from right to left.
+// Each iteration looks repeatedly at all 11 type parameters,
+// requiring a total of 10*11 = 110 iterations with the current
+// implementation. Pathological case.
+
+func h[K any, J ~*K, I ~*J, H ~*I, G ~*H, F ~*G, E ~*F, D ~*E, C ~*D, B ~*C, A ~*B](x A) {}
+
+func _(x **********int) {
+ h(x)
+}
+
+// Examples with channel constraints and tilde.
+
+func ch1[P chan<- int]() (_ P) { return } // core(P) == chan<- int (single type, no tilde)
+func ch2[P ~chan int]() { return } // core(P) == ~chan<- int (tilde)
+func ch3[P chan E, E any](E) { return } // core(P) == chan<- E (single type, no tilde)
+func ch4[P chan E | ~chan<- E, E any](E) { return } // core(P) == ~chan<- E (tilde)
+func ch5[P chan int | chan<- int]() { return } // core(P) == chan<- int (not a single type)
+
+func _() {
+ // P can be inferred as there's a single specific type and no tilde.
+ var _ chan int = ch1 /* ERRORx `cannot use ch1.*value of type chan<- int` */ ()
+ var _ chan<- int = ch1()
+
+ // P cannot be inferred as there's a tilde.
+ ch2 /* ERROR "cannot infer P" */ ()
+ type myChan chan int
+ ch2[myChan]()
+
+ // P can be inferred as there's a single specific type and no tilde.
+ var e int
+ ch3(e)
+
+ // P cannot be inferred as there's more than one specific type and a tilde.
+ ch4 /* ERROR "cannot infer P" */ (e)
+ _ = ch4[chan int]
+
+ // P cannot be inferred as there's more than one specific type.
+ ch5 /* ERROR "cannot infer P" */ ()
+ ch5[chan<- int]()
+}
+
+// test case from issue
+
+func equal[M1 ~map[K1]V1, M2 ~map[K2]V2, K1, K2 ~uint32, V1, V2 ~string](m1 M1, m2 M2) bool {
+ if len(m1) != len(m2) {
+ return false
+ }
+ for k, v1 := range m1 {
+ if v2, ok := m2[K2(k)]; !ok || V2(v1) != v2 {
+ return false
+ }
+ }
+ return true
+}
+
+func equalFixed[K1, K2 ~uint32, V1, V2 ~string](m1 map[K1]V1, m2 map[K2]V2) bool {
+ if len(m1) != len(m2) {
+ return false
+ }
+ for k, v1 := range m1 {
+ if v2, ok := m2[K2(k)]; !ok || v1 != V1(v2) {
+ return false
+ }
+ }
+ return true
+}
+
+type (
+ someNumericID uint32
+ someStringID string
+)
+
+func _() {
+ foo := map[uint32]string{10: "bar"}
+ bar := map[someNumericID]someStringID{10: "bar"}
+ equal(foo, bar)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51232.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51232.go
new file mode 100644
index 0000000000000000000000000000000000000000..c5832d2976914c7c9edbab6c7e8663f93f9ea699
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51232.go
@@ -0,0 +1,30 @@
+// 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 p
+
+type RC[RG any] interface {
+ ~[]RG
+}
+
+type Fn[RCT RC[RG], RG any] func(RCT)
+
+type F[RCT RC[RG], RG any] interface {
+ Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT]
+}
+
+type concreteF[RCT RC[RG], RG any] struct {
+ makeFn func() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT]
+}
+
+func (c *concreteF[RCT, RG]) Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] {
+ return c.makeFn()
+}
+
+func NewConcrete[RCT RC[RG], RG any](Rc RCT) F /* ERROR "not enough type arguments for type F: have 1, want 2" */ [RCT] {
+ // TODO(rfindley): eliminate the duplicate error below.
+ return & /* ERRORx `cannot use .* as F\[RCT\]` */ concreteF /* ERROR "not enough type arguments for type concreteF: have 1, want 2" */ [RCT]{
+ makeFn: nil,
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51233.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51233.go
new file mode 100644
index 0000000000000000000000000000000000000000..d96d3d1aa07fb2d10451b11cd305c1ad13201a85
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51233.go
@@ -0,0 +1,27 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+// As of issue #51527, type-type inference has been disabled.
+
+type RC[RG any] interface {
+ ~[]RG
+}
+
+type Fn[RCT RC[RG], RG any] func(RCT)
+
+type FFn[RCT RC[RG], RG any] func() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT]
+
+type F[RCT RC[RG], RG any] interface {
+ Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT]
+}
+
+type concreteF[RCT RC[RG], RG any] struct {
+ makeFn FFn /* ERROR "not enough type arguments for type FFn: have 1, want 2" */ [RCT]
+}
+
+func (c *concreteF[RCT, RG]) Fn() Fn /* ERROR "not enough type arguments for type Fn: have 1, want 2" */ [RCT] {
+ return c.makeFn()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51257.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51257.go
new file mode 100644
index 0000000000000000000000000000000000000000..828612b4283f2b605b17e06831d055637cf7334a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51257.go
@@ -0,0 +1,46 @@
+// 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 p
+
+func f[_ comparable]() {}
+
+type S1 struct{ x int }
+type S2 struct{ x any }
+type S3 struct{ x [10]interface{ m() } }
+
+func _[P1 comparable, P2 S2]() {
+ _ = f[S1]
+ _ = f[S2]
+ _ = f[S3]
+
+ type L1 struct { x P1 }
+ type L2 struct { x P2 }
+ _ = f[L1]
+ _ = f[L2 /* ERROR "L2 does not satisfy comparable" */ ]
+}
+
+
+// example from issue
+
+type Set[T comparable] map[T]struct{}
+
+func NewSetFromSlice[T comparable](items []T) *Set[T] {
+ s := Set[T]{}
+
+ for _, item := range items {
+ s[item] = struct{}{}
+ }
+
+ return &s
+}
+
+type T struct{ x any }
+
+func main() {
+ NewSetFromSlice([]T{
+ {"foo"},
+ {5},
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51335.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51335.go
new file mode 100644
index 0000000000000000000000000000000000000000..04dc04e1d7a36bd721217a8b80904fdde3cd1610
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51335.go
@@ -0,0 +1,16 @@
+// 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 p
+
+type S1 struct{}
+type S2 struct{}
+
+func _[P *S1|*S2]() {
+ _= []P{{ /* ERROR "invalid composite literal element type P (no core type)" */ }}
+}
+
+func _[P *S1|S1]() {
+ _= []P{{ /* ERROR "invalid composite literal element type P (no core type)" */ }}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51339.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51339.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd10daa2c24f10d903e71ef1cb293050d721b2f4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51339.go
@@ -0,0 +1,20 @@
+// 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.
+
+// This file is tested when running "go test -run Manual"
+// without source arguments. Use for one-off debugging.
+
+package p
+
+type T[P any, B *P] struct{}
+
+func (T /* ERROR "cannot use generic type" */) m0() {}
+
+// TODO(rfindley): eliminate the duplicate errors here.
+func ( /* ERROR "got 1 type parameter, but receiver base type declares 2" */ T /* ERROR "not enough type arguments for type" */ [_]) m1() {
+}
+func (T[_, _]) m2() {}
+
+// TODO(gri) this error is unfortunate (issue #51343)
+func (T /* ERROR "too many type arguments for type" */ [_, _, _]) m3() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51360.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51360.go
new file mode 100644
index 0000000000000000000000000000000000000000..1b9c45a9342f08c68243815b988582a51bd4284d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51360.go
@@ -0,0 +1,13 @@
+// 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 p
+
+func _() {
+ len.Println /* ERROR "cannot select on len" */
+ len.Println /* ERROR "cannot select on len" */ ()
+ _ = len.Println /* ERROR "cannot select on len" */
+ _ = len /* ERROR "cannot index len" */ [0]
+ _ = *len /* ERROR "cannot indirect len" */
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51376.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51376.go
new file mode 100644
index 0000000000000000000000000000000000000000..0f2ab8ea2242f4dbb0c43f976b6a550d957a6214
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51376.go
@@ -0,0 +1,24 @@
+// 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 p
+
+type Map map[string]int
+
+func f[M ~map[K]V, K comparable, V any](M) {}
+func g[M map[K]V, K comparable, V any](M) {}
+
+func _[M1 ~map[K]V, M2 map[K]V, K comparable, V any]() {
+ var m1 M1
+ f(m1)
+ g /* ERROR "M1 does not satisfy map[K]V" */ (m1) // M1 has tilde
+
+ var m2 M2
+ f(m2)
+ g(m2) // M1 does not have tilde
+
+ var m3 Map
+ f(m3)
+ g /* ERROR "Map does not satisfy map[string]int" */ (m3) // M in g does not have tilde
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51386.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51386.go
new file mode 100644
index 0000000000000000000000000000000000000000..ef6223927a21f41c6ba52cfc649574cec11e4500
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51386.go
@@ -0,0 +1,17 @@
+// 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 p
+
+type myString string
+
+func _[P ~string | ~[]byte | ~[]rune]() {
+ _ = P("")
+ const s myString = ""
+ _ = P(s)
+}
+
+func _[P myString]() {
+ _ = P("")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51437.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51437.go
new file mode 100644
index 0000000000000000000000000000000000000000..376261516eec92a8fb40d1f7d0ffbc552df55ef8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51437.go
@@ -0,0 +1,17 @@
+// 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 p
+
+type T struct{}
+
+func (T) m() []int { return nil }
+
+func f(x T) {
+ for _, x := range func() []int {
+ return x.m() // x declared in parameter list of f
+ }() {
+ _ = x // x declared by range clause
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51472.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51472.go
new file mode 100644
index 0000000000000000000000000000000000000000..6dfff05395979ce22b3a08e369dfbb8653b60b59
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51472.go
@@ -0,0 +1,54 @@
+// 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 p
+
+func _[T comparable](x T) {
+ _ = x == x
+}
+
+func _[T interface{interface{comparable}}](x T) {
+ _ = x == x
+}
+
+func _[T interface{comparable; interface{comparable}}](x T) {
+ _ = x == x
+}
+
+func _[T interface{comparable; ~int}](x T) {
+ _ = x == x
+}
+
+func _[T interface{comparable; ~[]byte}](x T) {
+ _ = x /* ERROR "empty type set" */ == x
+}
+
+// TODO(gri) The error message here should be better. See issue #51525.
+func _[T interface{comparable; ~int; ~string}](x T) {
+ _ = x /* ERROR "empty type set" */ == x
+}
+
+// TODO(gri) The error message here should be better. See issue #51525.
+func _[T interface{~int; ~string}](x T) {
+ _ = x /* ERROR "empty type set" */ == x
+}
+
+func _[T interface{comparable; interface{~int}; interface{int|float64}}](x T) {
+ _ = x == x
+}
+
+func _[T interface{interface{comparable; ~int}; interface{~float64; comparable; m()}}](x T) {
+ _ = x /* ERROR "empty type set" */ == x
+}
+
+// test case from issue
+
+func f[T interface{comparable; []byte|string}](x T) {
+ _ = x == x
+}
+
+func _(s []byte) {
+ f /* ERROR "T (type []byte) does not satisfy interface{comparable; []byte | string}" */ (s) // TODO(gri) better error message (T's type set only contains string!)
+ _ = f[[ /* ERROR "does not satisfy" */ ]byte]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51509.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51509.go
new file mode 100644
index 0000000000000000000000000000000000000000..4737a825056d761471b0d37e92e0429d28efc132
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51509.go
@@ -0,0 +1,7 @@
+// 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 p
+
+type T /* ERROR "invalid recursive type" */ T.x
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51525.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51525.go
new file mode 100644
index 0000000000000000000000000000000000000000..af569c854359d0096b575a0f3506cc011eb1ebcb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51525.go
@@ -0,0 +1,20 @@
+// 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 p
+
+func _[T interface {
+ int
+ string
+}](x T) {
+ _ = x /* ERROR "empty type set" */ == x
+ _ = x /* ERROR "empty type set" */ + x
+ <-x /* ERROR "empty type set" */
+ x <- /* ERROR "empty type set" */ 0
+ close(x /* ERROR "empty type set" */)
+}
+
+func _[T interface{ int | []byte }](x T) {
+ _ = x /* ERROR "incomparable types in type set" */ == x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51533.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51533.go
new file mode 100644
index 0000000000000000000000000000000000000000..166e5fe64ad3dc11b82b522626c88cd086aa03c3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51533.go
@@ -0,0 +1,20 @@
+// 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 p
+
+func _(x any) {
+ switch x {
+ case 0:
+ fallthrough // ERROR "fallthrough statement out of place"
+ _ = x
+ default:
+ }
+
+ switch x.(type) {
+ case int:
+ fallthrough // ERROR "cannot fallthrough in type switch"
+ default:
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51578.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51578.go
new file mode 100644
index 0000000000000000000000000000000000000000..d2e8a2855080e6895b2ef59f538ad89d7273a358
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51578.go
@@ -0,0 +1,17 @@
+// 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 p
+
+var _ = (*interface /* ERROR "interface contains type constraints" */ {int})(nil)
+
+// abbreviated test case from issue
+
+type TypeSet interface{ int | string }
+
+func _() {
+ f((*TypeSet /* ERROR "interface contains type constraints" */)(nil))
+}
+
+func f(any) {}
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51593.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51593.go
new file mode 100644
index 0000000000000000000000000000000000000000..62b0a5625ad9219590dd2ecd3d0e3d6bd6c465fb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51593.go
@@ -0,0 +1,13 @@
+// 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 p
+
+func f[P interface{ m(R) }, R any]() {}
+
+type T = interface { m(int) }
+
+func _() {
+ _ = f[T]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51607.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51607.go
new file mode 100644
index 0000000000000000000000000000000000000000..298adade4b9a0088ee9f15b18b6006fb1198fd88
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51607.go
@@ -0,0 +1,65 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+// Interface types must be ignored during overlap test.
+
+type (
+ T1 interface{int}
+ T2 interface{~int}
+ T3 interface{T1 | bool | string}
+ T4 interface{T2 | ~bool | ~string}
+)
+
+type (
+ // overlap errors for non-interface terms
+ // (like the interface terms, but explicitly inlined)
+ _ interface{int | int /* ERROR "overlapping terms int and int" */ }
+ _ interface{int | ~ /* ERROR "overlapping terms ~int and int" */ int}
+ _ interface{~int | int /* ERROR "overlapping terms int and ~int" */ }
+ _ interface{~int | ~ /* ERROR "overlapping terms ~int and ~int" */ int}
+
+ _ interface{T1 | bool | string | T1 | bool /* ERROR "overlapping terms bool and bool" */ | string /* ERROR "overlapping terms string and string" */ }
+ _ interface{T1 | bool | string | T2 | ~ /* ERROR "overlapping terms ~bool and bool" */ bool | ~ /* ERROR "overlapping terms ~string and string" */ string}
+
+ // no errors for interface terms
+ _ interface{T1 | T1}
+ _ interface{T1 | T2}
+ _ interface{T2 | T1}
+ _ interface{T2 | T2}
+
+ _ interface{T3 | T3 | int}
+ _ interface{T3 | T4 | bool }
+ _ interface{T4 | T3 | string }
+ _ interface{T4 | T4 | float64 }
+)
+
+func _[_ T1 | bool | string | T1 | bool /* ERROR "overlapping terms" */ ]() {}
+func _[_ T1 | bool | string | T2 | ~ /* ERROR "overlapping terms" */ bool ]() {}
+func _[_ T2 | ~bool | ~string | T1 | bool /* ERROR "overlapping terms" */ ]() {}
+func _[_ T2 | ~bool | ~string | T2 | ~ /* ERROR "overlapping terms" */ bool ]() {}
+
+func _[_ T3 | T3 | int]() {}
+func _[_ T3 | T4 | bool]() {}
+func _[_ T4 | T3 | string]() {}
+func _[_ T4 | T4 | float64]() {}
+
+// test cases from issue
+
+type _ interface {
+ interface {bool | int} | interface {bool | string}
+}
+
+type _ interface {
+ interface {bool | int} ; interface {bool | string}
+}
+
+type _ interface {
+ interface {bool; int} ; interface {bool; string}
+}
+
+type _ interface {
+ interface {bool; int} | interface {bool; string}
+}
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51610.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51610.go
new file mode 100644
index 0000000000000000000000000000000000000000..d0bc1ace9bf2ed3a54b00b26a972b166c071b728
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51610.go
@@ -0,0 +1,9 @@
+// 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 p
+
+func _[P int | float64 | complex128]() {
+ _ = map[P]int{1: 1, 1.0 /* ERROR "duplicate key 1" */ : 2, 1 /* ERROR "duplicate key (1 + 0i)" */ + 0i: 3}
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51616.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51616.go
new file mode 100644
index 0000000000000000000000000000000000000000..e0efc9e620ece2f84b42f3c21bbe62c7f2d59bd2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51616.go
@@ -0,0 +1,19 @@
+// 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 p
+
+type (
+ C[T any] interface{~int; M() T}
+
+ _ C[bool]
+ _ comparable
+ _ interface {~[]byte | ~string}
+
+ // Alias type declarations may refer to "constraint" types
+ // like ordinary type declarations.
+ _ = C[bool]
+ _ = comparable
+ _ = interface {~[]byte | ~string}
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51658.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51658.go
new file mode 100644
index 0000000000000000000000000000000000000000..36e2fdd37f2090107091c0e187b899d070521a64
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51658.go
@@ -0,0 +1,43 @@
+// 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.
+
+// This test checks syntax errors which differ between
+// go/parser and the syntax package.
+// TODO: consolidate eventually
+
+package p
+
+type F { // ERRORx "expected type|type declaration"
+ float64
+} // ERRORx "expected declaration|non-declaration statement"
+
+func _[T F | int](x T) {
+ _ = x == 0 // don't crash when recording type of 0
+}
+
+// test case from issue
+
+type FloatType { // ERRORx "expected type|type declaration"
+ float32 | float64
+} // ERRORx "expected declaration|non-declaration statement"
+
+type IntegerType interface {
+ int8 | int16 | int32 | int64 | int |
+ uint8 | uint16 | uint32 | uint64 | uint
+}
+
+type ComplexType interface {
+ complex64 | complex128
+}
+
+type Number interface {
+ FloatType | IntegerType | ComplexType
+}
+
+func GetDefaultNumber[T Number](value, defaultValue T) T {
+ if value == 0 {
+ return defaultValue
+ }
+ return value
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51877.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51877.go
new file mode 100644
index 0000000000000000000000000000000000000000..4b0e5bcd1fa7bcd7c51ab3ea9964a170ed548c1f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue51877.go
@@ -0,0 +1,18 @@
+// 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 p
+
+type S struct {
+ f1 int
+ f2 bool
+}
+
+var (
+ _ = S{0} /* ERROR "too few values in struct literal" */
+ _ = struct{ f1, f2 int }{0} /* ERROR "too few values in struct literal" */
+
+ _ = S{0, true, "foo" /* ERROR "too many values in struct literal" */}
+ _ = struct{ f1, f2 int }{0, 1, 2 /* ERROR "too many values in struct literal" */}
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52031.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52031.go
new file mode 100644
index 0000000000000000000000000000000000000000..5b75b75c0cc58326fcd8190eb78f6ce9e567818b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52031.go
@@ -0,0 +1,33 @@
+// -lang=go1.12
+
+// 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 p
+
+type resultFlags uint
+
+// Example from #52031.
+//
+// The following shifts should not produce errors on Go < 1.13, as their
+// untyped constant operands are representable by type uint.
+const (
+ _ resultFlags = (1 << iota) / 2
+
+ reportEqual
+ reportUnequal
+ reportByIgnore
+ reportByMethod
+ reportByFunc
+ reportByCycle
+)
+
+// Invalid cases.
+var x int = 1
+var _ = (8 << x /* ERRORx `signed shift count .* requires go1.13 or later` */)
+
+const _ = (1 << 1.2 /* ERROR "truncated to uint" */)
+
+var y float64
+var _ = (1 << y /* ERROR "must be integer" */)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52401.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52401.go
new file mode 100644
index 0000000000000000000000000000000000000000..ccc32d3b1ba534b261cc570f4797a1aa8bcfd1dc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52401.go
@@ -0,0 +1,11 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+func _() {
+ const x = 0
+ x /* ERROR "cannot assign to x" */ += 1
+ x /* ERROR "cannot assign to x" */ ++
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52529.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52529.go
new file mode 100644
index 0000000000000000000000000000000000000000..de7b2964b0ce1fc4dc94347c04f201d34964f851
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52529.go
@@ -0,0 +1,15 @@
+// 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 p
+
+type Foo[P any] struct {
+ _ *Bar[P]
+}
+
+type Bar[Q any] Foo[Q]
+
+func (v *Bar[R]) M() {
+ _ = (*Foo[R])(v)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52698.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52698.go
new file mode 100644
index 0000000000000000000000000000000000000000..20f24f09ffd96e56843f51403c9078941366b03e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52698.go
@@ -0,0 +1,62 @@
+// 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 p
+
+// correctness check: ensure that cycles through generic instantiations are detected
+type T[P any] struct {
+ _ P
+}
+
+type S /* ERROR "invalid recursive type" */ struct {
+ _ T[S]
+}
+
+// simplified test 1
+
+var _ A1[A1[string]]
+
+type A1[P any] struct {
+ _ B1[P]
+}
+
+type B1[P any] struct {
+ _ P
+}
+
+// simplified test 2
+var _ B2[A2]
+
+type A2 struct {
+ _ B2[string]
+}
+
+type B2[P any] struct {
+ _ C2[P]
+}
+
+type C2[P any] struct {
+ _ P
+}
+
+// test case from issue
+type T23 interface {
+ ~struct {
+ Field0 T13[T15]
+ }
+}
+
+type T1[P1 interface {
+}] struct {
+ Field2 P1
+}
+
+type T13[P2 interface {
+}] struct {
+ Field2 T1[P2]
+}
+
+type T15 struct {
+ Field0 T13[string]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52915.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52915.go
new file mode 100644
index 0000000000000000000000000000000000000000..70dc6643759d54688088098161b57b98201c3cd6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue52915.go
@@ -0,0 +1,23 @@
+// 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 p
+
+import "unsafe"
+
+type T[P any] struct {
+ T /* ERROR "invalid recursive type" */ [P]
+}
+
+func _[P any]() {
+ _ = unsafe.Sizeof(T[int]{})
+ _ = unsafe.Sizeof(struct{ T[int] }{})
+
+ _ = unsafe.Sizeof(T[P]{})
+ _ = unsafe.Sizeof(struct{ T[P] }{})
+}
+
+// TODO(gri) This is a follow-on error due to T[int] being invalid.
+// We should try to avoid it.
+const _ = unsafe /* ERROR "not constant" */ .Sizeof(T[int]{})
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53358.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53358.go
new file mode 100644
index 0000000000000000000000000000000000000000..67c095c2833e4c04a011a0a770ef083899874a92
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53358.go
@@ -0,0 +1,19 @@
+// 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 p
+
+type A struct{}
+
+func (*A) m() int { return 0 }
+
+var _ = A.m /* ERROR "invalid method expression A.m (needs pointer receiver (*A).m)" */ ()
+var _ = (*A).m(nil)
+
+type B struct{ A }
+
+var _ = B.m // ERROR "invalid method expression B.m (needs pointer receiver (*B).m)"
+var _ = (*B).m
+
+var _ = struct{ A }.m // ERROR "invalid method expression struct{A}.m (needs pointer receiver (*struct{A}).m)"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53650.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53650.go
new file mode 100644
index 0000000000000000000000000000000000000000..4bba59efbfaa9f8c2a5138b5c3049227860806fd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53650.go
@@ -0,0 +1,59 @@
+// 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 p
+
+import (
+ "reflect"
+ "testing"
+)
+
+type T1 int
+type T2 int
+
+func f[P T1 | T2, _ []P]() {}
+
+var _ = f[T1]
+
+// test case from issue
+
+type BaseT interface {
+ Type1 | Type2
+}
+type BaseType int
+type Type1 BaseType
+type Type2 BaseType // float64
+
+type ValueT[T BaseT] struct {
+ A1 T
+}
+
+func NewType1() *ValueT[Type1] {
+ r := NewT[Type1]()
+ return r
+}
+func NewType2() *ValueT[Type2] {
+ r := NewT[Type2]()
+ return r
+}
+
+func NewT[TBase BaseT, TVal ValueT[TBase]]() *TVal {
+ ret := TVal{}
+ return &ret
+}
+func TestGoType(t *testing.T) {
+ r1 := NewType1()
+ r2 := NewType2()
+ t.Log(r1, r2)
+ t.Log(reflect.TypeOf(r1), reflect.TypeOf(r2))
+ fooT1(r1.A1)
+ fooT2(r2.A1)
+}
+
+func fooT1(t1 Type1) {
+
+}
+func fooT2(t2 Type2) {
+
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53692.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53692.go
new file mode 100644
index 0000000000000000000000000000000000000000..dc1a76c723f675deb97925eca4e1b47b03e7c6e1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue53692.go
@@ -0,0 +1,15 @@
+// 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 p
+
+type Cache[K comparable, V any] interface{}
+
+type LRU[K comparable, V any] struct{}
+
+func WithLocking2[K comparable, V any](Cache[K, V]) {}
+
+func _() {
+ WithLocking2 /* ERROR "cannot infer V" */ [string](LRU[string, int]{})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54280.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54280.go
new file mode 100644
index 0000000000000000000000000000000000000000..9465894aed0b59168b275bdd8291c29f68f7f6ea
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54280.go
@@ -0,0 +1,7 @@
+// 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 p
+
+const C = 912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890_912 // ERROR "constant overflow"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54405.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54405.go
new file mode 100644
index 0000000000000000000000000000000000000000..688fee1f9e55551e70f3f9e5ada3440b6aa60320
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54405.go
@@ -0,0 +1,16 @@
+// 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.
+
+// Test that we don't see spurious errors for ==
+// for values with invalid types due to prior errors.
+
+package p
+
+var x struct {
+ f *NotAType /* ERROR "undefined" */
+}
+var _ = x.f == nil // no error expected here
+
+var y *NotAType /* ERROR "undefined" */
+var _ = y == nil // no error expected here
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54424.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54424.go
new file mode 100644
index 0000000000000000000000000000000000000000..ebfb83db09963ac24bee8590d36c5311fd8d762e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54424.go
@@ -0,0 +1,12 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+func f[P ~*T, T any]() {
+ var p P
+ var tp *T
+ tp = p // this assignment is valid
+ _ = tp
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54942.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54942.go
new file mode 100644
index 0000000000000000000000000000000000000000..b9a5cce4783cead8889d07abe5db9681423f459a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue54942.go
@@ -0,0 +1,38 @@
+// 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 p
+
+import (
+ "context"
+ "database/sql"
+)
+
+type I interface {
+ m(int, int, *int, int)
+}
+
+type T struct{}
+
+func (_ *T) m(a, b, c, d int) {}
+
+var _ I = new /* ERROR "have m(int, int, int, int)\n\t\twant m(int, int, *int, int)" */ (T)
+
+// (slightly modified) test case from issue
+
+type Result struct {
+ Value string
+}
+
+type Executor interface {
+ Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (Result, error)
+}
+
+type myExecutor struct{}
+
+func (_ *myExecutor) Execute(ctx context.Context, stmt sql.Stmt, maxrows int, args []sql.NamedArg, urgency int) (*Result, error) {
+ return &Result{}, nil
+}
+
+var ex Executor = new /* ERROR "have Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (*Result, error)\n\t\twant Execute(context.Context, sql.Stmt, int, []sql.NamedArg, int) (Result, error)" */ (myExecutor)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56351.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56351.go
new file mode 100644
index 0000000000000000000000000000000000000000..eee142c9938085d0a7a33fcf40b3a0ffaf80e769
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56351.go
@@ -0,0 +1,11 @@
+// -lang=go1.20
+
+// 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 p
+
+func _(s []int) {
+ clear /* ERROR "clear requires go1.21 or later" */ (s)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56425.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56425.go
new file mode 100644
index 0000000000000000000000000000000000000000..d85733faaac01db25db15935b32e857d0bfb4f9c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56425.go
@@ -0,0 +1,8 @@
+// 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 p
+
+const s float32 = 0
+var _ = 0 << s
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56665.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56665.go
new file mode 100644
index 0000000000000000000000000000000000000000..1f787d0bbc88554e3830e945e399494b651f2568
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue56665.go
@@ -0,0 +1,30 @@
+// 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 p
+
+// Example from the issue:
+type A[T any] interface {
+ *T
+}
+
+type B[T any] interface {
+ B /* ERROR "invalid recursive type" */ [*T]
+}
+
+type C[T any, U B[U]] interface {
+ *T
+}
+
+// Simplified reproducer:
+type X[T any] interface {
+ X /* ERROR "invalid recursive type" */ [*T]
+}
+
+var _ X[int]
+
+// A related example that doesn't go through interfaces.
+type A2[P any] [10]A2 /* ERROR "invalid recursive type" */ [*P]
+
+var _ A2[int]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57155.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57155.go
new file mode 100644
index 0000000000000000000000000000000000000000..ec9fb2bad3ff57381c0c6c9df3a6a973b4837e21
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57155.go
@@ -0,0 +1,14 @@
+// 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 p
+
+func f[P *Q, Q any](p P, q Q) {
+ func() {
+ _ = f[P]
+ f(p, q)
+ f[P](p, q)
+ f[P, Q](p, q)
+ }()
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57160.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57160.go
new file mode 100644
index 0000000000000000000000000000000000000000..446d019900c2a6c7fdf7a818790aa0286e8c98c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57160.go
@@ -0,0 +1,10 @@
+// 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 p
+
+func _(x *int) {
+ _ = 0 < x // ERROR "invalid operation"
+ _ = x < 0 // ERROR "invalid operation"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57192.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57192.go
new file mode 100644
index 0000000000000000000000000000000000000000..6c7894ac0f1e7efdab00593254c74f344fc69aec
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57192.go
@@ -0,0 +1,22 @@
+// 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 p
+
+type I1[T any] interface {
+ m1(T)
+}
+type I2[T any] interface {
+ I1[T]
+ m2(T)
+}
+
+var V1 I1[int]
+var V2 I2[int]
+
+func g[T any](I1[T]) {}
+func _() {
+ g(V1)
+ g(V2)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57352.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57352.go
new file mode 100644
index 0000000000000000000000000000000000000000..2b3170033785800a93abfc222520ddc315757e2b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57352.go
@@ -0,0 +1,21 @@
+// 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 p
+
+type A interface {
+ a()
+}
+
+type AB interface {
+ A
+ b()
+}
+
+type AAB struct {
+ A
+ AB
+}
+
+var _ AB = AAB /* ERROR "ambiguous selector AAB.a" */ {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57486.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57486.go
new file mode 100644
index 0000000000000000000000000000000000000000..933eeb4cf9a1a288de1f39b9afd85a12ed47bb41
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57486.go
@@ -0,0 +1,29 @@
+// 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 p
+
+type C1 interface {
+ comparable
+}
+
+type C2 interface {
+ comparable
+ [2]any | int
+}
+
+func G1[T C1](t T) { _ = t == t }
+func G2[T C2](t T) { _ = t == t }
+
+func F1[V [2]any](v V) {
+ _ = G1[V /* ERROR "V does not satisfy comparable" */]
+ _ = G1[[2]any]
+ _ = G1[int]
+}
+
+func F2[V [2]any](v V) {
+ _ = G2[V /* ERROR "V does not satisfy C2" */]
+ _ = G2[[ /* ERROR "[2]any does not satisfy C2 (C2 mentions [2]any, but [2]any is not in the type set of C2)" */ 2]any]
+ _ = G2[int]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57500.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57500.go
new file mode 100644
index 0000000000000000000000000000000000000000..4a90d47618fe9f071c2c7e2d5e7e010daa18c0f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57500.go
@@ -0,0 +1,16 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+type C interface {
+ comparable
+ [2]any | int
+}
+
+func f[T C]() {}
+
+func _() {
+ _ = f[[ /* ERROR "[2]any does not satisfy C (C mentions [2]any, but [2]any is not in the type set of C)" */ 2]any]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57522.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57522.go
new file mode 100644
index 0000000000000000000000000000000000000000..d83e5b2443e1aa14fa99911606f4836d179f3ce5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue57522.go
@@ -0,0 +1,24 @@
+// 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 p
+
+// A simplified version of the code in the original report.
+type S[T any] struct{}
+var V = S[any]{}
+func (fs *S[T]) M(V.M /* ERROR "V.M is not a type" */) {}
+
+// Other minimal reproducers.
+type S1[T any] V1.M /* ERROR "V1.M is not a type" */
+type V1 = S1[any]
+
+type S2[T any] struct{}
+type V2 = S2[any]
+func (fs *S2[T]) M(x V2.M /* ERROR "V2.M is not a type" */ ) {}
+
+// The following still panics, as the selector is reached from check.expr
+// rather than check.typexpr. TODO(rfindley): fix this.
+// type X[T any] int
+// func (X[T]) M(x [X[int].M]int) {}
+
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58611.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58611.go
new file mode 100644
index 0000000000000000000000000000000000000000..1ff30f74fa024ba1d94a6334b963ffd5505055f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58611.go
@@ -0,0 +1,27 @@
+// 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 p
+
+import (
+ "sort"
+ "strings"
+)
+
+func f[int any](x int) {
+ x = 0 /* ERRORx "cannot use 0.*(as int.*with int declared at|type parameter)" */
+}
+
+// test case from issue
+
+type Set[T comparable] map[T]struct{}
+
+func (s *Set[string]) String() string {
+ keys := make([]string, 0, len(*s))
+ for k := range *s {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys /* ERRORx "cannot use keys.*with string declared at.*|type parameter" */ )
+ return strings /* ERROR "cannot use strings.Join" */ .Join(keys /* ERRORx "cannot use keys.*with string declared at.*|type parameter" */ , ",")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58612.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58612.go
new file mode 100644
index 0000000000000000000000000000000000000000..db6a62d24721fd1f54fc5cb10c6e310b93abe176
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58612.go
@@ -0,0 +1,14 @@
+// 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 p
+
+func _() {
+ var x = new(T)
+ f[x /* ERROR "not a type" */ /* ERROR "use of .(type) outside type switch" */ .(type)]()
+}
+
+type T struct{}
+
+func f[_ any]() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58671.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58671.go
new file mode 100644
index 0000000000000000000000000000000000000000..fa964aa5fd2e812e5289ac49c927c2878ee111fe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58671.go
@@ -0,0 +1,20 @@
+// 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 p
+
+func g[P any](...P) P { var x P; return x }
+
+func _() {
+ var (
+ _ int = g(1, 2)
+ _ rune = g(1, 'a')
+ _ float64 = g(1, 'a', 2.3)
+ _ float64 = g('a', 2.3)
+ _ complex128 = g(2.3, 'a', 1i)
+ )
+ g(true, 'a' /* ERROR "mismatched types untyped bool and untyped rune (cannot infer P)" */)
+ g(1, "foo" /* ERROR "mismatched types untyped int and untyped string (cannot infer P)" */)
+ g(1, 2.3, "bar" /* ERROR "mismatched types untyped float and untyped string (cannot infer P)" */)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58742.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58742.go
new file mode 100644
index 0000000000000000000000000000000000000000..b649a497747a1ec100060835672e231d9862a94f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue58742.go
@@ -0,0 +1,18 @@
+// 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 p
+
+func _() (int, UndefinedType /* ERROR "undefined: UndefinedType" */ , string) {
+ return 0 // ERROR "not enough return values\n\thave (number)\n\twant (int, unknown type, string)"
+}
+
+func _() (int, UndefinedType /* ERROR "undefined: UndefinedType" */ ) {
+ return 0, 1, 2 // ERROR "too many return values\n\thave (number, number, number)\n\twant (int, unknown type)"
+}
+
+// test case from issue
+func _() UndefinedType /* ERROR "undefined: UndefinedType" */ {
+ return // ERROR "not enough return values\n\thave ()\n\twant (unknown type)"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59190.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59190.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd08303303d5a500a1fdf627c35d22701fb26496
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59190.go
@@ -0,0 +1,36 @@
+// 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 p
+
+import "unsafe"
+
+type E [1 << 30]complex128
+var a [1 << 30]E
+var _ = unsafe.Sizeof(a /* ERROR "too large" */ )
+
+var s struct {
+ _ [1 << 30]E
+ x int
+}
+var _ = unsafe.Offsetof(s /* ERROR "too large" */ .x)
+
+// Test case from issue (modified so it also triggers on 32-bit platforms).
+
+type A [1]int
+type S struct {
+ x A
+ y [1 << 30]A
+ z [1 << 30]struct{}
+}
+type T [1 << 30][1 << 30]S
+
+func _() {
+ var a A
+ var s S
+ var t T
+ _ = unsafe.Sizeof(a)
+ _ = unsafe.Sizeof(s)
+ _ = unsafe.Sizeof(t /* ERROR "too large" */ )
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59207.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59207.go
new file mode 100644
index 0000000000000000000000000000000000000000..59b36e243dfb4d20e039278fc363ae138c568d70
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59207.go
@@ -0,0 +1,12 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+import "unsafe"
+
+type E [1 << 32]byte
+
+var a [1 << 32]E // size of a must not overflow to 0
+var _ = unsafe.Sizeof(a /* ERROR "too large" */ )
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59209.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59209.go
new file mode 100644
index 0000000000000000000000000000000000000000..870ae528647c905b968dedf55f2cc76110f5ff38
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59209.go
@@ -0,0 +1,11 @@
+// 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 p
+
+type (
+ _ [1 /* ERROR "invalid array length" */ << 100]int
+ _ [1.0]int
+ _ [1.1 /* ERROR "must be integer" */ ]int
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338a.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338a.go
new file mode 100644
index 0000000000000000000000000000000000000000..34864dcd30bbcd718375e5da99fcfb8fdc68fc20
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338a.go
@@ -0,0 +1,21 @@
+// -lang=go1.20
+
+// 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 p
+
+func g[P any](P) {}
+func h[P, Q any](P) Q { panic(0) }
+
+var _ func(int) = g /* ERROR "implicitly instantiated function in assignment requires go1.21 or later" */
+var _ func(int) string = h[ /* ERROR "partially instantiated function in assignment requires go1.21 or later" */ int]
+
+func f1(func(int)) {}
+func f2(int, func(int)) {}
+
+func _() {
+ f1(g /* ERROR "implicitly instantiated function as argument requires go1.21 or later" */)
+ f2(0, g /* ERROR "implicitly instantiated function as argument requires go1.21 or later" */)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338b.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338b.go
new file mode 100644
index 0000000000000000000000000000000000000000..1a5530aeaefd5bda5741313552acd1bd631ad408
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59338b.go
@@ -0,0 +1,19 @@
+// 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 p
+
+func g[P any](P) {}
+func h[P, Q any](P) Q { panic(0) }
+
+var _ func(int) = g
+var _ func(int) string = h[int]
+
+func f1(func(int)) {}
+func f2(int, func(int)) {}
+
+func _() {
+ f1(g)
+ f2(0, g)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59371.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59371.go
new file mode 100644
index 0000000000000000000000000000000000000000..d5b4db6a858325aae24c645b0db6312af5d650b6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59371.go
@@ -0,0 +1,17 @@
+// 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 p
+
+var m map[int]int
+
+func _() {
+ _, ok /* ERROR "undefined: ok" */ = m[0] // must not crash
+}
+
+func _() {
+ var ok = undef /* ERROR "undefined: undef" */
+ x, ok := m[0] // must not crash
+ _, _ = x, ok
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59639.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59639.go
new file mode 100644
index 0000000000000000000000000000000000000000..1117668e98852c90e895cde7bed499b15590dc8f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59639.go
@@ -0,0 +1,11 @@
+// -lang=go1.17
+
+// 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 p
+
+func f[P /* ERROR "requires go1.18" */ interface{}](P) {}
+
+var v func(int) = f /* ERROR "requires go1.18" */
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59740.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59740.go
new file mode 100644
index 0000000000000000000000000000000000000000..31cd03b3af161fd8ad0cc1eff1127f1907a21b24
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59740.go
@@ -0,0 +1,25 @@
+// 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 p
+
+type F[T any] func(func(F[T]))
+
+func f(F[int]) {}
+func g[T any](F[T]) {}
+
+func _() {
+ g(f /* ERROR "type func(F[int]) of f does not match F[T] (cannot infer T)" */) // type inference/unification must not panic
+}
+
+// original test case from issue
+
+type List[T any] func(T, func(T, List[T]) T) T
+
+func nil[T any](n T, _ List[T]) T { return n }
+func cons[T any](h T, t List[T]) List[T] { return func(n T, f func(T, List[T]) T) T { return f(h, t) } }
+
+func nums[T any](t T) List[T] {
+ return cons(t, cons(t, nil /* ERROR "type func(n T, _ List[T]) T of nil[T] does not match inferred type List[T] for List[T]" */ [T]))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59848.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59848.go
new file mode 100644
index 0000000000000000000000000000000000000000..51da7475e5203101751b0b7a14e1f8a0654cce31
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59848.go
@@ -0,0 +1,10 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+type T struct{}
+type I interface{ M() }
+var _ I = T /* ERROR "missing method M" */ {} // must not crash
+func (T) m() {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59890.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59890.go
new file mode 100644
index 0000000000000000000000000000000000000000..ed7afd939aacf71859dad5ab2a2033884338ebce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59890.go
@@ -0,0 +1,17 @@
+// 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 p
+
+func _() { g /* ERROR "cannot infer T" */ () }
+
+func g[T any]() (_ /* ERROR "cannot use _ as value or type" */, int) { panic(0) }
+
+// test case from issue
+
+var _ = append(f /* ERROR "cannot infer T" */ ()())
+
+func f[T any]() (_ /* ERROR "cannot use _" */, _ /* ERROR "cannot use _" */, int) {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59953.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59953.go
new file mode 100644
index 0000000000000000000000000000000000000000..b10ced749b4a6a580ee925dfc7d6aa73921bcfd4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59953.go
@@ -0,0 +1,9 @@
+// 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 p
+
+func _() { f(g) }
+func f[P any](P) {}
+func g[Q int](Q) {}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59956.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59956.go
new file mode 100644
index 0000000000000000000000000000000000000000..646b50e7716e7b06689cb3bd4a91d729d97def6e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59956.go
@@ -0,0 +1,47 @@
+// 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 p
+
+func f1(func(int))
+func f2(func(int), func(string))
+func f3(func(int), func(string), func(float32))
+
+func g1[P any](P) {}
+
+func _() {
+ f1(g1)
+ f2(g1, g1)
+ f3(g1, g1, g1)
+}
+
+// More complex examples
+
+func g2[P any](P, P) {}
+func h3[P any](func(P), func(P), func() P) {}
+func h4[P, Q any](func(P), func(P, Q), func() Q, func(P, Q)) {}
+
+func r1() int { return 0 }
+
+func _() {
+ h3(g1, g1, r1)
+ h4(g1, g2, r1, g2)
+}
+
+// Variadic cases
+
+func f(func(int))
+func g[P any](P) {}
+
+func d[P any](...func(P)) {}
+
+func _() {
+ d /* ERROR "cannot infer P" */ ()
+ d(f)
+ d(f, g)
+ d(f, g, g)
+ d /* ERROR "cannot infer P" */ (g, g, g)
+ d(g, g, f)
+ d(g, f, g, f)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59958.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59958.go
new file mode 100644
index 0000000000000000000000000000000000000000..4a4b4dc921d5f7fce1e356d376b34cee4b7f6f84
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue59958.go
@@ -0,0 +1,22 @@
+// 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 p
+
+func f(func(int) string) {}
+
+func g2[P, Q any](P) Q { var q Q; return q }
+func g3[P, Q, R any](P) R { var r R; return r }
+
+func _() {
+ f(g2)
+ f(g2[int])
+ f(g2[int, string])
+
+ f(g3[int, bool])
+ f(g3[int, bool, string])
+
+ var _ func(int) string = g2
+ var _ func(int) string = g2[int]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60346.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60346.go
new file mode 100644
index 0000000000000000000000000000000000000000..6dc057b178454b2529997908135002aca9f55e0d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60346.go
@@ -0,0 +1,17 @@
+// -lang=go1.20
+
+// 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 p
+
+func F[P any, Q *P](p P) {}
+
+var _ = F[int]
+
+func G[R any](func(R)) {}
+
+func _() {
+ G(F[int])
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60377.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60377.go
new file mode 100644
index 0000000000000000000000000000000000000000..b754f89df7321c8c6329c3a6e7d3d99dcc9ec0f8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60377.go
@@ -0,0 +1,88 @@
+// 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 p
+
+// The type parameter P is not used in interface T1.
+// T1 is a defined parameterized interface type which
+// can be assigned to any other interface with the same
+// methods. We cannot infer a type argument in this case
+// because any type would do.
+
+type T1[P any] interface{ m() }
+
+func g[P any](T1[P]) {}
+
+func _() {
+ var x T1[int]
+ g /* ERROR "cannot infer P" */ (x)
+ g[int](x) // int is ok for P
+ g[string](x) // string is also ok for P!
+}
+
+// This is analogous to the above example,
+// but uses two interface types of the same structure.
+
+type T2[P any] interface{ m() }
+
+func _() {
+ var x T2[int]
+ g /* ERROR "cannot infer P" */ (x)
+ g[int](x) // int is ok for P
+ g[string](x) // string is also ok for P!
+}
+
+// Analogous to the T2 example but using an unparameterized interface T3.
+
+type T3 interface{ m() }
+
+func _() {
+ var x T3
+ g /* ERROR "cannot infer P" */ (x)
+ g[int](x) // int is ok for P
+ g[string](x) // string is also ok for P!
+}
+
+// The type parameter P is not used in struct S.
+// S is a defined parameterized (non-interface) type which can only
+// be assigned to another type S with the same type argument.
+// Therefore we can infer a type argument in this case.
+
+type S[P any] struct{}
+
+func g4[P any](S[P]) {}
+
+func _() {
+ var x S[int]
+ g4(x) // we can infer int for P
+ g4[int](x) // int is the correct type argument
+ g4[string](x /* ERROR "cannot use x (variable of type S[int]) as S[string] value in argument to g4[string]" */)
+}
+
+// This is similar to the first example but here T1 is a component
+// of a func type. In this case types must match exactly: P must
+// match int.
+
+func g5[P any](func(T1[P])) {}
+
+func _() {
+ var f func(T1[int])
+ g5(f)
+ g5[int](f)
+ g5[string](f /* ERROR "cannot use f (variable of type func(T1[int])) as func(T1[string]) value in argument to g5[string]" */)
+}
+
+// This example would fail if we were to infer the type argument int for P
+// exactly because any type argument would be ok for the first argument.
+// Choosing the wrong type would cause the second argument to not match.
+
+type T[P any] interface{}
+
+func g6[P any](T[P], P) {}
+
+func _() {
+ var x T[int]
+ g6(x, 1.2)
+ g6(x, "")
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60434.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60434.go
new file mode 100644
index 0000000000000000000000000000000000000000..e1d76527f3db63f83affbe2951d6a9ebd62cdd44
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60434.go
@@ -0,0 +1,17 @@
+// 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.
+
+// Test that there are no type inference errors
+// if function arguments are invalid.
+
+package p
+
+func f[S any](S) {}
+
+var s struct{ x int }
+
+func _() {
+ f(s.y /* ERROR "s.y undefined" */)
+ f(1 /* ERROR "cannot convert 1" */ / s)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60460.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60460.go
new file mode 100644
index 0000000000000000000000000000000000000000..a9cb3d91e735ae5bd201d7f860177e1b26db7533
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60460.go
@@ -0,0 +1,88 @@
+// 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 p
+
+// Simplified (representative) test case.
+
+func _() {
+ f(R1{})
+}
+
+func f[T any](R[T]) {}
+
+type R[T any] interface {
+ m(R[T])
+}
+
+type R1 struct{}
+
+func (R1) m(R[int]) {}
+
+// Test case from issue.
+
+func _() {
+ r := newTestRules()
+ NewSet(r)
+ r2 := newTestRules2()
+ NewSet(r2)
+}
+
+type Set[T any] struct {
+ rules Rules[T]
+}
+
+func NewSet[T any](rules Rules[T]) Set[T] {
+ return Set[T]{
+ rules: rules,
+ }
+}
+
+func (s Set[T]) Copy() Set[T] {
+ return NewSet(s.rules)
+}
+
+type Rules[T any] interface {
+ Hash(T) int
+ Equivalent(T, T) bool
+ SameRules(Rules[T]) bool
+}
+
+type testRules struct{}
+
+func newTestRules() Rules[int] {
+ return testRules{}
+}
+
+func (r testRules) Hash(val int) int {
+ return val % 16
+}
+
+func (r testRules) Equivalent(val1 int, val2 int) bool {
+ return val1 == val2
+}
+
+func (r testRules) SameRules(other Rules[int]) bool {
+ _, ok := other.(testRules)
+ return ok
+}
+
+type testRules2 struct{}
+
+func newTestRules2() Rules[string] {
+ return testRules2{}
+}
+
+func (r testRules2) Hash(val string) int {
+ return 16
+}
+
+func (r testRules2) Equivalent(val1 string, val2 string) bool {
+ return val1 == val2
+}
+
+func (r testRules2) SameRules(other Rules[string]) bool {
+ _, ok := other.(testRules2)
+ return ok
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60500.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60500.go
new file mode 100644
index 0000000000000000000000000000000000000000..be8ccaf94f615ed7112a95040521dde465adf56d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60500.go
@@ -0,0 +1,11 @@
+// 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 p
+
+func _() {
+ log("This is a test %v" /* ERROR "cannot use \"This is a test %v\" (untyped string constant) as bool value in argument to log" */, "foo")
+}
+
+func log(enabled bool, format string, args ...any)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60542.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60542.go
new file mode 100644
index 0000000000000000000000000000000000000000..b536ddb198b19d133c48e586ad3a952dd9d309fd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60542.go
@@ -0,0 +1,12 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+func Clip[S ~[]E, E any](s S) S {
+ return s
+}
+
+var versions func()
+var _ = Clip /* ERROR "S (type func()) does not satisfy ~[]E" */ (versions)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60556.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60556.go
new file mode 100644
index 0000000000000000000000000000000000000000..77e5034730cf51cd259bdcda6f8f3fa76d62af5c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60556.go
@@ -0,0 +1,19 @@
+// 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 p
+
+type I[T any] interface {
+ m(I[T])
+}
+
+type S[T any] struct{}
+
+func (S[T]) m(I[T]) {}
+
+func f[T I[E], E any](T) {}
+
+func _() {
+ f(S[int]{})
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60562.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60562.go
new file mode 100644
index 0000000000000000000000000000000000000000..c08bbf34fe51b3028f7266c8250a5147b877be21
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60562.go
@@ -0,0 +1,61 @@
+// 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 p
+
+type S[T any] struct{}
+
+func (S[T]) m(T) {}
+
+func f0[T any](chan S[T]) {}
+
+func _() {
+ var x chan interface{ m(int) }
+ f0(x /* ERROR "type chan interface{m(int)} of x does not match chan S[T] (cannot infer T)" */)
+}
+
+// variants of the theme
+
+func f1[T any]([]S[T]) {}
+
+func _() {
+ var x []interface{ m(int) }
+ f1(x /* ERROR "type []interface{m(int)} of x does not match []S[T] (cannot infer T)" */)
+}
+
+type I[T any] interface {
+ m(T)
+}
+
+func f2[T any](func(I[T])) {}
+
+func _() {
+ var x func(interface{ m(int) })
+ f2(x /* ERROR "type func(interface{m(int)}) of x does not match func(I[T]) (cannot infer T)" */)
+}
+
+func f3[T any](func(I[T])) {}
+
+func _() {
+ var x func(I[int])
+ f3(x) // but this is correct: I[T] and I[int] can be made identical with T == int
+}
+
+func f4[T any]([10]I[T]) {}
+
+func _() {
+ var x [10]interface{ I[int] }
+ f4(x /* ERROR "type [10]interface{I[int]} of x does not match [10]I[T] (cannot infer T)" */)
+}
+
+func f5[T any](I[T]) {}
+
+func _() {
+ var x interface {
+ m(int)
+ n()
+ }
+ f5(x)
+ f5[int](x) // ok
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60688.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60688.go
new file mode 100644
index 0000000000000000000000000000000000000000..61b9f915106db8bc09dde61d89d851a795f3515e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60688.go
@@ -0,0 +1,16 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package p
+
+type String string
+
+func g[P any](P, string) {}
+
+// String and string are not identical and thus must not unify
+// (they are element types of the func type and therefore must
+// be identical to match).
+// The result is an error from type inference, rather than an
+// error from an assignment mismatch.
+var f func(int, String) = g // ERROR "inferred type func(int, string) for func(P, string) does not match type func(int, String) of f"
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60747.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60747.go
new file mode 100644
index 0000000000000000000000000000000000000000..6587a4e55788e129a61fc1c93a5438f9981044b6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60747.go
@@ -0,0 +1,13 @@
+// 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 p
+
+func f[P any](P) P { panic(0) }
+
+var v func(string) int = f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of v"
+
+func _() func(string) int {
+ return f // ERROR "inferred type func(string) string for func(P) P does not match type func(string) int of result variable"
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60906.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60906.go
new file mode 100644
index 0000000000000000000000000000000000000000..2744e894555fac684a52f5dd86d7b470314c9ce7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60906.go
@@ -0,0 +1,11 @@
+// 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 p
+
+func _() {
+ var x int
+ var f func() []int
+ _ = f /* ERROR "cannot index f" */ [x]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60933.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60933.go
new file mode 100644
index 0000000000000000000000000000000000000000..9b10237e5dc474d05ac2345cde929fc524bdf32c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60933.go
@@ -0,0 +1,67 @@
+// 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 p
+
+import (
+ "io"
+ "os"
+)
+
+func g[T any](...T) {}
+
+// Interface and non-interface types do not match.
+func _() {
+ var file *os.File
+ g(file, io /* ERROR "type io.Writer of io.Discard does not match inferred type *os.File for T" */ .Discard)
+ g(file, os.Stdout)
+}
+
+func _() {
+ var a *os.File
+ var b any
+ g(a, a)
+ g(a, b /* ERROR "type any of b does not match inferred type *os.File for T" */)
+}
+
+var writer interface {
+ Write(p []byte) (n int, err error)
+}
+
+func _() {
+ var file *os.File
+ g(file, writer /* ERROR "type interface{Write(p []byte) (n int, err error)} of writer does not match inferred type *os.File for T" */)
+ g(writer, file /* ERROR "type *os.File of file does not match inferred type interface{Write(p []byte) (n int, err error)} for T" */)
+}
+
+// Different named interface types do not match.
+func _() {
+ g(io.ReadWriter(nil), io.ReadWriter(nil))
+ g(io.ReadWriter(nil), io /* ERROR "does not match" */ .Writer(nil))
+ g(io.Writer(nil), io /* ERROR "does not match" */ .ReadWriter(nil))
+}
+
+// Named and unnamed interface types match if they have the same methods.
+func _() {
+ g(io.Writer(nil), writer)
+ g(io.ReadWriter(nil), writer /* ERROR "does not match" */ )
+}
+
+// There must be no order dependency for named and unnamed interfaces.
+func f[T interface{ m(T) }](a, b T) {}
+
+type F interface {
+ m(F)
+}
+
+func _() {
+ var i F
+ var j interface {
+ m(F)
+ }
+
+ // order doesn't matter
+ f(i, j)
+ f(j, i)
+}
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60946.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60946.go
new file mode 100644
index 0000000000000000000000000000000000000000..a66254b6d05d30ac7a88cba7a0b1a92efdf24e5f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue60946.go
@@ -0,0 +1,38 @@
+// 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 p
+
+type Tn interface{ m() }
+type T1 struct{}
+type T2 struct{}
+
+func (*T1) m() {}
+func (*T2) m() {}
+
+func g[P any](...P) {}
+
+func _() {
+ var t interface{ m() }
+ var tn Tn
+ var t1 *T1
+ var t2 *T2
+
+ // these are ok (interface types only)
+ g(t, t)
+ g(t, tn)
+ g(tn, t)
+ g(tn, tn)
+
+ // these are not ok (interface and non-interface types)
+ g(t, t1 /* ERROR "does not match" */)
+ g(t1, t /* ERROR "does not match" */)
+ g(tn, t1 /* ERROR "does not match" */)
+ g(t1, tn /* ERROR "does not match" */)
+
+ g(t, t1 /* ERROR "does not match" */, t2)
+ g(t1, t2 /* ERROR "does not match" */, t)
+ g(tn, t1 /* ERROR "does not match" */, t2)
+ g(t1, t2 /* ERROR "does not match" */, tn)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61486.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61486.go
new file mode 100644
index 0000000000000000000000000000000000000000..b12a800f0d9e84003e265fb158a432c08646d8e9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61486.go
@@ -0,0 +1,9 @@
+// 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 p
+
+func _(s uint) {
+ _ = min(1 << s)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61685.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61685.go
new file mode 100644
index 0000000000000000000000000000000000000000..b88b222eb9e5d196c37bed9454a7e99e63541213
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61685.go
@@ -0,0 +1,15 @@
+// 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 p
+
+func _[T any](x any) {
+ f /* ERROR "T (type I[T]) does not satisfy I[T] (wrong type for method m)" */ (x.(I[T]))
+}
+
+func f[T I[T]](T) {}
+
+type I[T any] interface {
+ m(T)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61822.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61822.go
new file mode 100644
index 0000000000000000000000000000000000000000..0a91ebb7b25c66f7f69ba8ad96ee97f809706b9c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61822.go
@@ -0,0 +1,19 @@
+// -lang=go1.19
+
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build go1.20
+
+package p
+
+type I[P any] interface {
+ ~string | ~int
+ Error() P
+}
+
+func _[P I[string]]() {
+ var x P
+ var _ error = x
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61879.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61879.go
new file mode 100644
index 0000000000000000000000000000000000000000..542bc2d68a1643ec00c8caa8d2372773265a0ed9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61879.go
@@ -0,0 +1,57 @@
+// 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 p
+
+import "fmt"
+
+type Interface[T any] interface {
+ m(Interface[T])
+}
+
+func f[S []Interface[T], T any](S) {}
+
+func _() {
+ var s []Interface[int]
+ f(s) // panic here
+}
+
+// Larger example from issue
+
+type InterfaceA[T comparable] interface {
+ setData(string) InterfaceA[T]
+}
+
+type ImplA[T comparable] struct {
+ data string
+ args []any
+}
+
+func NewInterfaceA[T comparable](args ...any) InterfaceA[T] {
+ return &ImplA[T]{
+ data: fmt.Sprintf("%v", args...),
+ args: args,
+ }
+}
+
+func (k *ImplA[T]) setData(data string) InterfaceA[T] {
+ k.data = data
+ return k
+}
+
+func Foo[M ~map[InterfaceA[T]]V, T comparable, V any](m M) {
+ // DO SOMETHING HERE
+ return
+}
+
+func Bar() {
+ keys := make([]InterfaceA[int], 0, 10)
+ m := make(map[InterfaceA[int]]int)
+ for i := 0; i < 10; i++ {
+ keys = append(keys, NewInterfaceA[int](i))
+ m[keys[i]] = i
+ }
+
+ Foo(m) // panic here
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61903.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61903.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a6fcd9529193554715c54608f05d56f95c78c5c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue61903.go
@@ -0,0 +1,20 @@
+// -lang=go1.20
+
+// 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 p
+
+type T[P any] interface{}
+
+func f1[P any](T[P]) {}
+func f2[P any](T[P], P) {}
+
+func _() {
+ var t T[int]
+ f1(t)
+
+ var s string
+ f2(t, s /* ERROR "type string of s does not match inferred type int for P" */)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue62157.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue62157.go
new file mode 100644
index 0000000000000000000000000000000000000000..c44f921f44bf45c9f4c6faf4f25fc2b425385cf1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue62157.go
@@ -0,0 +1,128 @@
+// 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 p
+
+func f[T any](...T) T { var x T; return x }
+
+// Test case 1
+
+func _() {
+ var a chan string
+ var b <-chan string
+ f(a, b)
+ f(b, a)
+}
+
+// Test case 2
+
+type F[T any] func(T) bool
+
+func g[T any](T) F[<-chan T] { return nil }
+
+func f1[T any](T, F[T]) {}
+func f2[T any](F[T], T) {}
+
+func _() {
+ var ch chan string
+ f1(ch, g(""))
+ f2(g(""), ch)
+}
+
+// Test case 3: named and directional types combined
+
+func _() {
+ type namedA chan int
+ type namedB chan<- int
+
+ var a chan int
+ var A namedA
+ var b chan<- int
+ var B namedB
+
+ // Defined types win over channel types irrespective of channel direction.
+ f(A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */)
+ f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A)
+
+ f(a, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A)
+ f(a, A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */)
+ f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, A, a)
+ f(b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, a, A)
+ f(A, a, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */)
+ f(A, b /* ERROR "cannot use b (variable of type chan<- int) as namedA value in argument to f" */, a)
+
+ // Unnamed directed channels win over bidirectional channels.
+ b = f(a, b)
+ b = f(b, a)
+
+ // Defined directed channels win over defined bidirectional channels.
+ A = f(A, a)
+ A = f(a, A)
+ B = f(B, b)
+ B = f(b, B)
+
+ f(a, b, B)
+ f(a, B, b)
+ f(b, B, a)
+ f(b, a, B)
+ f(B, a, b)
+ f(B, b, a)
+
+ // Differently named channel types conflict irrespective of channel direction.
+ f(A, B /* ERROR "type namedB of B does not match inferred type namedA for T" */)
+ f(B, A /* ERROR "type namedA of A does not match inferred type namedB for T" */)
+
+ // Ensure that all combinations of directional and
+ // bidirectional channels with a named directional
+ // channel lead to the correct (named) directional
+ // channel.
+ B = f(a, b)
+ B = f(a, B)
+ B = f(b, a)
+ B = f(B, a)
+
+ B = f(a, b, B)
+ B = f(a, B, b)
+ B = f(b, B, a)
+ B = f(b, a, B)
+ B = f(B, a, b)
+ B = f(B, b, a)
+
+ // verify type error
+ A = f /* ERROR "cannot use f(B, b, a) (value of type namedB) as namedA value in assignment" */ (B, b, a)
+}
+
+// Test case 4: some more combinations
+
+func _() {
+ type A chan int
+ type B chan int
+ type C = chan int
+ type D = chan<- int
+
+ var a A
+ var b B
+ var c C
+ var d D
+
+ f(a, b /* ERROR "type B of b does not match inferred type A for T" */, c)
+ f(c, a, b /* ERROR "type B of b does not match inferred type A for T" */)
+ f(a, b /* ERROR "type B of b does not match inferred type A for T" */, d)
+ f(d, a, b /* ERROR "type B of b does not match inferred type A for T" */)
+}
+
+// Simplified test case from issue
+
+type Matcher[T any] func(T) bool
+
+func Produces[T any](T) Matcher[<-chan T] { return nil }
+
+func Assert1[T any](Matcher[T], T) {}
+func Assert2[T any](T, Matcher[T]) {}
+
+func _() {
+ var ch chan string
+ Assert1(Produces(""), ch)
+ Assert2(ch, Produces(""))
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue63563.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue63563.go
new file mode 100644
index 0000000000000000000000000000000000000000..b8134852765b5e057b79680b1b51247b6999eddf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue63563.go
@@ -0,0 +1,37 @@
+// 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 p
+
+var (
+ _ = int8(1 /* ERROR "constant 255 overflows int8" */ <<8 - 1)
+ _ = int16(1 /* ERROR "constant 65535 overflows int16" */ <<16 - 1)
+ _ = int32(1 /* ERROR "constant 4294967295 overflows int32" */ <<32 - 1)
+ _ = int64(1 /* ERROR "constant 18446744073709551615 overflows int64" */ <<64 - 1)
+
+ _ = uint8(1 /* ERROR "constant 256 overflows uint8" */ << 8)
+ _ = uint16(1 /* ERROR "constant 65536 overflows uint16" */ << 16)
+ _ = uint32(1 /* ERROR "constant 4294967296 overflows uint32" */ << 32)
+ _ = uint64(1 /* ERROR "constant 18446744073709551616 overflows uint64" */ << 64)
+)
+
+func _[P int8 | uint8]() {
+ _ = P(0)
+ _ = P(1 /* ERROR "constant 255 overflows int8 (in P)" */ <<8 - 1)
+}
+
+func _[P int16 | uint16]() {
+ _ = P(0)
+ _ = P(1 /* ERROR "constant 65535 overflows int16 (in P)" */ <<16 - 1)
+}
+
+func _[P int32 | uint32]() {
+ _ = P(0)
+ _ = P(1 /* ERROR "constant 4294967295 overflows int32 (in P)" */ <<32 - 1)
+}
+
+func _[P int64 | uint64]() {
+ _ = P(0)
+ _ = P(1 /* ERROR "constant 18446744073709551615 overflows int64 (in P)" */ <<64 - 1)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64406.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64406.go
new file mode 100644
index 0000000000000000000000000000000000000000..54b959dbba83be01af23546308ec42c3491da919
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64406.go
@@ -0,0 +1,23 @@
+// 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 issue64406
+
+import (
+ "unsafe"
+)
+
+func sliceData[E any, S ~[]E](s S) *E {
+ return unsafe.SliceData(s)
+}
+
+func slice[E any, S ~*E](s S) []E {
+ return unsafe.Slice(s, 0)
+}
+
+func f() {
+ s := []uint32{0}
+ _ = sliceData(s)
+ _ = slice(&s)
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64704.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64704.go
new file mode 100644
index 0000000000000000000000000000000000000000..c8e9056cdd5251a7580dc6e67ac330f66821ee08
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue64704.go
@@ -0,0 +1,12 @@
+// -lang=go1.21
+
+// 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 p
+
+func _() {
+ for range 10 /* ERROR "cannot range over 10 (untyped int constant): requires go1.22 or later" */ {
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue65854.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue65854.go
new file mode 100644
index 0000000000000000000000000000000000000000..744777a94f84575a0800c0089d3882c0f95b9c38
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue65854.go
@@ -0,0 +1,13 @@
+// -gotypesalias=1
+
+// 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 p
+
+type A = int
+
+type T[P any] *A
+
+var _ T[int]
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue6977.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue6977.go
new file mode 100644
index 0000000000000000000000000000000000000000..c455d3a849f2237b3c4dfa7e0cd3cda35b0c4129
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/fixedbugs/issue6977.go
@@ -0,0 +1,82 @@
+// 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
+
+import "io"
+
+// Alan's initial report.
+
+type I interface { f(); String() string }
+type J interface { g(); String() string }
+
+type IJ1 = interface { I; J }
+type IJ2 = interface { f(); g(); String() string }
+
+var _ = (*IJ1)(nil) == (*IJ2)(nil) // static assert that IJ1 and IJ2 are identical types
+
+// The canonical example.
+
+type ReadWriteCloser interface { io.ReadCloser; io.WriteCloser }
+
+// Some more cases.
+
+type M interface { m() }
+type M32 interface { m() int32 }
+type M64 interface { m() int64 }
+
+type U1 interface { m() }
+type U2 interface { m(); M }
+type U3 interface { M; m() }
+type U4 interface { M; M; M }
+type U5 interface { U1; U2; U3; U4 }
+
+type U6 interface { m(); m /* ERROR "duplicate method" */ () }
+type U7 interface { M32 /* ERROR "duplicate method" */ ; m() }
+type U8 interface { m(); M32 /* ERROR "duplicate method" */ }
+type U9 interface { M32; M64 /* ERROR "duplicate method" */ }
+
+// Verify that repeated embedding of the same interface(s)
+// eliminates duplicate methods early (rather than at the
+// end) to prevent exponential memory and time use.
+// Without early elimination, computing T29 may take dozens
+// of minutes.
+type (
+ T0 interface { m() }
+ T1 interface { T0; T0 }
+ T2 interface { T1; T1 }
+ T3 interface { T2; T2 }
+ T4 interface { T3; T3 }
+ T5 interface { T4; T4 }
+ T6 interface { T5; T5 }
+ T7 interface { T6; T6 }
+ T8 interface { T7; T7 }
+ T9 interface { T8; T8 }
+
+ T10 interface { T9; T9 }
+ T11 interface { T10; T10 }
+ T12 interface { T11; T11 }
+ T13 interface { T12; T12 }
+ T14 interface { T13; T13 }
+ T15 interface { T14; T14 }
+ T16 interface { T15; T15 }
+ T17 interface { T16; T16 }
+ T18 interface { T17; T17 }
+ T19 interface { T18; T18 }
+
+ T20 interface { T19; T19 }
+ T21 interface { T20; T20 }
+ T22 interface { T21; T21 }
+ T23 interface { T22; T22 }
+ T24 interface { T23; T23 }
+ T25 interface { T24; T24 }
+ T26 interface { T25; T25 }
+ T27 interface { T26; T26 }
+ T28 interface { T27; T27 }
+ T29 interface { T28; T28 }
+)
+
+// Verify that m is present.
+var x T29
+var _ = x.m
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/assignability.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/assignability.go
new file mode 100644
index 0000000000000000000000000000000000000000..2ce9a4a150134f03556d9ebca7f98c7d69cee795
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/assignability.go
@@ -0,0 +1,264 @@
+// 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 assignability
+
+// See the end of this package for the declarations
+// of the types and variables used in these tests.
+
+// "x's type is identical to T"
+func _[TP any](X TP) {
+ b = b
+ a = a
+ l = l
+ s = s
+ p = p
+ f = f
+ i = i
+ m = m
+ c = c
+ d = d
+
+ B = B
+ A = A
+ L = L
+ S = S
+ P = P
+ F = F
+ I = I
+ M = M
+ C = C
+ D = D
+ X = X
+}
+
+// "x's type V and T have identical underlying types
+// and at least one of V or T is not a named type."
+// (here a named type is a type with a name)
+func _[TP1, TP2 Interface](X1 TP1, X2 TP2) {
+ b = B // ERRORx `cannot use B .* as (int|_Basic.*) value`
+ a = A
+ l = L
+ s = S
+ p = P
+ f = F
+ i = I
+ m = M
+ c = C
+ d = D
+
+ B = b // ERRORx `cannot use b .* as Basic value`
+ A = a
+ L = l
+ S = s
+ P = p
+ F = f
+ I = i
+ M = m
+ C = c
+ D = d
+ X1 = i // ERRORx `cannot use i .* as TP1 value`
+ X1 = X2 // ERRORx `cannot use X2 .* as TP1 value`
+}
+
+// "T is an interface type and x implements T and T is not a type parameter"
+func _[TP Interface](X TP) {
+ i = d // ERROR "missing method m"
+ i = D
+ i = X
+ X = i // ERRORx `cannot use i .* as TP value`
+}
+
+// "x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type"
+// (here a named type is a type with a name)
+type (
+ _SendChan = chan<- int
+ _RecvChan = <-chan int
+
+ SendChan _SendChan
+ RecvChan _RecvChan
+)
+
+func _[
+ _CC ~_Chan,
+ _SC ~_SendChan,
+ _RC ~_RecvChan,
+
+ CC Chan,
+ SC SendChan,
+ RC RecvChan,
+]() {
+ var (
+ _ _SendChan = c
+ _ _RecvChan = c
+ _ _Chan = c
+
+ _ _SendChan = C
+ _ _RecvChan = C
+ _ _Chan = C
+
+ _ SendChan = c
+ _ RecvChan = c
+ _ Chan = c
+
+ _ SendChan = C // ERRORx `cannot use C .* as SendChan value`
+ _ RecvChan = C // ERRORx `cannot use C .* as RecvChan value`
+ _ Chan = C
+ _ Chan = make /* ERRORx `cannot use make\(chan Basic\) .* as Chan value` */ (chan Basic)
+ )
+
+ var (
+ _ _CC = C // ERRORx `cannot use C .* as _CC value`
+ _ _SC = C // ERRORx `cannot use C .* as _SC value`
+ _ _RC = C // ERRORx `cannot use C .* as _RC value`
+
+ _ CC = _CC /* ERRORx `cannot use _CC\(nil\) .* as CC value` */ (nil)
+ _ SC = _CC /* ERRORx `cannot use _CC\(nil\) .* as SC value` */ (nil)
+ _ RC = _CC /* ERRORx `cannot use _CC\(nil\) .* as RC value` */ (nil)
+
+ _ CC = C // ERRORx `cannot use C .* as CC value`
+ _ SC = C // ERRORx `cannot use C .* as SC value`
+ _ RC = C // ERRORx `cannot use C .* as RC value`
+ )
+}
+
+// "x's type V is not a named type and T is a type parameter, and x is assignable to each specific type in T's type set."
+func _[
+ TP0 any,
+ TP1 ~_Chan,
+ TP2 ~chan int | ~chan byte,
+]() {
+ var (
+ _ TP0 = c // ERRORx `cannot use c .* as TP0 value`
+ _ TP0 = C // ERRORx `cannot use C .* as TP0 value`
+ _ TP1 = c
+ _ TP1 = C // ERRORx `cannot use C .* as TP1 value`
+ _ TP2 = c // ERRORx `.* cannot assign (chan int|_Chan.*) to chan byte`
+ )
+}
+
+// "x's type V is a type parameter and T is not a named type, and values x' of each specific type in V's type set are assignable to T."
+func _[
+ TP0 Interface,
+ TP1 ~_Chan,
+ TP2 ~chan int | ~chan byte,
+](X0 TP0, X1 TP1, X2 TP2) {
+ i = X0
+ I = X0
+ c = X1
+ C = X1 // ERRORx `cannot use X1 .* as Chan value`
+ c = X2 // ERRORx `.* cannot assign chan byte \(in TP2\) to (chan int|_Chan.*)`
+}
+
+// "x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type"
+func _[TP Interface](X TP) {
+ b = nil // ERROR "cannot use nil"
+ a = nil // ERROR "cannot use nil"
+ l = nil
+ s = nil // ERROR "cannot use nil"
+ p = nil
+ f = nil
+ i = nil
+ m = nil
+ c = nil
+ d = nil // ERROR "cannot use nil"
+
+ B = nil // ERROR "cannot use nil"
+ A = nil // ERROR "cannot use nil"
+ L = nil
+ S = nil // ERROR "cannot use nil"
+ P = nil
+ F = nil
+ I = nil
+ M = nil
+ C = nil
+ D = nil // ERROR "cannot use nil"
+ X = nil // ERROR "cannot use nil"
+}
+
+// "x is an untyped constant representable by a value of type T"
+func _[
+ Int8 ~int8,
+ Int16 ~int16,
+ Int32 ~int32,
+ Int64 ~int64,
+ Int8_16 ~int8 | ~int16,
+](
+ i8 Int8,
+ i16 Int16,
+ i32 Int32,
+ i64 Int64,
+ i8_16 Int8_16,
+) {
+ b = 42
+ b = 42.0
+ // etc.
+
+ i8 = -1 << 7
+ i8 = 1<<7 - 1
+ i16 = -1 << 15
+ i16 = 1<<15 - 1
+ i32 = -1 << 31
+ i32 = 1<<31 - 1
+ i64 = -1 << 63
+ i64 = 1<<63 - 1
+
+ i8_16 = -1 << 7
+ i8_16 = 1<<7 - 1
+ i8_16 = - /* ERRORx `cannot use .* as Int8_16` */ 1 << 15
+ i8_16 = 1 /* ERRORx `cannot use .* as Int8_16` */ <<15 - 1
+}
+
+// proto-types for tests
+
+type (
+ _Basic = int
+ _Array = [10]int
+ _Slice = []int
+ _Struct = struct{ f int }
+ _Pointer = *int
+ _Func = func(x int) string
+ _Interface = interface{ m() int }
+ _Map = map[string]int
+ _Chan = chan int
+
+ Basic _Basic
+ Array _Array
+ Slice _Slice
+ Struct _Struct
+ Pointer _Pointer
+ Func _Func
+ Interface _Interface
+ Map _Map
+ Chan _Chan
+ Defined _Struct
+)
+
+func (Defined) m() int
+
+// proto-variables for tests
+
+var (
+ b _Basic
+ a _Array
+ l _Slice
+ s _Struct
+ p _Pointer
+ f _Func
+ i _Interface
+ m _Map
+ c _Chan
+ d _Struct
+
+ B Basic
+ A Array
+ L Slice
+ S Struct
+ P Pointer
+ F Func
+ I Interface
+ M Map
+ C Chan
+ D Defined
+)
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable.go
new file mode 100644
index 0000000000000000000000000000000000000000..211fa119a858b475b53c75fd7fc1ebc4836fa02c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable.go
@@ -0,0 +1,26 @@
+// 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 p
+
+func f1[_ comparable]() {}
+func f2[_ interface{ comparable }]() {}
+
+type T interface{ m() }
+
+func _[P comparable, Q ~int, R any]() {
+ _ = f1[int]
+ _ = f1[T /* T does satisfy comparable */]
+ _ = f1[any /* any does satisfy comparable */]
+ _ = f1[P]
+ _ = f1[Q]
+ _ = f1[R /* ERROR "R does not satisfy comparable" */]
+
+ _ = f2[int]
+ _ = f2[T /* T does satisfy comparable */]
+ _ = f2[any /* any does satisfy comparable */]
+ _ = f2[P]
+ _ = f2[Q]
+ _ = f2[R /* ERROR "R does not satisfy comparable" */]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable1.19.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable1.19.go
new file mode 100644
index 0000000000000000000000000000000000000000..7a4b2a0cfa497942c215e305c43a2f5b234372d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparable1.19.go
@@ -0,0 +1,28 @@
+// -lang=go1.19
+
+// 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 p
+
+func f1[_ comparable]() {}
+func f2[_ interface{ comparable }]() {}
+
+type T interface{ m() }
+
+func _[P comparable, Q ~int, R any]() {
+ _ = f1[int]
+ _ = f1[T /* ERROR "T to satisfy comparable requires go1.20 or later" */]
+ _ = f1[any /* ERROR "any to satisfy comparable requires go1.20 or later" */]
+ _ = f1[P]
+ _ = f1[Q]
+ _ = f1[R /* ERROR "R does not satisfy comparable" */]
+
+ _ = f2[int]
+ _ = f2[T /* ERROR "T to satisfy comparable requires go1.20 or later" */]
+ _ = f2[any /* ERROR "any to satisfy comparable requires go1.20 or later" */]
+ _ = f2[P]
+ _ = f2[Q]
+ _ = f2[R /* ERROR "R does not satisfy comparable" */]
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparisons.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparisons.go
new file mode 100644
index 0000000000000000000000000000000000000000..492890e49e9734a9f324deb9b172a560254bb8a0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/comparisons.go
@@ -0,0 +1,120 @@
+// 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 comparisons
+
+type (
+ B int // basic type representative
+ A [10]func()
+ L []byte
+ S struct{ f []byte }
+ P *S
+ F func()
+ I interface{}
+ M map[string]int
+ C chan int
+)
+
+var (
+ b B
+ a A
+ l L
+ s S
+ p P
+ f F
+ i I
+ m M
+ c C
+)
+
+func _() {
+ _ = nil == nil // ERROR "operator == not defined on untyped nil"
+ _ = b == b
+ _ = a /* ERROR "[10]func() cannot be compared" */ == a
+ _ = l /* ERROR "slice can only be compared to nil" */ == l
+ _ = s /* ERROR "struct containing []byte cannot be compared" */ == s
+ _ = p == p
+ _ = f /* ERROR "func can only be compared to nil" */ == f
+ _ = i == i
+ _ = m /* ERROR "map can only be compared to nil" */ == m
+ _ = c == c
+
+ _ = b == nil /* ERROR "mismatched types" */
+ _ = a == nil /* ERROR "mismatched types" */
+ _ = l == nil
+ _ = s == nil /* ERROR "mismatched types" */
+ _ = p == nil
+ _ = f == nil
+ _ = i == nil
+ _ = m == nil
+ _ = c == nil
+
+ _ = nil /* ERROR "operator < not defined on untyped nil" */ < nil
+ _ = b < b
+ _ = a /* ERROR "operator < not defined on array" */ < a
+ _ = l /* ERROR "operator < not defined on slice" */ < l
+ _ = s /* ERROR "operator < not defined on struct" */ < s
+ _ = p /* ERROR "operator < not defined on pointer" */ < p
+ _ = f /* ERROR "operator < not defined on func" */ < f
+ _ = i /* ERROR "operator < not defined on interface" */ < i
+ _ = m /* ERROR "operator < not defined on map" */ < m
+ _ = c /* ERROR "operator < not defined on chan" */ < c
+}
+
+func _[
+ B int,
+ A [10]func(),
+ L []byte,
+ S struct{ f []byte },
+ P *S,
+ F func(),
+ I interface{},
+ J comparable,
+ M map[string]int,
+ C chan int,
+](
+ b B,
+ a A,
+ l L,
+ s S,
+ p P,
+ f F,
+ i I,
+ j J,
+ m M,
+ c C,
+) {
+ _ = b == b
+ _ = a /* ERROR "incomparable types in type set" */ == a
+ _ = l /* ERROR "incomparable types in type set" */ == l
+ _ = s /* ERROR "incomparable types in type set" */ == s
+ _ = p == p
+ _ = f /* ERROR "incomparable types in type set" */ == f
+ _ = i /* ERROR "incomparable types in type set" */ == i
+ _ = j == j
+ _ = m /* ERROR "incomparable types in type set" */ == m
+ _ = c == c
+
+ _ = b == nil /* ERROR "mismatched types" */
+ _ = a == nil /* ERROR "mismatched types" */
+ _ = l == nil
+ _ = s == nil /* ERROR "mismatched types" */
+ _ = p == nil
+ _ = f == nil
+ _ = i == nil /* ERROR "mismatched types" */
+ _ = j == nil /* ERROR "mismatched types" */
+ _ = m == nil
+ _ = c == nil
+
+ _ = b < b
+ _ = a /* ERROR "type parameter A is not comparable with <" */ < a
+ _ = l /* ERROR "type parameter L is not comparable with <" */ < l
+ _ = s /* ERROR "type parameter S is not comparable with <" */ < s
+ _ = p /* ERROR "type parameter P is not comparable with <" */ < p
+ _ = f /* ERROR "type parameter F is not comparable with <" */ < f
+ _ = i /* ERROR "type parameter I is not comparable with <" */ < i
+ _ = j /* ERROR "type parameter J is not comparable with <" */ < j
+ _ = m /* ERROR "type parameter M is not comparable with <" */ < m
+ _ = c /* ERROR "type parameter C is not comparable with <" */ < c
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/conversions.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/conversions.go
new file mode 100644
index 0000000000000000000000000000000000000000..081439e3f200f051ef545f7cf888ebfa5373270a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/conversions.go
@@ -0,0 +1,208 @@
+// 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 conversions
+
+import "unsafe"
+
+// constant conversions
+
+func _[T ~byte]() T { return 255 }
+func _[T ~byte]() T { return 256 /* ERRORx `cannot use 256 .* as T value` */ }
+
+func _[T ~byte]() {
+ const _ = T /* ERRORx `T\(0\) .* is not constant` */ (0)
+ var _ T = 255
+ var _ T = 256 // ERRORx `cannot use 256 .* as T value`
+}
+
+func _[T ~string]() T { return T('a') }
+func _[T ~int | ~string]() T { return T('a') }
+func _[T ~byte | ~int | ~string]() T { return T(256 /* ERRORx `cannot convert 256 .* to type T` */) }
+
+// implicit conversions never convert to string
+func _[T ~string]() {
+ var _ string = 0 // ERRORx `cannot use .* as string value`
+ var _ T = 0 // ERRORx `cannot use .* as T value`
+}
+
+// failing const conversions of constants to type parameters report a cause
+func _[
+ T1 any,
+ T2 interface{ m() },
+ T3 ~int | ~float64 | ~bool,
+ T4 ~int | ~string,
+]() {
+ _ = T1(0 /* ERRORx `cannot convert 0 .* to type T1: T1 does not contain specific types` */)
+ _ = T2(1 /* ERRORx `cannot convert 1 .* to type T2: T2 does not contain specific types` */)
+ _ = T3(2 /* ERRORx `cannot convert 2 .* to type T3: cannot convert 2 .* to type bool \(in T3\)` */)
+ _ = T4(3.14 /* ERRORx `cannot convert 3.14 .* to type T4: cannot convert 3.14 .* to type int \(in T4\)` */)
+}
+
+// "x is assignable to T"
+// - tested via assignability tests
+
+// "x's type and T have identical underlying types if tags are ignored"
+
+func _[X ~int, T ~int](x X) T { return T(x) }
+func _[X struct {
+ f int "foo"
+}, T struct {
+ f int "bar"
+}](x X) T {
+ return T(x)
+}
+
+type Foo struct {
+ f int "foo"
+}
+type Bar struct {
+ f int "bar"
+}
+type Far struct{ f float64 }
+
+func _[X Foo, T Bar](x X) T { return T(x) }
+func _[X Foo | Bar, T Bar](x X) T { return T(x) }
+func _[X Foo, T Foo | Bar](x X) T { return T(x) }
+func _[X Foo, T Far](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by Foo) to type T: cannot convert Foo (in X) to type Far (in T)" */)
+}
+
+// "x's type and T are unnamed pointer types and their pointer base types
+// have identical underlying types if tags are ignored"
+
+func _[X ~*Foo, T ~*Bar](x X) T { return T(x) }
+func _[X ~*Foo | ~*Bar, T ~*Bar](x X) T { return T(x) }
+func _[X ~*Foo, T ~*Foo | ~*Bar](x X) T { return T(x) }
+func _[X ~*Foo, T ~*Far](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by ~*Foo) to type T: cannot convert *Foo (in X) to type *Far (in T)" */)
+}
+
+// Verify that the defined types in constraints are considered for the rule above.
+
+type (
+ B int
+ C int
+ X0 *B
+ T0 *C
+)
+
+func _(x X0) T0 { return T0(x /* ERROR "cannot convert" */) } // non-generic reference
+func _[X X0, T T0](x X) T { return T(x /* ERROR "cannot convert" */) }
+func _[T T0](x X0) T { return T(x /* ERROR "cannot convert" */) }
+func _[X X0](x X) T0 { return T0(x /* ERROR "cannot convert" */) }
+
+// "x's type and T are both integer or floating point types"
+
+func _[X Integer, T Integer](x X) T { return T(x) }
+func _[X Unsigned, T Integer](x X) T { return T(x) }
+func _[X Float, T Integer](x X) T { return T(x) }
+
+func _[X Integer, T Unsigned](x X) T { return T(x) }
+func _[X Unsigned, T Unsigned](x X) T { return T(x) }
+func _[X Float, T Unsigned](x X) T { return T(x) }
+
+func _[X Integer, T Float](x X) T { return T(x) }
+func _[X Unsigned, T Float](x X) T { return T(x) }
+func _[X Float, T Float](x X) T { return T(x) }
+
+func _[X, T Integer | Unsigned | Float](x X) T { return T(x) }
+func _[X, T Integer | ~string](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by Integer | ~string) to type T: cannot convert string (in X) to type int (in T)" */)
+}
+
+// "x's type and T are both complex types"
+
+func _[X, T Complex](x X) T { return T(x) }
+func _[X, T Float | Complex](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by Float | Complex) to type T: cannot convert float32 (in X) to type complex64 (in T)" */)
+}
+
+// "x is an integer or a slice of bytes or runes and T is a string type"
+
+type myInt int
+type myString string
+
+func _[T ~string](x int) T { return T(x) }
+func _[T ~string](x myInt) T { return T(x) }
+func _[X Integer](x X) string { return string(x) }
+func _[X Integer](x X) myString { return myString(x) }
+func _[X Integer](x X) *string {
+ return (*string)(x /* ERROR "cannot convert x (variable of type X constrained by Integer) to type *string: cannot convert int (in X) to type *string" */)
+}
+
+func _[T ~string](x []byte) T { return T(x) }
+func _[T ~string](x []rune) T { return T(x) }
+func _[X ~[]byte, T ~string](x X) T { return T(x) }
+func _[X ~[]rune, T ~string](x X) T { return T(x) }
+func _[X Integer | ~[]byte | ~[]rune, T ~string](x X) T { return T(x) }
+func _[X Integer | ~[]byte | ~[]rune, T ~*string](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by Integer | ~[]byte | ~[]rune) to type T: cannot convert int (in X) to type *string (in T)" */)
+}
+
+// "x is a string and T is a slice of bytes or runes"
+
+func _[T ~[]byte](x string) T { return T(x) }
+func _[T ~[]rune](x string) T { return T(x) }
+func _[T ~[]rune](x *string) T {
+ return T(x /* ERROR "cannot convert x (variable of type *string) to type T: cannot convert *string to type []rune (in T)" */)
+}
+
+func _[X ~string, T ~[]byte](x X) T { return T(x) }
+func _[X ~string, T ~[]rune](x X) T { return T(x) }
+func _[X ~string, T ~[]byte | ~[]rune](x X) T { return T(x) }
+func _[X ~*string, T ~[]byte | ~[]rune](x X) T {
+ return T(x /* ERROR "cannot convert x (variable of type X constrained by ~*string) to type T: cannot convert *string (in X) to type []byte (in T)" */)
+}
+
+// package unsafe:
+// "any pointer or value of underlying type uintptr can be converted into a unsafe.Pointer"
+
+type myUintptr uintptr
+
+func _[X ~uintptr](x X) unsafe.Pointer { return unsafe.Pointer(x) }
+func _[T unsafe.Pointer](x myUintptr) T { return T(x) }
+func _[T unsafe.Pointer](x int64) T {
+ return T(x /* ERROR "cannot convert x (variable of type int64) to type T: cannot convert int64 to type unsafe.Pointer (in T)" */)
+}
+
+// "and vice versa"
+
+func _[T ~uintptr](x unsafe.Pointer) T { return T(x) }
+func _[X unsafe.Pointer](x X) uintptr { return uintptr(x) }
+func _[X unsafe.Pointer](x X) myUintptr { return myUintptr(x) }
+func _[X unsafe.Pointer](x X) int64 {
+ return int64(x /* ERROR "cannot convert x (variable of type X constrained by unsafe.Pointer) to type int64: cannot convert unsafe.Pointer (in X) to type int64" */)
+}
+
+// "x is a slice, T is an array or pointer-to-array type,
+// and the slice and array types have identical element types."
+
+func _[X ~[]E, T ~[10]E, E any](x X) T { return T(x) }
+func _[X ~[]E, T ~*[10]E, E any](x X) T { return T(x) }
+
+// ----------------------------------------------------------------------------
+// The following declarations can be replaced by the exported types of the
+// constraints package once all builders support importing interfaces with
+// type constraints.
+
+type Signed interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64
+}
+
+type Unsigned interface {
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
+}
+
+type Integer interface {
+ Signed | Unsigned
+}
+
+type Float interface {
+ ~float32 | ~float64
+}
+
+type Complex interface {
+ ~complex64 | ~complex128
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range.go
new file mode 100644
index 0000000000000000000000000000000000000000..4ae270d233d7b2694f7e6e423b15640300491a90
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range.go
@@ -0,0 +1,157 @@
+// -goexperiment=rangefunc
+
+// 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 p
+
+type MyInt int32
+type MyBool bool
+type MyString string
+type MyFunc1 func(func(int) bool)
+type MyFunc2 func(int) bool
+type MyFunc3 func(MyFunc2)
+
+type T struct{}
+
+func (*T) PM() {}
+func (T) M() {}
+
+func f1() {}
+func f2(func()) {}
+func f4(func(int) bool) {}
+func f5(func(int, string) bool) {}
+func f7(func(int) MyBool) {}
+func f8(func(MyInt, MyString) MyBool) {}
+
+func test() {
+ // TODO: Would be nice to 'for range T.M' and 'for range (*T).PM' directly,
+ // but there is no gofmt-friendly way to write the error pattern in the right place.
+ m1 := T.M
+ for range m1 /* ERROR "cannot range over m1 (variable of type func(T)): func must be func(yield func(...) bool): argument is not func" */ {
+ }
+ m2 := (*T).PM
+ for range m2 /* ERROR "cannot range over m2 (variable of type func(*T)): func must be func(yield func(...) bool): argument is not func" */ {
+ }
+ for range f1 /* ERROR "cannot range over f1 (value of type func()): func must be func(yield func(...) bool): wrong argument count" */ {
+ }
+ for range f2 /* ERROR "cannot range over f2 (value of type func(func())): func must be func(yield func(...) bool): yield func does not return bool" */ {
+ }
+ for range f4 /* ERROR "range over f4 (value of type func(func(int) bool)) must have one iteration variable" */ {
+ }
+ for _ = range f4 {
+ }
+ for _, _ = range f5 {
+ }
+ for _ = range f7 {
+ }
+ for _, _ = range f8 {
+ }
+ for range 1 {
+ }
+ for range uint8(1) {
+ }
+ for range int64(1) {
+ }
+ for range MyInt(1) {
+ }
+ for range 'x' {
+ }
+ for range 1.0 /* ERROR "cannot range over 1.0 (untyped float constant 1)" */ {
+ }
+ for _ = range MyFunc1(nil) {
+ }
+ for _ = range MyFunc3(nil) {
+ }
+ for _ = range (func(MyFunc2))(nil) {
+ }
+
+ var i int
+ var s string
+ var mi MyInt
+ var ms MyString
+ for i := range f4 {
+ _ = i
+ }
+ for i = range f4 {
+ _ = i
+ }
+ for i, s := range f5 {
+ _, _ = i, s
+ }
+ for i, s = range f5 {
+ _, _ = i, s
+ }
+ for i, _ := range f5 {
+ _ = i
+ }
+ for i, _ = range f5 {
+ _ = i
+ }
+ for i := range f7 {
+ _ = i
+ }
+ for i = range f7 {
+ _ = i
+ }
+ for mi, _ := range f8 {
+ _ = mi
+ }
+ for mi, _ = range f8 {
+ _ = mi
+ }
+ for mi, ms := range f8 {
+ _, _ = mi, ms
+ }
+ for i /* ERROR "cannot use i (value of type MyInt) as int value in assignment" */, s /* ERROR "cannot use s (value of type MyString) as string value in assignment" */ = range f8 {
+ _, _ = mi, ms
+ }
+ for mi, ms := range f8 {
+ i, s = mi /* ERROR "cannot use mi (variable of type MyInt) as int value in assignment" */, ms /* ERROR "cannot use ms (variable of type MyString) as string value in assignment" */
+ }
+ for mi, ms = range f8 {
+ _, _ = mi, ms
+ }
+
+ for i := range 10 {
+ _ = i
+ }
+ for i = range 10 {
+ _ = i
+ }
+ for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ := range 10 {
+ _, _ = i, j
+ }
+ for mi := range MyInt(10) {
+ _ = mi
+ }
+ for mi = range MyInt(10) {
+ _ = mi
+ }
+}
+
+func _[T int | string](x T) {
+ for range x /* ERROR "cannot range over x (variable of type T constrained by int | string): no core type" */ {
+ }
+}
+
+func _[T int | int64](x T) {
+ for range x /* ERROR "cannot range over x (variable of type T constrained by int | int64): no core type" */ {
+ }
+}
+
+func _[T ~int](x T) {
+ for range x { // ok
+ }
+}
+
+func _[T any](x func(func(T) bool)) {
+ for _ = range x { // ok
+ }
+}
+
+func _[T ~func(func(int) bool)](x T) {
+ for _ = range x { // ok
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range_int.go b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range_int.go
new file mode 100644
index 0000000000000000000000000000000000000000..766736cc1556efc904f7a7355286f42e860bb296
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/types/testdata/spec/range_int.go
@@ -0,0 +1,190 @@
+// 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.
+
+// This is a subset of the tests in range.go for range over integers,
+// with extra tests, and without the need for -goexperiment=range.
+
+package p
+
+// test framework assumes 64-bit int/uint sizes by default
+const (
+ maxInt = 1<<63 - 1
+ maxUint = 1<<64 - 1
+)
+
+type MyInt int32
+
+func _() {
+ for range -1 {
+ }
+ for range 0 {
+ }
+ for range 1 {
+ }
+ for range uint8(1) {
+ }
+ for range int64(1) {
+ }
+ for range MyInt(1) {
+ }
+ for range 'x' {
+ }
+ for range 1.0 /* ERROR "cannot range over 1.0 (untyped float constant 1)" */ {
+ }
+
+ var i int
+ var mi MyInt
+ for i := range 10 {
+ _ = i
+ }
+ for i = range 10 {
+ _ = i
+ }
+ for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ := range 10 {
+ _, _ = i, j
+ }
+ for i = range MyInt /* ERROR "cannot use MyInt(10) (constant 10 of type MyInt) as int value in range clause" */ (10) {
+ _ = i
+ }
+ for mi := range MyInt(10) {
+ _ = mi
+ }
+ for mi = range MyInt(10) {
+ _ = mi
+ }
+}
+
+func _[T int | string](x T) {
+ for range x /* ERROR "cannot range over x (variable of type T constrained by int | string): no core type" */ {
+ }
+}
+
+func _[T int | int64](x T) {
+ for range x /* ERROR "cannot range over x (variable of type T constrained by int | int64): no core type" */ {
+ }
+}
+
+func _[T ~int](x T) {
+ for range x { // ok
+ }
+}
+
+func issue65133() {
+ for range maxInt {
+ }
+ for range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 {
+ }
+ for range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ {
+ }
+
+ for i := range maxInt {
+ _ = i
+ }
+ for i := range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 {
+ _ = i
+ }
+ for i := range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ {
+ _ = i
+ }
+
+ var i int
+ _ = i
+ for i = range maxInt {
+ }
+ for i = range maxInt /* ERROR "cannot use maxInt + 1 (untyped int constant 9223372036854775808) as int value in range clause (overflows)" */ + 1 {
+ }
+ for i = range maxUint /* ERROR "cannot use maxUint (untyped int constant 18446744073709551615) as int value in range clause (overflows)" */ {
+ }
+
+ var j uint
+ _ = j
+ for j = range maxInt {
+ }
+ for j = range maxInt + 1 {
+ }
+ for j = range maxUint {
+ }
+ for j = range maxUint /* ERROR "cannot use maxUint + 1 (untyped int constant 18446744073709551616) as uint value in range clause (overflows)" */ + 1 {
+ }
+
+ for range 256 {
+ }
+ for _ = range 256 {
+ }
+ for i = range 256 {
+ }
+ for i := range 256 {
+ _ = i
+ }
+
+ var u8 uint8
+ _ = u8
+ for u8 = range - /* ERROR "cannot use -1 (untyped int constant) as uint8 value in range clause (overflows)" */ 1 {
+ }
+ for u8 = range 0 {
+ }
+ for u8 = range 255 {
+ }
+ for u8 = range 256 /* ERROR "cannot use 256 (untyped int constant) as uint8 value in range clause (overflows)" */ {
+ }
+}
+
+func issue64471() {
+ for i := range 'a' {
+ var _ *rune = &i // ensure i has type rune
+ }
+}
+
+func issue66561() {
+ for range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ {
+ }
+ for range 1e3 /* ERROR "cannot range over 1e3 (untyped float constant 1000)" */ {
+ }
+ for range 1 /* ERROR "cannot range over 1 + 0i (untyped complex constant (1 + 0i))" */ + 0i {
+ }
+
+ for range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ {
+ }
+ for range 1i /* ERROR "cannot range over 1i (untyped complex constant (0 + 1i))" */ {
+ }
+
+ for i := range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ {
+ _ = i
+ }
+ for i := range 1e3 /* ERROR "cannot range over 1e3 (untyped float constant 1000)" */ {
+ _ = i
+ }
+ for i := range 1 /* ERROR "cannot range over 1 + 0i (untyped complex constant (1 + 0i))" */ + 0i {
+ _ = i
+ }
+
+ for i := range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ {
+ _ = i
+ }
+ for i := range 1i /* ERROR "cannot range over 1i (untyped complex constant (0 + 1i))" */ {
+ _ = i
+ }
+
+ var j float64
+ _ = j
+ for j /* ERROR "cannot use iteration variable of type float64" */ = range 1 {
+ }
+ for j = range 1.1 /* ERROR "cannot range over 1.1 (untyped float constant)" */ {
+ }
+ for j = range 10.0 /* ERROR "cannot range over 10.0 (untyped float constant 10)" */ {
+ }
+
+ // There shouldn't be assignment errors if there are more iteration variables than permitted.
+ var i int
+ _ = i
+ for i, j /* ERROR "range over 10 (untyped int constant) permits only one iteration variable" */ = range 10 {
+ }
+}
+
+func issue67027() {
+ var i float64
+ _ = i
+ for i /* ERROR "cannot use iteration variable of type float64" */ = range 10 {
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-empty b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-empty
new file mode 100644
index 0000000000000000000000000000000000000000..851ccc51236947fa0fe8527ea14204f1566ee171
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-empty
@@ -0,0 +1,2 @@
+
+0 0 0 0 0 0
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-ppc64 b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-ppc64
new file mode 100644
index 0000000000000000000000000000000000000000..a8d4979d121f71266b57bc33c0e55e2b8a679cbb
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/bigar-ppc64 differ
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec
new file mode 100644
index 0000000000000000000000000000000000000000..810e21a0dfc78b29f2dfc5afe2bc588763177ea6
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc32-aix-dwarf2-exec differ
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec
new file mode 100644
index 0000000000000000000000000000000000000000..707d01ebd43487081a620250a213dcdba7a80379
Binary files /dev/null and b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/gcc-ppc64-aix-dwarf2-exec differ
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/hello.c b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/hello.c
new file mode 100644
index 0000000000000000000000000000000000000000..34d9ee79234ef29ea03feeb69d220b0796295636
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/hello.c
@@ -0,0 +1,7 @@
+#include
+
+void
+main(int argc, char *argv[])
+{
+ printf("hello, world\n");
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printbye.c b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printbye.c
new file mode 100644
index 0000000000000000000000000000000000000000..904507998ab1b9948129a3b74a285ed43e6320ec
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printbye.c
@@ -0,0 +1,5 @@
+#include
+
+void printbye(){
+ printf("Goodbye\n");
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printhello.c b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printhello.c
new file mode 100644
index 0000000000000000000000000000000000000000..182aa09728abc457d8eab9c25ccb481a0f0649ff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/xcoff/testdata/printhello.c
@@ -0,0 +1,5 @@
+#include
+
+void printhello(){
+ printf("Helloworld\n");
+}
diff --git a/platform/dbops/binaries/go/go/src/internal/zstd/testdata/1890a371.gettysburg.txt-100x.zst b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/1890a371.gettysburg.txt-100x.zst
new file mode 100644
index 0000000000000000000000000000000000000000..463e42d879efa35e828d7044fd5bafb29b83b457
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/1890a371.gettysburg.txt-100x.zst
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:02cf0b8550e9228b9ce44f11413277954fbedf59a07a935d46785a1fec7f2751
+size 826
diff --git a/platform/dbops/binaries/go/go/src/internal/zstd/testdata/README b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/README
new file mode 100644
index 0000000000000000000000000000000000000000..1a6dbb3a8f8c5c3fec7be52f7023cc1c1654182e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/README
@@ -0,0 +1,10 @@
+This directory holds files for testing zstd.NewReader.
+
+Each one is a Zstandard compressed file named as hash.arbitrary-name.zst,
+where hash is the first eight hexadecimal digits of the SHA256 hash
+of the expected uncompressed content:
+
+ zstd -d < 1890a371.gettysburg.txt-100x.zst | sha256sum | head -c 8
+ 1890a371
+
+The test uses hash value to verify decompression result.
diff --git a/platform/dbops/binaries/go/go/src/internal/zstd/testdata/f2a8e35c.helloworld-11000x.zst b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/f2a8e35c.helloworld-11000x.zst
new file mode 100644
index 0000000000000000000000000000000000000000..1f86b421f01fadc50984246cc2503fd00ee1050f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/f2a8e35c.helloworld-11000x.zst
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ca79a0a0124aafb0c2a02bf8c6f6fee52533f780a3ea6237835e0043924b0501
+size 47
diff --git a/platform/dbops/binaries/go/go/src/internal/zstd/testdata/fcf30b99.zero-dictionary-ids.zst b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/fcf30b99.zero-dictionary-ids.zst
new file mode 100644
index 0000000000000000000000000000000000000000..d4290347d859e600dcf0796078aa2ceb7f90ee42
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/internal/zstd/testdata/fcf30b99.zero-dictionary-ids.zst
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e3df579972ae147447edaa04f782853ec3a7bb630c8ed531df729c426ed6f098
+size 64
diff --git a/platform/dbops/binaries/go/go/src/io/fs/example_test.go b/platform/dbops/binaries/go/go/src/io/fs/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c9027034c4a5b571128b1f7f05e91e9092dcf6ab
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/example_test.go
@@ -0,0 +1,25 @@
+// 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 fs_test
+
+import (
+ "fmt"
+ "io/fs"
+ "log"
+ "os"
+)
+
+func ExampleWalkDir() {
+ root := "/usr/local/go/bin"
+ fileSystem := os.DirFS(root)
+
+ fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println(path)
+ return nil
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/format.go b/platform/dbops/binaries/go/go/src/io/fs/format.go
new file mode 100644
index 0000000000000000000000000000000000000000..60b40df1e83e2094db3b9c097c9804173381ab3f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/format.go
@@ -0,0 +1,76 @@
+// 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 fs
+
+import (
+ "time"
+)
+
+// FormatFileInfo returns a formatted version of info for human readability.
+// Implementations of [FileInfo] can call this from a String method.
+// The output for a file named "hello.go", 100 bytes, mode 0o644, created
+// January 1, 1970 at noon is
+//
+// -rw-r--r-- 100 1970-01-01 12:00:00 hello.go
+func FormatFileInfo(info FileInfo) string {
+ name := info.Name()
+ b := make([]byte, 0, 40+len(name))
+ b = append(b, info.Mode().String()...)
+ b = append(b, ' ')
+
+ size := info.Size()
+ var usize uint64
+ if size >= 0 {
+ usize = uint64(size)
+ } else {
+ b = append(b, '-')
+ usize = uint64(-size)
+ }
+ var buf [20]byte
+ i := len(buf) - 1
+ for usize >= 10 {
+ q := usize / 10
+ buf[i] = byte('0' + usize - q*10)
+ i--
+ usize = q
+ }
+ buf[i] = byte('0' + usize)
+ b = append(b, buf[i:]...)
+ b = append(b, ' ')
+
+ b = append(b, info.ModTime().Format(time.DateTime)...)
+ b = append(b, ' ')
+
+ b = append(b, name...)
+ if info.IsDir() {
+ b = append(b, '/')
+ }
+
+ return string(b)
+}
+
+// FormatDirEntry returns a formatted version of dir for human readability.
+// Implementations of [DirEntry] can call this from a String method.
+// The outputs for a directory named subdir and a file named hello.go are:
+//
+// d subdir/
+// - hello.go
+func FormatDirEntry(dir DirEntry) string {
+ name := dir.Name()
+ b := make([]byte, 0, 5+len(name))
+
+ // The Type method does not return any permission bits,
+ // so strip them from the string.
+ mode := dir.Type().String()
+ mode = mode[:len(mode)-9]
+
+ b = append(b, mode...)
+ b = append(b, ' ')
+ b = append(b, name...)
+ if dir.IsDir() {
+ b = append(b, '/')
+ }
+ return string(b)
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/format_test.go b/platform/dbops/binaries/go/go/src/io/fs/format_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a5f5066f36d0c30a6bf84a5cf960d0510c998890
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/format_test.go
@@ -0,0 +1,123 @@
+// 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 fs_test
+
+import (
+ . "io/fs"
+ "testing"
+ "time"
+)
+
+// formatTest implements FileInfo to test FormatFileInfo,
+// and implements DirEntry to test FormatDirEntry.
+type formatTest struct {
+ name string
+ size int64
+ mode FileMode
+ modTime time.Time
+ isDir bool
+}
+
+func (fs *formatTest) Name() string {
+ return fs.name
+}
+
+func (fs *formatTest) Size() int64 {
+ return fs.size
+}
+
+func (fs *formatTest) Mode() FileMode {
+ return fs.mode
+}
+
+func (fs *formatTest) ModTime() time.Time {
+ return fs.modTime
+}
+
+func (fs *formatTest) IsDir() bool {
+ return fs.isDir
+}
+
+func (fs *formatTest) Sys() any {
+ return nil
+}
+
+func (fs *formatTest) Type() FileMode {
+ return fs.mode.Type()
+}
+
+func (fs *formatTest) Info() (FileInfo, error) {
+ return fs, nil
+}
+
+var formatTests = []struct {
+ input formatTest
+ wantFileInfo string
+ wantDirEntry string
+}{
+ {
+ formatTest{
+ name: "hello.go",
+ size: 100,
+ mode: 0o644,
+ modTime: time.Date(1970, time.January, 1, 12, 0, 0, 0, time.UTC),
+ isDir: false,
+ },
+ "-rw-r--r-- 100 1970-01-01 12:00:00 hello.go",
+ "- hello.go",
+ },
+ {
+ formatTest{
+ name: "home/gopher",
+ size: 0,
+ mode: ModeDir | 0o755,
+ modTime: time.Date(1970, time.January, 1, 12, 0, 0, 0, time.UTC),
+ isDir: true,
+ },
+ "drwxr-xr-x 0 1970-01-01 12:00:00 home/gopher/",
+ "d home/gopher/",
+ },
+ {
+ formatTest{
+ name: "big",
+ size: 0x7fffffffffffffff,
+ mode: ModeIrregular | 0o644,
+ modTime: time.Date(1970, time.January, 1, 12, 0, 0, 0, time.UTC),
+ isDir: false,
+ },
+ "?rw-r--r-- 9223372036854775807 1970-01-01 12:00:00 big",
+ "? big",
+ },
+ {
+ formatTest{
+ name: "small",
+ size: -0x8000000000000000,
+ mode: ModeSocket | ModeSetuid | 0o644,
+ modTime: time.Date(1970, time.January, 1, 12, 0, 0, 0, time.UTC),
+ isDir: false,
+ },
+ "Surw-r--r-- -9223372036854775808 1970-01-01 12:00:00 small",
+ "S small",
+ },
+}
+
+func TestFormatFileInfo(t *testing.T) {
+ for i, test := range formatTests {
+ got := FormatFileInfo(&test.input)
+ if got != test.wantFileInfo {
+ t.Errorf("%d: FormatFileInfo(%#v) = %q, want %q", i, test.input, got, test.wantFileInfo)
+ }
+ }
+}
+
+func TestFormatDirEntry(t *testing.T) {
+ for i, test := range formatTests {
+ got := FormatDirEntry(&test.input)
+ if got != test.wantDirEntry {
+ t.Errorf("%d: FormatDirEntry(%#v) = %q, want %q", i, test.input, got, test.wantDirEntry)
+ }
+ }
+
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/fs.go b/platform/dbops/binaries/go/go/src/io/fs/fs.go
new file mode 100644
index 0000000000000000000000000000000000000000..6891d75a0e838ad5f4b7cf97595af05d57a28214
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/fs.go
@@ -0,0 +1,264 @@
+// 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 fs defines basic interfaces to a file system.
+// A file system can be provided by the host operating system
+// but also by other packages.
+//
+// See the [testing/fstest] package for support with testing
+// implementations of file systems.
+package fs
+
+import (
+ "internal/oserror"
+ "time"
+ "unicode/utf8"
+)
+
+// An FS provides access to a hierarchical file system.
+//
+// The FS interface is the minimum implementation required of the file system.
+// A file system may implement additional interfaces,
+// such as [ReadFileFS], to provide additional or optimized functionality.
+//
+// [testing/fstest.TestFS] may be used to test implementations of an FS for
+// correctness.
+type FS interface {
+ // Open opens the named file.
+ //
+ // When Open returns an error, it should be of type *PathError
+ // with the Op field set to "open", the Path field set to name,
+ // and the Err field describing the problem.
+ //
+ // Open should reject attempts to open names that do not satisfy
+ // ValidPath(name), returning a *PathError with Err set to
+ // ErrInvalid or ErrNotExist.
+ Open(name string) (File, error)
+}
+
+// ValidPath reports whether the given path name
+// is valid for use in a call to Open.
+//
+// Path names passed to open are UTF-8-encoded,
+// unrooted, slash-separated sequences of path elements, like “x/y/z”.
+// Path names must not contain an element that is “.” or “..” or the empty string,
+// except for the special case that the root directory is named “.”.
+// Paths must not start or end with a slash: “/x” and “x/” are invalid.
+//
+// Note that paths are slash-separated on all systems, even Windows.
+// Paths containing other characters such as backslash and colon
+// are accepted as valid, but those characters must never be
+// interpreted by an [FS] implementation as path element separators.
+func ValidPath(name string) bool {
+ if !utf8.ValidString(name) {
+ return false
+ }
+
+ if name == "." {
+ // special case
+ return true
+ }
+
+ // Iterate over elements in name, checking each.
+ for {
+ i := 0
+ for i < len(name) && name[i] != '/' {
+ i++
+ }
+ elem := name[:i]
+ if elem == "" || elem == "." || elem == ".." {
+ return false
+ }
+ if i == len(name) {
+ return true // reached clean ending
+ }
+ name = name[i+1:]
+ }
+}
+
+// A File provides access to a single file.
+// The File interface is the minimum implementation required of the file.
+// Directory files should also implement [ReadDirFile].
+// A file may implement [io.ReaderAt] or [io.Seeker] as optimizations.
+type File interface {
+ Stat() (FileInfo, error)
+ Read([]byte) (int, error)
+ Close() error
+}
+
+// A DirEntry is an entry read from a directory
+// (using the [ReadDir] function or a [ReadDirFile]'s ReadDir method).
+type DirEntry interface {
+ // Name returns the name of the file (or subdirectory) described by the entry.
+ // This name is only the final element of the path (the base name), not the entire path.
+ // For example, Name would return "hello.go" not "home/gopher/hello.go".
+ Name() string
+
+ // IsDir reports whether the entry describes a directory.
+ IsDir() bool
+
+ // Type returns the type bits for the entry.
+ // The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
+ Type() FileMode
+
+ // Info returns the FileInfo for the file or subdirectory described by the entry.
+ // The returned FileInfo may be from the time of the original directory read
+ // or from the time of the call to Info. If the file has been removed or renamed
+ // since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
+ // If the entry denotes a symbolic link, Info reports the information about the link itself,
+ // not the link's target.
+ Info() (FileInfo, error)
+}
+
+// A ReadDirFile is a directory file whose entries can be read with the ReadDir method.
+// Every directory file should implement this interface.
+// (It is permissible for any file to implement this interface,
+// but if so ReadDir should return an error for non-directories.)
+type ReadDirFile interface {
+ File
+
+ // ReadDir reads the contents of the directory and returns
+ // a slice of up to n DirEntry values in directory order.
+ // Subsequent calls on the same file will yield further DirEntry values.
+ //
+ // If n > 0, ReadDir returns at most n DirEntry structures.
+ // In this case, if ReadDir returns an empty slice, it will return
+ // a non-nil error explaining why.
+ // At the end of a directory, the error is io.EOF.
+ // (ReadDir must return io.EOF itself, not an error wrapping io.EOF.)
+ //
+ // If n <= 0, ReadDir returns all the DirEntry values from the directory
+ // in a single slice. In this case, if ReadDir succeeds (reads all the way
+ // to the end of the directory), it returns the slice and a nil error.
+ // If it encounters an error before the end of the directory,
+ // ReadDir returns the DirEntry list read until that point and a non-nil error.
+ ReadDir(n int) ([]DirEntry, error)
+}
+
+// Generic file system errors.
+// Errors returned by file systems can be tested against these errors
+// using [errors.Is].
+var (
+ ErrInvalid = errInvalid() // "invalid argument"
+ ErrPermission = errPermission() // "permission denied"
+ ErrExist = errExist() // "file already exists"
+ ErrNotExist = errNotExist() // "file does not exist"
+ ErrClosed = errClosed() // "file already closed"
+)
+
+func errInvalid() error { return oserror.ErrInvalid }
+func errPermission() error { return oserror.ErrPermission }
+func errExist() error { return oserror.ErrExist }
+func errNotExist() error { return oserror.ErrNotExist }
+func errClosed() error { return oserror.ErrClosed }
+
+// A FileInfo describes a file and is returned by [Stat].
+type FileInfo interface {
+ Name() string // base name of the file
+ Size() int64 // length in bytes for regular files; system-dependent for others
+ Mode() FileMode // file mode bits
+ ModTime() time.Time // modification time
+ IsDir() bool // abbreviation for Mode().IsDir()
+ Sys() any // underlying data source (can return nil)
+}
+
+// A FileMode represents a file's mode and permission bits.
+// The bits have the same definition on all systems, so that
+// information about files can be moved from one system
+// to another portably. Not all bits apply to all systems.
+// The only required bit is [ModeDir] for directories.
+type FileMode uint32
+
+// The defined file mode bits are the most significant bits of the [FileMode].
+// The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
+// The values of these bits should be considered part of the public API and
+// may be used in wire protocols or disk representations: they must not be
+// changed, although new bits might be added.
+const (
+ // The single letters are the abbreviations
+ // used by the String method's formatting.
+ ModeDir FileMode = 1 << (32 - 1 - iota) // d: is a directory
+ ModeAppend // a: append-only
+ ModeExclusive // l: exclusive use
+ ModeTemporary // T: temporary file; Plan 9 only
+ ModeSymlink // L: symbolic link
+ ModeDevice // D: device file
+ ModeNamedPipe // p: named pipe (FIFO)
+ ModeSocket // S: Unix domain socket
+ ModeSetuid // u: setuid
+ ModeSetgid // g: setgid
+ ModeCharDevice // c: Unix character device, when ModeDevice is set
+ ModeSticky // t: sticky
+ ModeIrregular // ?: non-regular file; nothing else is known about this file
+
+ // Mask for the type bits. For regular files, none will be set.
+ ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular
+
+ ModePerm FileMode = 0777 // Unix permission bits
+)
+
+func (m FileMode) String() string {
+ const str = "dalTLDpSugct?"
+ var buf [32]byte // Mode is uint32.
+ w := 0
+ for i, c := range str {
+ if m&(1< pathSeparatorsLimit {
+ return nil, path.ErrBadPattern
+ }
+ if fsys, ok := fsys.(GlobFS); ok {
+ return fsys.Glob(pattern)
+ }
+
+ // Check pattern is well-formed.
+ if _, err := path.Match(pattern, ""); err != nil {
+ return nil, err
+ }
+ if !hasMeta(pattern) {
+ if _, err = Stat(fsys, pattern); err != nil {
+ return nil, nil
+ }
+ return []string{pattern}, nil
+ }
+
+ dir, file := path.Split(pattern)
+ dir = cleanGlobPath(dir)
+
+ if !hasMeta(dir) {
+ return glob(fsys, dir, file, nil)
+ }
+
+ // Prevent infinite recursion. See issue 15879.
+ if dir == pattern {
+ return nil, path.ErrBadPattern
+ }
+
+ var m []string
+ m, err = globWithLimit(fsys, dir, depth+1)
+ if err != nil {
+ return nil, err
+ }
+ for _, d := range m {
+ matches, err = glob(fsys, d, file, matches)
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// cleanGlobPath prepares path for glob matching.
+func cleanGlobPath(path string) string {
+ switch path {
+ case "":
+ return "."
+ default:
+ return path[0 : len(path)-1] // chop off trailing separator
+ }
+}
+
+// glob searches for files matching pattern in the directory dir
+// and appends them to matches, returning the updated slice.
+// If the directory cannot be opened, glob returns the existing matches.
+// New matches are added in lexicographical order.
+func glob(fs FS, dir, pattern string, matches []string) (m []string, e error) {
+ m = matches
+ infos, err := ReadDir(fs, dir)
+ if err != nil {
+ return // ignore I/O error
+ }
+
+ for _, info := range infos {
+ n := info.Name()
+ matched, err := path.Match(pattern, n)
+ if err != nil {
+ return m, err
+ }
+ if matched {
+ m = append(m, path.Join(dir, n))
+ }
+ }
+ return
+}
+
+// hasMeta reports whether path contains any of the magic characters
+// recognized by path.Match.
+func hasMeta(path string) bool {
+ for i := 0; i < len(path); i++ {
+ switch path[i] {
+ case '*', '?', '[', '\\':
+ return true
+ }
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/glob_test.go b/platform/dbops/binaries/go/go/src/io/fs/glob_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d052eab371366f00a17692774c87fec260b89946
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/glob_test.go
@@ -0,0 +1,97 @@
+// 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 fs_test
+
+import (
+ . "io/fs"
+ "os"
+ "path"
+ "strings"
+ "testing"
+)
+
+var globTests = []struct {
+ fs FS
+ pattern, result string
+}{
+ {os.DirFS("."), "glob.go", "glob.go"},
+ {os.DirFS("."), "gl?b.go", "glob.go"},
+ {os.DirFS("."), `gl\ob.go`, "glob.go"},
+ {os.DirFS("."), "*", "glob.go"},
+ {os.DirFS(".."), "*/glob.go", "fs/glob.go"},
+}
+
+func TestGlob(t *testing.T) {
+ for _, tt := range globTests {
+ matches, err := Glob(tt.fs, tt.pattern)
+ if err != nil {
+ t.Errorf("Glob error for %q: %s", tt.pattern, err)
+ continue
+ }
+ if !contains(matches, tt.result) {
+ t.Errorf("Glob(%#q) = %#v want %v", tt.pattern, matches, tt.result)
+ }
+ }
+ for _, pattern := range []string{"no_match", "../*/no_match", `\*`} {
+ matches, err := Glob(os.DirFS("."), pattern)
+ if err != nil {
+ t.Errorf("Glob error for %q: %s", pattern, err)
+ continue
+ }
+ if len(matches) != 0 {
+ t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
+ }
+ }
+}
+
+func TestGlobError(t *testing.T) {
+ bad := []string{`[]`, `nonexist/[]`}
+ for _, pattern := range bad {
+ _, err := Glob(os.DirFS("."), pattern)
+ if err != path.ErrBadPattern {
+ t.Errorf("Glob(fs, %#q) returned err=%v, want path.ErrBadPattern", pattern, err)
+ }
+ }
+}
+
+func TestCVE202230630(t *testing.T) {
+ // Prior to CVE-2022-30630, a stack exhaustion would occur given a large
+ // number of separators. There is now a limit of 10,000.
+ _, err := Glob(os.DirFS("."), "/*"+strings.Repeat("/", 10001))
+ if err != path.ErrBadPattern {
+ t.Fatalf("Glob returned err=%v, want %v", err, path.ErrBadPattern)
+ }
+}
+
+// contains reports whether vector contains the string s.
+func contains(vector []string, s string) bool {
+ for _, elem := range vector {
+ if elem == s {
+ return true
+ }
+ }
+ return false
+}
+
+type globOnly struct{ GlobFS }
+
+func (globOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestGlobMethod(t *testing.T) {
+ check := func(desc string, names []string, err error) {
+ t.Helper()
+ if err != nil || len(names) != 1 || names[0] != "hello.txt" {
+ t.Errorf("Glob(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt"})
+ }
+ }
+
+ // Test that ReadDir uses the method when present.
+ names, err := Glob(globOnly{testFsys}, "*.txt")
+ check("readDirOnly", names, err)
+
+ // Test that ReadDir uses Open when the method is not present.
+ names, err = Glob(openOnly{testFsys}, "*.txt")
+ check("openOnly", names, err)
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/readdir.go b/platform/dbops/binaries/go/go/src/io/fs/readdir.go
new file mode 100644
index 0000000000000000000000000000000000000000..22ced48073be7a0495202ac140cee1caa4a2943d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/readdir.go
@@ -0,0 +1,81 @@
+// 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 fs
+
+import (
+ "errors"
+ "sort"
+)
+
+// ReadDirFS is the interface implemented by a file system
+// that provides an optimized implementation of [ReadDir].
+type ReadDirFS interface {
+ FS
+
+ // ReadDir reads the named directory
+ // and returns a list of directory entries sorted by filename.
+ ReadDir(name string) ([]DirEntry, error)
+}
+
+// ReadDir reads the named directory
+// and returns a list of directory entries sorted by filename.
+//
+// If fs implements [ReadDirFS], ReadDir calls fs.ReadDir.
+// Otherwise ReadDir calls fs.Open and uses ReadDir and Close
+// on the returned file.
+func ReadDir(fsys FS, name string) ([]DirEntry, error) {
+ if fsys, ok := fsys.(ReadDirFS); ok {
+ return fsys.ReadDir(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ dir, ok := file.(ReadDirFile)
+ if !ok {
+ return nil, &PathError{Op: "readdir", Path: name, Err: errors.New("not implemented")}
+ }
+
+ list, err := dir.ReadDir(-1)
+ sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
+ return list, err
+}
+
+// dirInfo is a DirEntry based on a FileInfo.
+type dirInfo struct {
+ fileInfo FileInfo
+}
+
+func (di dirInfo) IsDir() bool {
+ return di.fileInfo.IsDir()
+}
+
+func (di dirInfo) Type() FileMode {
+ return di.fileInfo.Mode().Type()
+}
+
+func (di dirInfo) Info() (FileInfo, error) {
+ return di.fileInfo, nil
+}
+
+func (di dirInfo) Name() string {
+ return di.fileInfo.Name()
+}
+
+func (di dirInfo) String() string {
+ return FormatDirEntry(di)
+}
+
+// FileInfoToDirEntry returns a [DirEntry] that returns information from info.
+// If info is nil, FileInfoToDirEntry returns nil.
+func FileInfoToDirEntry(info FileInfo) DirEntry {
+ if info == nil {
+ return nil
+ }
+ return dirInfo{fileInfo: info}
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/readdir_test.go b/platform/dbops/binaries/go/go/src/io/fs/readdir_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4c409ae7a010e2cb9c202a2431674de39a235f3a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/readdir_test.go
@@ -0,0 +1,111 @@
+// 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 fs_test
+
+import (
+ "errors"
+ . "io/fs"
+ "os"
+ "testing"
+ "testing/fstest"
+ "time"
+)
+
+type readDirOnly struct{ ReadDirFS }
+
+func (readDirOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestReadDir(t *testing.T) {
+ check := func(desc string, dirs []DirEntry, err error) {
+ t.Helper()
+ if err != nil || len(dirs) != 2 || dirs[0].Name() != "hello.txt" || dirs[1].Name() != "sub" {
+ var names []string
+ for _, d := range dirs {
+ names = append(names, d.Name())
+ }
+ t.Errorf("ReadDir(%s) = %v, %v, want %v, nil", desc, names, err, []string{"hello.txt", "sub"})
+ }
+ }
+
+ // Test that ReadDir uses the method when present.
+ dirs, err := ReadDir(readDirOnly{testFsys}, ".")
+ check("readDirOnly", dirs, err)
+
+ // Test that ReadDir uses Open when the method is not present.
+ dirs, err = ReadDir(openOnly{testFsys}, ".")
+ check("openOnly", dirs, err)
+
+ // Test that ReadDir on Sub of . works (sub_test checks non-trivial subs).
+ sub, err := Sub(testFsys, ".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dirs, err = ReadDir(sub, ".")
+ check("sub(.)", dirs, err)
+}
+
+func TestFileInfoToDirEntry(t *testing.T) {
+ testFs := fstest.MapFS{
+ "notadir.txt": {
+ Data: []byte("hello, world"),
+ Mode: 0,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
+ "adir": {
+ Data: nil,
+ Mode: os.ModeDir,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
+ }
+
+ tests := []struct {
+ path string
+ wantMode FileMode
+ wantDir bool
+ }{
+ {path: "notadir.txt", wantMode: 0, wantDir: false},
+ {path: "adir", wantMode: os.ModeDir, wantDir: true},
+ }
+
+ for _, test := range tests {
+ test := test
+ t.Run(test.path, func(t *testing.T) {
+ fi, err := Stat(testFs, test.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ dirEntry := FileInfoToDirEntry(fi)
+ if g, w := dirEntry.Type(), test.wantMode; g != w {
+ t.Errorf("FileMode mismatch: got=%v, want=%v", g, w)
+ }
+ if g, w := dirEntry.Name(), test.path; g != w {
+ t.Errorf("Name mismatch: got=%v, want=%v", g, w)
+ }
+ if g, w := dirEntry.IsDir(), test.wantDir; g != w {
+ t.Errorf("IsDir mismatch: got=%v, want=%v", g, w)
+ }
+ })
+ }
+}
+
+func errorPath(err error) string {
+ var perr *PathError
+ if !errors.As(err, &perr) {
+ return ""
+ }
+ return perr.Path
+}
+
+func TestReadDirPath(t *testing.T) {
+ fsys := os.DirFS(t.TempDir())
+ _, err1 := ReadDir(fsys, "non-existent")
+ _, err2 := ReadDir(struct{ FS }{fsys}, "non-existent")
+ if s1, s2 := errorPath(err1), errorPath(err2); s1 != s2 {
+ t.Fatalf("s1: %s != s2: %s", s1, s2)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/readfile.go b/platform/dbops/binaries/go/go/src/io/fs/readfile.go
new file mode 100644
index 0000000000000000000000000000000000000000..41ca5bfcf6eb0020134583054a20870b5ef50bf9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/readfile.go
@@ -0,0 +1,66 @@
+// 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 fs
+
+import "io"
+
+// ReadFileFS is the interface implemented by a file system
+// that provides an optimized implementation of [ReadFile].
+type ReadFileFS interface {
+ FS
+
+ // ReadFile reads the named file and returns its contents.
+ // A successful call returns a nil error, not io.EOF.
+ // (Because ReadFile reads the whole file, the expected EOF
+ // from the final Read is not treated as an error to be reported.)
+ //
+ // The caller is permitted to modify the returned byte slice.
+ // This method should return a copy of the underlying data.
+ ReadFile(name string) ([]byte, error)
+}
+
+// ReadFile reads the named file from the file system fs and returns its contents.
+// A successful call returns a nil error, not [io.EOF].
+// (Because ReadFile reads the whole file, the expected EOF
+// from the final Read is not treated as an error to be reported.)
+//
+// If fs implements [ReadFileFS], ReadFile calls fs.ReadFile.
+// Otherwise ReadFile calls fs.Open and uses Read and Close
+// on the returned [File].
+func ReadFile(fsys FS, name string) ([]byte, error) {
+ if fsys, ok := fsys.(ReadFileFS); ok {
+ return fsys.ReadFile(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ var size int
+ if info, err := file.Stat(); err == nil {
+ size64 := info.Size()
+ if int64(int(size64)) == size64 {
+ size = int(size64)
+ }
+ }
+
+ data := make([]byte, 0, size+1)
+ for {
+ if len(data) >= cap(data) {
+ d := append(data[:cap(data)], 0)
+ data = d[:len(data)]
+ }
+ n, err := file.Read(data[len(data):cap(data)])
+ data = data[:len(data)+n]
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ }
+ return data, err
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/readfile_test.go b/platform/dbops/binaries/go/go/src/io/fs/readfile_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3c521f61427c2ba1796d314925c1699fc5e4baf3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/readfile_test.go
@@ -0,0 +1,69 @@
+// 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 fs_test
+
+import (
+ . "io/fs"
+ "os"
+ "testing"
+ "testing/fstest"
+ "time"
+)
+
+var testFsys = fstest.MapFS{
+ "hello.txt": {
+ Data: []byte("hello, world"),
+ Mode: 0456,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
+ "sub/goodbye.txt": {
+ Data: []byte("goodbye, world"),
+ Mode: 0456,
+ ModTime: time.Now(),
+ Sys: &sysValue,
+ },
+}
+
+var sysValue int
+
+type readFileOnly struct{ ReadFileFS }
+
+func (readFileOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+type openOnly struct{ FS }
+
+func TestReadFile(t *testing.T) {
+ // Test that ReadFile uses the method when present.
+ data, err := ReadFile(readFileOnly{testFsys}, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(readFileOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
+
+ // Test that ReadFile uses Open when the method is not present.
+ data, err = ReadFile(openOnly{testFsys}, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(openOnly, "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
+
+ // Test that ReadFile on Sub of . works (sub_test checks non-trivial subs).
+ sub, err := Sub(testFsys, ".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err = ReadFile(sub, "hello.txt")
+ if string(data) != "hello, world" || err != nil {
+ t.Fatalf(`ReadFile(sub(.), "hello.txt") = %q, %v, want %q, nil`, data, err, "hello, world")
+ }
+}
+
+func TestReadFilePath(t *testing.T) {
+ fsys := os.DirFS(t.TempDir())
+ _, err1 := ReadFile(fsys, "non-existent")
+ _, err2 := ReadFile(struct{ FS }{fsys}, "non-existent")
+ if s1, s2 := errorPath(err1), errorPath(err2); s1 != s2 {
+ t.Fatalf("s1: %s != s2: %s", s1, s2)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/stat.go b/platform/dbops/binaries/go/go/src/io/fs/stat.go
new file mode 100644
index 0000000000000000000000000000000000000000..bbb91c2eae669123b7305d4a164b23bd12721f0b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/stat.go
@@ -0,0 +1,31 @@
+// 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 fs
+
+// A StatFS is a file system with a Stat method.
+type StatFS interface {
+ FS
+
+ // Stat returns a FileInfo describing the file.
+ // If there is an error, it should be of type *PathError.
+ Stat(name string) (FileInfo, error)
+}
+
+// Stat returns a [FileInfo] describing the named file from the file system.
+//
+// If fs implements [StatFS], Stat calls fs.Stat.
+// Otherwise, Stat opens the [File] to stat it.
+func Stat(fsys FS, name string) (FileInfo, error) {
+ if fsys, ok := fsys.(StatFS); ok {
+ return fsys.Stat(name)
+ }
+
+ file, err := fsys.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ return file.Stat()
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/stat_test.go b/platform/dbops/binaries/go/go/src/io/fs/stat_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e312b6fbd917e40f85a388fa08759ea477f0983f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/stat_test.go
@@ -0,0 +1,36 @@
+// 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 fs_test
+
+import (
+ "fmt"
+ . "io/fs"
+ "testing"
+)
+
+type statOnly struct{ StatFS }
+
+func (statOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestStat(t *testing.T) {
+ check := func(desc string, info FileInfo, err error) {
+ t.Helper()
+ if err != nil || info == nil || info.Mode() != 0456 {
+ infoStr := ""
+ if info != nil {
+ infoStr = fmt.Sprintf("FileInfo(Mode: %#o)", info.Mode())
+ }
+ t.Fatalf("Stat(%s) = %v, %v, want Mode:0456, nil", desc, infoStr, err)
+ }
+ }
+
+ // Test that Stat uses the method when present.
+ info, err := Stat(statOnly{testFsys}, "hello.txt")
+ check("statOnly", info, err)
+
+ // Test that Stat uses Open when the method is not present.
+ info, err = Stat(openOnly{testFsys}, "hello.txt")
+ check("openOnly", info, err)
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/sub.go b/platform/dbops/binaries/go/go/src/io/fs/sub.go
new file mode 100644
index 0000000000000000000000000000000000000000..9999e63b26f2c3b843d0679d0520d068c03952f9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/sub.go
@@ -0,0 +1,138 @@
+// 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 fs
+
+import (
+ "errors"
+ "path"
+)
+
+// A SubFS is a file system with a Sub method.
+type SubFS interface {
+ FS
+
+ // Sub returns an FS corresponding to the subtree rooted at dir.
+ Sub(dir string) (FS, error)
+}
+
+// Sub returns an [FS] corresponding to the subtree rooted at fsys's dir.
+//
+// If dir is ".", Sub returns fsys unchanged.
+// Otherwise, if fs implements [SubFS], Sub returns fsys.Sub(dir).
+// Otherwise, Sub returns a new [FS] implementation sub that,
+// in effect, implements sub.Open(name) as fsys.Open(path.Join(dir, name)).
+// The implementation also translates calls to ReadDir, ReadFile, and Glob appropriately.
+//
+// Note that Sub(os.DirFS("/"), "prefix") is equivalent to os.DirFS("/prefix")
+// and that neither of them guarantees to avoid operating system
+// accesses outside "/prefix", because the implementation of [os.DirFS]
+// does not check for symbolic links inside "/prefix" that point to
+// other directories. That is, [os.DirFS] is not a general substitute for a
+// chroot-style security mechanism, and Sub does not change that fact.
+func Sub(fsys FS, dir string) (FS, error) {
+ if !ValidPath(dir) {
+ return nil, &PathError{Op: "sub", Path: dir, Err: errors.New("invalid name")}
+ }
+ if dir == "." {
+ return fsys, nil
+ }
+ if fsys, ok := fsys.(SubFS); ok {
+ return fsys.Sub(dir)
+ }
+ return &subFS{fsys, dir}, nil
+}
+
+type subFS struct {
+ fsys FS
+ dir string
+}
+
+// fullName maps name to the fully-qualified name dir/name.
+func (f *subFS) fullName(op string, name string) (string, error) {
+ if !ValidPath(name) {
+ return "", &PathError{Op: op, Path: name, Err: errors.New("invalid name")}
+ }
+ return path.Join(f.dir, name), nil
+}
+
+// shorten maps name, which should start with f.dir, back to the suffix after f.dir.
+func (f *subFS) shorten(name string) (rel string, ok bool) {
+ if name == f.dir {
+ return ".", true
+ }
+ if len(name) >= len(f.dir)+2 && name[len(f.dir)] == '/' && name[:len(f.dir)] == f.dir {
+ return name[len(f.dir)+1:], true
+ }
+ return "", false
+}
+
+// fixErr shortens any reported names in PathErrors by stripping f.dir.
+func (f *subFS) fixErr(err error) error {
+ if e, ok := err.(*PathError); ok {
+ if short, ok := f.shorten(e.Path); ok {
+ e.Path = short
+ }
+ }
+ return err
+}
+
+func (f *subFS) Open(name string) (File, error) {
+ full, err := f.fullName("open", name)
+ if err != nil {
+ return nil, err
+ }
+ file, err := f.fsys.Open(full)
+ return file, f.fixErr(err)
+}
+
+func (f *subFS) ReadDir(name string) ([]DirEntry, error) {
+ full, err := f.fullName("read", name)
+ if err != nil {
+ return nil, err
+ }
+ dir, err := ReadDir(f.fsys, full)
+ return dir, f.fixErr(err)
+}
+
+func (f *subFS) ReadFile(name string) ([]byte, error) {
+ full, err := f.fullName("read", name)
+ if err != nil {
+ return nil, err
+ }
+ data, err := ReadFile(f.fsys, full)
+ return data, f.fixErr(err)
+}
+
+func (f *subFS) Glob(pattern string) ([]string, error) {
+ // Check pattern is well-formed.
+ if _, err := path.Match(pattern, ""); err != nil {
+ return nil, err
+ }
+ if pattern == "." {
+ return []string{"."}, nil
+ }
+
+ full := f.dir + "/" + pattern
+ list, err := Glob(f.fsys, full)
+ for i, name := range list {
+ name, ok := f.shorten(name)
+ if !ok {
+ return nil, errors.New("invalid result from inner fsys Glob: " + name + " not in " + f.dir) // can't use fmt in this package
+ }
+ list[i] = name
+ }
+ return list, f.fixErr(err)
+}
+
+func (f *subFS) Sub(dir string) (FS, error) {
+ if dir == "." {
+ return f, nil
+ }
+ full, err := f.fullName("sub", dir)
+ if err != nil {
+ return nil, err
+ }
+ return &subFS{f.fsys, full}, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/sub_test.go b/platform/dbops/binaries/go/go/src/io/fs/sub_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..451b0efb02f1856b4cf1c4f31f2b1879dfc97170
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/sub_test.go
@@ -0,0 +1,57 @@
+// 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 fs_test
+
+import (
+ . "io/fs"
+ "testing"
+)
+
+type subOnly struct{ SubFS }
+
+func (subOnly) Open(name string) (File, error) { return nil, ErrNotExist }
+
+func TestSub(t *testing.T) {
+ check := func(desc string, sub FS, err error) {
+ t.Helper()
+ if err != nil {
+ t.Errorf("Sub(sub): %v", err)
+ return
+ }
+ data, err := ReadFile(sub, "goodbye.txt")
+ if string(data) != "goodbye, world" || err != nil {
+ t.Errorf(`ReadFile(%s, "goodbye.txt" = %q, %v, want %q, nil`, desc, string(data), err, "goodbye, world")
+ }
+
+ dirs, err := ReadDir(sub, ".")
+ if err != nil || len(dirs) != 1 || dirs[0].Name() != "goodbye.txt" {
+ var names []string
+ for _, d := range dirs {
+ names = append(names, d.Name())
+ }
+ t.Errorf(`ReadDir(%s, ".") = %v, %v, want %v, nil`, desc, names, err, []string{"goodbye.txt"})
+ }
+ }
+
+ // Test that Sub uses the method when present.
+ sub, err := Sub(subOnly{testFsys}, "sub")
+ check("subOnly", sub, err)
+
+ // Test that Sub uses Open when the method is not present.
+ sub, err = Sub(openOnly{testFsys}, "sub")
+ check("openOnly", sub, err)
+
+ _, err = sub.Open("nonexist")
+ if err == nil {
+ t.Fatal("Open(nonexist): succeeded")
+ }
+ pe, ok := err.(*PathError)
+ if !ok {
+ t.Fatalf("Open(nonexist): error is %T, want *PathError", err)
+ }
+ if pe.Path != "nonexist" {
+ t.Fatalf("Open(nonexist): err.Path = %q, want %q", pe.Path, "nonexist")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/walk.go b/platform/dbops/binaries/go/go/src/io/fs/walk.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e8a8db1116fdc7aaf3cc8651904d7d8299dc863
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/walk.go
@@ -0,0 +1,128 @@
+// 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 fs
+
+import (
+ "errors"
+ "path"
+)
+
+// SkipDir is used as a return value from [WalkDirFunc] to indicate that
+// the directory named in the call is to be skipped. It is not returned
+// as an error by any function.
+var SkipDir = errors.New("skip this directory")
+
+// SkipAll is used as a return value from [WalkDirFunc] to indicate that
+// all remaining files and directories are to be skipped. It is not returned
+// as an error by any function.
+var SkipAll = errors.New("skip everything and stop the walk")
+
+// WalkDirFunc is the type of the function called by [WalkDir] to visit
+// each file or directory.
+//
+// The path argument contains the argument to [WalkDir] as a prefix.
+// That is, if WalkDir is called with root argument "dir" and finds a file
+// named "a" in that directory, the walk function will be called with
+// argument "dir/a".
+//
+// The d argument is the [DirEntry] for the named path.
+//
+// The error result returned by the function controls how [WalkDir]
+// continues. If the function returns the special value [SkipDir], WalkDir
+// skips the current directory (path if d.IsDir() is true, otherwise
+// path's parent directory). If the function returns the special value
+// [SkipAll], WalkDir skips all remaining files and directories. Otherwise,
+// if the function returns a non-nil error, WalkDir stops entirely and
+// returns that error.
+//
+// The err argument reports an error related to path, signaling that
+// [WalkDir] will not walk into that directory. The function can decide how
+// to handle that error; as described earlier, returning the error will
+// cause WalkDir to stop walking the entire tree.
+//
+// [WalkDir] calls the function with a non-nil err argument in two cases.
+//
+// First, if the initial [Stat] on the root directory fails, WalkDir
+// calls the function with path set to root, d set to nil, and err set to
+// the error from [fs.Stat].
+//
+// Second, if a directory's ReadDir method (see [ReadDirFile]) fails, WalkDir calls the
+// function with path set to the directory's path, d set to an
+// [DirEntry] describing the directory, and err set to the error from
+// ReadDir. In this second case, the function is called twice with the
+// path of the directory: the first call is before the directory read is
+// attempted and has err set to nil, giving the function a chance to
+// return [SkipDir] or [SkipAll] and avoid the ReadDir entirely. The second call
+// is after a failed ReadDir and reports the error from ReadDir.
+// (If ReadDir succeeds, there is no second call.)
+//
+// The differences between WalkDirFunc compared to [path/filepath.WalkFunc] are:
+//
+// - The second argument has type [DirEntry] instead of [FileInfo].
+// - The function is called before reading a directory, to allow [SkipDir]
+// or [SkipAll] to bypass the directory read entirely or skip all remaining
+// files and directories respectively.
+// - If a directory read fails, the function is called a second time
+// for that directory to report the error.
+type WalkDirFunc func(path string, d DirEntry, err error) error
+
+// walkDir recursively descends path, calling walkDirFn.
+func walkDir(fsys FS, name string, d DirEntry, walkDirFn WalkDirFunc) error {
+ if err := walkDirFn(name, d, nil); err != nil || !d.IsDir() {
+ if err == SkipDir && d.IsDir() {
+ // Successfully skipped directory.
+ err = nil
+ }
+ return err
+ }
+
+ dirs, err := ReadDir(fsys, name)
+ if err != nil {
+ // Second call, to report ReadDir error.
+ err = walkDirFn(name, d, err)
+ if err != nil {
+ if err == SkipDir && d.IsDir() {
+ err = nil
+ }
+ return err
+ }
+ }
+
+ for _, d1 := range dirs {
+ name1 := path.Join(name, d1.Name())
+ if err := walkDir(fsys, name1, d1, walkDirFn); err != nil {
+ if err == SkipDir {
+ break
+ }
+ return err
+ }
+ }
+ return nil
+}
+
+// WalkDir walks the file tree rooted at root, calling fn for each file or
+// directory in the tree, including root.
+//
+// All errors that arise visiting files and directories are filtered by fn:
+// see the [fs.WalkDirFunc] documentation for details.
+//
+// The files are walked in lexical order, which makes the output deterministic
+// but requires WalkDir to read an entire directory into memory before proceeding
+// to walk that directory.
+//
+// WalkDir does not follow symbolic links found in directories,
+// but if root itself is a symbolic link, its target will be walked.
+func WalkDir(fsys FS, root string, fn WalkDirFunc) error {
+ info, err := Stat(fsys, root)
+ if err != nil {
+ err = fn(root, nil, err)
+ } else {
+ err = walkDir(fsys, root, FileInfoToDirEntry(info), fn)
+ }
+ if err == SkipDir || err == SkipAll {
+ return nil
+ }
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/io/fs/walk_test.go b/platform/dbops/binaries/go/go/src/io/fs/walk_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..40f4e1ab9d6139950884d60551fc8cdf730b4f93
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/fs/walk_test.go
@@ -0,0 +1,151 @@
+// 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 fs_test
+
+import (
+ . "io/fs"
+ "os"
+ pathpkg "path"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "testing/fstest"
+)
+
+type Node struct {
+ name string
+ entries []*Node // nil if the entry is a file
+ mark int
+}
+
+var tree = &Node{
+ "testdata",
+ []*Node{
+ {"a", nil, 0},
+ {"b", []*Node{}, 0},
+ {"c", nil, 0},
+ {
+ "d",
+ []*Node{
+ {"x", nil, 0},
+ {"y", []*Node{}, 0},
+ {
+ "z",
+ []*Node{
+ {"u", nil, 0},
+ {"v", nil, 0},
+ },
+ 0,
+ },
+ },
+ 0,
+ },
+ },
+ 0,
+}
+
+func walkTree(n *Node, path string, f func(path string, n *Node)) {
+ f(path, n)
+ for _, e := range n.entries {
+ walkTree(e, pathpkg.Join(path, e.name), f)
+ }
+}
+
+func makeTree() FS {
+ fsys := fstest.MapFS{}
+ walkTree(tree, tree.name, func(path string, n *Node) {
+ if n.entries == nil {
+ fsys[path] = &fstest.MapFile{}
+ } else {
+ fsys[path] = &fstest.MapFile{Mode: ModeDir}
+ }
+ })
+ return fsys
+}
+
+// Assumes that each node name is unique. Good enough for a test.
+// If clear is true, any incoming error is cleared before return. The errors
+// are always accumulated, though.
+func mark(entry DirEntry, err error, errors *[]error, clear bool) error {
+ name := entry.Name()
+ walkTree(tree, tree.name, func(path string, n *Node) {
+ if n.name == name {
+ n.mark++
+ }
+ })
+ if err != nil {
+ *errors = append(*errors, err)
+ if clear {
+ return nil
+ }
+ return err
+ }
+ return nil
+}
+
+func TestWalkDir(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ origDir, err := os.Getwd()
+ if err != nil {
+ t.Fatal("finding working dir:", err)
+ }
+ if err = os.Chdir(tmpDir); err != nil {
+ t.Fatal("entering temp dir:", err)
+ }
+ defer os.Chdir(origDir)
+
+ fsys := makeTree()
+ errors := make([]error, 0, 10)
+ clear := true
+ markFn := func(path string, entry DirEntry, err error) error {
+ return mark(entry, err, &errors, clear)
+ }
+ // Expect no errors.
+ err = WalkDir(fsys, ".", markFn)
+ if err != nil {
+ t.Fatalf("no error expected, found: %s", err)
+ }
+ if len(errors) != 0 {
+ t.Fatalf("unexpected errors: %s", errors)
+ }
+ walkTree(tree, tree.name, func(path string, n *Node) {
+ if n.mark != 1 {
+ t.Errorf("node %s mark = %d; expected 1", path, n.mark)
+ }
+ n.mark = 0
+ })
+}
+
+func TestIssue51617(t *testing.T) {
+ dir := t.TempDir()
+ for _, sub := range []string{"a", filepath.Join("a", "bad"), filepath.Join("a", "next")} {
+ if err := os.Mkdir(filepath.Join(dir, sub), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ bad := filepath.Join(dir, "a", "bad")
+ if err := os.Chmod(bad, 0); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(bad, 0700) // avoid errors on cleanup
+ var saw []string
+ err := WalkDir(os.DirFS(dir), ".", func(path string, d DirEntry, err error) error {
+ if err != nil {
+ return filepath.SkipDir
+ }
+ if d.IsDir() {
+ saw = append(saw, path)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{".", "a", "a/bad", "a/next"}
+ if !reflect.DeepEqual(saw, want) {
+ t.Errorf("got directories %v, want %v", saw, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/example_test.go b/platform/dbops/binaries/go/go/src/io/ioutil/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..78b0730c652a31e8c8a0d3742ab78d2d37fa675a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/example_test.go
@@ -0,0 +1,132 @@
+// 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.
+
+package ioutil_test
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+func ExampleReadAll() {
+ r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
+
+ b, err := ioutil.ReadAll(r)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s", b)
+
+ // Output:
+ // Go is a general-purpose language designed with systems programming in mind.
+}
+
+func ExampleReadDir() {
+ files, err := ioutil.ReadDir(".")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ for _, file := range files {
+ fmt.Println(file.Name())
+ }
+}
+
+func ExampleTempDir() {
+ content := []byte("temporary file's content")
+ dir, err := ioutil.TempDir("", "example")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ defer os.RemoveAll(dir) // clean up
+
+ tmpfn := filepath.Join(dir, "tmpfile")
+ if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
+ log.Fatal(err)
+ }
+}
+
+func ExampleTempDir_suffix() {
+ parentDir := os.TempDir()
+ logsDir, err := ioutil.TempDir(parentDir, "*-logs")
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer os.RemoveAll(logsDir) // clean up
+
+ // Logs can be cleaned out earlier if needed by searching
+ // for all directories whose suffix ends in *-logs.
+ globPattern := filepath.Join(parentDir, "*-logs")
+ matches, err := filepath.Glob(globPattern)
+ if err != nil {
+ log.Fatalf("Failed to match %q: %v", globPattern, err)
+ }
+
+ for _, match := range matches {
+ if err := os.RemoveAll(match); err != nil {
+ log.Printf("Failed to remove %q: %v", match, err)
+ }
+ }
+}
+
+func ExampleTempFile() {
+ content := []byte("temporary file's content")
+ tmpfile, err := ioutil.TempFile("", "example")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ defer os.Remove(tmpfile.Name()) // clean up
+
+ if _, err := tmpfile.Write(content); err != nil {
+ log.Fatal(err)
+ }
+ if err := tmpfile.Close(); err != nil {
+ log.Fatal(err)
+ }
+}
+
+func ExampleTempFile_suffix() {
+ content := []byte("temporary file's content")
+ tmpfile, err := ioutil.TempFile("", "example.*.txt")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ defer os.Remove(tmpfile.Name()) // clean up
+
+ if _, err := tmpfile.Write(content); err != nil {
+ tmpfile.Close()
+ log.Fatal(err)
+ }
+ if err := tmpfile.Close(); err != nil {
+ log.Fatal(err)
+ }
+}
+
+func ExampleReadFile() {
+ content, err := ioutil.ReadFile("testdata/hello")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("File contents: %s", content)
+
+ // Output:
+ // File contents: Hello, Gophers!
+}
+
+func ExampleWriteFile() {
+ message := []byte("Hello, Gophers!")
+ err := ioutil.WriteFile("hello", message, 0644)
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/ioutil.go b/platform/dbops/binaries/go/go/src/io/ioutil/ioutil.go
new file mode 100644
index 0000000000000000000000000000000000000000..67768e54cf55c221b401f4297d683aaff7387057
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/ioutil.go
@@ -0,0 +1,95 @@
+// 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 ioutil implements some I/O utility functions.
+//
+// Deprecated: As of Go 1.16, the same functionality is now provided
+// by package [io] or package [os], and those implementations
+// should be preferred in new code.
+// See the specific function documentation for details.
+package ioutil
+
+import (
+ "io"
+ "io/fs"
+ "os"
+ "sort"
+)
+
+// ReadAll reads from r until an error or EOF and returns the data it read.
+// A successful call returns err == nil, not err == EOF. Because ReadAll is
+// defined to read from src until EOF, it does not treat an EOF from Read
+// as an error to be reported.
+//
+// Deprecated: As of Go 1.16, this function simply calls [io.ReadAll].
+func ReadAll(r io.Reader) ([]byte, error) {
+ return io.ReadAll(r)
+}
+
+// ReadFile reads the file named by filename and returns the contents.
+// A successful call returns err == nil, not err == EOF. Because ReadFile
+// reads the whole file, it does not treat an EOF from Read as an error
+// to be reported.
+//
+// Deprecated: As of Go 1.16, this function simply calls [os.ReadFile].
+func ReadFile(filename string) ([]byte, error) {
+ return os.ReadFile(filename)
+}
+
+// WriteFile writes data to a file named by filename.
+// If the file does not exist, WriteFile creates it with permissions perm
+// (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
+//
+// Deprecated: As of Go 1.16, this function simply calls [os.WriteFile].
+func WriteFile(filename string, data []byte, perm fs.FileMode) error {
+ return os.WriteFile(filename, data, perm)
+}
+
+// ReadDir reads the directory named by dirname and returns
+// a list of fs.FileInfo for the directory's contents,
+// sorted by filename. If an error occurs reading the directory,
+// ReadDir returns no directory entries along with the error.
+//
+// Deprecated: As of Go 1.16, [os.ReadDir] is a more efficient and correct choice:
+// it returns a list of [fs.DirEntry] instead of [fs.FileInfo],
+// and it returns partial results in the case of an error
+// midway through reading a directory.
+//
+// If you must continue obtaining a list of [fs.FileInfo], you still can:
+//
+// entries, err := os.ReadDir(dirname)
+// if err != nil { ... }
+// infos := make([]fs.FileInfo, 0, len(entries))
+// for _, entry := range entries {
+// info, err := entry.Info()
+// if err != nil { ... }
+// infos = append(infos, info)
+// }
+func ReadDir(dirname string) ([]fs.FileInfo, error) {
+ f, err := os.Open(dirname)
+ if err != nil {
+ return nil, err
+ }
+ list, err := f.Readdir(-1)
+ f.Close()
+ if err != nil {
+ return nil, err
+ }
+ sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
+ return list, nil
+}
+
+// NopCloser returns a ReadCloser with a no-op Close method wrapping
+// the provided Reader r.
+//
+// Deprecated: As of Go 1.16, this function simply calls [io.NopCloser].
+func NopCloser(r io.Reader) io.ReadCloser {
+ return io.NopCloser(r)
+}
+
+// Discard is an io.Writer on which all Write calls succeed
+// without doing anything.
+//
+// Deprecated: As of Go 1.16, this value is simply [io.Discard].
+var Discard io.Writer = io.Discard
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/ioutil_test.go b/platform/dbops/binaries/go/go/src/io/ioutil/ioutil_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6bff8c691c53530af83cd981e97e12dde385ddd1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/ioutil_test.go
@@ -0,0 +1,134 @@
+// 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 ioutil_test
+
+import (
+ "bytes"
+ . "io/ioutil"
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+)
+
+func checkSize(t *testing.T, path string, size int64) {
+ dir, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("Stat %q (looking for size %d): %s", path, size, err)
+ }
+ if dir.Size() != size {
+ t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size)
+ }
+}
+
+func TestReadFile(t *testing.T) {
+ filename := "rumpelstilzchen"
+ contents, err := ReadFile(filename)
+ if err == nil {
+ t.Fatalf("ReadFile %s: error expected, none found", filename)
+ }
+
+ filename = "ioutil_test.go"
+ contents, err = ReadFile(filename)
+ if err != nil {
+ t.Fatalf("ReadFile %s: %v", filename, err)
+ }
+
+ checkSize(t, filename, int64(len(contents)))
+}
+
+func TestWriteFile(t *testing.T) {
+ f, err := TempFile("", "ioutil-test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ filename := f.Name()
+ data := "Programming today is a race between software engineers striving to " +
+ "build bigger and better idiot-proof programs, and the Universe trying " +
+ "to produce bigger and better idiots. So far, the Universe is winning."
+
+ if err := WriteFile(filename, []byte(data), 0644); err != nil {
+ t.Fatalf("WriteFile %s: %v", filename, err)
+ }
+
+ contents, err := ReadFile(filename)
+ if err != nil {
+ t.Fatalf("ReadFile %s: %v", filename, err)
+ }
+
+ if string(contents) != data {
+ t.Fatalf("contents = %q\nexpected = %q", string(contents), data)
+ }
+
+ // cleanup
+ f.Close()
+ os.Remove(filename) // ignore error
+}
+
+func TestReadOnlyWriteFile(t *testing.T) {
+ if os.Getuid() == 0 {
+ t.Skipf("Root can write to read-only files anyway, so skip the read-only test.")
+ }
+ if runtime.GOOS == "wasip1" {
+ t.Skip("file permissions are not supported by wasip1")
+ }
+
+ // We don't want to use TempFile directly, since that opens a file for us as 0600.
+ tempDir, err := TempDir("", t.Name())
+ if err != nil {
+ t.Fatalf("TempDir %s: %v", t.Name(), err)
+ }
+ defer os.RemoveAll(tempDir)
+ filename := filepath.Join(tempDir, "blurp.txt")
+
+ shmorp := []byte("shmorp")
+ florp := []byte("florp")
+ err = WriteFile(filename, shmorp, 0444)
+ if err != nil {
+ t.Fatalf("WriteFile %s: %v", filename, err)
+ }
+ err = WriteFile(filename, florp, 0444)
+ if err == nil {
+ t.Fatalf("Expected an error when writing to read-only file %s", filename)
+ }
+ got, err := ReadFile(filename)
+ if err != nil {
+ t.Fatalf("ReadFile %s: %v", filename, err)
+ }
+ if !bytes.Equal(got, shmorp) {
+ t.Fatalf("want %s, got %s", shmorp, got)
+ }
+}
+
+func TestReadDir(t *testing.T) {
+ dirname := "rumpelstilzchen"
+ _, err := ReadDir(dirname)
+ if err == nil {
+ t.Fatalf("ReadDir %s: error expected, none found", dirname)
+ }
+
+ dirname = ".."
+ list, err := ReadDir(dirname)
+ if err != nil {
+ t.Fatalf("ReadDir %s: %v", dirname, err)
+ }
+
+ foundFile := false
+ foundSubDir := false
+ for _, dir := range list {
+ switch {
+ case !dir.IsDir() && dir.Name() == "io_test.go":
+ foundFile = true
+ case dir.IsDir() && dir.Name() == "ioutil":
+ foundSubDir = true
+ }
+ }
+ if !foundFile {
+ t.Fatalf("ReadDir %s: io_test.go file not found", dirname)
+ }
+ if !foundSubDir {
+ t.Fatalf("ReadDir %s: ioutil directory not found", dirname)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/tempfile.go b/platform/dbops/binaries/go/go/src/io/ioutil/tempfile.go
new file mode 100644
index 0000000000000000000000000000000000000000..47b2e4012f7622334111b7df0a40e910945a6907
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/tempfile.go
@@ -0,0 +1,41 @@
+// 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 ioutil
+
+import (
+ "os"
+)
+
+// TempFile creates a new temporary file in the directory dir,
+// opens the file for reading and writing, and returns the resulting *[os.File].
+// The filename is generated by taking pattern and adding a random
+// string to the end. If pattern includes a "*", the random string
+// replaces the last "*".
+// If dir is the empty string, TempFile uses the default directory
+// for temporary files (see [os.TempDir]).
+// Multiple programs calling TempFile simultaneously
+// will not choose the same file. The caller can use f.Name()
+// to find the pathname of the file. It is the caller's responsibility
+// to remove the file when no longer needed.
+//
+// Deprecated: As of Go 1.17, this function simply calls [os.CreateTemp].
+func TempFile(dir, pattern string) (f *os.File, err error) {
+ return os.CreateTemp(dir, pattern)
+}
+
+// TempDir creates a new temporary directory in the directory dir.
+// The directory name is generated by taking pattern and applying a
+// random string to the end. If pattern includes a "*", the random string
+// replaces the last "*". TempDir returns the name of the new directory.
+// If dir is the empty string, TempDir uses the
+// default directory for temporary files (see [os.TempDir]).
+// Multiple programs calling TempDir simultaneously
+// will not choose the same directory. It is the caller's responsibility
+// to remove the directory when no longer needed.
+//
+// Deprecated: As of Go 1.17, this function simply calls [os.MkdirTemp].
+func TempDir(dir, pattern string) (name string, err error) {
+ return os.MkdirTemp(dir, pattern)
+}
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/tempfile_test.go b/platform/dbops/binaries/go/go/src/io/ioutil/tempfile_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..818fcdadf8a87b8e9b1145176d68b11c9138ddd4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/tempfile_test.go
@@ -0,0 +1,196 @@
+// 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 ioutil_test
+
+import (
+ "io/fs"
+ . "io/ioutil"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestTempFile(t *testing.T) {
+ dir, err := TempDir("", "TestTempFile_BadDir")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+
+ nonexistentDir := filepath.Join(dir, "_not_exists_")
+ f, err := TempFile(nonexistentDir, "foo")
+ if f != nil || err == nil {
+ t.Errorf("TempFile(%q, `foo`) = %v, %v", nonexistentDir, f, err)
+ }
+}
+
+func TestTempFile_pattern(t *testing.T) {
+ tests := []struct{ pattern, prefix, suffix string }{
+ {"ioutil_test", "ioutil_test", ""},
+ {"ioutil_test*", "ioutil_test", ""},
+ {"ioutil_test*xyz", "ioutil_test", "xyz"},
+ }
+ for _, test := range tests {
+ f, err := TempFile("", test.pattern)
+ if err != nil {
+ t.Errorf("TempFile(..., %q) error: %v", test.pattern, err)
+ continue
+ }
+ defer os.Remove(f.Name())
+ base := filepath.Base(f.Name())
+ f.Close()
+ if !(strings.HasPrefix(base, test.prefix) && strings.HasSuffix(base, test.suffix)) {
+ t.Errorf("TempFile pattern %q created bad name %q; want prefix %q & suffix %q",
+ test.pattern, base, test.prefix, test.suffix)
+ }
+ }
+}
+
+// This string is from os.errPatternHasSeparator.
+const patternHasSeparator = "pattern contains path separator"
+
+func TestTempFile_BadPattern(t *testing.T) {
+ tmpDir, err := TempDir("", t.Name())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ const sep = string(os.PathSeparator)
+ tests := []struct {
+ pattern string
+ wantErr bool
+ }{
+ {"ioutil*test", false},
+ {"ioutil_test*foo", false},
+ {"ioutil_test" + sep + "foo", true},
+ {"ioutil_test*" + sep + "foo", true},
+ {"ioutil_test" + sep + "*foo", true},
+ {sep + "ioutil_test" + sep + "*foo", true},
+ {"ioutil_test*foo" + sep, true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.pattern, func(t *testing.T) {
+ tmpfile, err := TempFile(tmpDir, tt.pattern)
+ defer func() {
+ if tmpfile != nil {
+ tmpfile.Close()
+ }
+ }()
+ if tt.wantErr {
+ if err == nil {
+ t.Errorf("Expected an error for pattern %q", tt.pattern)
+ } else if !strings.Contains(err.Error(), patternHasSeparator) {
+ t.Errorf("Error mismatch: got %#v, want %q for pattern %q", err, patternHasSeparator, tt.pattern)
+ }
+ } else if err != nil {
+ t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern)
+ }
+ })
+ }
+}
+
+func TestTempDir(t *testing.T) {
+ name, err := TempDir("/_not_exists_", "foo")
+ if name != "" || err == nil {
+ t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err)
+ }
+
+ tests := []struct {
+ pattern string
+ wantPrefix, wantSuffix string
+ }{
+ {"ioutil_test", "ioutil_test", ""},
+ {"ioutil_test*", "ioutil_test", ""},
+ {"ioutil_test*xyz", "ioutil_test", "xyz"},
+ }
+
+ dir := os.TempDir()
+
+ runTestTempDir := func(t *testing.T, pattern, wantRePat string) {
+ name, err := TempDir(dir, pattern)
+ if name == "" || err != nil {
+ t.Fatalf("TempDir(dir, `ioutil_test`) = %v, %v", name, err)
+ }
+ defer os.Remove(name)
+
+ re := regexp.MustCompile(wantRePat)
+ if !re.MatchString(name) {
+ t.Errorf("TempDir(%q, %q) created bad name\n\t%q\ndid not match pattern\n\t%q", dir, pattern, name, wantRePat)
+ }
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.pattern, func(t *testing.T) {
+ wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir, tt.wantPrefix)) + "[0-9]+" + regexp.QuoteMeta(tt.wantSuffix) + "$"
+ runTestTempDir(t, tt.pattern, wantRePat)
+ })
+ }
+
+ // Separately testing "*xyz" (which has no prefix). That is when constructing the
+ // pattern to assert on, as in the previous loop, using filepath.Join for an empty
+ // prefix filepath.Join(dir, ""), produces the pattern:
+ // ^[0-9]+xyz$
+ // yet we just want to match
+ // "^/[0-9]+xyz"
+ t.Run("*xyz", func(t *testing.T) {
+ wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir)) + regexp.QuoteMeta(string(filepath.Separator)) + "[0-9]+xyz$"
+ runTestTempDir(t, "*xyz", wantRePat)
+ })
+}
+
+// test that we return a nice error message if the dir argument to TempDir doesn't
+// exist (or that it's empty and os.TempDir doesn't exist)
+func TestTempDir_BadDir(t *testing.T) {
+ dir, err := TempDir("", "TestTempDir_BadDir")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+
+ badDir := filepath.Join(dir, "not-exist")
+ _, err = TempDir(badDir, "foo")
+ if pe, ok := err.(*fs.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir {
+ t.Errorf("TempDir error = %#v; want PathError for path %q satisfying os.IsNotExist", err, badDir)
+ }
+}
+
+func TestTempDir_BadPattern(t *testing.T) {
+ tmpDir, err := TempDir("", t.Name())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ const sep = string(os.PathSeparator)
+ tests := []struct {
+ pattern string
+ wantErr bool
+ }{
+ {"ioutil*test", false},
+ {"ioutil_test*foo", false},
+ {"ioutil_test" + sep + "foo", true},
+ {"ioutil_test*" + sep + "foo", true},
+ {"ioutil_test" + sep + "*foo", true},
+ {sep + "ioutil_test" + sep + "*foo", true},
+ {"ioutil_test*foo" + sep, true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.pattern, func(t *testing.T) {
+ _, err := TempDir(tmpDir, tt.pattern)
+ if tt.wantErr {
+ if err == nil {
+ t.Errorf("Expected an error for pattern %q", tt.pattern)
+ } else if !strings.Contains(err.Error(), patternHasSeparator) {
+ t.Errorf("Error mismatch: got %#v, want %q for pattern %q", err, patternHasSeparator, tt.pattern)
+ }
+ } else if err != nil {
+ t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/ioutil/testdata/hello b/platform/dbops/binaries/go/go/src/io/ioutil/testdata/hello
new file mode 100644
index 0000000000000000000000000000000000000000..e47c092a51a3db2682d6e882e0685c8357834573
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/ioutil/testdata/hello
@@ -0,0 +1 @@
+Hello, Gophers!
diff --git a/platform/dbops/binaries/go/go/src/log/internal/internal.go b/platform/dbops/binaries/go/go/src/log/internal/internal.go
new file mode 100644
index 0000000000000000000000000000000000000000..d5af2c536c5c19a223cac6f121ff446579626021
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/internal/internal.go
@@ -0,0 +1,12 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package internal contains definitions used by both log and log/slog.
+package internal
+
+// DefaultOutput holds a function which calls the default log.Logger's
+// output function.
+// It allows slog.defaultHandler to call into an unexported function of
+// the log package.
+var DefaultOutput func(pc uintptr, data []byte) error
diff --git a/platform/dbops/binaries/go/go/src/log/slog/attr.go b/platform/dbops/binaries/go/go/src/log/slog/attr.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f459467cb6f2888b68a9404f6bd6b04ae10e017
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/attr.go
@@ -0,0 +1,102 @@
+// 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 slog
+
+import (
+ "fmt"
+ "time"
+)
+
+// An Attr is a key-value pair.
+type Attr struct {
+ Key string
+ Value Value
+}
+
+// String returns an Attr for a string value.
+func String(key, value string) Attr {
+ return Attr{key, StringValue(value)}
+}
+
+// Int64 returns an Attr for an int64.
+func Int64(key string, value int64) Attr {
+ return Attr{key, Int64Value(value)}
+}
+
+// Int converts an int to an int64 and returns
+// an Attr with that value.
+func Int(key string, value int) Attr {
+ return Int64(key, int64(value))
+}
+
+// Uint64 returns an Attr for a uint64.
+func Uint64(key string, v uint64) Attr {
+ return Attr{key, Uint64Value(v)}
+}
+
+// Float64 returns an Attr for a floating-point number.
+func Float64(key string, v float64) Attr {
+ return Attr{key, Float64Value(v)}
+}
+
+// Bool returns an Attr for a bool.
+func Bool(key string, v bool) Attr {
+ return Attr{key, BoolValue(v)}
+}
+
+// Time returns an Attr for a [time.Time].
+// It discards the monotonic portion.
+func Time(key string, v time.Time) Attr {
+ return Attr{key, TimeValue(v)}
+}
+
+// Duration returns an Attr for a [time.Duration].
+func Duration(key string, v time.Duration) Attr {
+ return Attr{key, DurationValue(v)}
+}
+
+// Group returns an Attr for a Group [Value].
+// The first argument is the key; the remaining arguments
+// are converted to Attrs as in [Logger.Log].
+//
+// Use Group to collect several key-value pairs under a single
+// key on a log line, or as the result of LogValue
+// in order to log a single value as multiple Attrs.
+func Group(key string, args ...any) Attr {
+ return Attr{key, GroupValue(argsToAttrSlice(args)...)}
+}
+
+func argsToAttrSlice(args []any) []Attr {
+ var (
+ attr Attr
+ attrs []Attr
+ )
+ for len(args) > 0 {
+ attr, args = argsToAttr(args)
+ attrs = append(attrs, attr)
+ }
+ return attrs
+}
+
+// Any returns an Attr for the supplied value.
+// See [AnyValue] for how values are treated.
+func Any(key string, value any) Attr {
+ return Attr{key, AnyValue(value)}
+}
+
+// Equal reports whether a and b have equal keys and values.
+func (a Attr) Equal(b Attr) bool {
+ return a.Key == b.Key && a.Value.Equal(b.Value)
+}
+
+func (a Attr) String() string {
+ return fmt.Sprintf("%s=%s", a.Key, a.Value)
+}
+
+// isEmpty reports whether a has an empty key and a nil value.
+// That can be written as Attr{} or Any("", nil).
+func (a Attr) isEmpty() bool {
+ return a.Key == "" && a.Value.num == 0 && a.Value.any == nil
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/attr_test.go b/platform/dbops/binaries/go/go/src/log/slog/attr_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1187a856fd354af851d9dd026773baf4199de938
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/attr_test.go
@@ -0,0 +1,43 @@
+// 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 slog
+
+import (
+ "internal/testenv"
+ "testing"
+ "time"
+)
+
+func TestAttrNoAlloc(t *testing.T) {
+ testenv.SkipIfOptimizationOff(t)
+ // Assign values just to make sure the compiler doesn't optimize away the statements.
+ var (
+ i int64
+ u uint64
+ f float64
+ b bool
+ s string
+ x any
+ p = &i
+ d time.Duration
+ )
+ a := int(testing.AllocsPerRun(5, func() {
+ i = Int64("key", 1).Value.Int64()
+ u = Uint64("key", 1).Value.Uint64()
+ f = Float64("key", 1).Value.Float64()
+ b = Bool("key", true).Value.Bool()
+ s = String("key", "foo").Value.String()
+ d = Duration("key", d).Value.Duration()
+ x = Any("key", p).Value.Any()
+ }))
+ if a != 0 {
+ t.Errorf("got %d allocs, want zero", a)
+ }
+ _ = u
+ _ = f
+ _ = b
+ _ = s
+ _ = x
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/doc.go b/platform/dbops/binaries/go/go/src/log/slog/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..001559326b3eea36ff56beacf58dc1ff23f2ef50
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/doc.go
@@ -0,0 +1,320 @@
+// 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 slog provides structured logging,
+in which log records include a message,
+a severity level, and various other attributes
+expressed as key-value pairs.
+
+It defines a type, [Logger],
+which provides several methods (such as [Logger.Info] and [Logger.Error])
+for reporting events of interest.
+
+Each Logger is associated with a [Handler].
+A Logger output method creates a [Record] from the method arguments
+and passes it to the Handler, which decides how to handle it.
+There is a default Logger accessible through top-level functions
+(such as [Info] and [Error]) that call the corresponding Logger methods.
+
+A log record consists of a time, a level, a message, and a set of key-value
+pairs, where the keys are strings and the values may be of any type.
+As an example,
+
+ slog.Info("hello", "count", 3)
+
+creates a record containing the time of the call,
+a level of Info, the message "hello", and a single
+pair with key "count" and value 3.
+
+The [Info] top-level function calls the [Logger.Info] method on the default Logger.
+In addition to [Logger.Info], there are methods for Debug, Warn and Error levels.
+Besides these convenience methods for common levels,
+there is also a [Logger.Log] method which takes the level as an argument.
+Each of these methods has a corresponding top-level function that uses the
+default logger.
+
+The default handler formats the log record's message, time, level, and attributes
+as a string and passes it to the [log] package.
+
+ 2022/11/08 15:28:26 INFO hello count=3
+
+For more control over the output format, create a logger with a different handler.
+This statement uses [New] to create a new logger with a [TextHandler]
+that writes structured records in text form to standard error:
+
+ logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
+
+[TextHandler] output is a sequence of key=value pairs, easily and unambiguously
+parsed by machine. This statement:
+
+ logger.Info("hello", "count", 3)
+
+produces this output:
+
+ time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3
+
+The package also provides [JSONHandler], whose output is line-delimited JSON:
+
+ logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
+ logger.Info("hello", "count", 3)
+
+produces this output:
+
+ {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}
+
+Both [TextHandler] and [JSONHandler] can be configured with [HandlerOptions].
+There are options for setting the minimum level (see Levels, below),
+displaying the source file and line of the log call, and
+modifying attributes before they are logged.
+
+Setting a logger as the default with
+
+ slog.SetDefault(logger)
+
+will cause the top-level functions like [Info] to use it.
+[SetDefault] also updates the default logger used by the [log] package,
+so that existing applications that use [log.Printf] and related functions
+will send log records to the logger's handler without needing to be rewritten.
+
+Some attributes are common to many log calls.
+For example, you may wish to include the URL or trace identifier of a server request
+with all log events arising from the request.
+Rather than repeat the attribute with every log call, you can use [Logger.With]
+to construct a new Logger containing the attributes:
+
+ logger2 := logger.With("url", r.URL)
+
+The arguments to With are the same key-value pairs used in [Logger.Info].
+The result is a new Logger with the same handler as the original, but additional
+attributes that will appear in the output of every call.
+
+# Levels
+
+A [Level] is an integer representing the importance or severity of a log event.
+The higher the level, the more severe the event.
+This package defines constants for the most common levels,
+but any int can be used as a level.
+
+In an application, you may wish to log messages only at a certain level or greater.
+One common configuration is to log messages at Info or higher levels,
+suppressing debug logging until it is needed.
+The built-in handlers can be configured with the minimum level to output by
+setting [HandlerOptions.Level].
+The program's `main` function typically does this.
+The default value is LevelInfo.
+
+Setting the [HandlerOptions.Level] field to a [Level] value
+fixes the handler's minimum level throughout its lifetime.
+Setting it to a [LevelVar] allows the level to be varied dynamically.
+A LevelVar holds a Level and is safe to read or write from multiple
+goroutines.
+To vary the level dynamically for an entire program, first initialize
+a global LevelVar:
+
+ var programLevel = new(slog.LevelVar) // Info by default
+
+Then use the LevelVar to construct a handler, and make it the default:
+
+ h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel})
+ slog.SetDefault(slog.New(h))
+
+Now the program can change its logging level with a single statement:
+
+ programLevel.Set(slog.LevelDebug)
+
+# Groups
+
+Attributes can be collected into groups.
+A group has a name that is used to qualify the names of its attributes.
+How this qualification is displayed depends on the handler.
+[TextHandler] separates the group and attribute names with a dot.
+[JSONHandler] treats each group as a separate JSON object, with the group name as the key.
+
+Use [Group] to create a Group attribute from a name and a list of key-value pairs:
+
+ slog.Group("request",
+ "method", r.Method,
+ "url", r.URL)
+
+TextHandler would display this group as
+
+ request.method=GET request.url=http://example.com
+
+JSONHandler would display it as
+
+ "request":{"method":"GET","url":"http://example.com"}
+
+Use [Logger.WithGroup] to qualify all of a Logger's output
+with a group name. Calling WithGroup on a Logger results in a
+new Logger with the same Handler as the original, but with all
+its attributes qualified by the group name.
+
+This can help prevent duplicate attribute keys in large systems,
+where subsystems might use the same keys.
+Pass each subsystem a different Logger with its own group name so that
+potential duplicates are qualified:
+
+ logger := slog.Default().With("id", systemID)
+ parserLogger := logger.WithGroup("parser")
+ parseInput(input, parserLogger)
+
+When parseInput logs with parserLogger, its keys will be qualified with "parser",
+so even if it uses the common key "id", the log line will have distinct keys.
+
+# Contexts
+
+Some handlers may wish to include information from the [context.Context] that is
+available at the call site. One example of such information
+is the identifier for the current span when tracing is enabled.
+
+The [Logger.Log] and [Logger.LogAttrs] methods take a context as a first
+argument, as do their corresponding top-level functions.
+
+Although the convenience methods on Logger (Info and so on) and the
+corresponding top-level functions do not take a context, the alternatives ending
+in "Context" do. For example,
+
+ slog.InfoContext(ctx, "message")
+
+It is recommended to pass a context to an output method if one is available.
+
+# Attrs and Values
+
+An [Attr] is a key-value pair. The Logger output methods accept Attrs as well as
+alternating keys and values. The statement
+
+ slog.Info("hello", slog.Int("count", 3))
+
+behaves the same as
+
+ slog.Info("hello", "count", 3)
+
+There are convenience constructors for [Attr] such as [Int], [String], and [Bool]
+for common types, as well as the function [Any] for constructing Attrs of any
+type.
+
+The value part of an Attr is a type called [Value].
+Like an [any], a Value can hold any Go value,
+but it can represent typical values, including all numbers and strings,
+without an allocation.
+
+For the most efficient log output, use [Logger.LogAttrs].
+It is similar to [Logger.Log] but accepts only Attrs, not alternating
+keys and values; this allows it, too, to avoid allocation.
+
+The call
+
+ logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3))
+
+is the most efficient way to achieve the same output as
+
+ slog.InfoContext(ctx, "hello", "count", 3)
+
+# Customizing a type's logging behavior
+
+If a type implements the [LogValuer] interface, the [Value] returned from its LogValue
+method is used for logging. You can use this to control how values of the type
+appear in logs. For example, you can redact secret information like passwords,
+or gather a struct's fields in a Group. See the examples under [LogValuer] for
+details.
+
+A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve]
+method handles these cases carefully, avoiding infinite loops and unbounded recursion.
+Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly.
+
+# Wrapping output methods
+
+The logger functions use reflection over the call stack to find the file name
+and line number of the logging call within the application. This can produce
+incorrect source information for functions that wrap slog. For instance, if you
+define this function in file mylog.go:
+
+ func Infof(logger *slog.Logger, format string, args ...any) {
+ logger.Info(fmt.Sprintf(format, args...))
+ }
+
+and you call it like this in main.go:
+
+ Infof(slog.Default(), "hello, %s", "world")
+
+then slog will report the source file as mylog.go, not main.go.
+
+A correct implementation of Infof will obtain the source location
+(pc) and pass it to NewRecord.
+The Infof function in the package-level example called "wrapping"
+demonstrates how to do this.
+
+# Working with Records
+
+Sometimes a Handler will need to modify a Record
+before passing it on to another Handler or backend.
+A Record contains a mixture of simple public fields (e.g. Time, Level, Message)
+and hidden fields that refer to state (such as attributes) indirectly. This
+means that modifying a simple copy of a Record (e.g. by calling
+[Record.Add] or [Record.AddAttrs] to add attributes)
+may have unexpected effects on the original.
+Before modifying a Record, use [Record.Clone] to
+create a copy that shares no state with the original,
+or create a new Record with [NewRecord]
+and build up its Attrs by traversing the old ones with [Record.Attrs].
+
+# Performance considerations
+
+If profiling your application demonstrates that logging is taking significant time,
+the following suggestions may help.
+
+If many log lines have a common attribute, use [Logger.With] to create a Logger with
+that attribute. The built-in handlers will format that attribute only once, at the
+call to [Logger.With]. The [Handler] interface is designed to allow that optimization,
+and a well-written Handler should take advantage of it.
+
+The arguments to a log call are always evaluated, even if the log event is discarded.
+If possible, defer computation so that it happens only if the value is actually logged.
+For example, consider the call
+
+ slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily
+
+The URL.String method will be called even if the logger discards Info-level events.
+Instead, pass the URL directly:
+
+ slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed
+
+The built-in [TextHandler] will call its String method, but only
+if the log event is enabled.
+Avoiding the call to String also preserves the structure of the underlying value.
+For example [JSONHandler] emits the components of the parsed URL as a JSON object.
+If you want to avoid eagerly paying the cost of the String call
+without causing the handler to potentially inspect the structure of the value,
+wrap the value in a fmt.Stringer implementation that hides its Marshal methods.
+
+You can also use the [LogValuer] interface to avoid unnecessary work in disabled log
+calls. Say you need to log some expensive value:
+
+ slog.Debug("frobbing", "value", computeExpensiveValue(arg))
+
+Even if this line is disabled, computeExpensiveValue will be called.
+To avoid that, define a type implementing LogValuer:
+
+ type expensive struct { arg int }
+
+ func (e expensive) LogValue() slog.Value {
+ return slog.AnyValue(computeExpensiveValue(e.arg))
+ }
+
+Then use a value of that type in log calls:
+
+ slog.Debug("frobbing", "value", expensive{arg})
+
+Now computeExpensiveValue will only be called when the line is enabled.
+
+The built-in handlers acquire a lock before calling [io.Writer.Write]
+to ensure that each record is written in one piece. User-defined
+handlers are responsible for their own locking.
+
+# Writing a handler
+
+For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide.
+*/
+package slog
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_custom_levels_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_custom_levels_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7351ca493b18f8877f22edc8ea4c8d29ceb4d876
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_custom_levels_test.go
@@ -0,0 +1,93 @@
+// 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 slog_test
+
+import (
+ "context"
+ "log/slog"
+ "os"
+)
+
+// This example demonstrates using custom log levels and custom log level names.
+// In addition to the default log levels, it introduces Trace, Notice, and
+// Emergency levels. The ReplaceAttr changes the way levels are printed for both
+// the standard log levels and the custom log levels.
+func ExampleHandlerOptions_customLevels() {
+ // Exported constants from a custom logging package.
+ const (
+ LevelTrace = slog.Level(-8)
+ LevelDebug = slog.LevelDebug
+ LevelInfo = slog.LevelInfo
+ LevelNotice = slog.Level(2)
+ LevelWarning = slog.LevelWarn
+ LevelError = slog.LevelError
+ LevelEmergency = slog.Level(12)
+ )
+
+ th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+ // Set a custom level to show all log output. The default value is
+ // LevelInfo, which would drop Debug and Trace logs.
+ Level: LevelTrace,
+
+ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
+ // Remove time from the output for predictable test output.
+ if a.Key == slog.TimeKey {
+ return slog.Attr{}
+ }
+
+ // Customize the name of the level key and the output string, including
+ // custom level values.
+ if a.Key == slog.LevelKey {
+ // Rename the level key from "level" to "sev".
+ a.Key = "sev"
+
+ // Handle custom level values.
+ level := a.Value.Any().(slog.Level)
+
+ // This could also look up the name from a map or other structure, but
+ // this demonstrates using a switch statement to rename levels. For
+ // maximum performance, the string values should be constants, but this
+ // example uses the raw strings for readability.
+ switch {
+ case level < LevelDebug:
+ a.Value = slog.StringValue("TRACE")
+ case level < LevelInfo:
+ a.Value = slog.StringValue("DEBUG")
+ case level < LevelNotice:
+ a.Value = slog.StringValue("INFO")
+ case level < LevelWarning:
+ a.Value = slog.StringValue("NOTICE")
+ case level < LevelError:
+ a.Value = slog.StringValue("WARNING")
+ case level < LevelEmergency:
+ a.Value = slog.StringValue("ERROR")
+ default:
+ a.Value = slog.StringValue("EMERGENCY")
+ }
+ }
+
+ return a
+ },
+ })
+
+ logger := slog.New(th)
+ ctx := context.Background()
+ logger.Log(ctx, LevelEmergency, "missing pilots")
+ logger.Error("failed to start engines", "err", "missing fuel")
+ logger.Warn("falling back to default value")
+ logger.Log(ctx, LevelNotice, "all systems are running")
+ logger.Info("initiating launch")
+ logger.Debug("starting background job")
+ logger.Log(ctx, LevelTrace, "button clicked")
+
+ // Output:
+ // sev=EMERGENCY msg="missing pilots"
+ // sev=ERROR msg="failed to start engines" err="missing fuel"
+ // sev=WARNING msg="falling back to default value"
+ // sev=NOTICE msg="all systems are running"
+ // sev=INFO msg="initiating launch"
+ // sev=DEBUG msg="starting background job"
+ // sev=TRACE msg="button clicked"
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_level_handler_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_level_handler_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1ff91d47635faa37454bb9baff81d0d5e9e0aafe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_level_handler_test.go
@@ -0,0 +1,73 @@
+// 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 slog_test
+
+import (
+ "context"
+ "log/slog"
+ "log/slog/internal/slogtest"
+ "os"
+)
+
+// A LevelHandler wraps a Handler with an Enabled method
+// that returns false for levels below a minimum.
+type LevelHandler struct {
+ level slog.Leveler
+ handler slog.Handler
+}
+
+// NewLevelHandler returns a LevelHandler with the given level.
+// All methods except Enabled delegate to h.
+func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
+ // Optimization: avoid chains of LevelHandlers.
+ if lh, ok := h.(*LevelHandler); ok {
+ h = lh.Handler()
+ }
+ return &LevelHandler{level, h}
+}
+
+// Enabled implements Handler.Enabled by reporting whether
+// level is at least as large as h's level.
+func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
+ return level >= h.level.Level()
+}
+
+// Handle implements Handler.Handle.
+func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
+ return h.handler.Handle(ctx, r)
+}
+
+// WithAttrs implements Handler.WithAttrs.
+func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
+}
+
+// WithGroup implements Handler.WithGroup.
+func (h *LevelHandler) WithGroup(name string) slog.Handler {
+ return NewLevelHandler(h.level, h.handler.WithGroup(name))
+}
+
+// Handler returns the Handler wrapped by h.
+func (h *LevelHandler) Handler() slog.Handler {
+ return h.handler
+}
+
+// This example shows how to Use a LevelHandler to change the level of an
+// existing Handler while preserving its other behavior.
+//
+// This example demonstrates increasing the log level to reduce a logger's
+// output.
+//
+// Another typical use would be to decrease the log level (to LevelDebug, say)
+// during a part of the program that was suspected of containing a bug.
+func ExampleHandler_levelHandler() {
+ th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})
+ logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
+ logger.Info("not printed")
+ logger.Warn("printed")
+
+ // Output:
+ // level=WARN msg=printed
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_log_level_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_log_level_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ca8db416e5cdfb491b5a8c6c93847f6549da3b62
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_log_level_test.go
@@ -0,0 +1,58 @@
+// 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 slog_test
+
+import (
+ "log"
+ "log/slog"
+ "log/slog/internal/slogtest"
+ "os"
+)
+
+// This example shows how to use slog.SetLogLoggerLevel to change the minimal level
+// of the internal default handler for slog package before calling slog.SetDefault.
+func ExampleSetLogLoggerLevel_log() {
+ defer log.SetFlags(log.Flags()) // revert changes after the example
+ log.SetFlags(0)
+ defer log.SetOutput(log.Writer()) // revert changes after the example
+ log.SetOutput(os.Stdout)
+
+ // Default logging level is slog.LevelInfo.
+ log.Print("log debug") // log debug
+ slog.Debug("debug") // no output
+ slog.Info("info") // INFO info
+
+ // Set the default logging level to slog.LevelDebug.
+ currentLogLevel := slog.SetLogLoggerLevel(slog.LevelDebug)
+ defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
+
+ log.Print("log debug") // log debug
+ slog.Debug("debug") // DEBUG debug
+ slog.Info("info") // INFO info
+
+ // Output:
+ // log debug
+ // INFO info
+ // log debug
+ // DEBUG debug
+ // INFO info
+}
+
+// This example shows how to use slog.SetLogLoggerLevel to change the minimal level
+// of the internal writer that uses the custom handler for log package after
+// calling slog.SetDefault.
+func ExampleSetLogLoggerLevel_slog() {
+ // Set the default logging level to slog.LevelError.
+ currentLogLevel := slog.SetLogLoggerLevel(slog.LevelError)
+ defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
+
+ defer slog.SetDefault(slog.Default()) // revert changes after the example
+ slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})))
+
+ log.Print("error") // level=ERROR msg=error
+
+ // Output:
+ // level=ERROR msg=error
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_group_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_group_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4cc478fda22f2d3c9f5ed4dfbd9906bdd98479c7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_group_test.go
@@ -0,0 +1,35 @@
+// 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 slog_test
+
+import "log/slog"
+
+type Name struct {
+ First, Last string
+}
+
+// LogValue implements slog.LogValuer.
+// It returns a group containing the fields of
+// the Name, so that they appear together in the log output.
+func (n Name) LogValue() slog.Value {
+ return slog.GroupValue(
+ slog.String("first", n.First),
+ slog.String("last", n.Last))
+}
+
+func ExampleLogValuer_group() {
+ n := Name{"Perry", "Platypus"}
+ slog.Info("mission accomplished", "agent", n)
+
+ // JSON Output would look in part like:
+ // {
+ // ...
+ // "msg": "mission accomplished",
+ // "agent": {
+ // "first": "Perry",
+ // "last": "Platypus"
+ // }
+ // }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_secret_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_secret_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..51d002079383a5639bfe95f4f60930e73ef07b22
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_logvaluer_secret_test.go
@@ -0,0 +1,31 @@
+// 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 slog_test
+
+import (
+ "log/slog"
+ "log/slog/internal/slogtest"
+ "os"
+)
+
+// A token is a secret value that grants permissions.
+type Token string
+
+// LogValue implements slog.LogValuer.
+// It avoids revealing the token.
+func (Token) LogValue() slog.Value {
+ return slog.StringValue("REDACTED_TOKEN")
+}
+
+// This example demonstrates a Value that replaces itself
+// with an alternative representation to avoid revealing secrets.
+func ExampleLogValuer_secret() {
+ t := Token("shhhh!")
+ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
+ logger.Info("permission granted", "user", "Perry", "token", t)
+
+ // Output:
+ // level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b03cc01066ccca47f01d3880629ef3c4e42a5a12
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_test.go
@@ -0,0 +1,37 @@
+// 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 slog_test
+
+import (
+ "log/slog"
+ "net/http"
+ "os"
+ "time"
+)
+
+func ExampleGroup() {
+ r, _ := http.NewRequest("GET", "localhost", nil)
+ // ...
+
+ logger := slog.New(
+ slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
+ if a.Key == slog.TimeKey && len(groups) == 0 {
+ return slog.Attr{}
+ }
+ return a
+ },
+ }),
+ )
+ logger.Info("finished",
+ slog.Group("req",
+ slog.String("method", r.Method),
+ slog.String("url", r.URL.String())),
+ slog.Int("status", http.StatusOK),
+ slog.Duration("duration", time.Second))
+
+ // Output:
+ // level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/example_wrap_test.go b/platform/dbops/binaries/go/go/src/log/slog/example_wrap_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dcc87b833cd37ba4c734b056804cfc38c4968703
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/example_wrap_test.go
@@ -0,0 +1,47 @@
+// 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 slog_test
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+ "time"
+)
+
+// Infof is an example of a user-defined logging function that wraps slog.
+// The log record contains the source position of the caller of Infof.
+func Infof(logger *slog.Logger, format string, args ...any) {
+ if !logger.Enabled(context.Background(), slog.LevelInfo) {
+ return
+ }
+ var pcs [1]uintptr
+ runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
+ r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
+ _ = logger.Handler().Handle(context.Background(), r)
+}
+
+func Example_wrapping() {
+ replace := func(groups []string, a slog.Attr) slog.Attr {
+ // Remove time.
+ if a.Key == slog.TimeKey && len(groups) == 0 {
+ return slog.Attr{}
+ }
+ // Remove the directory from the source's filename.
+ if a.Key == slog.SourceKey {
+ source := a.Value.Any().(*slog.Source)
+ source.File = filepath.Base(source.File)
+ }
+ return a
+ }
+ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
+ Infof(logger, "message, %s", "formatted")
+
+ // Output:
+ // level=INFO source=example_wrap_test.go:43 msg="message, formatted"
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/handler.go b/platform/dbops/binaries/go/go/src/log/slog/handler.go
new file mode 100644
index 0000000000000000000000000000000000000000..2ff85b582ef32e6335fcd2d7d04ed7814cd7b5e7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/handler.go
@@ -0,0 +1,604 @@
+// 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 slog
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog/internal/buffer"
+ "reflect"
+ "slices"
+ "strconv"
+ "sync"
+ "time"
+)
+
+// A Handler handles log records produced by a Logger.
+//
+// A typical handler may print log records to standard error,
+// or write them to a file or database, or perhaps augment them
+// with additional attributes and pass them on to another handler.
+//
+// Any of the Handler's methods may be called concurrently with itself
+// or with other methods. It is the responsibility of the Handler to
+// manage this concurrency.
+//
+// Users of the slog package should not invoke Handler methods directly.
+// They should use the methods of [Logger] instead.
+type Handler interface {
+ // Enabled reports whether the handler handles records at the given level.
+ // The handler ignores records whose level is lower.
+ // It is called early, before any arguments are processed,
+ // to save effort if the log event should be discarded.
+ // If called from a Logger method, the first argument is the context
+ // passed to that method, or context.Background() if nil was passed
+ // or the method does not take a context.
+ // The context is passed so Enabled can use its values
+ // to make a decision.
+ Enabled(context.Context, Level) bool
+
+ // Handle handles the Record.
+ // It will only be called when Enabled returns true.
+ // The Context argument is as for Enabled.
+ // It is present solely to provide Handlers access to the context's values.
+ // Canceling the context should not affect record processing.
+ // (Among other things, log messages may be necessary to debug a
+ // cancellation-related problem.)
+ //
+ // Handle methods that produce output should observe the following rules:
+ // - If r.Time is the zero time, ignore the time.
+ // - If r.PC is zero, ignore it.
+ // - Attr's values should be resolved.
+ // - If an Attr's key and value are both the zero value, ignore the Attr.
+ // This can be tested with attr.Equal(Attr{}).
+ // - If a group's key is empty, inline the group's Attrs.
+ // - If a group has no Attrs (even if it has a non-empty key),
+ // ignore it.
+ Handle(context.Context, Record) error
+
+ // WithAttrs returns a new Handler whose attributes consist of
+ // both the receiver's attributes and the arguments.
+ // The Handler owns the slice: it may retain, modify or discard it.
+ WithAttrs(attrs []Attr) Handler
+
+ // WithGroup returns a new Handler with the given group appended to
+ // the receiver's existing groups.
+ // The keys of all subsequent attributes, whether added by With or in a
+ // Record, should be qualified by the sequence of group names.
+ //
+ // How this qualification happens is up to the Handler, so long as
+ // this Handler's attribute keys differ from those of another Handler
+ // with a different sequence of group names.
+ //
+ // A Handler should treat WithGroup as starting a Group of Attrs that ends
+ // at the end of the log event. That is,
+ //
+ // logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2))
+ //
+ // should behave like
+ //
+ // logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
+ //
+ // If the name is empty, WithGroup returns the receiver.
+ WithGroup(name string) Handler
+}
+
+type defaultHandler struct {
+ ch *commonHandler
+ // internal.DefaultOutput, except for testing
+ output func(pc uintptr, data []byte) error
+}
+
+func newDefaultHandler(output func(uintptr, []byte) error) *defaultHandler {
+ return &defaultHandler{
+ ch: &commonHandler{json: false},
+ output: output,
+ }
+}
+
+func (*defaultHandler) Enabled(_ context.Context, l Level) bool {
+ return l >= logLoggerLevel.Level()
+}
+
+// Collect the level, attributes and message in a string and
+// write it with the default log.Logger.
+// Let the log.Logger handle time and file/line.
+func (h *defaultHandler) Handle(ctx context.Context, r Record) error {
+ buf := buffer.New()
+ buf.WriteString(r.Level.String())
+ buf.WriteByte(' ')
+ buf.WriteString(r.Message)
+ state := h.ch.newHandleState(buf, true, " ")
+ defer state.free()
+ state.appendNonBuiltIns(r)
+ return h.output(r.PC, *buf)
+}
+
+func (h *defaultHandler) WithAttrs(as []Attr) Handler {
+ return &defaultHandler{h.ch.withAttrs(as), h.output}
+}
+
+func (h *defaultHandler) WithGroup(name string) Handler {
+ return &defaultHandler{h.ch.withGroup(name), h.output}
+}
+
+// HandlerOptions are options for a [TextHandler] or [JSONHandler].
+// A zero HandlerOptions consists entirely of default values.
+type HandlerOptions struct {
+ // AddSource causes the handler to compute the source code position
+ // of the log statement and add a SourceKey attribute to the output.
+ AddSource bool
+
+ // Level reports the minimum record level that will be logged.
+ // The handler discards records with lower levels.
+ // If Level is nil, the handler assumes LevelInfo.
+ // The handler calls Level.Level for each record processed;
+ // to adjust the minimum level dynamically, use a LevelVar.
+ Level Leveler
+
+ // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
+ // The attribute's value has been resolved (see [Value.Resolve]).
+ // If ReplaceAttr returns a zero Attr, the attribute is discarded.
+ //
+ // The built-in attributes with keys "time", "level", "source", and "msg"
+ // are passed to this function, except that time is omitted
+ // if zero, and source is omitted if AddSource is false.
+ //
+ // The first argument is a list of currently open groups that contain the
+ // Attr. It must not be retained or modified. ReplaceAttr is never called
+ // for Group attributes, only their contents. For example, the attribute
+ // list
+ //
+ // Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
+ //
+ // results in consecutive calls to ReplaceAttr with the following arguments:
+ //
+ // nil, Int("a", 1)
+ // []string{"g"}, Int("b", 2)
+ // nil, Int("c", 3)
+ //
+ // ReplaceAttr can be used to change the default keys of the built-in
+ // attributes, convert types (for example, to replace a `time.Time` with the
+ // integer seconds since the Unix epoch), sanitize personal information, or
+ // remove attributes from the output.
+ ReplaceAttr func(groups []string, a Attr) Attr
+}
+
+// Keys for "built-in" attributes.
+const (
+ // TimeKey is the key used by the built-in handlers for the time
+ // when the log method is called. The associated Value is a [time.Time].
+ TimeKey = "time"
+ // LevelKey is the key used by the built-in handlers for the level
+ // of the log call. The associated value is a [Level].
+ LevelKey = "level"
+ // MessageKey is the key used by the built-in handlers for the
+ // message of the log call. The associated value is a string.
+ MessageKey = "msg"
+ // SourceKey is the key used by the built-in handlers for the source file
+ // and line of the log call. The associated value is a *[Source].
+ SourceKey = "source"
+)
+
+type commonHandler struct {
+ json bool // true => output JSON; false => output text
+ opts HandlerOptions
+ preformattedAttrs []byte
+ // groupPrefix is for the text handler only.
+ // It holds the prefix for groups that were already pre-formatted.
+ // A group will appear here when a call to WithGroup is followed by
+ // a call to WithAttrs.
+ groupPrefix string
+ groups []string // all groups started from WithGroup
+ nOpenGroups int // the number of groups opened in preformattedAttrs
+ mu *sync.Mutex
+ w io.Writer
+}
+
+func (h *commonHandler) clone() *commonHandler {
+ // We can't use assignment because we can't copy the mutex.
+ return &commonHandler{
+ json: h.json,
+ opts: h.opts,
+ preformattedAttrs: slices.Clip(h.preformattedAttrs),
+ groupPrefix: h.groupPrefix,
+ groups: slices.Clip(h.groups),
+ nOpenGroups: h.nOpenGroups,
+ w: h.w,
+ mu: h.mu, // mutex shared among all clones of this handler
+ }
+}
+
+// enabled reports whether l is greater than or equal to the
+// minimum level.
+func (h *commonHandler) enabled(l Level) bool {
+ minLevel := LevelInfo
+ if h.opts.Level != nil {
+ minLevel = h.opts.Level.Level()
+ }
+ return l >= minLevel
+}
+
+func (h *commonHandler) withAttrs(as []Attr) *commonHandler {
+ // We are going to ignore empty groups, so if the entire slice consists of
+ // them, there is nothing to do.
+ if countEmptyGroups(as) == len(as) {
+ return h
+ }
+ h2 := h.clone()
+ // Pre-format the attributes as an optimization.
+ state := h2.newHandleState((*buffer.Buffer)(&h2.preformattedAttrs), false, "")
+ defer state.free()
+ state.prefix.WriteString(h.groupPrefix)
+ if pfa := h2.preformattedAttrs; len(pfa) > 0 {
+ state.sep = h.attrSep()
+ if h2.json && pfa[len(pfa)-1] == '{' {
+ state.sep = ""
+ }
+ }
+ // Remember the position in the buffer, in case all attrs are empty.
+ pos := state.buf.Len()
+ state.openGroups()
+ if !state.appendAttrs(as) {
+ state.buf.SetLen(pos)
+ } else {
+ // Remember the new prefix for later keys.
+ h2.groupPrefix = state.prefix.String()
+ // Remember how many opened groups are in preformattedAttrs,
+ // so we don't open them again when we handle a Record.
+ h2.nOpenGroups = len(h2.groups)
+ }
+ return h2
+}
+
+func (h *commonHandler) withGroup(name string) *commonHandler {
+ h2 := h.clone()
+ h2.groups = append(h2.groups, name)
+ return h2
+}
+
+// handle is the internal implementation of Handler.Handle
+// used by TextHandler and JSONHandler.
+func (h *commonHandler) handle(r Record) error {
+ state := h.newHandleState(buffer.New(), true, "")
+ defer state.free()
+ if h.json {
+ state.buf.WriteByte('{')
+ }
+ // Built-in attributes. They are not in a group.
+ stateGroups := state.groups
+ state.groups = nil // So ReplaceAttrs sees no groups instead of the pre groups.
+ rep := h.opts.ReplaceAttr
+ // time
+ if !r.Time.IsZero() {
+ key := TimeKey
+ val := r.Time.Round(0) // strip monotonic to match Attr behavior
+ if rep == nil {
+ state.appendKey(key)
+ state.appendTime(val)
+ } else {
+ state.appendAttr(Time(key, val))
+ }
+ }
+ // level
+ key := LevelKey
+ val := r.Level
+ if rep == nil {
+ state.appendKey(key)
+ state.appendString(val.String())
+ } else {
+ state.appendAttr(Any(key, val))
+ }
+ // source
+ if h.opts.AddSource {
+ state.appendAttr(Any(SourceKey, r.source()))
+ }
+ key = MessageKey
+ msg := r.Message
+ if rep == nil {
+ state.appendKey(key)
+ state.appendString(msg)
+ } else {
+ state.appendAttr(String(key, msg))
+ }
+ state.groups = stateGroups // Restore groups passed to ReplaceAttrs.
+ state.appendNonBuiltIns(r)
+ state.buf.WriteByte('\n')
+
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ _, err := h.w.Write(*state.buf)
+ return err
+}
+
+func (s *handleState) appendNonBuiltIns(r Record) {
+ // preformatted Attrs
+ if pfa := s.h.preformattedAttrs; len(pfa) > 0 {
+ s.buf.WriteString(s.sep)
+ s.buf.Write(pfa)
+ s.sep = s.h.attrSep()
+ if s.h.json && pfa[len(pfa)-1] == '{' {
+ s.sep = ""
+ }
+ }
+ // Attrs in Record -- unlike the built-in ones, they are in groups started
+ // from WithGroup.
+ // If the record has no Attrs, don't output any groups.
+ nOpenGroups := s.h.nOpenGroups
+ if r.NumAttrs() > 0 {
+ s.prefix.WriteString(s.h.groupPrefix)
+ // The group may turn out to be empty even though it has attrs (for
+ // example, ReplaceAttr may delete all the attrs).
+ // So remember where we are in the buffer, to restore the position
+ // later if necessary.
+ pos := s.buf.Len()
+ s.openGroups()
+ nOpenGroups = len(s.h.groups)
+ empty := true
+ r.Attrs(func(a Attr) bool {
+ if s.appendAttr(a) {
+ empty = false
+ }
+ return true
+ })
+ if empty {
+ s.buf.SetLen(pos)
+ nOpenGroups = s.h.nOpenGroups
+ }
+ }
+ if s.h.json {
+ // Close all open groups.
+ for range s.h.groups[:nOpenGroups] {
+ s.buf.WriteByte('}')
+ }
+ // Close the top-level object.
+ s.buf.WriteByte('}')
+ }
+}
+
+// attrSep returns the separator between attributes.
+func (h *commonHandler) attrSep() string {
+ if h.json {
+ return ","
+ }
+ return " "
+}
+
+// handleState holds state for a single call to commonHandler.handle.
+// The initial value of sep determines whether to emit a separator
+// before the next key, after which it stays true.
+type handleState struct {
+ h *commonHandler
+ buf *buffer.Buffer
+ freeBuf bool // should buf be freed?
+ sep string // separator to write before next key
+ prefix *buffer.Buffer // for text: key prefix
+ groups *[]string // pool-allocated slice of active groups, for ReplaceAttr
+}
+
+var groupPool = sync.Pool{New: func() any {
+ s := make([]string, 0, 10)
+ return &s
+}}
+
+func (h *commonHandler) newHandleState(buf *buffer.Buffer, freeBuf bool, sep string) handleState {
+ s := handleState{
+ h: h,
+ buf: buf,
+ freeBuf: freeBuf,
+ sep: sep,
+ prefix: buffer.New(),
+ }
+ if h.opts.ReplaceAttr != nil {
+ s.groups = groupPool.Get().(*[]string)
+ *s.groups = append(*s.groups, h.groups[:h.nOpenGroups]...)
+ }
+ return s
+}
+
+func (s *handleState) free() {
+ if s.freeBuf {
+ s.buf.Free()
+ }
+ if gs := s.groups; gs != nil {
+ *gs = (*gs)[:0]
+ groupPool.Put(gs)
+ }
+ s.prefix.Free()
+}
+
+func (s *handleState) openGroups() {
+ for _, n := range s.h.groups[s.h.nOpenGroups:] {
+ s.openGroup(n)
+ }
+}
+
+// Separator for group names and keys.
+const keyComponentSep = '.'
+
+// openGroup starts a new group of attributes
+// with the given name.
+func (s *handleState) openGroup(name string) {
+ if s.h.json {
+ s.appendKey(name)
+ s.buf.WriteByte('{')
+ s.sep = ""
+ } else {
+ s.prefix.WriteString(name)
+ s.prefix.WriteByte(keyComponentSep)
+ }
+ // Collect group names for ReplaceAttr.
+ if s.groups != nil {
+ *s.groups = append(*s.groups, name)
+ }
+}
+
+// closeGroup ends the group with the given name.
+func (s *handleState) closeGroup(name string) {
+ if s.h.json {
+ s.buf.WriteByte('}')
+ } else {
+ (*s.prefix) = (*s.prefix)[:len(*s.prefix)-len(name)-1 /* for keyComponentSep */]
+ }
+ s.sep = s.h.attrSep()
+ if s.groups != nil {
+ *s.groups = (*s.groups)[:len(*s.groups)-1]
+ }
+}
+
+// appendAttrs appends the slice of Attrs.
+// It reports whether something was appended.
+func (s *handleState) appendAttrs(as []Attr) bool {
+ nonEmpty := false
+ for _, a := range as {
+ if s.appendAttr(a) {
+ nonEmpty = true
+ }
+ }
+ return nonEmpty
+}
+
+// appendAttr appends the Attr's key and value.
+// It handles replacement and checking for an empty key.
+// It reports whether something was appended.
+func (s *handleState) appendAttr(a Attr) bool {
+ a.Value = a.Value.Resolve()
+ if rep := s.h.opts.ReplaceAttr; rep != nil && a.Value.Kind() != KindGroup {
+ var gs []string
+ if s.groups != nil {
+ gs = *s.groups
+ }
+ // a.Value is resolved before calling ReplaceAttr, so the user doesn't have to.
+ a = rep(gs, a)
+ // The ReplaceAttr function may return an unresolved Attr.
+ a.Value = a.Value.Resolve()
+ }
+ // Elide empty Attrs.
+ if a.isEmpty() {
+ return false
+ }
+ // Special case: Source.
+ if v := a.Value; v.Kind() == KindAny {
+ if src, ok := v.Any().(*Source); ok {
+ if s.h.json {
+ a.Value = src.group()
+ } else {
+ a.Value = StringValue(fmt.Sprintf("%s:%d", src.File, src.Line))
+ }
+ }
+ }
+ if a.Value.Kind() == KindGroup {
+ attrs := a.Value.Group()
+ // Output only non-empty groups.
+ if len(attrs) > 0 {
+ // The group may turn out to be empty even though it has attrs (for
+ // example, ReplaceAttr may delete all the attrs).
+ // So remember where we are in the buffer, to restore the position
+ // later if necessary.
+ pos := s.buf.Len()
+ // Inline a group with an empty key.
+ if a.Key != "" {
+ s.openGroup(a.Key)
+ }
+ if !s.appendAttrs(attrs) {
+ s.buf.SetLen(pos)
+ return false
+ }
+ if a.Key != "" {
+ s.closeGroup(a.Key)
+ }
+ }
+ } else {
+ s.appendKey(a.Key)
+ s.appendValue(a.Value)
+ }
+ return true
+}
+
+func (s *handleState) appendError(err error) {
+ s.appendString(fmt.Sprintf("!ERROR:%v", err))
+}
+
+func (s *handleState) appendKey(key string) {
+ s.buf.WriteString(s.sep)
+ if s.prefix != nil && len(*s.prefix) > 0 {
+ // TODO: optimize by avoiding allocation.
+ s.appendString(string(*s.prefix) + key)
+ } else {
+ s.appendString(key)
+ }
+ if s.h.json {
+ s.buf.WriteByte(':')
+ } else {
+ s.buf.WriteByte('=')
+ }
+ s.sep = s.h.attrSep()
+}
+
+func (s *handleState) appendString(str string) {
+ if s.h.json {
+ s.buf.WriteByte('"')
+ *s.buf = appendEscapedJSONString(*s.buf, str)
+ s.buf.WriteByte('"')
+ } else {
+ // text
+ if needsQuoting(str) {
+ *s.buf = strconv.AppendQuote(*s.buf, str)
+ } else {
+ s.buf.WriteString(str)
+ }
+ }
+}
+
+func (s *handleState) appendValue(v Value) {
+ defer func() {
+ if r := recover(); r != nil {
+ // If it panics with a nil pointer, the most likely cases are
+ // an encoding.TextMarshaler or error fails to guard against nil,
+ // in which case "" seems to be the feasible choice.
+ //
+ // Adapted from the code in fmt/print.go.
+ if v := reflect.ValueOf(v.any); v.Kind() == reflect.Pointer && v.IsNil() {
+ s.appendString("")
+ return
+ }
+
+ // Otherwise just print the original panic message.
+ s.appendString(fmt.Sprintf("!PANIC: %v", r))
+ }
+ }()
+
+ var err error
+ if s.h.json {
+ err = appendJSONValue(s, v)
+ } else {
+ err = appendTextValue(s, v)
+ }
+ if err != nil {
+ s.appendError(err)
+ }
+}
+
+func (s *handleState) appendTime(t time.Time) {
+ if s.h.json {
+ appendJSONTime(s, t)
+ } else {
+ *s.buf = appendRFC3339Millis(*s.buf, t)
+ }
+}
+
+func appendRFC3339Millis(b []byte, t time.Time) []byte {
+ // Format according to time.RFC3339Nano since it is highly optimized,
+ // but truncate it to use millisecond resolution.
+ // Unfortunately, that format trims trailing 0s, so add 1/10 millisecond
+ // to guarantee that there are exactly 4 digits after the period.
+ const prefixLen = len("2006-01-02T15:04:05.000")
+ n := len(b)
+ t = t.Truncate(time.Millisecond).Add(time.Millisecond / 10)
+ b = t.AppendFormat(b, time.RFC3339Nano)
+ b = append(b[:n+prefixLen], b[n+prefixLen+1:]...) // drop the 4th digit
+ return b
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/handler_test.go b/platform/dbops/binaries/go/go/src/log/slog/handler_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ce34526d0ba44aaa57d6bc822aff5425b5e73f8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/handler_test.go
@@ -0,0 +1,713 @@
+// 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.
+
+// TODO: verify that the output of Marshal{Text,JSON} is suitably escaped.
+
+package slog
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestDefaultHandle(t *testing.T) {
+ ctx := context.Background()
+ preAttrs := []Attr{Int("pre", 0)}
+ attrs := []Attr{Int("a", 1), String("b", "two")}
+ for _, test := range []struct {
+ name string
+ with func(Handler) Handler
+ attrs []Attr
+ want string
+ }{
+ {
+ name: "no attrs",
+ want: "INFO message",
+ },
+ {
+ name: "attrs",
+ attrs: attrs,
+ want: "INFO message a=1 b=two",
+ },
+ {
+ name: "preformatted",
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs) },
+ attrs: attrs,
+ want: "INFO message pre=0 a=1 b=two",
+ },
+ {
+ name: "groups",
+ attrs: []Attr{
+ Int("a", 1),
+ Group("g",
+ Int("b", 2),
+ Group("h", Int("c", 3)),
+ Int("d", 4)),
+ Int("e", 5),
+ },
+ want: "INFO message a=1 g.b=2 g.h.c=3 g.d=4 e=5",
+ },
+ {
+ name: "group",
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs).WithGroup("s") },
+ attrs: attrs,
+ want: "INFO message pre=0 s.a=1 s.b=two",
+ },
+ {
+ name: "preformatted groups",
+ with: func(h Handler) Handler {
+ return h.WithAttrs([]Attr{Int("p1", 1)}).
+ WithGroup("s1").
+ WithAttrs([]Attr{Int("p2", 2)}).
+ WithGroup("s2")
+ },
+ attrs: attrs,
+ want: "INFO message p1=1 s1.p2=2 s1.s2.a=1 s1.s2.b=two",
+ },
+ {
+ name: "two with-groups",
+ with: func(h Handler) Handler {
+ return h.WithAttrs([]Attr{Int("p1", 1)}).
+ WithGroup("s1").
+ WithGroup("s2")
+ },
+ attrs: attrs,
+ want: "INFO message p1=1 s1.s2.a=1 s1.s2.b=two",
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var got string
+ var h Handler = newDefaultHandler(func(_ uintptr, b []byte) error {
+ got = string(b)
+ return nil
+ })
+ if test.with != nil {
+ h = test.with(h)
+ }
+ r := NewRecord(time.Time{}, LevelInfo, "message", 0)
+ r.AddAttrs(test.attrs...)
+ if err := h.Handle(ctx, r); err != nil {
+ t.Fatal(err)
+ }
+ if got != test.want {
+ t.Errorf("\ngot %s\nwant %s", got, test.want)
+ }
+ })
+ }
+}
+
+func TestConcurrentWrites(t *testing.T) {
+ ctx := context.Background()
+ count := 1000
+ for _, handlerType := range []string{"text", "json"} {
+ t.Run(handlerType, func(t *testing.T) {
+ var buf bytes.Buffer
+ var h Handler
+ switch handlerType {
+ case "text":
+ h = NewTextHandler(&buf, nil)
+ case "json":
+ h = NewJSONHandler(&buf, nil)
+ default:
+ t.Fatalf("unexpected handlerType %q", handlerType)
+ }
+ sub1 := h.WithAttrs([]Attr{Bool("sub1", true)})
+ sub2 := h.WithAttrs([]Attr{Bool("sub2", true)})
+ var wg sync.WaitGroup
+ for i := 0; i < count; i++ {
+ sub1Record := NewRecord(time.Time{}, LevelInfo, "hello from sub1", 0)
+ sub1Record.AddAttrs(Int("i", i))
+ sub2Record := NewRecord(time.Time{}, LevelInfo, "hello from sub2", 0)
+ sub2Record.AddAttrs(Int("i", i))
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if err := sub1.Handle(ctx, sub1Record); err != nil {
+ t.Error(err)
+ }
+ if err := sub2.Handle(ctx, sub2Record); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ wg.Wait()
+ for i := 1; i <= 2; i++ {
+ want := "hello from sub" + strconv.Itoa(i)
+ n := strings.Count(buf.String(), want)
+ if n != count {
+ t.Fatalf("want %d occurrences of %q, got %d", count, want, n)
+ }
+ }
+ })
+ }
+}
+
+// Verify the common parts of TextHandler and JSONHandler.
+func TestJSONAndTextHandlers(t *testing.T) {
+ // remove all Attrs
+ removeAll := func(_ []string, a Attr) Attr { return Attr{} }
+
+ attrs := []Attr{String("a", "one"), Int("b", 2), Any("", nil)}
+ preAttrs := []Attr{Int("pre", 3), String("x", "y")}
+
+ for _, test := range []struct {
+ name string
+ replace func([]string, Attr) Attr
+ addSource bool
+ with func(Handler) Handler
+ preAttrs []Attr
+ attrs []Attr
+ wantText string
+ wantJSON string
+ }{
+ {
+ name: "basic",
+ attrs: attrs,
+ wantText: "time=2000-01-02T03:04:05.000Z level=INFO msg=message a=one b=2",
+ wantJSON: `{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"message","a":"one","b":2}`,
+ },
+ {
+ name: "empty key",
+ attrs: append(slices.Clip(attrs), Any("", "v")),
+ wantText: `time=2000-01-02T03:04:05.000Z level=INFO msg=message a=one b=2 ""=v`,
+ wantJSON: `{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"message","a":"one","b":2,"":"v"}`,
+ },
+ {
+ name: "cap keys",
+ replace: upperCaseKey,
+ attrs: attrs,
+ wantText: "TIME=2000-01-02T03:04:05.000Z LEVEL=INFO MSG=message A=one B=2",
+ wantJSON: `{"TIME":"2000-01-02T03:04:05Z","LEVEL":"INFO","MSG":"message","A":"one","B":2}`,
+ },
+ {
+ name: "remove all",
+ replace: removeAll,
+ attrs: attrs,
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "preformatted",
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs) },
+ preAttrs: preAttrs,
+ attrs: attrs,
+ wantText: "time=2000-01-02T03:04:05.000Z level=INFO msg=message pre=3 x=y a=one b=2",
+ wantJSON: `{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"message","pre":3,"x":"y","a":"one","b":2}`,
+ },
+ {
+ name: "preformatted cap keys",
+ replace: upperCaseKey,
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs) },
+ preAttrs: preAttrs,
+ attrs: attrs,
+ wantText: "TIME=2000-01-02T03:04:05.000Z LEVEL=INFO MSG=message PRE=3 X=y A=one B=2",
+ wantJSON: `{"TIME":"2000-01-02T03:04:05Z","LEVEL":"INFO","MSG":"message","PRE":3,"X":"y","A":"one","B":2}`,
+ },
+ {
+ name: "preformatted remove all",
+ replace: removeAll,
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs) },
+ preAttrs: preAttrs,
+ attrs: attrs,
+ wantText: "",
+ wantJSON: "{}",
+ },
+ {
+ name: "remove built-in",
+ replace: removeKeys(TimeKey, LevelKey, MessageKey),
+ attrs: attrs,
+ wantText: "a=one b=2",
+ wantJSON: `{"a":"one","b":2}`,
+ },
+ {
+ name: "preformatted remove built-in",
+ replace: removeKeys(TimeKey, LevelKey, MessageKey),
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs) },
+ attrs: attrs,
+ wantText: "pre=3 x=y a=one b=2",
+ wantJSON: `{"pre":3,"x":"y","a":"one","b":2}`,
+ },
+ {
+ name: "groups",
+ replace: removeKeys(TimeKey, LevelKey), // to simplify the result
+ attrs: []Attr{
+ Int("a", 1),
+ Group("g",
+ Int("b", 2),
+ Group("h", Int("c", 3)),
+ Int("d", 4)),
+ Int("e", 5),
+ },
+ wantText: "msg=message a=1 g.b=2 g.h.c=3 g.d=4 e=5",
+ wantJSON: `{"msg":"message","a":1,"g":{"b":2,"h":{"c":3},"d":4},"e":5}`,
+ },
+ {
+ name: "empty group",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{Group("g"), Group("h", Int("a", 1))},
+ wantText: "msg=message h.a=1",
+ wantJSON: `{"msg":"message","h":{"a":1}}`,
+ },
+ {
+ name: "nested empty group",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{
+ Group("g",
+ Group("h",
+ Group("i"), Group("j"))),
+ },
+ wantText: `msg=message`,
+ wantJSON: `{"msg":"message"}`,
+ },
+ {
+ name: "nested non-empty group",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{
+ Group("g",
+ Group("h",
+ Group("i"), Group("j", Int("a", 1)))),
+ },
+ wantText: `msg=message g.h.j.a=1`,
+ wantJSON: `{"msg":"message","g":{"h":{"j":{"a":1}}}}`,
+ },
+ {
+ name: "escapes",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{
+ String("a b", "x\t\n\000y"),
+ Group(" b.c=\"\\x2E\t",
+ String("d=e", "f.g\""),
+ Int("m.d", 1)), // dot is not escaped
+ },
+ wantText: `msg=message "a b"="x\t\n\x00y" " b.c=\"\\x2E\t.d=e"="f.g\"" " b.c=\"\\x2E\t.m.d"=1`,
+ wantJSON: `{"msg":"message","a b":"x\t\n\u0000y"," b.c=\"\\x2E\t":{"d=e":"f.g\"","m.d":1}}`,
+ },
+ {
+ name: "LogValuer",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{
+ Int("a", 1),
+ Any("name", logValueName{"Ren", "Hoek"}),
+ Int("b", 2),
+ },
+ wantText: "msg=message a=1 name.first=Ren name.last=Hoek b=2",
+ wantJSON: `{"msg":"message","a":1,"name":{"first":"Ren","last":"Hoek"},"b":2}`,
+ },
+ {
+ // Test resolution when there is no ReplaceAttr function.
+ name: "resolve",
+ attrs: []Attr{
+ Any("", &replace{Value{}}), // should be elided
+ Any("name", logValueName{"Ren", "Hoek"}),
+ },
+ wantText: "time=2000-01-02T03:04:05.000Z level=INFO msg=message name.first=Ren name.last=Hoek",
+ wantJSON: `{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"message","name":{"first":"Ren","last":"Hoek"}}`,
+ },
+ {
+ name: "with-group",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler { return h.WithAttrs(preAttrs).WithGroup("s") },
+ attrs: attrs,
+ wantText: "msg=message pre=3 x=y s.a=one s.b=2",
+ wantJSON: `{"msg":"message","pre":3,"x":"y","s":{"a":"one","b":2}}`,
+ },
+ {
+ name: "preformatted with-groups",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler {
+ return h.WithAttrs([]Attr{Int("p1", 1)}).
+ WithGroup("s1").
+ WithAttrs([]Attr{Int("p2", 2)}).
+ WithGroup("s2").
+ WithAttrs([]Attr{Int("p3", 3)})
+ },
+ attrs: attrs,
+ wantText: "msg=message p1=1 s1.p2=2 s1.s2.p3=3 s1.s2.a=one s1.s2.b=2",
+ wantJSON: `{"msg":"message","p1":1,"s1":{"p2":2,"s2":{"p3":3,"a":"one","b":2}}}`,
+ },
+ {
+ name: "two with-groups",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler {
+ return h.WithAttrs([]Attr{Int("p1", 1)}).
+ WithGroup("s1").
+ WithGroup("s2")
+ },
+ attrs: attrs,
+ wantText: "msg=message p1=1 s1.s2.a=one s1.s2.b=2",
+ wantJSON: `{"msg":"message","p1":1,"s1":{"s2":{"a":"one","b":2}}}`,
+ },
+ {
+ name: "empty with-groups",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler {
+ return h.WithGroup("x").WithGroup("y")
+ },
+ wantText: "msg=message",
+ wantJSON: `{"msg":"message"}`,
+ },
+ {
+ name: "empty with-groups, no non-empty attrs",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler {
+ return h.WithGroup("x").WithAttrs([]Attr{Group("g")}).WithGroup("y")
+ },
+ wantText: "msg=message",
+ wantJSON: `{"msg":"message"}`,
+ },
+ {
+ name: "one empty with-group",
+ replace: removeKeys(TimeKey, LevelKey),
+ with: func(h Handler) Handler {
+ return h.WithGroup("x").WithAttrs([]Attr{Int("a", 1)}).WithGroup("y")
+ },
+ attrs: []Attr{Group("g", Group("h"))},
+ wantText: "msg=message x.a=1",
+ wantJSON: `{"msg":"message","x":{"a":1}}`,
+ },
+ {
+ name: "GroupValue as Attr value",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{{"v", AnyValue(IntValue(3))}},
+ wantText: "msg=message v=3",
+ wantJSON: `{"msg":"message","v":3}`,
+ },
+ {
+ name: "byte slice",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{Any("bs", []byte{1, 2, 3, 4})},
+ wantText: `msg=message bs="\x01\x02\x03\x04"`,
+ wantJSON: `{"msg":"message","bs":"AQIDBA=="}`,
+ },
+ {
+ name: "json.RawMessage",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{Any("bs", json.RawMessage([]byte("1234")))},
+ wantText: `msg=message bs="1234"`,
+ wantJSON: `{"msg":"message","bs":1234}`,
+ },
+ {
+ name: "inline group",
+ replace: removeKeys(TimeKey, LevelKey),
+ attrs: []Attr{
+ Int("a", 1),
+ Group("", Int("b", 2), Int("c", 3)),
+ Int("d", 4),
+ },
+ wantText: `msg=message a=1 b=2 c=3 d=4`,
+ wantJSON: `{"msg":"message","a":1,"b":2,"c":3,"d":4}`,
+ },
+ {
+ name: "Source",
+ replace: func(gs []string, a Attr) Attr {
+ if a.Key == SourceKey {
+ s := a.Value.Any().(*Source)
+ s.File = filepath.Base(s.File)
+ return Any(a.Key, s)
+ }
+ return removeKeys(TimeKey, LevelKey)(gs, a)
+ },
+ addSource: true,
+ wantText: `source=handler_test.go:$LINE msg=message`,
+ wantJSON: `{"source":{"function":"log/slog.TestJSONAndTextHandlers","file":"handler_test.go","line":$LINE},"msg":"message"}`,
+ },
+ {
+ name: "replace built-in with group",
+ replace: func(_ []string, a Attr) Attr {
+ if a.Key == TimeKey {
+ return Group(TimeKey, "mins", 3, "secs", 2)
+ }
+ if a.Key == LevelKey {
+ return Attr{}
+ }
+ return a
+ },
+ wantText: `time.mins=3 time.secs=2 msg=message`,
+ wantJSON: `{"time":{"mins":3,"secs":2},"msg":"message"}`,
+ },
+ {
+ name: "replace empty",
+ replace: func([]string, Attr) Attr { return Attr{} },
+ attrs: []Attr{Group("g", Int("a", 1))},
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "replace empty 1",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("a", 1)})
+ },
+ replace: func([]string, Attr) Attr { return Attr{} },
+ attrs: []Attr{Group("h", Int("b", 2))},
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "replace empty 2",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("a", 1)}).WithGroup("h").WithAttrs([]Attr{Int("b", 2)})
+ },
+ replace: func([]string, Attr) Attr { return Attr{} },
+ attrs: []Attr{Group("i", Int("c", 3))},
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "replace empty 3",
+ with: func(h Handler) Handler { return h.WithGroup("g") },
+ replace: func([]string, Attr) Attr { return Attr{} },
+ attrs: []Attr{Int("a", 1)},
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "replace empty inline",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("a", 1)}).WithGroup("h").WithAttrs([]Attr{Int("b", 2)})
+ },
+ replace: func([]string, Attr) Attr { return Attr{} },
+ attrs: []Attr{Group("", Int("c", 3))},
+ wantText: "",
+ wantJSON: `{}`,
+ },
+ {
+ name: "replace partial empty attrs 1",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("a", 1)}).WithGroup("h").WithAttrs([]Attr{Int("b", 2)})
+ },
+ replace: func(groups []string, attr Attr) Attr {
+ return removeKeys(TimeKey, LevelKey, MessageKey, "a")(groups, attr)
+ },
+ attrs: []Attr{Group("i", Int("c", 3))},
+ wantText: "g.h.b=2 g.h.i.c=3",
+ wantJSON: `{"g":{"h":{"b":2,"i":{"c":3}}}}`,
+ },
+ {
+ name: "replace partial empty attrs 2",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("a", 1)}).WithAttrs([]Attr{Int("n", 4)}).WithGroup("h").WithAttrs([]Attr{Int("b", 2)})
+ },
+ replace: func(groups []string, attr Attr) Attr {
+ return removeKeys(TimeKey, LevelKey, MessageKey, "a", "b")(groups, attr)
+ },
+ attrs: []Attr{Group("i", Int("c", 3))},
+ wantText: "g.n=4 g.h.i.c=3",
+ wantJSON: `{"g":{"n":4,"h":{"i":{"c":3}}}}`,
+ },
+ {
+ name: "replace partial empty attrs 3",
+ with: func(h Handler) Handler {
+ return h.WithGroup("g").WithAttrs([]Attr{Int("x", 0)}).WithAttrs([]Attr{Int("a", 1)}).WithAttrs([]Attr{Int("n", 4)}).WithGroup("h").WithAttrs([]Attr{Int("b", 2)})
+ },
+ replace: func(groups []string, attr Attr) Attr {
+ return removeKeys(TimeKey, LevelKey, MessageKey, "a", "c")(groups, attr)
+ },
+ attrs: []Attr{Group("i", Int("c", 3))},
+ wantText: "g.x=0 g.n=4 g.h.b=2",
+ wantJSON: `{"g":{"x":0,"n":4,"h":{"b":2}}}`,
+ },
+ {
+ name: "replace resolved group",
+ replace: func(groups []string, a Attr) Attr {
+ if a.Value.Kind() == KindGroup {
+ return Attr{"bad", IntValue(1)}
+ }
+ return removeKeys(TimeKey, LevelKey, MessageKey)(groups, a)
+ },
+ attrs: []Attr{Any("name", logValueName{"Perry", "Platypus"})},
+ wantText: "name.first=Perry name.last=Platypus",
+ wantJSON: `{"name":{"first":"Perry","last":"Platypus"}}`,
+ },
+ } {
+ r := NewRecord(testTime, LevelInfo, "message", callerPC(2))
+ line := strconv.Itoa(r.source().Line)
+ r.AddAttrs(test.attrs...)
+ var buf bytes.Buffer
+ opts := HandlerOptions{ReplaceAttr: test.replace, AddSource: test.addSource}
+ t.Run(test.name, func(t *testing.T) {
+ for _, handler := range []struct {
+ name string
+ h Handler
+ want string
+ }{
+ {"text", NewTextHandler(&buf, &opts), test.wantText},
+ {"json", NewJSONHandler(&buf, &opts), test.wantJSON},
+ } {
+ t.Run(handler.name, func(t *testing.T) {
+ h := handler.h
+ if test.with != nil {
+ h = test.with(h)
+ }
+ buf.Reset()
+ if err := h.Handle(nil, r); err != nil {
+ t.Fatal(err)
+ }
+ want := strings.ReplaceAll(handler.want, "$LINE", line)
+ got := strings.TrimSuffix(buf.String(), "\n")
+ if got != want {
+ t.Errorf("\ngot %s\nwant %s\n", got, want)
+ }
+ })
+ }
+ })
+ }
+}
+
+// removeKeys returns a function suitable for HandlerOptions.ReplaceAttr
+// that removes all Attrs with the given keys.
+func removeKeys(keys ...string) func([]string, Attr) Attr {
+ return func(_ []string, a Attr) Attr {
+ for _, k := range keys {
+ if a.Key == k {
+ return Attr{}
+ }
+ }
+ return a
+ }
+}
+
+func upperCaseKey(_ []string, a Attr) Attr {
+ a.Key = strings.ToUpper(a.Key)
+ return a
+}
+
+type logValueName struct {
+ first, last string
+}
+
+func (n logValueName) LogValue() Value {
+ return GroupValue(
+ String("first", n.first),
+ String("last", n.last))
+}
+
+func TestHandlerEnabled(t *testing.T) {
+ levelVar := func(l Level) *LevelVar {
+ var al LevelVar
+ al.Set(l)
+ return &al
+ }
+
+ for _, test := range []struct {
+ leveler Leveler
+ want bool
+ }{
+ {nil, true},
+ {LevelWarn, false},
+ {&LevelVar{}, true}, // defaults to Info
+ {levelVar(LevelWarn), false},
+ {LevelDebug, true},
+ {levelVar(LevelDebug), true},
+ } {
+ h := &commonHandler{opts: HandlerOptions{Level: test.leveler}}
+ got := h.enabled(LevelInfo)
+ if got != test.want {
+ t.Errorf("%v: got %t, want %t", test.leveler, got, test.want)
+ }
+ }
+}
+
+func TestSecondWith(t *testing.T) {
+ // Verify that a second call to Logger.With does not corrupt
+ // the original.
+ var buf bytes.Buffer
+ h := NewTextHandler(&buf, &HandlerOptions{ReplaceAttr: removeKeys(TimeKey)})
+ logger := New(h).With(
+ String("app", "playground"),
+ String("role", "tester"),
+ Int("data_version", 2),
+ )
+ appLogger := logger.With("type", "log") // this becomes type=met
+ _ = logger.With("type", "metric")
+ appLogger.Info("foo")
+ got := strings.TrimSpace(buf.String())
+ want := `level=INFO msg=foo app=playground role=tester data_version=2 type=log`
+ if got != want {
+ t.Errorf("\ngot %s\nwant %s", got, want)
+ }
+}
+
+func TestReplaceAttrGroups(t *testing.T) {
+ // Verify that ReplaceAttr is called with the correct groups.
+ type ga struct {
+ groups string
+ key string
+ val string
+ }
+
+ var got []ga
+
+ h := NewTextHandler(io.Discard, &HandlerOptions{ReplaceAttr: func(gs []string, a Attr) Attr {
+ v := a.Value.String()
+ if a.Key == TimeKey {
+ v = ""
+ }
+ got = append(got, ga{strings.Join(gs, ","), a.Key, v})
+ return a
+ }})
+ New(h).
+ With(Int("a", 1)).
+ WithGroup("g1").
+ With(Int("b", 2)).
+ WithGroup("g2").
+ With(
+ Int("c", 3),
+ Group("g3", Int("d", 4)),
+ Int("e", 5)).
+ Info("m",
+ Int("f", 6),
+ Group("g4", Int("h", 7)),
+ Int("i", 8))
+
+ want := []ga{
+ {"", "a", "1"},
+ {"g1", "b", "2"},
+ {"g1,g2", "c", "3"},
+ {"g1,g2,g3", "d", "4"},
+ {"g1,g2", "e", "5"},
+ {"", "time", ""},
+ {"", "level", "INFO"},
+ {"", "msg", "m"},
+ {"g1,g2", "f", "6"},
+ {"g1,g2,g4", "h", "7"},
+ {"g1,g2", "i", "8"},
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("\ngot %v\nwant %v", got, want)
+ }
+}
+
+const rfc3339Millis = "2006-01-02T15:04:05.000Z07:00"
+
+func TestWriteTimeRFC3339(t *testing.T) {
+ for _, tm := range []time.Time{
+ time.Date(2000, 1, 2, 3, 4, 5, 0, time.UTC),
+ time.Date(2000, 1, 2, 3, 4, 5, 400, time.Local),
+ time.Date(2000, 11, 12, 3, 4, 500, 5e7, time.UTC),
+ } {
+ got := string(appendRFC3339Millis(nil, tm))
+ want := tm.Format(rfc3339Millis)
+ if got != want {
+ t.Errorf("got %s, want %s", got, want)
+ }
+ }
+}
+
+func BenchmarkWriteTime(b *testing.B) {
+ tm := time.Date(2022, 3, 4, 5, 6, 7, 823456789, time.Local)
+ b.ResetTimer()
+ var buf []byte
+ for i := 0; i < b.N; i++ {
+ buf = appendRFC3339Millis(buf[:0], tm)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks.go b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a28523beb44aeb11c893bde975083cf557160f2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks.go
@@ -0,0 +1,50 @@
+// 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 benchmarks contains benchmarks for slog.
+//
+// These benchmarks are loosely based on github.com/uber-go/zap/benchmarks.
+// They have the following desirable properties:
+//
+// - They test a complete log event, from the user's call to its return.
+//
+// - The benchmarked code is run concurrently in multiple goroutines, to
+// better simulate a real server (the most common environment for structured
+// logs).
+//
+// - Some handlers are optimistic versions of real handlers, doing real-world
+// tasks as fast as possible (and sometimes faster, in that an
+// implementation may not be concurrency-safe). This gives us an upper bound
+// on handler performance, so we can evaluate the (handler-independent) core
+// activity of the package in an end-to-end context without concern that a
+// slow handler implementation is skewing the results.
+//
+// - We also test the built-in handlers, for comparison.
+package benchmarks
+
+import (
+ "errors"
+ "log/slog"
+ "time"
+)
+
+const testMessage = "Test logging, but use a somewhat realistic message length."
+
+var (
+ testTime = time.Date(2022, time.May, 1, 0, 0, 0, 0, time.UTC)
+ testString = "7e3b3b2aaeff56a7108fe11e154200dd/7819479873059528190"
+ testInt = 32768
+ testDuration = 23 * time.Second
+ testError = errors.New("fail")
+)
+
+var testAttrs = []slog.Attr{
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+}
+
+const wantText = "time=1651363200 level=0 msg=Test logging, but use a somewhat realistic message length. string=7e3b3b2aaeff56a7108fe11e154200dd/7819479873059528190 status=32768 duration=23000000000 time=1651363200 error=fail\n"
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks_test.go b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..18643b73e6c8a0f62586311aa2a8d84218917237
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/benchmarks_test.go
@@ -0,0 +1,152 @@
+// 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 benchmarks
+
+import (
+ "context"
+ "flag"
+ "internal/race"
+ "io"
+ "log/slog"
+ "log/slog/internal"
+ "testing"
+)
+
+func init() {
+ flag.BoolVar(&internal.IgnorePC, "nopc", false, "do not invoke runtime.Callers")
+}
+
+// We pass Attrs inline because it affects allocations: building
+// up a list outside of the benchmarked code and passing it in with "..."
+// reduces measured allocations.
+
+func BenchmarkAttrs(b *testing.B) {
+ ctx := context.Background()
+ for _, handler := range []struct {
+ name string
+ h slog.Handler
+ skipRace bool
+ }{
+ {"disabled", disabledHandler{}, false},
+ {"async discard", newAsyncHandler(), true},
+ {"fastText discard", newFastTextHandler(io.Discard), false},
+ {"Text discard", slog.NewTextHandler(io.Discard, nil), false},
+ {"JSON discard", slog.NewJSONHandler(io.Discard, nil), false},
+ } {
+ logger := slog.New(handler.h)
+ b.Run(handler.name, func(b *testing.B) {
+ if handler.skipRace && race.Enabled {
+ b.Skip("skipping benchmark in race mode")
+ }
+ for _, call := range []struct {
+ name string
+ f func()
+ }{
+ {
+ // The number should match nAttrsInline in slog/record.go.
+ // This should exercise the code path where no allocations
+ // happen in Record or Attr. If there are allocations, they
+ // should only be from Duration.String and Time.String.
+ "5 args",
+ func() {
+ logger.LogAttrs(nil, slog.LevelInfo, testMessage,
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ )
+ },
+ },
+ {
+ "5 args ctx",
+ func() {
+ logger.LogAttrs(ctx, slog.LevelInfo, testMessage,
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ )
+ },
+ },
+ {
+ "10 args",
+ func() {
+ logger.LogAttrs(nil, slog.LevelInfo, testMessage,
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ )
+ },
+ },
+ {
+ // Try an extreme value to see if the results are reasonable.
+ "40 args",
+ func() {
+ logger.LogAttrs(nil, slog.LevelInfo, testMessage,
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ slog.String("string", testString),
+ slog.Int("status", testInt),
+ slog.Duration("duration", testDuration),
+ slog.Time("time", testTime),
+ slog.Any("error", testError),
+ )
+ },
+ },
+ } {
+ b.Run(call.name, func(b *testing.B) {
+ b.ReportAllocs()
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ call.f()
+ }
+ })
+ })
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers.go b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers.go
new file mode 100644
index 0000000000000000000000000000000000000000..091e2ddcca0ac1af58f143d952b9d12b558fe963
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers.go
@@ -0,0 +1,148 @@
+// 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 benchmarks
+
+// Handlers for benchmarking.
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "log/slog/internal/buffer"
+ "strconv"
+ "time"
+)
+
+// A fastTextHandler writes a Record to an io.Writer in a format similar to
+// slog.TextHandler, but without quoting or locking. It has a few other
+// performance-motivated shortcuts, like writing times as seconds since the
+// epoch instead of strings.
+//
+// It is intended to represent a high-performance Handler that synchronously
+// writes text (as opposed to binary).
+type fastTextHandler struct {
+ w io.Writer
+}
+
+func newFastTextHandler(w io.Writer) slog.Handler {
+ return &fastTextHandler{w: w}
+}
+
+func (h *fastTextHandler) Enabled(context.Context, slog.Level) bool { return true }
+
+func (h *fastTextHandler) Handle(_ context.Context, r slog.Record) error {
+ buf := buffer.New()
+ defer buf.Free()
+
+ if !r.Time.IsZero() {
+ buf.WriteString("time=")
+ h.appendTime(buf, r.Time)
+ buf.WriteByte(' ')
+ }
+ buf.WriteString("level=")
+ *buf = strconv.AppendInt(*buf, int64(r.Level), 10)
+ buf.WriteByte(' ')
+ buf.WriteString("msg=")
+ buf.WriteString(r.Message)
+ r.Attrs(func(a slog.Attr) bool {
+ buf.WriteByte(' ')
+ buf.WriteString(a.Key)
+ buf.WriteByte('=')
+ h.appendValue(buf, a.Value)
+ return true
+ })
+ buf.WriteByte('\n')
+ _, err := h.w.Write(*buf)
+ return err
+}
+
+func (h *fastTextHandler) appendValue(buf *buffer.Buffer, v slog.Value) {
+ switch v.Kind() {
+ case slog.KindString:
+ buf.WriteString(v.String())
+ case slog.KindInt64:
+ *buf = strconv.AppendInt(*buf, v.Int64(), 10)
+ case slog.KindUint64:
+ *buf = strconv.AppendUint(*buf, v.Uint64(), 10)
+ case slog.KindFloat64:
+ *buf = strconv.AppendFloat(*buf, v.Float64(), 'g', -1, 64)
+ case slog.KindBool:
+ *buf = strconv.AppendBool(*buf, v.Bool())
+ case slog.KindDuration:
+ *buf = strconv.AppendInt(*buf, v.Duration().Nanoseconds(), 10)
+ case slog.KindTime:
+ h.appendTime(buf, v.Time())
+ case slog.KindAny:
+ a := v.Any()
+ switch a := a.(type) {
+ case error:
+ buf.WriteString(a.Error())
+ default:
+ fmt.Fprint(buf, a)
+ }
+ default:
+ panic(fmt.Sprintf("bad kind: %s", v.Kind()))
+ }
+}
+
+func (h *fastTextHandler) appendTime(buf *buffer.Buffer, t time.Time) {
+ *buf = strconv.AppendInt(*buf, t.Unix(), 10)
+}
+
+func (h *fastTextHandler) WithAttrs([]slog.Attr) slog.Handler {
+ panic("fastTextHandler: With unimplemented")
+}
+
+func (*fastTextHandler) WithGroup(string) slog.Handler {
+ panic("fastTextHandler: WithGroup unimplemented")
+}
+
+// An asyncHandler simulates a Handler that passes Records to a
+// background goroutine for processing.
+// Because sending to a channel can be expensive due to locking,
+// we simulate a lock-free queue by adding the Record to a ring buffer.
+// Omitting the locking makes this little more than a copy of the Record,
+// but that is a worthwhile thing to measure because Records are on the large
+// side. Since nothing actually reads from the ring buffer, it can handle an
+// arbitrary number of Records without either blocking or allocation.
+type asyncHandler struct {
+ ringBuffer [100]slog.Record
+ next int
+}
+
+func newAsyncHandler() *asyncHandler {
+ return &asyncHandler{}
+}
+
+func (*asyncHandler) Enabled(context.Context, slog.Level) bool { return true }
+
+func (h *asyncHandler) Handle(_ context.Context, r slog.Record) error {
+ h.ringBuffer[h.next] = r.Clone()
+ h.next = (h.next + 1) % len(h.ringBuffer)
+ return nil
+}
+
+func (*asyncHandler) WithAttrs([]slog.Attr) slog.Handler {
+ panic("asyncHandler: With unimplemented")
+}
+
+func (*asyncHandler) WithGroup(string) slog.Handler {
+ panic("asyncHandler: WithGroup unimplemented")
+}
+
+// A disabledHandler's Enabled method always returns false.
+type disabledHandler struct{}
+
+func (disabledHandler) Enabled(context.Context, slog.Level) bool { return false }
+func (disabledHandler) Handle(context.Context, slog.Record) error { panic("should not be called") }
+
+func (disabledHandler) WithAttrs([]slog.Attr) slog.Handler {
+ panic("disabledHandler: With unimplemented")
+}
+
+func (disabledHandler) WithGroup(string) slog.Handler {
+ panic("disabledHandler: WithGroup unimplemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers_test.go b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0e0fbf169f3f4e93718133946c12c7a3c2e78d1e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/benchmarks/handlers_test.go
@@ -0,0 +1,46 @@
+// 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 benchmarks
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "slices"
+ "testing"
+)
+
+func TestHandlers(t *testing.T) {
+ ctx := context.Background()
+ r := slog.NewRecord(testTime, slog.LevelInfo, testMessage, 0)
+ r.AddAttrs(testAttrs...)
+ t.Run("text", func(t *testing.T) {
+ var b bytes.Buffer
+ h := newFastTextHandler(&b)
+ if err := h.Handle(ctx, r); err != nil {
+ t.Fatal(err)
+ }
+ got := b.String()
+ if got != wantText {
+ t.Errorf("\ngot %q\nwant %q", got, wantText)
+ }
+ })
+ t.Run("async", func(t *testing.T) {
+ h := newAsyncHandler()
+ if err := h.Handle(ctx, r); err != nil {
+ t.Fatal(err)
+ }
+ got := h.ringBuffer[0]
+ if !got.Time.Equal(r.Time) || !slices.EqualFunc(attrSlice(got), attrSlice(r), slog.Attr.Equal) {
+ t.Errorf("got %+v, want %+v", got, r)
+ }
+ })
+}
+
+func attrSlice(r slog.Record) []slog.Attr {
+ var as []slog.Attr
+ r.Attrs(func(a slog.Attr) bool { as = append(as, a); return true })
+ return as
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer.go b/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..310ec37d4a12156814874e2db084057f008031ec
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer.go
@@ -0,0 +1,63 @@
+// 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 buffer provides a pool-allocated byte buffer.
+package buffer
+
+import "sync"
+
+// buffer adapted from go/src/fmt/print.go
+type Buffer []byte
+
+// Having an initial size gives a dramatic speedup.
+var bufPool = sync.Pool{
+ New: func() any {
+ b := make([]byte, 0, 1024)
+ return (*Buffer)(&b)
+ },
+}
+
+func New() *Buffer {
+ return bufPool.Get().(*Buffer)
+}
+
+func (b *Buffer) Free() {
+ // To reduce peak allocation, return only smaller buffers to the pool.
+ const maxBufferSize = 16 << 10
+ if cap(*b) <= maxBufferSize {
+ *b = (*b)[:0]
+ bufPool.Put(b)
+ }
+}
+
+func (b *Buffer) Reset() {
+ b.SetLen(0)
+}
+
+func (b *Buffer) Write(p []byte) (int, error) {
+ *b = append(*b, p...)
+ return len(p), nil
+}
+
+func (b *Buffer) WriteString(s string) (int, error) {
+ *b = append(*b, s...)
+ return len(s), nil
+}
+
+func (b *Buffer) WriteByte(c byte) error {
+ *b = append(*b, c)
+ return nil
+}
+
+func (b *Buffer) String() string {
+ return string(*b)
+}
+
+func (b *Buffer) Len() int {
+ return len(*b)
+}
+
+func (b *Buffer) SetLen(n int) {
+ *b = (*b)[:n]
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer_test.go b/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..06f8284651151c9e27c8042cded46f471fcb1e6c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/buffer/buffer_test.go
@@ -0,0 +1,40 @@
+// 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 buffer
+
+import (
+ "internal/race"
+ "internal/testenv"
+ "testing"
+)
+
+func Test(t *testing.T) {
+ b := New()
+ defer b.Free()
+ b.WriteString("hello")
+ b.WriteByte(',')
+ b.Write([]byte(" world"))
+
+ got := b.String()
+ want := "hello, world"
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
+func TestAlloc(t *testing.T) {
+ if race.Enabled {
+ t.Skip("skipping test in race mode")
+ }
+ testenv.SkipIfOptimizationOff(t)
+ got := int(testing.AllocsPerRun(5, func() {
+ b := New()
+ defer b.Free()
+ b.WriteString("not 1K worth of bytes")
+ }))
+ if got != 0 {
+ t.Errorf("got %d allocs, want 0", got)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/ignorepc.go b/platform/dbops/binaries/go/go/src/log/slog/internal/ignorepc.go
new file mode 100644
index 0000000000000000000000000000000000000000..d1256426ff22f8fbb87c64648bd8ed1ec4ba3808
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/ignorepc.go
@@ -0,0 +1,9 @@
+// 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 internal
+
+// If IgnorePC is true, do not invoke runtime.Callers to get the pc.
+// This is solely for benchmarking the slowdown from runtime.Callers.
+var IgnorePC = false
diff --git a/platform/dbops/binaries/go/go/src/log/slog/internal/slogtest/slogtest.go b/platform/dbops/binaries/go/go/src/log/slog/internal/slogtest/slogtest.go
new file mode 100644
index 0000000000000000000000000000000000000000..d58766284430ce3ec9c41a4fdfb7678ba33d2f3b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/internal/slogtest/slogtest.go
@@ -0,0 +1,18 @@
+// 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 slogtest contains support functions for testing slog.
+package slogtest
+
+import "log/slog"
+
+// RemoveTime removes the top-level time attribute.
+// It is intended to be used as a ReplaceAttr function,
+// to make example output deterministic.
+func RemoveTime(groups []string, a slog.Attr) slog.Attr {
+ if a.Key == slog.TimeKey && len(groups) == 0 {
+ return slog.Attr{}
+ }
+ return a
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/json_handler.go b/platform/dbops/binaries/go/go/src/log/slog/json_handler.go
new file mode 100644
index 0000000000000000000000000000000000000000..da3eae1a8ec0d35bd35548f794f1f22d4d3bc7c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/json_handler.go
@@ -0,0 +1,336 @@
+// 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 slog
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog/internal/buffer"
+ "strconv"
+ "sync"
+ "time"
+ "unicode/utf8"
+)
+
+// JSONHandler is a [Handler] that writes Records to an [io.Writer] as
+// line-delimited JSON objects.
+type JSONHandler struct {
+ *commonHandler
+}
+
+// NewJSONHandler creates a [JSONHandler] that writes to w,
+// using the given options.
+// If opts is nil, the default options are used.
+func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler {
+ if opts == nil {
+ opts = &HandlerOptions{}
+ }
+ return &JSONHandler{
+ &commonHandler{
+ json: true,
+ w: w,
+ opts: *opts,
+ mu: &sync.Mutex{},
+ },
+ }
+}
+
+// Enabled reports whether the handler handles records at the given level.
+// The handler ignores records whose level is lower.
+func (h *JSONHandler) Enabled(_ context.Context, level Level) bool {
+ return h.commonHandler.enabled(level)
+}
+
+// WithAttrs returns a new [JSONHandler] whose attributes consists
+// of h's attributes followed by attrs.
+func (h *JSONHandler) WithAttrs(attrs []Attr) Handler {
+ return &JSONHandler{commonHandler: h.commonHandler.withAttrs(attrs)}
+}
+
+func (h *JSONHandler) WithGroup(name string) Handler {
+ return &JSONHandler{commonHandler: h.commonHandler.withGroup(name)}
+}
+
+// Handle formats its argument [Record] as a JSON object on a single line.
+//
+// If the Record's time is zero, the time is omitted.
+// Otherwise, the key is "time"
+// and the value is output as with json.Marshal.
+//
+// If the Record's level is zero, the level is omitted.
+// Otherwise, the key is "level"
+// and the value of [Level.String] is output.
+//
+// If the AddSource option is set and source information is available,
+// the key is "source", and the value is a record of type [Source].
+//
+// The message's key is "msg".
+//
+// To modify these or other attributes, or remove them from the output, use
+// [HandlerOptions.ReplaceAttr].
+//
+// Values are formatted as with an [encoding/json.Encoder] with SetEscapeHTML(false),
+// with two exceptions.
+//
+// First, an Attr whose Value is of type error is formatted as a string, by
+// calling its Error method. Only errors in Attrs receive this special treatment,
+// not errors embedded in structs, slices, maps or other data structures that
+// are processed by the [encoding/json] package.
+//
+// Second, an encoding failure does not cause Handle to return an error.
+// Instead, the error message is formatted as a string.
+//
+// Each call to Handle results in a single serialized call to io.Writer.Write.
+func (h *JSONHandler) Handle(_ context.Context, r Record) error {
+ return h.commonHandler.handle(r)
+}
+
+// Adapted from time.Time.MarshalJSON to avoid allocation.
+func appendJSONTime(s *handleState, t time.Time) {
+ if y := t.Year(); y < 0 || y >= 10000 {
+ // RFC 3339 is clear that years are 4 digits exactly.
+ // See golang.org/issue/4556#c15 for more discussion.
+ s.appendError(errors.New("time.Time year outside of range [0,9999]"))
+ }
+ s.buf.WriteByte('"')
+ *s.buf = t.AppendFormat(*s.buf, time.RFC3339Nano)
+ s.buf.WriteByte('"')
+}
+
+func appendJSONValue(s *handleState, v Value) error {
+ switch v.Kind() {
+ case KindString:
+ s.appendString(v.str())
+ case KindInt64:
+ *s.buf = strconv.AppendInt(*s.buf, v.Int64(), 10)
+ case KindUint64:
+ *s.buf = strconv.AppendUint(*s.buf, v.Uint64(), 10)
+ case KindFloat64:
+ // json.Marshal is funny about floats; it doesn't
+ // always match strconv.AppendFloat. So just call it.
+ // That's expensive, but floats are rare.
+ if err := appendJSONMarshal(s.buf, v.Float64()); err != nil {
+ return err
+ }
+ case KindBool:
+ *s.buf = strconv.AppendBool(*s.buf, v.Bool())
+ case KindDuration:
+ // Do what json.Marshal does.
+ *s.buf = strconv.AppendInt(*s.buf, int64(v.Duration()), 10)
+ case KindTime:
+ s.appendTime(v.Time())
+ case KindAny:
+ a := v.Any()
+ _, jm := a.(json.Marshaler)
+ if err, ok := a.(error); ok && !jm {
+ s.appendString(err.Error())
+ } else {
+ return appendJSONMarshal(s.buf, a)
+ }
+ default:
+ panic(fmt.Sprintf("bad kind: %s", v.Kind()))
+ }
+ return nil
+}
+
+func appendJSONMarshal(buf *buffer.Buffer, v any) error {
+ // Use a json.Encoder to avoid escaping HTML.
+ var bb bytes.Buffer
+ enc := json.NewEncoder(&bb)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(v); err != nil {
+ return err
+ }
+ bs := bb.Bytes()
+ buf.Write(bs[:len(bs)-1]) // remove final newline
+ return nil
+}
+
+// appendEscapedJSONString escapes s for JSON and appends it to buf.
+// It does not surround the string in quotation marks.
+//
+// Modified from encoding/json/encode.go:encodeState.string,
+// with escapeHTML set to false.
+func appendEscapedJSONString(buf []byte, s string) []byte {
+ char := func(b byte) { buf = append(buf, b) }
+ str := func(s string) { buf = append(buf, s...) }
+
+ start := 0
+ for i := 0; i < len(s); {
+ if b := s[i]; b < utf8.RuneSelf {
+ if safeSet[b] {
+ i++
+ continue
+ }
+ if start < i {
+ str(s[start:i])
+ }
+ char('\\')
+ switch b {
+ case '\\', '"':
+ char(b)
+ case '\n':
+ char('n')
+ case '\r':
+ char('r')
+ case '\t':
+ char('t')
+ default:
+ // This encodes bytes < 0x20 except for \t, \n and \r.
+ str(`u00`)
+ char(hex[b>>4])
+ char(hex[b&0xF])
+ }
+ i++
+ start = i
+ continue
+ }
+ c, size := utf8.DecodeRuneInString(s[i:])
+ if c == utf8.RuneError && size == 1 {
+ if start < i {
+ str(s[start:i])
+ }
+ str(`\ufffd`)
+ i += size
+ start = i
+ continue
+ }
+ // U+2028 is LINE SEPARATOR.
+ // U+2029 is PARAGRAPH SEPARATOR.
+ // They are both technically valid characters in JSON strings,
+ // but don't work in JSONP, which has to be evaluated as JavaScript,
+ // and can lead to security holes there. It is valid JSON to
+ // escape them, so we do so unconditionally.
+ // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
+ if c == '\u2028' || c == '\u2029' {
+ if start < i {
+ str(s[start:i])
+ }
+ str(`\u202`)
+ char(hex[c&0xF])
+ i += size
+ start = i
+ continue
+ }
+ i += size
+ }
+ if start < len(s) {
+ str(s[start:])
+ }
+ return buf
+}
+
+const hex = "0123456789abcdef"
+
+// Copied from encoding/json/tables.go.
+//
+// safeSet holds the value true if the ASCII character with the given array
+// position can be represented inside a JSON string without any further
+// escaping.
+//
+// All values are true except for the ASCII control characters (0-31), the
+// double quote ("), and the backslash character ("\").
+var safeSet = [utf8.RuneSelf]bool{
+ ' ': true,
+ '!': true,
+ '"': false,
+ '#': true,
+ '$': true,
+ '%': true,
+ '&': true,
+ '\'': true,
+ '(': true,
+ ')': true,
+ '*': true,
+ '+': true,
+ ',': true,
+ '-': true,
+ '.': true,
+ '/': true,
+ '0': true,
+ '1': true,
+ '2': true,
+ '3': true,
+ '4': true,
+ '5': true,
+ '6': true,
+ '7': true,
+ '8': true,
+ '9': true,
+ ':': true,
+ ';': true,
+ '<': true,
+ '=': true,
+ '>': true,
+ '?': true,
+ '@': true,
+ 'A': true,
+ 'B': true,
+ 'C': true,
+ 'D': true,
+ 'E': true,
+ 'F': true,
+ 'G': true,
+ 'H': true,
+ 'I': true,
+ 'J': true,
+ 'K': true,
+ 'L': true,
+ 'M': true,
+ 'N': true,
+ 'O': true,
+ 'P': true,
+ 'Q': true,
+ 'R': true,
+ 'S': true,
+ 'T': true,
+ 'U': true,
+ 'V': true,
+ 'W': true,
+ 'X': true,
+ 'Y': true,
+ 'Z': true,
+ '[': true,
+ '\\': false,
+ ']': true,
+ '^': true,
+ '_': true,
+ '`': true,
+ 'a': true,
+ 'b': true,
+ 'c': true,
+ 'd': true,
+ 'e': true,
+ 'f': true,
+ 'g': true,
+ 'h': true,
+ 'i': true,
+ 'j': true,
+ 'k': true,
+ 'l': true,
+ 'm': true,
+ 'n': true,
+ 'o': true,
+ 'p': true,
+ 'q': true,
+ 'r': true,
+ 's': true,
+ 't': true,
+ 'u': true,
+ 'v': true,
+ 'w': true,
+ 'x': true,
+ 'y': true,
+ 'z': true,
+ '{': true,
+ '|': true,
+ '}': true,
+ '~': true,
+ '\u007f': true,
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/json_handler_test.go b/platform/dbops/binaries/go/go/src/log/slog/json_handler_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..65130f2426e70d9139037b36a0b6c19f203313f3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/json_handler_test.go
@@ -0,0 +1,284 @@
+// 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 slog
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog/internal/buffer"
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestJSONHandler(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ opts HandlerOptions
+ want string
+ }{
+ {
+ "none",
+ HandlerOptions{},
+ `{"time":"2000-01-02T03:04:05Z","level":"INFO","msg":"m","a":1,"m":{"b":2}}`,
+ },
+ {
+ "replace",
+ HandlerOptions{ReplaceAttr: upperCaseKey},
+ `{"TIME":"2000-01-02T03:04:05Z","LEVEL":"INFO","MSG":"m","A":1,"M":{"b":2}}`,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ h := NewJSONHandler(&buf, &test.opts)
+ r := NewRecord(testTime, LevelInfo, "m", 0)
+ r.AddAttrs(Int("a", 1), Any("m", map[string]int{"b": 2}))
+ if err := h.Handle(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+ got := strings.TrimSuffix(buf.String(), "\n")
+ if got != test.want {
+ t.Errorf("\ngot %s\nwant %s", got, test.want)
+ }
+ })
+ }
+}
+
+// for testing json.Marshaler
+type jsonMarshaler struct {
+ s string
+}
+
+func (j jsonMarshaler) String() string { return j.s } // should be ignored
+
+func (j jsonMarshaler) MarshalJSON() ([]byte, error) {
+ if j.s == "" {
+ return nil, errors.New("json: empty string")
+ }
+ return []byte(fmt.Sprintf(`[%q]`, j.s)), nil
+}
+
+type jsonMarshalerError struct {
+ jsonMarshaler
+}
+
+func (jsonMarshalerError) Error() string { return "oops" }
+
+func TestAppendJSONValue(t *testing.T) {
+ // jsonAppendAttrValue should always agree with json.Marshal.
+ for _, value := range []any{
+ "hello\r\n\t\a",
+ `"[{escape}]"`,
+ "",
+ // \u2028\u2029 is an edge case in JavaScript vs JSON.
+ // \xF6 is an incomplete encoding.
+ "\u03B8\u2028\u2029\uFFFF\xF6",
+ `-123`,
+ int64(-9_200_123_456_789_123_456),
+ uint64(9_200_123_456_789_123_456),
+ -12.75,
+ 1.23e-9,
+ false,
+ time.Minute,
+ testTime,
+ jsonMarshaler{"xyz"},
+ jsonMarshalerError{jsonMarshaler{"pqr"}},
+ LevelWarn,
+ } {
+ got := jsonValueString(AnyValue(value))
+ want, err := marshalJSON(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != want {
+ t.Errorf("%v: got %s, want %s", value, got, want)
+ }
+ }
+}
+
+func marshalJSON(x any) (string, error) {
+ var buf bytes.Buffer
+ enc := json.NewEncoder(&buf)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(x); err != nil {
+ return "", err
+ }
+ return strings.TrimSpace(buf.String()), nil
+}
+
+func TestJSONAppendAttrValueSpecial(t *testing.T) {
+ // Attr values that render differently from json.Marshal.
+ for _, test := range []struct {
+ value any
+ want string
+ }{
+ {math.NaN(), `"!ERROR:json: unsupported value: NaN"`},
+ {math.Inf(+1), `"!ERROR:json: unsupported value: +Inf"`},
+ {math.Inf(-1), `"!ERROR:json: unsupported value: -Inf"`},
+ {io.EOF, `"EOF"`},
+ } {
+ got := jsonValueString(AnyValue(test.value))
+ if got != test.want {
+ t.Errorf("%v: got %s, want %s", test.value, got, test.want)
+ }
+ }
+}
+
+func jsonValueString(v Value) string {
+ var buf []byte
+ s := &handleState{h: &commonHandler{json: true}, buf: (*buffer.Buffer)(&buf)}
+ if err := appendJSONValue(s, v); err != nil {
+ s.appendError(err)
+ }
+ return string(buf)
+}
+
+func BenchmarkJSONHandler(b *testing.B) {
+ for _, bench := range []struct {
+ name string
+ opts HandlerOptions
+ }{
+ {"defaults", HandlerOptions{}},
+ {"time format", HandlerOptions{
+ ReplaceAttr: func(_ []string, a Attr) Attr {
+ v := a.Value
+ if v.Kind() == KindTime {
+ return String(a.Key, v.Time().Format(rfc3339Millis))
+ }
+ if a.Key == "level" {
+ return Attr{"severity", a.Value}
+ }
+ return a
+ },
+ }},
+ {"time unix", HandlerOptions{
+ ReplaceAttr: func(_ []string, a Attr) Attr {
+ v := a.Value
+ if v.Kind() == KindTime {
+ return Int64(a.Key, v.Time().UnixNano())
+ }
+ if a.Key == "level" {
+ return Attr{"severity", a.Value}
+ }
+ return a
+ },
+ }},
+ } {
+ b.Run(bench.name, func(b *testing.B) {
+ ctx := context.Background()
+ l := New(NewJSONHandler(io.Discard, &bench.opts)).With(
+ String("program", "my-test-program"),
+ String("package", "log/slog"),
+ String("traceID", "2039232309232309"),
+ String("URL", "https://pkg.go.dev/golang.org/x/log/slog"))
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ l.LogAttrs(ctx, LevelInfo, "this is a typical log message",
+ String("module", "github.com/google/go-cmp"),
+ String("version", "v1.23.4"),
+ Int("count", 23),
+ Int("number", 123456),
+ )
+ }
+ })
+ }
+}
+
+func BenchmarkPreformatting(b *testing.B) {
+ type req struct {
+ Method string
+ URL string
+ TraceID string
+ Addr string
+ }
+
+ structAttrs := []any{
+ String("program", "my-test-program"),
+ String("package", "log/slog"),
+ Any("request", &req{
+ Method: "GET",
+ URL: "https://pkg.go.dev/golang.org/x/log/slog",
+ TraceID: "2039232309232309",
+ Addr: "127.0.0.1:8080",
+ }),
+ }
+
+ outFile, err := os.Create(filepath.Join(b.TempDir(), "bench.log"))
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer func() {
+ if err := outFile.Close(); err != nil {
+ b.Fatal(err)
+ }
+ }()
+
+ for _, bench := range []struct {
+ name string
+ wc io.Writer
+ attrs []any
+ }{
+ {"separate", io.Discard, []any{
+ String("program", "my-test-program"),
+ String("package", "log/slog"),
+ String("method", "GET"),
+ String("URL", "https://pkg.go.dev/golang.org/x/log/slog"),
+ String("traceID", "2039232309232309"),
+ String("addr", "127.0.0.1:8080"),
+ }},
+ {"struct", io.Discard, structAttrs},
+ {"struct file", outFile, structAttrs},
+ } {
+ ctx := context.Background()
+ b.Run(bench.name, func(b *testing.B) {
+ l := New(NewJSONHandler(bench.wc, nil)).With(bench.attrs...)
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ l.LogAttrs(ctx, LevelInfo, "this is a typical log message",
+ String("module", "github.com/google/go-cmp"),
+ String("version", "v1.23.4"),
+ Int("count", 23),
+ Int("number", 123456),
+ )
+ }
+ })
+ }
+}
+
+func BenchmarkJSONEncoding(b *testing.B) {
+ value := 3.14
+ buf := buffer.New()
+ defer buf.Free()
+ b.Run("json.Marshal", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ by, err := json.Marshal(value)
+ if err != nil {
+ b.Fatal(err)
+ }
+ buf.Write(by)
+ *buf = (*buf)[:0]
+ }
+ })
+ b.Run("Encoder.Encode", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ if err := json.NewEncoder(buf).Encode(value); err != nil {
+ b.Fatal(err)
+ }
+ *buf = (*buf)[:0]
+ }
+ })
+ _ = buf
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/level.go b/platform/dbops/binaries/go/go/src/log/slog/level.go
new file mode 100644
index 0000000000000000000000000000000000000000..7cddf4cfba5ca27fe036114e12aa7c69f92ee0f2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/level.go
@@ -0,0 +1,200 @@
+// 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 slog
+
+import (
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "sync/atomic"
+)
+
+// A Level is the importance or severity of a log event.
+// The higher the level, the more important or severe the event.
+type Level int
+
+// Names for common levels.
+//
+// Level numbers are inherently arbitrary,
+// but we picked them to satisfy three constraints.
+// Any system can map them to another numbering scheme if it wishes.
+//
+// First, we wanted the default level to be Info, Since Levels are ints, Info is
+// the default value for int, zero.
+//
+// Second, we wanted to make it easy to use levels to specify logger verbosity.
+// Since a larger level means a more severe event, a logger that accepts events
+// with smaller (or more negative) level means a more verbose logger. Logger
+// verbosity is thus the negation of event severity, and the default verbosity
+// of 0 accepts all events at least as severe as INFO.
+//
+// Third, we wanted some room between levels to accommodate schemes with named
+// levels between ours. For example, Google Cloud Logging defines a Notice level
+// between Info and Warn. Since there are only a few of these intermediate
+// levels, the gap between the numbers need not be large. Our gap of 4 matches
+// OpenTelemetry's mapping. Subtracting 9 from an OpenTelemetry level in the
+// DEBUG, INFO, WARN and ERROR ranges converts it to the corresponding slog
+// Level range. OpenTelemetry also has the names TRACE and FATAL, which slog
+// does not. But those OpenTelemetry levels can still be represented as slog
+// Levels by using the appropriate integers.
+const (
+ LevelDebug Level = -4
+ LevelInfo Level = 0
+ LevelWarn Level = 4
+ LevelError Level = 8
+)
+
+// String returns a name for the level.
+// If the level has a name, then that name
+// in uppercase is returned.
+// If the level is between named values, then
+// an integer is appended to the uppercased name.
+// Examples:
+//
+// LevelWarn.String() => "WARN"
+// (LevelInfo+2).String() => "INFO+2"
+func (l Level) String() string {
+ str := func(base string, val Level) string {
+ if val == 0 {
+ return base
+ }
+ return fmt.Sprintf("%s%+d", base, val)
+ }
+
+ switch {
+ case l < LevelInfo:
+ return str("DEBUG", l-LevelDebug)
+ case l < LevelWarn:
+ return str("INFO", l-LevelInfo)
+ case l < LevelError:
+ return str("WARN", l-LevelWarn)
+ default:
+ return str("ERROR", l-LevelError)
+ }
+}
+
+// MarshalJSON implements [encoding/json.Marshaler]
+// by quoting the output of [Level.String].
+func (l Level) MarshalJSON() ([]byte, error) {
+ // AppendQuote is sufficient for JSON-encoding all Level strings.
+ // They don't contain any runes that would produce invalid JSON
+ // when escaped.
+ return strconv.AppendQuote(nil, l.String()), nil
+}
+
+// UnmarshalJSON implements [encoding/json.Unmarshaler]
+// It accepts any string produced by [Level.MarshalJSON],
+// ignoring case.
+// It also accepts numeric offsets that would result in a different string on
+// output. For example, "Error-8" would marshal as "INFO".
+func (l *Level) UnmarshalJSON(data []byte) error {
+ s, err := strconv.Unquote(string(data))
+ if err != nil {
+ return err
+ }
+ return l.parse(s)
+}
+
+// MarshalText implements [encoding.TextMarshaler]
+// by calling [Level.String].
+func (l Level) MarshalText() ([]byte, error) {
+ return []byte(l.String()), nil
+}
+
+// UnmarshalText implements [encoding.TextUnmarshaler].
+// It accepts any string produced by [Level.MarshalText],
+// ignoring case.
+// It also accepts numeric offsets that would result in a different string on
+// output. For example, "Error-8" would marshal as "INFO".
+func (l *Level) UnmarshalText(data []byte) error {
+ return l.parse(string(data))
+}
+
+func (l *Level) parse(s string) (err error) {
+ defer func() {
+ if err != nil {
+ err = fmt.Errorf("slog: level string %q: %w", s, err)
+ }
+ }()
+
+ name := s
+ offset := 0
+ if i := strings.IndexAny(s, "+-"); i >= 0 {
+ name = s[:i]
+ offset, err = strconv.Atoi(s[i:])
+ if err != nil {
+ return err
+ }
+ }
+ switch strings.ToUpper(name) {
+ case "DEBUG":
+ *l = LevelDebug
+ case "INFO":
+ *l = LevelInfo
+ case "WARN":
+ *l = LevelWarn
+ case "ERROR":
+ *l = LevelError
+ default:
+ return errors.New("unknown name")
+ }
+ *l += Level(offset)
+ return nil
+}
+
+// Level returns the receiver.
+// It implements [Leveler].
+func (l Level) Level() Level { return l }
+
+// A LevelVar is a [Level] variable, to allow a [Handler] level to change
+// dynamically.
+// It implements [Leveler] as well as a Set method,
+// and it is safe for use by multiple goroutines.
+// The zero LevelVar corresponds to [LevelInfo].
+type LevelVar struct {
+ val atomic.Int64
+}
+
+// Level returns v's level.
+func (v *LevelVar) Level() Level {
+ return Level(int(v.val.Load()))
+}
+
+// Set sets v's level to l.
+func (v *LevelVar) Set(l Level) {
+ v.val.Store(int64(l))
+}
+
+func (v *LevelVar) String() string {
+ return fmt.Sprintf("LevelVar(%s)", v.Level())
+}
+
+// MarshalText implements [encoding.TextMarshaler]
+// by calling [Level.MarshalText].
+func (v *LevelVar) MarshalText() ([]byte, error) {
+ return v.Level().MarshalText()
+}
+
+// UnmarshalText implements [encoding.TextUnmarshaler]
+// by calling [Level.UnmarshalText].
+func (v *LevelVar) UnmarshalText(data []byte) error {
+ var l Level
+ if err := l.UnmarshalText(data); err != nil {
+ return err
+ }
+ v.Set(l)
+ return nil
+}
+
+// A Leveler provides a [Level] value.
+//
+// As Level itself implements Leveler, clients typically supply
+// a Level value wherever a Leveler is needed, such as in [HandlerOptions].
+// Clients who need to vary the level dynamically can provide a more complex
+// Leveler implementation such as *[LevelVar].
+type Leveler interface {
+ Level() Level
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/level_test.go b/platform/dbops/binaries/go/go/src/log/slog/level_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b28e71e4c6e8bd6fece17e63680497b401c91cb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/level_test.go
@@ -0,0 +1,178 @@
+// 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 slog
+
+import (
+ "flag"
+ "strings"
+ "testing"
+)
+
+func TestLevelString(t *testing.T) {
+ for _, test := range []struct {
+ in Level
+ want string
+ }{
+ {0, "INFO"},
+ {LevelError, "ERROR"},
+ {LevelError + 2, "ERROR+2"},
+ {LevelError - 2, "WARN+2"},
+ {LevelWarn, "WARN"},
+ {LevelWarn - 1, "INFO+3"},
+ {LevelInfo, "INFO"},
+ {LevelInfo + 1, "INFO+1"},
+ {LevelInfo - 3, "DEBUG+1"},
+ {LevelDebug, "DEBUG"},
+ {LevelDebug - 2, "DEBUG-2"},
+ } {
+ got := test.in.String()
+ if got != test.want {
+ t.Errorf("%d: got %s, want %s", test.in, got, test.want)
+ }
+ }
+}
+
+func TestLevelVar(t *testing.T) {
+ var al LevelVar
+ if got, want := al.Level(), LevelInfo; got != want {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ al.Set(LevelWarn)
+ if got, want := al.Level(), LevelWarn; got != want {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ al.Set(LevelInfo)
+ if got, want := al.Level(), LevelInfo; got != want {
+ t.Errorf("got %v, want %v", got, want)
+ }
+
+}
+
+func TestMarshalJSON(t *testing.T) {
+ want := LevelWarn - 3
+ data, err := want.MarshalJSON()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got Level
+ if err := got.UnmarshalJSON(data); err != nil {
+ t.Fatal(err)
+ }
+ if got != want {
+ t.Errorf("got %s, want %s", got, want)
+ }
+}
+
+func TestLevelMarshalText(t *testing.T) {
+ want := LevelWarn - 3
+ data, err := want.MarshalText()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got Level
+ if err := got.UnmarshalText(data); err != nil {
+ t.Fatal(err)
+ }
+ if got != want {
+ t.Errorf("got %s, want %s", got, want)
+ }
+}
+
+func TestLevelParse(t *testing.T) {
+ for _, test := range []struct {
+ in string
+ want Level
+ }{
+ {"DEBUG", LevelDebug},
+ {"INFO", LevelInfo},
+ {"WARN", LevelWarn},
+ {"ERROR", LevelError},
+ {"debug", LevelDebug},
+ {"iNfo", LevelInfo},
+ {"INFO+87", LevelInfo + 87},
+ {"Error-18", LevelError - 18},
+ {"Error-8", LevelInfo},
+ } {
+ var got Level
+ if err := got.parse(test.in); err != nil {
+ t.Fatalf("%q: %v", test.in, err)
+ }
+ if got != test.want {
+ t.Errorf("%q: got %s, want %s", test.in, got, test.want)
+ }
+ }
+}
+
+func TestLevelParseError(t *testing.T) {
+ for _, test := range []struct {
+ in string
+ want string // error string should contain this
+ }{
+ {"", "unknown name"},
+ {"dbg", "unknown name"},
+ {"INFO+", "invalid syntax"},
+ {"INFO-", "invalid syntax"},
+ {"ERROR+23x", "invalid syntax"},
+ } {
+ var l Level
+ err := l.parse(test.in)
+ if err == nil || !strings.Contains(err.Error(), test.want) {
+ t.Errorf("%q: got %v, want string containing %q", test.in, err, test.want)
+ }
+ }
+}
+
+func TestLevelFlag(t *testing.T) {
+ fs := flag.NewFlagSet("test", flag.ContinueOnError)
+ lf := LevelInfo
+ fs.TextVar(&lf, "level", lf, "set level")
+ err := fs.Parse([]string{"-level", "WARN+3"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if g, w := lf, LevelWarn+3; g != w {
+ t.Errorf("got %v, want %v", g, w)
+ }
+}
+
+func TestLevelVarMarshalText(t *testing.T) {
+ var v LevelVar
+ v.Set(LevelWarn)
+ data, err := v.MarshalText()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var v2 LevelVar
+ if err := v2.UnmarshalText(data); err != nil {
+ t.Fatal(err)
+ }
+ if g, w := v2.Level(), LevelWarn; g != w {
+ t.Errorf("got %s, want %s", g, w)
+ }
+}
+
+func TestLevelVarFlag(t *testing.T) {
+ fs := flag.NewFlagSet("test", flag.ContinueOnError)
+ v := &LevelVar{}
+ v.Set(LevelWarn + 3)
+ fs.TextVar(v, "level", v, "set level")
+ err := fs.Parse([]string{"-level", "WARN+3"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if g, w := v.Level(), LevelWarn+3; g != w {
+ t.Errorf("got %v, want %v", g, w)
+ }
+}
+
+func TestLevelVarString(t *testing.T) {
+ var v LevelVar
+ v.Set(LevelError)
+ got := v.String()
+ want := "LevelVar(ERROR)"
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/logger.go b/platform/dbops/binaries/go/go/src/log/slog/logger.go
new file mode 100644
index 0000000000000000000000000000000000000000..10aa6a2b314feb49a1c5aaa0e28ae92fbe795ac2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/logger.go
@@ -0,0 +1,328 @@
+// 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 slog
+
+import (
+ "context"
+ "log"
+ loginternal "log/internal"
+ "log/slog/internal"
+ "runtime"
+ "sync/atomic"
+ "time"
+)
+
+var defaultLogger atomic.Pointer[Logger]
+
+var logLoggerLevel LevelVar
+
+// SetLogLoggerLevel controls the level for the bridge to the [log] package.
+//
+// Before [SetDefault] is called, slog top-level logging functions call the default [log.Logger].
+// In that mode, SetLogLoggerLevel sets the minimum level for those calls.
+// By default, the minimum level is Info, so calls to [Debug]
+// (as well as top-level logging calls at lower levels)
+// will not be passed to the log.Logger. After calling
+//
+// slog.SetLogLoggerLevel(slog.LevelDebug)
+//
+// calls to [Debug] will be passed to the log.Logger.
+//
+// After [SetDefault] is called, calls to the default [log.Logger] are passed to the
+// slog default handler. In that mode,
+// SetLogLoggerLevel sets the level at which those calls are logged.
+// That is, after calling
+//
+// slog.SetLogLoggerLevel(slog.LevelDebug)
+//
+// A call to [log.Printf] will result in output at level [LevelDebug].
+//
+// SetLogLoggerLevel returns the previous value.
+func SetLogLoggerLevel(level Level) (oldLevel Level) {
+ oldLevel = logLoggerLevel.Level()
+ logLoggerLevel.Set(level)
+ return
+}
+
+func init() {
+ defaultLogger.Store(New(newDefaultHandler(loginternal.DefaultOutput)))
+}
+
+// Default returns the default [Logger].
+func Default() *Logger { return defaultLogger.Load() }
+
+// SetDefault makes l the default [Logger], which is used by
+// the top-level functions [Info], [Debug] and so on.
+// After this call, output from the log package's default Logger
+// (as with [log.Print], etc.) will be logged using l's Handler,
+// at a level controlled by [SetLogLoggerLevel].
+func SetDefault(l *Logger) {
+ defaultLogger.Store(l)
+ // If the default's handler is a defaultHandler, then don't use a handleWriter,
+ // or we'll deadlock as they both try to acquire the log default mutex.
+ // The defaultHandler will use whatever the log default writer is currently
+ // set to, which is correct.
+ // This can occur with SetDefault(Default()).
+ // See TestSetDefault.
+ if _, ok := l.Handler().(*defaultHandler); !ok {
+ capturePC := log.Flags()&(log.Lshortfile|log.Llongfile) != 0
+ log.SetOutput(&handlerWriter{l.Handler(), &logLoggerLevel, capturePC})
+ log.SetFlags(0) // we want just the log message, no time or location
+ }
+}
+
+// handlerWriter is an io.Writer that calls a Handler.
+// It is used to link the default log.Logger to the default slog.Logger.
+type handlerWriter struct {
+ h Handler
+ level Leveler
+ capturePC bool
+}
+
+func (w *handlerWriter) Write(buf []byte) (int, error) {
+ level := w.level.Level()
+ if !w.h.Enabled(context.Background(), level) {
+ return 0, nil
+ }
+ var pc uintptr
+ if !internal.IgnorePC && w.capturePC {
+ // skip [runtime.Callers, w.Write, Logger.Output, log.Print]
+ var pcs [1]uintptr
+ runtime.Callers(4, pcs[:])
+ pc = pcs[0]
+ }
+
+ // Remove final newline.
+ origLen := len(buf) // Report that the entire buf was written.
+ if len(buf) > 0 && buf[len(buf)-1] == '\n' {
+ buf = buf[:len(buf)-1]
+ }
+ r := NewRecord(time.Now(), level, string(buf), pc)
+ return origLen, w.h.Handle(context.Background(), r)
+}
+
+// A Logger records structured information about each call to its
+// Log, Debug, Info, Warn, and Error methods.
+// For each call, it creates a [Record] and passes it to a [Handler].
+//
+// To create a new Logger, call [New] or a Logger method
+// that begins "With".
+type Logger struct {
+ handler Handler // for structured logging
+}
+
+func (l *Logger) clone() *Logger {
+ c := *l
+ return &c
+}
+
+// Handler returns l's Handler.
+func (l *Logger) Handler() Handler { return l.handler }
+
+// With returns a Logger that includes the given attributes
+// in each output operation. Arguments are converted to
+// attributes as if by [Logger.Log].
+func (l *Logger) With(args ...any) *Logger {
+ if len(args) == 0 {
+ return l
+ }
+ c := l.clone()
+ c.handler = l.handler.WithAttrs(argsToAttrSlice(args))
+ return c
+}
+
+// WithGroup returns a Logger that starts a group, if name is non-empty.
+// The keys of all attributes added to the Logger will be qualified by the given
+// name. (How that qualification happens depends on the [Handler.WithGroup]
+// method of the Logger's Handler.)
+//
+// If name is empty, WithGroup returns the receiver.
+func (l *Logger) WithGroup(name string) *Logger {
+ if name == "" {
+ return l
+ }
+ c := l.clone()
+ c.handler = l.handler.WithGroup(name)
+ return c
+}
+
+// New creates a new Logger with the given non-nil Handler.
+func New(h Handler) *Logger {
+ if h == nil {
+ panic("nil Handler")
+ }
+ return &Logger{handler: h}
+}
+
+// With calls [Logger.With] on the default logger.
+func With(args ...any) *Logger {
+ return Default().With(args...)
+}
+
+// Enabled reports whether l emits log records at the given context and level.
+func (l *Logger) Enabled(ctx context.Context, level Level) bool {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ return l.Handler().Enabled(ctx, level)
+}
+
+// NewLogLogger returns a new [log.Logger] such that each call to its Output method
+// dispatches a Record to the specified handler. The logger acts as a bridge from
+// the older log API to newer structured logging handlers.
+func NewLogLogger(h Handler, level Level) *log.Logger {
+ return log.New(&handlerWriter{h, level, true}, "", 0)
+}
+
+// Log emits a log record with the current time and the given level and message.
+// The Record's Attrs consist of the Logger's attributes followed by
+// the Attrs specified by args.
+//
+// The attribute arguments are processed as follows:
+// - If an argument is an Attr, it is used as is.
+// - If an argument is a string and this is not the last argument,
+// the following argument is treated as the value and the two are combined
+// into an Attr.
+// - Otherwise, the argument is treated as a value with key "!BADKEY".
+func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any) {
+ l.log(ctx, level, msg, args...)
+}
+
+// LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs.
+func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) {
+ l.logAttrs(ctx, level, msg, attrs...)
+}
+
+// Debug logs at [LevelDebug].
+func (l *Logger) Debug(msg string, args ...any) {
+ l.log(context.Background(), LevelDebug, msg, args...)
+}
+
+// DebugContext logs at [LevelDebug] with the given context.
+func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) {
+ l.log(ctx, LevelDebug, msg, args...)
+}
+
+// Info logs at [LevelInfo].
+func (l *Logger) Info(msg string, args ...any) {
+ l.log(context.Background(), LevelInfo, msg, args...)
+}
+
+// InfoContext logs at [LevelInfo] with the given context.
+func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) {
+ l.log(ctx, LevelInfo, msg, args...)
+}
+
+// Warn logs at [LevelWarn].
+func (l *Logger) Warn(msg string, args ...any) {
+ l.log(context.Background(), LevelWarn, msg, args...)
+}
+
+// WarnContext logs at [LevelWarn] with the given context.
+func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) {
+ l.log(ctx, LevelWarn, msg, args...)
+}
+
+// Error logs at [LevelError].
+func (l *Logger) Error(msg string, args ...any) {
+ l.log(context.Background(), LevelError, msg, args...)
+}
+
+// ErrorContext logs at [LevelError] with the given context.
+func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) {
+ l.log(ctx, LevelError, msg, args...)
+}
+
+// log is the low-level logging method for methods that take ...any.
+// It must always be called directly by an exported logging method
+// or function, because it uses a fixed call depth to obtain the pc.
+func (l *Logger) log(ctx context.Context, level Level, msg string, args ...any) {
+ if !l.Enabled(ctx, level) {
+ return
+ }
+ var pc uintptr
+ if !internal.IgnorePC {
+ var pcs [1]uintptr
+ // skip [runtime.Callers, this function, this function's caller]
+ runtime.Callers(3, pcs[:])
+ pc = pcs[0]
+ }
+ r := NewRecord(time.Now(), level, msg, pc)
+ r.Add(args...)
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ _ = l.Handler().Handle(ctx, r)
+}
+
+// logAttrs is like [Logger.log], but for methods that take ...Attr.
+func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) {
+ if !l.Enabled(ctx, level) {
+ return
+ }
+ var pc uintptr
+ if !internal.IgnorePC {
+ var pcs [1]uintptr
+ // skip [runtime.Callers, this function, this function's caller]
+ runtime.Callers(3, pcs[:])
+ pc = pcs[0]
+ }
+ r := NewRecord(time.Now(), level, msg, pc)
+ r.AddAttrs(attrs...)
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ _ = l.Handler().Handle(ctx, r)
+}
+
+// Debug calls [Logger.Debug] on the default logger.
+func Debug(msg string, args ...any) {
+ Default().log(context.Background(), LevelDebug, msg, args...)
+}
+
+// DebugContext calls [Logger.DebugContext] on the default logger.
+func DebugContext(ctx context.Context, msg string, args ...any) {
+ Default().log(ctx, LevelDebug, msg, args...)
+}
+
+// Info calls [Logger.Info] on the default logger.
+func Info(msg string, args ...any) {
+ Default().log(context.Background(), LevelInfo, msg, args...)
+}
+
+// InfoContext calls [Logger.InfoContext] on the default logger.
+func InfoContext(ctx context.Context, msg string, args ...any) {
+ Default().log(ctx, LevelInfo, msg, args...)
+}
+
+// Warn calls [Logger.Warn] on the default logger.
+func Warn(msg string, args ...any) {
+ Default().log(context.Background(), LevelWarn, msg, args...)
+}
+
+// WarnContext calls [Logger.WarnContext] on the default logger.
+func WarnContext(ctx context.Context, msg string, args ...any) {
+ Default().log(ctx, LevelWarn, msg, args...)
+}
+
+// Error calls [Logger.Error] on the default logger.
+func Error(msg string, args ...any) {
+ Default().log(context.Background(), LevelError, msg, args...)
+}
+
+// ErrorContext calls [Logger.ErrorContext] on the default logger.
+func ErrorContext(ctx context.Context, msg string, args ...any) {
+ Default().log(ctx, LevelError, msg, args...)
+}
+
+// Log calls [Logger.Log] on the default logger.
+func Log(ctx context.Context, level Level, msg string, args ...any) {
+ Default().log(ctx, level, msg, args...)
+}
+
+// LogAttrs calls [Logger.LogAttrs] on the default logger.
+func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) {
+ Default().logAttrs(ctx, level, msg, attrs...)
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/logger_test.go b/platform/dbops/binaries/go/go/src/log/slog/logger_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bb1c8a16ea46ac4b988c9a0ab27645f7e8c93440
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/logger_test.go
@@ -0,0 +1,717 @@
+// 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 slog
+
+import (
+ "bytes"
+ "context"
+ "internal/race"
+ "internal/testenv"
+ "io"
+ "log"
+ loginternal "log/internal"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// textTimeRE is a regexp to match log timestamps for Text handler.
+// This is RFC3339Nano with the fixed 3 digit sub-second precision.
+const textTimeRE = `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}(Z|[+-]\d{2}:\d{2})`
+
+// jsonTimeRE is a regexp to match log timestamps for Text handler.
+// This is RFC3339Nano with an arbitrary sub-second precision.
+const jsonTimeRE = `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})`
+
+func TestLogTextHandler(t *testing.T) {
+ ctx := context.Background()
+ var buf bytes.Buffer
+
+ l := New(NewTextHandler(&buf, nil))
+
+ check := func(want string) {
+ t.Helper()
+ if want != "" {
+ want = "time=" + textTimeRE + " " + want
+ }
+ checkLogOutput(t, buf.String(), want)
+ buf.Reset()
+ }
+
+ l.Info("msg", "a", 1, "b", 2)
+ check(`level=INFO msg=msg a=1 b=2`)
+
+ // By default, debug messages are not printed.
+ l.Debug("bg", Int("a", 1), "b", 2)
+ check("")
+
+ l.Warn("w", Duration("dur", 3*time.Second))
+ check(`level=WARN msg=w dur=3s`)
+
+ l.Error("bad", "a", 1)
+ check(`level=ERROR msg=bad a=1`)
+
+ l.Log(ctx, LevelWarn+1, "w", Int("a", 1), String("b", "two"))
+ check(`level=WARN\+1 msg=w a=1 b=two`)
+
+ l.LogAttrs(ctx, LevelInfo+1, "a b c", Int("a", 1), String("b", "two"))
+ check(`level=INFO\+1 msg="a b c" a=1 b=two`)
+
+ l.Info("info", "a", []Attr{Int("i", 1)})
+ check(`level=INFO msg=info a.i=1`)
+
+ l.Info("info", "a", GroupValue(Int("i", 1)))
+ check(`level=INFO msg=info a.i=1`)
+}
+
+func TestConnections(t *testing.T) {
+ var logbuf, slogbuf bytes.Buffer
+
+ // Revert any changes to the default logger. This is important because other
+ // tests might change the default logger using SetDefault. Also ensure we
+ // restore the default logger at the end of the test.
+ currentLogger := Default()
+ currentLogWriter := log.Writer()
+ currentLogFlags := log.Flags()
+ SetDefault(New(newDefaultHandler(loginternal.DefaultOutput)))
+ t.Cleanup(func() {
+ SetDefault(currentLogger)
+ log.SetOutput(currentLogWriter)
+ log.SetFlags(currentLogFlags)
+ })
+
+ // The default slog.Logger's handler uses the log package's default output.
+ log.SetOutput(&logbuf)
+ log.SetFlags(log.Lshortfile &^ log.LstdFlags)
+ Info("msg", "a", 1)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: INFO msg a=1`)
+ logbuf.Reset()
+ Info("msg", "p", nil)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: INFO msg p=`)
+ logbuf.Reset()
+ var r *regexp.Regexp
+ Info("msg", "r", r)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: INFO msg r=`)
+ logbuf.Reset()
+ Warn("msg", "b", 2)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: WARN msg b=2`)
+ logbuf.Reset()
+ Error("msg", "err", io.EOF, "c", 3)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: ERROR msg err=EOF c=3`)
+
+ // Levels below Info are not printed.
+ logbuf.Reset()
+ Debug("msg", "c", 3)
+ checkLogOutput(t, logbuf.String(), "")
+
+ t.Run("wrap default handler", func(t *testing.T) {
+ // It should be possible to wrap the default handler and get the right output.
+ // This works because the default handler uses the pc in the Record
+ // to get the source line, rather than a call depth.
+ logger := New(wrappingHandler{Default().Handler()})
+ logger.Info("msg", "d", 4)
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: INFO msg d=4`)
+ })
+
+ // Once slog.SetDefault is called, the direction is reversed: the default
+ // log.Logger's output goes through the handler.
+ SetDefault(New(NewTextHandler(&slogbuf, &HandlerOptions{AddSource: true})))
+ log.Print("msg2")
+ checkLogOutput(t, slogbuf.String(), "time="+textTimeRE+` level=INFO source=.*logger_test.go:\d{3}"? msg=msg2`)
+
+ // The default log.Logger always outputs at Info level.
+ slogbuf.Reset()
+ SetDefault(New(NewTextHandler(&slogbuf, &HandlerOptions{Level: LevelWarn})))
+ log.Print("should not appear")
+ if got := slogbuf.String(); got != "" {
+ t.Errorf("got %q, want empty", got)
+ }
+
+ // Setting log's output again breaks the connection.
+ logbuf.Reset()
+ slogbuf.Reset()
+ log.SetOutput(&logbuf)
+ log.SetFlags(log.Lshortfile &^ log.LstdFlags)
+ log.Print("msg3")
+ checkLogOutput(t, logbuf.String(), `logger_test.go:\d+: msg3`)
+ if got := slogbuf.String(); got != "" {
+ t.Errorf("got %q, want empty", got)
+ }
+}
+
+type wrappingHandler struct {
+ h Handler
+}
+
+func (h wrappingHandler) Enabled(ctx context.Context, level Level) bool {
+ return h.h.Enabled(ctx, level)
+}
+func (h wrappingHandler) WithGroup(name string) Handler { return h.h.WithGroup(name) }
+func (h wrappingHandler) WithAttrs(as []Attr) Handler { return h.h.WithAttrs(as) }
+func (h wrappingHandler) Handle(ctx context.Context, r Record) error { return h.h.Handle(ctx, r) }
+
+func TestAttrs(t *testing.T) {
+ check := func(got []Attr, want ...Attr) {
+ t.Helper()
+ if !attrsEqual(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ }
+
+ l1 := New(&captureHandler{}).With("a", 1)
+ l2 := New(l1.Handler()).With("b", 2)
+ l2.Info("m", "c", 3)
+ h := l2.Handler().(*captureHandler)
+ check(h.attrs, Int("a", 1), Int("b", 2))
+ check(attrsSlice(h.r), Int("c", 3))
+}
+
+func TestCallDepth(t *testing.T) {
+ ctx := context.Background()
+ h := &captureHandler{}
+ var startLine int
+
+ check := func(count int) {
+ t.Helper()
+ const wantFunc = "log/slog.TestCallDepth"
+ const wantFile = "logger_test.go"
+ wantLine := startLine + count*2
+ got := h.r.source()
+ gotFile := filepath.Base(got.File)
+ if got.Function != wantFunc || gotFile != wantFile || got.Line != wantLine {
+ t.Errorf("got (%s, %s, %d), want (%s, %s, %d)",
+ got.Function, gotFile, got.Line, wantFunc, wantFile, wantLine)
+ }
+ }
+
+ defer SetDefault(Default()) // restore
+ logger := New(h)
+ SetDefault(logger)
+
+ // Calls to check must be one line apart.
+ // Determine line where calls start.
+ f, _ := runtime.CallersFrames([]uintptr{callerPC(2)}).Next()
+ startLine = f.Line + 4
+ // Do not change the number of lines between here and the call to check(0).
+
+ logger.Log(ctx, LevelInfo, "")
+ check(0)
+ logger.LogAttrs(ctx, LevelInfo, "")
+ check(1)
+ logger.Debug("")
+ check(2)
+ logger.Info("")
+ check(3)
+ logger.Warn("")
+ check(4)
+ logger.Error("")
+ check(5)
+ Debug("")
+ check(6)
+ Info("")
+ check(7)
+ Warn("")
+ check(8)
+ Error("")
+ check(9)
+ Log(ctx, LevelInfo, "")
+ check(10)
+ LogAttrs(ctx, LevelInfo, "")
+ check(11)
+}
+
+func TestAlloc(t *testing.T) {
+ ctx := context.Background()
+ dl := New(discardHandler{})
+ defer SetDefault(Default()) // restore
+ SetDefault(dl)
+
+ t.Run("Info", func(t *testing.T) {
+ wantAllocs(t, 0, func() { Info("hello") })
+ })
+ t.Run("Error", func(t *testing.T) {
+ wantAllocs(t, 0, func() { Error("hello") })
+ })
+ t.Run("logger.Info", func(t *testing.T) {
+ wantAllocs(t, 0, func() { dl.Info("hello") })
+ })
+ t.Run("logger.Log", func(t *testing.T) {
+ wantAllocs(t, 0, func() { dl.Log(ctx, LevelDebug, "hello") })
+ })
+ t.Run("2 pairs", func(t *testing.T) {
+ s := "abc"
+ i := 2000
+ wantAllocs(t, 2, func() {
+ dl.Info("hello",
+ "n", i,
+ "s", s,
+ )
+ })
+ })
+ t.Run("2 pairs disabled inline", func(t *testing.T) {
+ l := New(discardHandler{disabled: true})
+ s := "abc"
+ i := 2000
+ wantAllocs(t, 2, func() {
+ l.Log(ctx, LevelInfo, "hello",
+ "n", i,
+ "s", s,
+ )
+ })
+ })
+ t.Run("2 pairs disabled", func(t *testing.T) {
+ l := New(discardHandler{disabled: true})
+ s := "abc"
+ i := 2000
+ wantAllocs(t, 0, func() {
+ if l.Enabled(ctx, LevelInfo) {
+ l.Log(ctx, LevelInfo, "hello",
+ "n", i,
+ "s", s,
+ )
+ }
+ })
+ })
+ t.Run("9 kvs", func(t *testing.T) {
+ s := "abc"
+ i := 2000
+ d := time.Second
+ wantAllocs(t, 10, func() {
+ dl.Info("hello",
+ "n", i, "s", s, "d", d,
+ "n", i, "s", s, "d", d,
+ "n", i, "s", s, "d", d)
+ })
+ })
+ t.Run("pairs", func(t *testing.T) {
+ wantAllocs(t, 0, func() { dl.Info("", "error", io.EOF) })
+ })
+ t.Run("attrs1", func(t *testing.T) {
+ wantAllocs(t, 0, func() { dl.LogAttrs(ctx, LevelInfo, "", Int("a", 1)) })
+ wantAllocs(t, 0, func() { dl.LogAttrs(ctx, LevelInfo, "", Any("error", io.EOF)) })
+ })
+ t.Run("attrs3", func(t *testing.T) {
+ wantAllocs(t, 0, func() {
+ dl.LogAttrs(ctx, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
+ })
+ })
+ t.Run("attrs3 disabled", func(t *testing.T) {
+ logger := New(discardHandler{disabled: true})
+ wantAllocs(t, 0, func() {
+ logger.LogAttrs(ctx, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
+ })
+ })
+ t.Run("attrs6", func(t *testing.T) {
+ wantAllocs(t, 1, func() {
+ dl.LogAttrs(ctx, LevelInfo, "hello",
+ Int("a", 1), String("b", "two"), Duration("c", time.Second),
+ Int("d", 1), String("e", "two"), Duration("f", time.Second))
+ })
+ })
+ t.Run("attrs9", func(t *testing.T) {
+ wantAllocs(t, 1, func() {
+ dl.LogAttrs(ctx, LevelInfo, "hello",
+ Int("a", 1), String("b", "two"), Duration("c", time.Second),
+ Int("d", 1), String("e", "two"), Duration("f", time.Second),
+ Int("d", 1), String("e", "two"), Duration("f", time.Second))
+ })
+ })
+}
+
+func TestSetAttrs(t *testing.T) {
+ for _, test := range []struct {
+ args []any
+ want []Attr
+ }{
+ {nil, nil},
+ {[]any{"a", 1}, []Attr{Int("a", 1)}},
+ {[]any{"a", 1, "b", "two"}, []Attr{Int("a", 1), String("b", "two")}},
+ {[]any{"a"}, []Attr{String(badKey, "a")}},
+ {[]any{"a", 1, "b"}, []Attr{Int("a", 1), String(badKey, "b")}},
+ {[]any{"a", 1, 2, 3}, []Attr{Int("a", 1), Int(badKey, 2), Int(badKey, 3)}},
+ } {
+ r := NewRecord(time.Time{}, 0, "", 0)
+ r.Add(test.args...)
+ got := attrsSlice(r)
+ if !attrsEqual(got, test.want) {
+ t.Errorf("%v:\ngot %v\nwant %v", test.args, got, test.want)
+ }
+ }
+}
+
+func TestSetDefault(t *testing.T) {
+ // Verify that setting the default to itself does not result in deadlock.
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ defer func(w io.Writer) { log.SetOutput(w) }(log.Writer())
+ log.SetOutput(io.Discard)
+ go func() {
+ Info("A")
+ SetDefault(Default())
+ Info("B")
+ cancel()
+ }()
+ <-ctx.Done()
+ if err := ctx.Err(); err != context.Canceled {
+ t.Errorf("wanted canceled, got %v", err)
+ }
+}
+
+// Test defaultHandler minimum level without calling slog.SetDefault.
+func TestLogLoggerLevelForDefaultHandler(t *testing.T) {
+ // Revert any changes to the default logger, flags, and level of log and slog.
+ currentLogLoggerLevel := logLoggerLevel.Level()
+ currentLogWriter := log.Writer()
+ currentLogFlags := log.Flags()
+ t.Cleanup(func() {
+ logLoggerLevel.Set(currentLogLoggerLevel)
+ log.SetOutput(currentLogWriter)
+ log.SetFlags(currentLogFlags)
+ })
+
+ var logBuf bytes.Buffer
+ log.SetOutput(&logBuf)
+ log.SetFlags(0)
+
+ for _, test := range []struct {
+ logLevel Level
+ logFn func(string, ...any)
+ want string
+ }{
+ {LevelDebug, Debug, "DEBUG a"},
+ {LevelDebug, Info, "INFO a"},
+ {LevelInfo, Debug, ""},
+ {LevelInfo, Info, "INFO a"},
+ } {
+ SetLogLoggerLevel(test.logLevel)
+ test.logFn("a")
+ checkLogOutput(t, logBuf.String(), test.want)
+ logBuf.Reset()
+ }
+}
+
+// Test handlerWriter minimum level by calling slog.SetDefault.
+func TestLogLoggerLevelForHandlerWriter(t *testing.T) {
+ removeTime := func(_ []string, a Attr) Attr {
+ if a.Key == TimeKey {
+ return Attr{}
+ }
+ return a
+ }
+
+ // Revert any changes to the default logger. This is important because other
+ // tests might change the default logger using SetDefault. Also ensure we
+ // restore the default logger at the end of the test.
+ currentLogger := Default()
+ currentLogLoggerLevel := logLoggerLevel.Level()
+ currentLogWriter := log.Writer()
+ currentFlags := log.Flags()
+ t.Cleanup(func() {
+ SetDefault(currentLogger)
+ logLoggerLevel.Set(currentLogLoggerLevel)
+ log.SetOutput(currentLogWriter)
+ log.SetFlags(currentFlags)
+ })
+
+ var logBuf bytes.Buffer
+ log.SetOutput(&logBuf)
+ log.SetFlags(0)
+ SetLogLoggerLevel(LevelError)
+ SetDefault(New(NewTextHandler(&logBuf, &HandlerOptions{ReplaceAttr: removeTime})))
+ log.Print("error")
+ checkLogOutput(t, logBuf.String(), `level=ERROR msg=error`)
+}
+
+func TestLoggerError(t *testing.T) {
+ var buf bytes.Buffer
+
+ removeTime := func(_ []string, a Attr) Attr {
+ if a.Key == TimeKey {
+ return Attr{}
+ }
+ return a
+ }
+ l := New(NewTextHandler(&buf, &HandlerOptions{ReplaceAttr: removeTime}))
+ l.Error("msg", "err", io.EOF, "a", 1)
+ checkLogOutput(t, buf.String(), `level=ERROR msg=msg err=EOF a=1`)
+ buf.Reset()
+ // use local var 'args' to defeat vet check
+ args := []any{"err", io.EOF, "a"}
+ l.Error("msg", args...)
+ checkLogOutput(t, buf.String(), `level=ERROR msg=msg err=EOF !BADKEY=a`)
+}
+
+func TestNewLogLogger(t *testing.T) {
+ var buf bytes.Buffer
+ h := NewTextHandler(&buf, nil)
+ ll := NewLogLogger(h, LevelWarn)
+ ll.Print("hello")
+ checkLogOutput(t, buf.String(), "time="+textTimeRE+` level=WARN msg=hello`)
+}
+
+func TestLoggerNoOps(t *testing.T) {
+ l := Default()
+ if l.With() != l {
+ t.Error("wanted receiver, didn't get it")
+ }
+ if With() != l {
+ t.Error("wanted receiver, didn't get it")
+ }
+ if l.WithGroup("") != l {
+ t.Error("wanted receiver, didn't get it")
+ }
+}
+
+func TestContext(t *testing.T) {
+ // Verify that the context argument to log output methods is passed to the handler.
+ // Also check the level.
+ h := &captureHandler{}
+ l := New(h)
+ defer SetDefault(Default()) // restore
+ SetDefault(l)
+
+ for _, test := range []struct {
+ f func(context.Context, string, ...any)
+ wantLevel Level
+ }{
+ {l.DebugContext, LevelDebug},
+ {l.InfoContext, LevelInfo},
+ {l.WarnContext, LevelWarn},
+ {l.ErrorContext, LevelError},
+ {DebugContext, LevelDebug},
+ {InfoContext, LevelInfo},
+ {WarnContext, LevelWarn},
+ {ErrorContext, LevelError},
+ } {
+ h.clear()
+ ctx := context.WithValue(context.Background(), "L", test.wantLevel)
+
+ test.f(ctx, "msg")
+ if gv := h.ctx.Value("L"); gv != test.wantLevel || h.r.Level != test.wantLevel {
+ t.Errorf("got context value %v, level %s; want %s for both", gv, h.r.Level, test.wantLevel)
+ }
+ }
+}
+
+func checkLogOutput(t *testing.T, got, wantRegexp string) {
+ t.Helper()
+ got = clean(got)
+ wantRegexp = "^" + wantRegexp + "$"
+ matched, err := regexp.MatchString(wantRegexp, got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !matched {
+ t.Errorf("\ngot %s\nwant %s", got, wantRegexp)
+ }
+}
+
+// clean prepares log output for comparison.
+func clean(s string) string {
+ if len(s) > 0 && s[len(s)-1] == '\n' {
+ s = s[:len(s)-1]
+ }
+ return strings.ReplaceAll(s, "\n", "~")
+}
+
+type captureHandler struct {
+ mu sync.Mutex
+ ctx context.Context
+ r Record
+ attrs []Attr
+ groups []string
+}
+
+func (h *captureHandler) Handle(ctx context.Context, r Record) error {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.ctx = ctx
+ h.r = r
+ return nil
+}
+
+func (*captureHandler) Enabled(context.Context, Level) bool { return true }
+
+func (c *captureHandler) WithAttrs(as []Attr) Handler {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var c2 captureHandler
+ c2.r = c.r
+ c2.groups = c.groups
+ c2.attrs = concat(c.attrs, as)
+ return &c2
+}
+
+func (c *captureHandler) WithGroup(name string) Handler {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var c2 captureHandler
+ c2.r = c.r
+ c2.attrs = c.attrs
+ c2.groups = append(slices.Clip(c.groups), name)
+ return &c2
+}
+
+func (c *captureHandler) clear() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.ctx = nil
+ c.r = Record{}
+}
+
+type discardHandler struct {
+ disabled bool
+ attrs []Attr
+}
+
+func (d discardHandler) Enabled(context.Context, Level) bool { return !d.disabled }
+func (discardHandler) Handle(context.Context, Record) error { return nil }
+func (d discardHandler) WithAttrs(as []Attr) Handler {
+ d.attrs = concat(d.attrs, as)
+ return d
+}
+func (h discardHandler) WithGroup(name string) Handler {
+ return h
+}
+
+// concat returns a new slice with the elements of s1 followed
+// by those of s2. The slice has no additional capacity.
+func concat[T any](s1, s2 []T) []T {
+ s := make([]T, len(s1)+len(s2))
+ copy(s, s1)
+ copy(s[len(s1):], s2)
+ return s
+}
+
+// This is a simple benchmark. See the benchmarks subdirectory for more extensive ones.
+func BenchmarkNopLog(b *testing.B) {
+ ctx := context.Background()
+ l := New(&captureHandler{})
+ b.Run("no attrs", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ l.LogAttrs(ctx, LevelInfo, "msg")
+ }
+ })
+ b.Run("attrs", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ l.LogAttrs(ctx, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
+ }
+ })
+ b.Run("attrs-parallel", func(b *testing.B) {
+ b.ReportAllocs()
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ l.LogAttrs(ctx, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
+ }
+ })
+ })
+ b.Run("keys-values", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ l.Log(ctx, LevelInfo, "msg", "a", 1, "b", "two", "c", true)
+ }
+ })
+ b.Run("WithContext", func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ l.LogAttrs(ctx, LevelInfo, "msg2", Int("a", 1), String("b", "two"), Bool("c", true))
+ }
+ })
+ b.Run("WithContext-parallel", func(b *testing.B) {
+ b.ReportAllocs()
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ l.LogAttrs(ctx, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
+ }
+ })
+ })
+}
+
+// callerPC returns the program counter at the given stack depth.
+func callerPC(depth int) uintptr {
+ var pcs [1]uintptr
+ runtime.Callers(depth, pcs[:])
+ return pcs[0]
+}
+
+func wantAllocs(t *testing.T, want int, f func()) {
+ if race.Enabled {
+ t.Skip("skipping test in race mode")
+ }
+ testenv.SkipIfOptimizationOff(t)
+ t.Helper()
+ got := int(testing.AllocsPerRun(5, f))
+ if got != want {
+ t.Errorf("got %d allocs, want %d", got, want)
+ }
+}
+
+// panicTextAndJsonMarshaler is a type that panics in MarshalText and MarshalJSON.
+type panicTextAndJsonMarshaler struct {
+ msg any
+}
+
+func (p panicTextAndJsonMarshaler) MarshalText() ([]byte, error) {
+ panic(p.msg)
+}
+
+func (p panicTextAndJsonMarshaler) MarshalJSON() ([]byte, error) {
+ panic(p.msg)
+}
+
+func TestPanics(t *testing.T) {
+ // Revert any changes to the default logger. This is important because other
+ // tests might change the default logger using SetDefault. Also ensure we
+ // restore the default logger at the end of the test.
+ currentLogger := Default()
+ currentLogWriter := log.Writer()
+ currentLogFlags := log.Flags()
+ t.Cleanup(func() {
+ SetDefault(currentLogger)
+ log.SetOutput(currentLogWriter)
+ log.SetFlags(currentLogFlags)
+ })
+
+ var logBuf bytes.Buffer
+ log.SetOutput(&logBuf)
+ log.SetFlags(log.Lshortfile &^ log.LstdFlags)
+
+ SetDefault(New(newDefaultHandler(loginternal.DefaultOutput)))
+ for _, pt := range []struct {
+ in any
+ out string
+ }{
+ {(*panicTextAndJsonMarshaler)(nil), `logger_test.go:\d+: INFO msg p=`},
+ {panicTextAndJsonMarshaler{io.ErrUnexpectedEOF}, `logger_test.go:\d+: INFO msg p="!PANIC: unexpected EOF"`},
+ {panicTextAndJsonMarshaler{"panicking"}, `logger_test.go:\d+: INFO msg p="!PANIC: panicking"`},
+ {panicTextAndJsonMarshaler{42}, `logger_test.go:\d+: INFO msg p="!PANIC: 42"`},
+ } {
+ Info("msg", "p", pt.in)
+ checkLogOutput(t, logBuf.String(), pt.out)
+ logBuf.Reset()
+ }
+
+ SetDefault(New(NewJSONHandler(&logBuf, nil)))
+ for _, pt := range []struct {
+ in any
+ out string
+ }{
+ {(*panicTextAndJsonMarshaler)(nil), `{"time":"` + jsonTimeRE + `","level":"INFO","msg":"msg","p":null}`},
+ {panicTextAndJsonMarshaler{io.ErrUnexpectedEOF}, `{"time":"` + jsonTimeRE + `","level":"INFO","msg":"msg","p":"!PANIC: unexpected EOF"}`},
+ {panicTextAndJsonMarshaler{"panicking"}, `{"time":"` + jsonTimeRE + `","level":"INFO","msg":"msg","p":"!PANIC: panicking"}`},
+ {panicTextAndJsonMarshaler{42}, `{"time":"` + jsonTimeRE + `","level":"INFO","msg":"msg","p":"!PANIC: 42"}`},
+ } {
+ Info("msg", "p", pt.in)
+ checkLogOutput(t, logBuf.String(), pt.out)
+ logBuf.Reset()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/record.go b/platform/dbops/binaries/go/go/src/log/slog/record.go
new file mode 100644
index 0000000000000000000000000000000000000000..97c87019a6aff5bbee9a96c4084ab815f0737f66
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/record.go
@@ -0,0 +1,226 @@
+// 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 slog
+
+import (
+ "runtime"
+ "slices"
+ "time"
+)
+
+const nAttrsInline = 5
+
+// A Record holds information about a log event.
+// Copies of a Record share state.
+// Do not modify a Record after handing out a copy to it.
+// Call [NewRecord] to create a new Record.
+// Use [Record.Clone] to create a copy with no shared state.
+type Record struct {
+ // The time at which the output method (Log, Info, etc.) was called.
+ Time time.Time
+
+ // The log message.
+ Message string
+
+ // The level of the event.
+ Level Level
+
+ // The program counter at the time the record was constructed, as determined
+ // by runtime.Callers. If zero, no program counter is available.
+ //
+ // The only valid use for this value is as an argument to
+ // [runtime.CallersFrames]. In particular, it must not be passed to
+ // [runtime.FuncForPC].
+ PC uintptr
+
+ // Allocation optimization: an inline array sized to hold
+ // the majority of log calls (based on examination of open-source
+ // code). It holds the start of the list of Attrs.
+ front [nAttrsInline]Attr
+
+ // The number of Attrs in front.
+ nFront int
+
+ // The list of Attrs except for those in front.
+ // Invariants:
+ // - len(back) > 0 iff nFront == len(front)
+ // - Unused array elements are zero. Used to detect mistakes.
+ back []Attr
+}
+
+// NewRecord creates a [Record] from the given arguments.
+// Use [Record.AddAttrs] to add attributes to the Record.
+//
+// NewRecord is intended for logging APIs that want to support a [Handler] as
+// a backend.
+func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record {
+ return Record{
+ Time: t,
+ Message: msg,
+ Level: level,
+ PC: pc,
+ }
+}
+
+// Clone returns a copy of the record with no shared state.
+// The original record and the clone can both be modified
+// without interfering with each other.
+func (r Record) Clone() Record {
+ r.back = slices.Clip(r.back) // prevent append from mutating shared array
+ return r
+}
+
+// NumAttrs returns the number of attributes in the [Record].
+func (r Record) NumAttrs() int {
+ return r.nFront + len(r.back)
+}
+
+// Attrs calls f on each Attr in the [Record].
+// Iteration stops if f returns false.
+func (r Record) Attrs(f func(Attr) bool) {
+ for i := 0; i < r.nFront; i++ {
+ if !f(r.front[i]) {
+ return
+ }
+ }
+ for _, a := range r.back {
+ if !f(a) {
+ return
+ }
+ }
+}
+
+// AddAttrs appends the given Attrs to the [Record]'s list of Attrs.
+// It omits empty groups.
+func (r *Record) AddAttrs(attrs ...Attr) {
+ var i int
+ for i = 0; i < len(attrs) && r.nFront < len(r.front); i++ {
+ a := attrs[i]
+ if a.Value.isEmptyGroup() {
+ continue
+ }
+ r.front[r.nFront] = a
+ r.nFront++
+ }
+ // Check if a copy was modified by slicing past the end
+ // and seeing if the Attr there is non-zero.
+ if cap(r.back) > len(r.back) {
+ end := r.back[:len(r.back)+1][len(r.back)]
+ if !end.isEmpty() {
+ // Don't panic; copy and muddle through.
+ r.back = slices.Clip(r.back)
+ r.back = append(r.back, String("!BUG", "AddAttrs unsafely called on copy of Record made without using Record.Clone"))
+ }
+ }
+ ne := countEmptyGroups(attrs[i:])
+ r.back = slices.Grow(r.back, len(attrs[i:])-ne)
+ for _, a := range attrs[i:] {
+ if !a.Value.isEmptyGroup() {
+ r.back = append(r.back, a)
+ }
+ }
+}
+
+// Add converts the args to Attrs as described in [Logger.Log],
+// then appends the Attrs to the [Record]'s list of Attrs.
+// It omits empty groups.
+func (r *Record) Add(args ...any) {
+ var a Attr
+ for len(args) > 0 {
+ a, args = argsToAttr(args)
+ if a.Value.isEmptyGroup() {
+ continue
+ }
+ if r.nFront < len(r.front) {
+ r.front[r.nFront] = a
+ r.nFront++
+ } else {
+ if r.back == nil {
+ r.back = make([]Attr, 0, countAttrs(args)+1)
+ }
+ r.back = append(r.back, a)
+ }
+ }
+}
+
+// countAttrs returns the number of Attrs that would be created from args.
+func countAttrs(args []any) int {
+ n := 0
+ for i := 0; i < len(args); i++ {
+ n++
+ if _, ok := args[i].(string); ok {
+ i++
+ }
+ }
+ return n
+}
+
+const badKey = "!BADKEY"
+
+// argsToAttr turns a prefix of the nonempty args slice into an Attr
+// and returns the unconsumed portion of the slice.
+// If args[0] is an Attr, it returns it.
+// If args[0] is a string, it treats the first two elements as
+// a key-value pair.
+// Otherwise, it treats args[0] as a value with a missing key.
+func argsToAttr(args []any) (Attr, []any) {
+ switch x := args[0].(type) {
+ case string:
+ if len(args) == 1 {
+ return String(badKey, x), nil
+ }
+ return Any(x, args[1]), args[2:]
+
+ case Attr:
+ return x, args[1:]
+
+ default:
+ return Any(badKey, x), args[1:]
+ }
+}
+
+// Source describes the location of a line of source code.
+type Source struct {
+ // Function is the package path-qualified function name containing the
+ // source line. If non-empty, this string uniquely identifies a single
+ // function in the program. This may be the empty string if not known.
+ Function string `json:"function"`
+ // File and Line are the file name and line number (1-based) of the source
+ // line. These may be the empty string and zero, respectively, if not known.
+ File string `json:"file"`
+ Line int `json:"line"`
+}
+
+// group returns the non-zero fields of s as a slice of attrs.
+// It is similar to a LogValue method, but we don't want Source
+// to implement LogValuer because it would be resolved before
+// the ReplaceAttr function was called.
+func (s *Source) group() Value {
+ var as []Attr
+ if s.Function != "" {
+ as = append(as, String("function", s.Function))
+ }
+ if s.File != "" {
+ as = append(as, String("file", s.File))
+ }
+ if s.Line != 0 {
+ as = append(as, Int("line", s.Line))
+ }
+ return GroupValue(as...)
+}
+
+// source returns a Source for the log event.
+// If the Record was created without the necessary information,
+// or if the location is unavailable, it returns a non-nil *Source
+// with zero fields.
+func (r Record) source() *Source {
+ fs := runtime.CallersFrames([]uintptr{r.PC})
+ f, _ := fs.Next()
+ return &Source{
+ Function: f.Function,
+ File: f.File,
+ Line: f.Line,
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/record_test.go b/platform/dbops/binaries/go/go/src/log/slog/record_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..931ab660418db0bf470aacff46f2294f2370c57d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/record_test.go
@@ -0,0 +1,159 @@
+// 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 slog
+
+import (
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestRecordAttrs(t *testing.T) {
+ as := []Attr{Int("k1", 1), String("k2", "foo"), Int("k3", 3),
+ Int64("k4", -1), Float64("f", 3.1), Uint64("u", 999)}
+ r := newRecordWithAttrs(as)
+ if g, w := r.NumAttrs(), len(as); g != w {
+ t.Errorf("NumAttrs: got %d, want %d", g, w)
+ }
+ if got := attrsSlice(r); !attrsEqual(got, as) {
+ t.Errorf("got %v, want %v", got, as)
+ }
+
+ // Early return.
+ // Hit both loops in Record.Attrs: front and back.
+ for _, stop := range []int{2, 6} {
+ var got []Attr
+ r.Attrs(func(a Attr) bool {
+ got = append(got, a)
+ return len(got) < stop
+ })
+ want := as[:stop]
+ if !attrsEqual(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ }
+}
+
+func TestRecordSource(t *testing.T) {
+ // Zero call depth => empty *Source.
+ for _, test := range []struct {
+ depth int
+ wantFunction string
+ wantFile string
+ wantLinePositive bool
+ }{
+ {0, "", "", false},
+ {-16, "", "", false},
+ {1, "log/slog.TestRecordSource", "record_test.go", true}, // 1: caller of NewRecord
+ {2, "testing.tRunner", "testing.go", true},
+ } {
+ var pc uintptr
+ if test.depth > 0 {
+ pc = callerPC(test.depth + 1)
+ }
+ r := NewRecord(time.Time{}, 0, "", pc)
+ got := r.source()
+ if i := strings.LastIndexByte(got.File, '/'); i >= 0 {
+ got.File = got.File[i+1:]
+ }
+ if got.Function != test.wantFunction || got.File != test.wantFile || (got.Line > 0) != test.wantLinePositive {
+ t.Errorf("depth %d: got (%q, %q, %d), want (%q, %q, %t)",
+ test.depth,
+ got.Function, got.File, got.Line,
+ test.wantFunction, test.wantFile, test.wantLinePositive)
+ }
+ }
+}
+
+func TestAliasingAndClone(t *testing.T) {
+ intAttrs := func(from, to int) []Attr {
+ var as []Attr
+ for i := from; i < to; i++ {
+ as = append(as, Int("k", i))
+ }
+ return as
+ }
+
+ check := func(r Record, want []Attr) {
+ t.Helper()
+ got := attrsSlice(r)
+ if !attrsEqual(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ }
+
+ // Create a record whose Attrs overflow the inline array,
+ // creating a slice in r.back.
+ r1 := NewRecord(time.Time{}, 0, "", 0)
+ r1.AddAttrs(intAttrs(0, nAttrsInline+1)...)
+ // Ensure that r1.back's capacity exceeds its length.
+ b := make([]Attr, len(r1.back), len(r1.back)+1)
+ copy(b, r1.back)
+ r1.back = b
+ // Make a copy that shares state.
+ r2 := r1
+ // Adding to both should insert a special Attr in the second.
+ r1AttrsBefore := attrsSlice(r1)
+ r1.AddAttrs(Int("p", 0))
+ r2.AddAttrs(Int("p", 1))
+ check(r1, append(slices.Clip(r1AttrsBefore), Int("p", 0)))
+ r1Attrs := attrsSlice(r1)
+ check(r2, append(slices.Clip(r1AttrsBefore),
+ String("!BUG", "AddAttrs unsafely called on copy of Record made without using Record.Clone"), Int("p", 1)))
+
+ // Adding to a clone is fine.
+ r2 = r1.Clone()
+ check(r2, r1Attrs)
+ r2.AddAttrs(Int("p", 2))
+ check(r1, r1Attrs) // r1 is unchanged
+ check(r2, append(slices.Clip(r1Attrs), Int("p", 2)))
+}
+
+func newRecordWithAttrs(as []Attr) Record {
+ r := NewRecord(time.Now(), LevelInfo, "", 0)
+ r.AddAttrs(as...)
+ return r
+}
+
+func attrsSlice(r Record) []Attr {
+ s := make([]Attr, 0, r.NumAttrs())
+ r.Attrs(func(a Attr) bool { s = append(s, a); return true })
+ return s
+}
+
+func attrsEqual(as1, as2 []Attr) bool {
+ return slices.EqualFunc(as1, as2, Attr.Equal)
+}
+
+// Currently, pc(2) takes over 400ns, which is too expensive
+// to call it for every log message.
+func BenchmarkPC(b *testing.B) {
+ for depth := 0; depth < 5; depth++ {
+ b.Run(strconv.Itoa(depth), func(b *testing.B) {
+ b.ReportAllocs()
+ var x uintptr
+ for i := 0; i < b.N; i++ {
+ x = callerPC(depth)
+ }
+ _ = x
+ })
+ }
+}
+
+func BenchmarkRecord(b *testing.B) {
+ const nAttrs = nAttrsInline * 10
+ var a Attr
+
+ for i := 0; i < b.N; i++ {
+ r := NewRecord(time.Time{}, LevelInfo, "", 0)
+ for j := 0; j < nAttrs; j++ {
+ r.AddAttrs(Int("k", j))
+ }
+ r.Attrs(func(b Attr) bool { a = b; return true })
+ }
+ _ = a
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/slogtest_test.go b/platform/dbops/binaries/go/go/src/log/slog/slogtest_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4887cc8c77d1e926f68271c660e1a26ff0b7061f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/slogtest_test.go
@@ -0,0 +1,104 @@
+// 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 slog_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "strings"
+ "testing"
+ "testing/slogtest"
+)
+
+func TestSlogtest(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ new func(io.Writer) slog.Handler
+ parse func([]byte) (map[string]any, error)
+ }{
+ {"JSON", func(w io.Writer) slog.Handler { return slog.NewJSONHandler(w, nil) }, parseJSON},
+ {"Text", func(w io.Writer) slog.Handler { return slog.NewTextHandler(w, nil) }, parseText},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ h := test.new(&buf)
+ results := func() []map[string]any {
+ ms, err := parseLines(buf.Bytes(), test.parse)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ms
+ }
+ if err := slogtest.TestHandler(h, results); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
+func parseLines(src []byte, parse func([]byte) (map[string]any, error)) ([]map[string]any, error) {
+ var records []map[string]any
+ for _, line := range bytes.Split(src, []byte{'\n'}) {
+ if len(line) == 0 {
+ continue
+ }
+ m, err := parse(line)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", string(line), err)
+ }
+ records = append(records, m)
+ }
+ return records, nil
+}
+
+func parseJSON(bs []byte) (map[string]any, error) {
+ var m map[string]any
+ if err := json.Unmarshal(bs, &m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// parseText parses the output of a single call to TextHandler.Handle.
+// It can parse the output of the tests in this package,
+// but it doesn't handle quoted keys or values.
+// It doesn't need to handle all cases, because slogtest deliberately
+// uses simple inputs so handler writers can focus on testing
+// handler behavior, not parsing.
+func parseText(bs []byte) (map[string]any, error) {
+ top := map[string]any{}
+ s := string(bytes.TrimSpace(bs))
+ for len(s) > 0 {
+ kv, rest, _ := strings.Cut(s, " ") // assumes exactly one space between attrs
+ k, value, found := strings.Cut(kv, "=")
+ if !found {
+ return nil, fmt.Errorf("no '=' in %q", kv)
+ }
+ keys := strings.Split(k, ".")
+ // Populate a tree of maps for a dotted path such as "a.b.c=x".
+ m := top
+ for _, key := range keys[:len(keys)-1] {
+ x, ok := m[key]
+ var m2 map[string]any
+ if !ok {
+ m2 = map[string]any{}
+ m[key] = m2
+ } else {
+ m2, ok = x.(map[string]any)
+ if !ok {
+ return nil, fmt.Errorf("value for %q in composite key %q is not map[string]any", key, k)
+
+ }
+ }
+ m = m2
+ }
+ m[keys[len(keys)-1]] = value
+ s = rest
+ }
+ return top, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/text_handler.go b/platform/dbops/binaries/go/go/src/log/slog/text_handler.go
new file mode 100644
index 0000000000000000000000000000000000000000..6819e633bb713f20bce1399a06cb773ffff51bc3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/text_handler.go
@@ -0,0 +1,163 @@
+// 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 slog
+
+import (
+ "context"
+ "encoding"
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "sync"
+ "unicode"
+ "unicode/utf8"
+)
+
+// TextHandler is a [Handler] that writes Records to an [io.Writer] as a
+// sequence of key=value pairs separated by spaces and followed by a newline.
+type TextHandler struct {
+ *commonHandler
+}
+
+// NewTextHandler creates a [TextHandler] that writes to w,
+// using the given options.
+// If opts is nil, the default options are used.
+func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler {
+ if opts == nil {
+ opts = &HandlerOptions{}
+ }
+ return &TextHandler{
+ &commonHandler{
+ json: false,
+ w: w,
+ opts: *opts,
+ mu: &sync.Mutex{},
+ },
+ }
+}
+
+// Enabled reports whether the handler handles records at the given level.
+// The handler ignores records whose level is lower.
+func (h *TextHandler) Enabled(_ context.Context, level Level) bool {
+ return h.commonHandler.enabled(level)
+}
+
+// WithAttrs returns a new [TextHandler] whose attributes consists
+// of h's attributes followed by attrs.
+func (h *TextHandler) WithAttrs(attrs []Attr) Handler {
+ return &TextHandler{commonHandler: h.commonHandler.withAttrs(attrs)}
+}
+
+func (h *TextHandler) WithGroup(name string) Handler {
+ return &TextHandler{commonHandler: h.commonHandler.withGroup(name)}
+}
+
+// Handle formats its argument [Record] as a single line of space-separated
+// key=value items.
+//
+// If the Record's time is zero, the time is omitted.
+// Otherwise, the key is "time"
+// and the value is output in RFC3339 format with millisecond precision.
+//
+// If the Record's level is zero, the level is omitted.
+// Otherwise, the key is "level"
+// and the value of [Level.String] is output.
+//
+// If the AddSource option is set and source information is available,
+// the key is "source" and the value is output as FILE:LINE.
+//
+// The message's key is "msg".
+//
+// To modify these or other attributes, or remove them from the output, use
+// [HandlerOptions.ReplaceAttr].
+//
+// If a value implements [encoding.TextMarshaler], the result of MarshalText is
+// written. Otherwise, the result of [fmt.Sprint] is written.
+//
+// Keys and values are quoted with [strconv.Quote] if they contain Unicode space
+// characters, non-printing characters, '"' or '='.
+//
+// Keys inside groups consist of components (keys or group names) separated by
+// dots. No further escaping is performed.
+// Thus there is no way to determine from the key "a.b.c" whether there
+// are two groups "a" and "b" and a key "c", or a single group "a.b" and a key "c",
+// or single group "a" and a key "b.c".
+// If it is necessary to reconstruct the group structure of a key
+// even in the presence of dots inside components, use
+// [HandlerOptions.ReplaceAttr] to encode that information in the key.
+//
+// Each call to Handle results in a single serialized call to
+// io.Writer.Write.
+func (h *TextHandler) Handle(_ context.Context, r Record) error {
+ return h.commonHandler.handle(r)
+}
+
+func appendTextValue(s *handleState, v Value) error {
+ switch v.Kind() {
+ case KindString:
+ s.appendString(v.str())
+ case KindTime:
+ s.appendTime(v.time())
+ case KindAny:
+ if tm, ok := v.any.(encoding.TextMarshaler); ok {
+ data, err := tm.MarshalText()
+ if err != nil {
+ return err
+ }
+ // TODO: avoid the conversion to string.
+ s.appendString(string(data))
+ return nil
+ }
+ if bs, ok := byteSlice(v.any); ok {
+ // As of Go 1.19, this only allocates for strings longer than 32 bytes.
+ s.buf.WriteString(strconv.Quote(string(bs)))
+ return nil
+ }
+ s.appendString(fmt.Sprintf("%+v", v.Any()))
+ default:
+ *s.buf = v.append(*s.buf)
+ }
+ return nil
+}
+
+// byteSlice returns its argument as a []byte if the argument's
+// underlying type is []byte, along with a second return value of true.
+// Otherwise it returns nil, false.
+func byteSlice(a any) ([]byte, bool) {
+ if bs, ok := a.([]byte); ok {
+ return bs, true
+ }
+ // Like Printf's %s, we allow both the slice type and the byte element type to be named.
+ t := reflect.TypeOf(a)
+ if t != nil && t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
+ return reflect.ValueOf(a).Bytes(), true
+ }
+ return nil, false
+}
+
+func needsQuoting(s string) bool {
+ if len(s) == 0 {
+ return true
+ }
+ for i := 0; i < len(s); {
+ b := s[i]
+ if b < utf8.RuneSelf {
+ // Quote anything except a backslash that would need quoting in a
+ // JSON string, as well as space and '='
+ if b != '\\' && (b == ' ' || b == '=' || !safeSet[b]) {
+ return true
+ }
+ i++
+ continue
+ }
+ r, size := utf8.DecodeRuneInString(s[i:])
+ if r == utf8.RuneError || unicode.IsSpace(r) || !unicode.IsPrint(r) {
+ return true
+ }
+ i += size
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/text_handler_test.go b/platform/dbops/binaries/go/go/src/log/slog/text_handler_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..591c243b11f01df84bdea3d996bb48b55e6afb27
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/text_handler_test.go
@@ -0,0 +1,176 @@
+// 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 slog
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "strings"
+ "testing"
+ "time"
+)
+
+var testTime = time.Date(2000, 1, 2, 3, 4, 5, 0, time.UTC)
+
+func TestTextHandler(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ attr Attr
+ wantKey, wantVal string
+ }{
+ {
+ "unquoted",
+ Int("a", 1),
+ "a", "1",
+ },
+ {
+ "quoted",
+ String("x = y", `qu"o`),
+ `"x = y"`, `"qu\"o"`,
+ },
+ {
+ "String method",
+ Any("name", name{"Ren", "Hoek"}),
+ `name`, `"Hoek, Ren"`,
+ },
+ {
+ "struct",
+ Any("x", &struct{ A, b int }{A: 1, b: 2}),
+ `x`, `"&{A:1 b:2}"`,
+ },
+ {
+ "TextMarshaler",
+ Any("t", text{"abc"}),
+ `t`, `"text{\"abc\"}"`,
+ },
+ {
+ "TextMarshaler error",
+ Any("t", text{""}),
+ `t`, `"!ERROR:text: empty string"`,
+ },
+ {
+ "nil value",
+ Any("a", nil),
+ `a`, ``,
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ for _, opts := range []struct {
+ name string
+ opts HandlerOptions
+ wantPrefix string
+ modKey func(string) string
+ }{
+ {
+ "none",
+ HandlerOptions{},
+ `time=2000-01-02T03:04:05.000Z level=INFO msg="a message"`,
+ func(s string) string { return s },
+ },
+ {
+ "replace",
+ HandlerOptions{ReplaceAttr: upperCaseKey},
+ `TIME=2000-01-02T03:04:05.000Z LEVEL=INFO MSG="a message"`,
+ strings.ToUpper,
+ },
+ } {
+ t.Run(opts.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ h := NewTextHandler(&buf, &opts.opts)
+ r := NewRecord(testTime, LevelInfo, "a message", 0)
+ r.AddAttrs(test.attr)
+ if err := h.Handle(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+ got := buf.String()
+ // Remove final newline.
+ got = got[:len(got)-1]
+ want := opts.wantPrefix + " " + opts.modKey(test.wantKey) + "=" + test.wantVal
+ if got != want {
+ t.Errorf("\ngot %s\nwant %s", got, want)
+ }
+ })
+ }
+ })
+ }
+}
+
+// for testing fmt.Sprint
+type name struct {
+ First, Last string
+}
+
+func (n name) String() string { return n.Last + ", " + n.First }
+
+// for testing TextMarshaler
+type text struct {
+ s string
+}
+
+func (t text) String() string { return t.s } // should be ignored
+
+func (t text) MarshalText() ([]byte, error) {
+ if t.s == "" {
+ return nil, errors.New("text: empty string")
+ }
+ return []byte(fmt.Sprintf("text{%q}", t.s)), nil
+}
+
+func TestTextHandlerPreformatted(t *testing.T) {
+ var buf bytes.Buffer
+ var h Handler = NewTextHandler(&buf, nil)
+ h = h.WithAttrs([]Attr{Duration("dur", time.Minute), Bool("b", true)})
+ // Also test omitting time.
+ r := NewRecord(time.Time{}, 0 /* 0 Level is INFO */, "m", 0)
+ r.AddAttrs(Int("a", 1))
+ if err := h.Handle(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+ got := strings.TrimSuffix(buf.String(), "\n")
+ want := `level=INFO msg=m dur=1m0s b=true a=1`
+ if got != want {
+ t.Errorf("got %s, want %s", got, want)
+ }
+}
+
+func TestTextHandlerAlloc(t *testing.T) {
+ testenv.SkipIfOptimizationOff(t)
+ r := NewRecord(time.Now(), LevelInfo, "msg", 0)
+ for i := 0; i < 10; i++ {
+ r.AddAttrs(Int("x = y", i))
+ }
+ var h Handler = NewTextHandler(io.Discard, nil)
+ wantAllocs(t, 0, func() { h.Handle(context.Background(), r) })
+
+ h = h.WithGroup("s")
+ r.AddAttrs(Group("g", Int("a", 1)))
+ wantAllocs(t, 0, func() { h.Handle(context.Background(), r) })
+}
+
+func TestNeedsQuoting(t *testing.T) {
+ for _, test := range []struct {
+ in string
+ want bool
+ }{
+ {"", true},
+ {"ab", false},
+ {"a=b", true},
+ {`"ab"`, true},
+ {"\a\b", true},
+ {"a\tb", true},
+ {"µåπ", false},
+ {"a b", true},
+ {"badutf8\xF6", true},
+ } {
+ got := needsQuoting(test.in)
+ if got != test.want {
+ t.Errorf("%q: got %t, want %t", test.in, got, test.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/value.go b/platform/dbops/binaries/go/go/src/log/slog/value.go
new file mode 100644
index 0000000000000000000000000000000000000000..d278d9b923559fb5aaa7015961d7b2f581b5a246
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/value.go
@@ -0,0 +1,520 @@
+// 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 slog
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+ "unsafe"
+)
+
+// A Value can represent any Go value, but unlike type any,
+// it can represent most small values without an allocation.
+// The zero Value corresponds to nil.
+type Value struct {
+ _ [0]func() // disallow ==
+ // num holds the value for Kinds Int64, Uint64, Float64, Bool and Duration,
+ // the string length for KindString, and nanoseconds since the epoch for KindTime.
+ num uint64
+ // If any is of type Kind, then the value is in num as described above.
+ // If any is of type *time.Location, then the Kind is Time and time.Time value
+ // can be constructed from the Unix nanos in num and the location (monotonic time
+ // is not preserved).
+ // If any is of type stringptr, then the Kind is String and the string value
+ // consists of the length in num and the pointer in any.
+ // Otherwise, the Kind is Any and any is the value.
+ // (This implies that Attrs cannot store values of type Kind, *time.Location
+ // or stringptr.)
+ any any
+}
+
+type (
+ stringptr *byte // used in Value.any when the Value is a string
+ groupptr *Attr // used in Value.any when the Value is a []Attr
+)
+
+// Kind is the kind of a [Value].
+type Kind int
+
+// The following list is sorted alphabetically, but it's also important that
+// KindAny is 0 so that a zero Value represents nil.
+
+const (
+ KindAny Kind = iota
+ KindBool
+ KindDuration
+ KindFloat64
+ KindInt64
+ KindString
+ KindTime
+ KindUint64
+ KindGroup
+ KindLogValuer
+)
+
+var kindStrings = []string{
+ "Any",
+ "Bool",
+ "Duration",
+ "Float64",
+ "Int64",
+ "String",
+ "Time",
+ "Uint64",
+ "Group",
+ "LogValuer",
+}
+
+func (k Kind) String() string {
+ if k >= 0 && int(k) < len(kindStrings) {
+ return kindStrings[k]
+ }
+ return ""
+}
+
+// Unexported version of Kind, just so we can store Kinds in Values.
+// (No user-provided value has this type.)
+type kind Kind
+
+// Kind returns v's Kind.
+func (v Value) Kind() Kind {
+ switch x := v.any.(type) {
+ case Kind:
+ return x
+ case stringptr:
+ return KindString
+ case timeLocation:
+ return KindTime
+ case groupptr:
+ return KindGroup
+ case LogValuer:
+ return KindLogValuer
+ case kind: // a kind is just a wrapper for a Kind
+ return KindAny
+ default:
+ return KindAny
+ }
+}
+
+//////////////// Constructors
+
+// StringValue returns a new [Value] for a string.
+func StringValue(value string) Value {
+ return Value{num: uint64(len(value)), any: stringptr(unsafe.StringData(value))}
+}
+
+// IntValue returns a [Value] for an int.
+func IntValue(v int) Value {
+ return Int64Value(int64(v))
+}
+
+// Int64Value returns a [Value] for an int64.
+func Int64Value(v int64) Value {
+ return Value{num: uint64(v), any: KindInt64}
+}
+
+// Uint64Value returns a [Value] for a uint64.
+func Uint64Value(v uint64) Value {
+ return Value{num: v, any: KindUint64}
+}
+
+// Float64Value returns a [Value] for a floating-point number.
+func Float64Value(v float64) Value {
+ return Value{num: math.Float64bits(v), any: KindFloat64}
+}
+
+// BoolValue returns a [Value] for a bool.
+func BoolValue(v bool) Value {
+ u := uint64(0)
+ if v {
+ u = 1
+ }
+ return Value{num: u, any: KindBool}
+}
+
+// Unexported version of *time.Location, just so we can store *time.Locations in
+// Values. (No user-provided value has this type.)
+type timeLocation *time.Location
+
+// TimeValue returns a [Value] for a [time.Time].
+// It discards the monotonic portion.
+func TimeValue(v time.Time) Value {
+ if v.IsZero() {
+ // UnixNano on the zero time is undefined, so represent the zero time
+ // with a nil *time.Location instead. time.Time.Location method never
+ // returns nil, so a Value with any == timeLocation(nil) cannot be
+ // mistaken for any other Value, time.Time or otherwise.
+ return Value{any: timeLocation(nil)}
+ }
+ return Value{num: uint64(v.UnixNano()), any: timeLocation(v.Location())}
+}
+
+// DurationValue returns a [Value] for a [time.Duration].
+func DurationValue(v time.Duration) Value {
+ return Value{num: uint64(v.Nanoseconds()), any: KindDuration}
+}
+
+// GroupValue returns a new [Value] for a list of Attrs.
+// The caller must not subsequently mutate the argument slice.
+func GroupValue(as ...Attr) Value {
+ // Remove empty groups.
+ // It is simpler overall to do this at construction than
+ // to check each Group recursively for emptiness.
+ if n := countEmptyGroups(as); n > 0 {
+ as2 := make([]Attr, 0, len(as)-n)
+ for _, a := range as {
+ if !a.Value.isEmptyGroup() {
+ as2 = append(as2, a)
+ }
+ }
+ as = as2
+ }
+ return Value{num: uint64(len(as)), any: groupptr(unsafe.SliceData(as))}
+}
+
+// countEmptyGroups returns the number of empty group values in its argument.
+func countEmptyGroups(as []Attr) int {
+ n := 0
+ for _, a := range as {
+ if a.Value.isEmptyGroup() {
+ n++
+ }
+ }
+ return n
+}
+
+// AnyValue returns a [Value] for the supplied value.
+//
+// If the supplied value is of type Value, it is returned
+// unmodified.
+//
+// Given a value of one of Go's predeclared string, bool, or
+// (non-complex) numeric types, AnyValue returns a Value of kind
+// [KindString], [KindBool], [KindUint64], [KindInt64], or [KindFloat64].
+// The width of the original numeric type is not preserved.
+//
+// Given a [time.Time] or [time.Duration] value, AnyValue returns a Value of kind
+// [KindTime] or [KindDuration]. The monotonic time is not preserved.
+//
+// For nil, or values of all other types, including named types whose
+// underlying type is numeric, AnyValue returns a value of kind [KindAny].
+func AnyValue(v any) Value {
+ switch v := v.(type) {
+ case string:
+ return StringValue(v)
+ case int:
+ return Int64Value(int64(v))
+ case uint:
+ return Uint64Value(uint64(v))
+ case int64:
+ return Int64Value(v)
+ case uint64:
+ return Uint64Value(v)
+ case bool:
+ return BoolValue(v)
+ case time.Duration:
+ return DurationValue(v)
+ case time.Time:
+ return TimeValue(v)
+ case uint8:
+ return Uint64Value(uint64(v))
+ case uint16:
+ return Uint64Value(uint64(v))
+ case uint32:
+ return Uint64Value(uint64(v))
+ case uintptr:
+ return Uint64Value(uint64(v))
+ case int8:
+ return Int64Value(int64(v))
+ case int16:
+ return Int64Value(int64(v))
+ case int32:
+ return Int64Value(int64(v))
+ case float64:
+ return Float64Value(v)
+ case float32:
+ return Float64Value(float64(v))
+ case []Attr:
+ return GroupValue(v...)
+ case Kind:
+ return Value{any: kind(v)}
+ case Value:
+ return v
+ default:
+ return Value{any: v}
+ }
+}
+
+//////////////// Accessors
+
+// Any returns v's value as an any.
+func (v Value) Any() any {
+ switch v.Kind() {
+ case KindAny:
+ if k, ok := v.any.(kind); ok {
+ return Kind(k)
+ }
+ return v.any
+ case KindLogValuer:
+ return v.any
+ case KindGroup:
+ return v.group()
+ case KindInt64:
+ return int64(v.num)
+ case KindUint64:
+ return v.num
+ case KindFloat64:
+ return v.float()
+ case KindString:
+ return v.str()
+ case KindBool:
+ return v.bool()
+ case KindDuration:
+ return v.duration()
+ case KindTime:
+ return v.time()
+ default:
+ panic(fmt.Sprintf("bad kind: %s", v.Kind()))
+ }
+}
+
+// String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike
+// the methods Int64, Float64, and so on, which panic if v is of the
+// wrong kind, String never panics.
+func (v Value) String() string {
+ if sp, ok := v.any.(stringptr); ok {
+ return unsafe.String(sp, v.num)
+ }
+ var buf []byte
+ return string(v.append(buf))
+}
+
+func (v Value) str() string {
+ return unsafe.String(v.any.(stringptr), v.num)
+}
+
+// Int64 returns v's value as an int64. It panics
+// if v is not a signed integer.
+func (v Value) Int64() int64 {
+ if g, w := v.Kind(), KindInt64; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+ return int64(v.num)
+}
+
+// Uint64 returns v's value as a uint64. It panics
+// if v is not an unsigned integer.
+func (v Value) Uint64() uint64 {
+ if g, w := v.Kind(), KindUint64; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+ return v.num
+}
+
+// Bool returns v's value as a bool. It panics
+// if v is not a bool.
+func (v Value) Bool() bool {
+ if g, w := v.Kind(), KindBool; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+ return v.bool()
+}
+
+func (v Value) bool() bool {
+ return v.num == 1
+}
+
+// Duration returns v's value as a [time.Duration]. It panics
+// if v is not a time.Duration.
+func (v Value) Duration() time.Duration {
+ if g, w := v.Kind(), KindDuration; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+
+ return v.duration()
+}
+
+func (v Value) duration() time.Duration {
+ return time.Duration(int64(v.num))
+}
+
+// Float64 returns v's value as a float64. It panics
+// if v is not a float64.
+func (v Value) Float64() float64 {
+ if g, w := v.Kind(), KindFloat64; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+
+ return v.float()
+}
+
+func (v Value) float() float64 {
+ return math.Float64frombits(v.num)
+}
+
+// Time returns v's value as a [time.Time]. It panics
+// if v is not a time.Time.
+func (v Value) Time() time.Time {
+ if g, w := v.Kind(), KindTime; g != w {
+ panic(fmt.Sprintf("Value kind is %s, not %s", g, w))
+ }
+ return v.time()
+}
+
+func (v Value) time() time.Time {
+ loc := v.any.(timeLocation)
+ if loc == nil {
+ return time.Time{}
+ }
+ return time.Unix(0, int64(v.num)).In(loc)
+}
+
+// LogValuer returns v's value as a LogValuer. It panics
+// if v is not a LogValuer.
+func (v Value) LogValuer() LogValuer {
+ return v.any.(LogValuer)
+}
+
+// Group returns v's value as a []Attr.
+// It panics if v's [Kind] is not [KindGroup].
+func (v Value) Group() []Attr {
+ if sp, ok := v.any.(groupptr); ok {
+ return unsafe.Slice((*Attr)(sp), v.num)
+ }
+ panic("Group: bad kind")
+}
+
+func (v Value) group() []Attr {
+ return unsafe.Slice((*Attr)(v.any.(groupptr)), v.num)
+}
+
+//////////////// Other
+
+// Equal reports whether v and w represent the same Go value.
+func (v Value) Equal(w Value) bool {
+ k1 := v.Kind()
+ k2 := w.Kind()
+ if k1 != k2 {
+ return false
+ }
+ switch k1 {
+ case KindInt64, KindUint64, KindBool, KindDuration:
+ return v.num == w.num
+ case KindString:
+ return v.str() == w.str()
+ case KindFloat64:
+ return v.float() == w.float()
+ case KindTime:
+ return v.time().Equal(w.time())
+ case KindAny, KindLogValuer:
+ return v.any == w.any // may panic if non-comparable
+ case KindGroup:
+ return slices.EqualFunc(v.group(), w.group(), Attr.Equal)
+ default:
+ panic(fmt.Sprintf("bad kind: %s", k1))
+ }
+}
+
+// isEmptyGroup reports whether v is a group that has no attributes.
+func (v Value) isEmptyGroup() bool {
+ if v.Kind() != KindGroup {
+ return false
+ }
+ // We do not need to recursively examine the group's Attrs for emptiness,
+ // because GroupValue removed them when the group was constructed, and
+ // groups are immutable.
+ return len(v.group()) == 0
+}
+
+// append appends a text representation of v to dst.
+// v is formatted as with fmt.Sprint.
+func (v Value) append(dst []byte) []byte {
+ switch v.Kind() {
+ case KindString:
+ return append(dst, v.str()...)
+ case KindInt64:
+ return strconv.AppendInt(dst, int64(v.num), 10)
+ case KindUint64:
+ return strconv.AppendUint(dst, v.num, 10)
+ case KindFloat64:
+ return strconv.AppendFloat(dst, v.float(), 'g', -1, 64)
+ case KindBool:
+ return strconv.AppendBool(dst, v.bool())
+ case KindDuration:
+ return append(dst, v.duration().String()...)
+ case KindTime:
+ return append(dst, v.time().String()...)
+ case KindGroup:
+ return fmt.Append(dst, v.group())
+ case KindAny, KindLogValuer:
+ return fmt.Append(dst, v.any)
+ default:
+ panic(fmt.Sprintf("bad kind: %s", v.Kind()))
+ }
+}
+
+// A LogValuer is any Go value that can convert itself into a Value for logging.
+//
+// This mechanism may be used to defer expensive operations until they are
+// needed, or to expand a single value into a sequence of components.
+type LogValuer interface {
+ LogValue() Value
+}
+
+const maxLogValues = 100
+
+// Resolve repeatedly calls LogValue on v while it implements [LogValuer],
+// and returns the result.
+// If v resolves to a group, the group's attributes' values are not recursively
+// resolved.
+// If the number of LogValue calls exceeds a threshold, a Value containing an
+// error is returned.
+// Resolve's return value is guaranteed not to be of Kind [KindLogValuer].
+func (v Value) Resolve() (rv Value) {
+ orig := v
+ defer func() {
+ if r := recover(); r != nil {
+ rv = AnyValue(fmt.Errorf("LogValue panicked\n%s", stack(3, 5)))
+ }
+ }()
+
+ for i := 0; i < maxLogValues; i++ {
+ if v.Kind() != KindLogValuer {
+ return v
+ }
+ v = v.LogValuer().LogValue()
+ }
+ err := fmt.Errorf("LogValue called too many times on Value of type %T", orig.Any())
+ return AnyValue(err)
+}
+
+func stack(skip, nFrames int) string {
+ pcs := make([]uintptr, nFrames+1)
+ n := runtime.Callers(skip+1, pcs)
+ if n == 0 {
+ return "(no stack)"
+ }
+ frames := runtime.CallersFrames(pcs[:n])
+ var b strings.Builder
+ i := 0
+ for {
+ frame, more := frames.Next()
+ fmt.Fprintf(&b, "called from %s (%s:%d)\n", frame.Function, frame.File, frame.Line)
+ if !more {
+ break
+ }
+ i++
+ if i >= nFrames {
+ fmt.Fprintf(&b, "(rest of stack elided)\n")
+ break
+ }
+ }
+ return b.String()
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/value_access_benchmark_test.go b/platform/dbops/binaries/go/go/src/log/slog/value_access_benchmark_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3bd70716ee10a8887e8770223b00fb333006ec9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/value_access_benchmark_test.go
@@ -0,0 +1,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.
+
+// Benchmark for accessing Value values.
+
+package slog
+
+import (
+ "testing"
+ "time"
+)
+
+// The "As" form is the slowest.
+// The switch-panic and visitor times are almost the same.
+// BenchmarkDispatch/switch-checked-8 8669427 137.7 ns/op
+// BenchmarkDispatch/As-8 8212087 145.3 ns/op
+// BenchmarkDispatch/Visit-8 8926146 135.3 ns/op
+func BenchmarkDispatch(b *testing.B) {
+ vs := []Value{
+ Int64Value(32768),
+ Uint64Value(0xfacecafe),
+ StringValue("anything"),
+ BoolValue(true),
+ Float64Value(1.2345),
+ DurationValue(time.Second),
+ AnyValue(b),
+ }
+ var (
+ ii int64
+ s string
+ bb bool
+ u uint64
+ d time.Duration
+ f float64
+ a any
+ )
+ b.Run("switch-checked", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, v := range vs {
+ switch v.Kind() {
+ case KindString:
+ s = v.String()
+ case KindInt64:
+ ii = v.Int64()
+ case KindUint64:
+ u = v.Uint64()
+ case KindFloat64:
+ f = v.Float64()
+ case KindBool:
+ bb = v.Bool()
+ case KindDuration:
+ d = v.Duration()
+ case KindAny:
+ a = v.Any()
+ default:
+ panic("bad kind")
+ }
+ }
+ }
+ _ = ii
+ _ = s
+ _ = bb
+ _ = u
+ _ = d
+ _ = f
+ _ = a
+
+ })
+ b.Run("As", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, kv := range vs {
+ if v, ok := kv.AsString(); ok {
+ s = v
+ } else if v, ok := kv.AsInt64(); ok {
+ ii = v
+ } else if v, ok := kv.AsUint64(); ok {
+ u = v
+ } else if v, ok := kv.AsFloat64(); ok {
+ f = v
+ } else if v, ok := kv.AsBool(); ok {
+ bb = v
+ } else if v, ok := kv.AsDuration(); ok {
+ d = v
+ } else if v, ok := kv.AsAny(); ok {
+ a = v
+ } else {
+ panic("bad kind")
+ }
+ }
+ }
+ _ = ii
+ _ = s
+ _ = bb
+ _ = u
+ _ = d
+ _ = f
+ _ = a
+ })
+
+ b.Run("Visit", func(b *testing.B) {
+ v := &setVisitor{}
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ for _, kv := range vs {
+ kv.Visit(v)
+ }
+ }
+ })
+}
+
+type setVisitor struct {
+ i int64
+ s string
+ b bool
+ u uint64
+ d time.Duration
+ f float64
+ a any
+}
+
+func (v *setVisitor) String(s string) { v.s = s }
+func (v *setVisitor) Int64(i int64) { v.i = i }
+func (v *setVisitor) Uint64(x uint64) { v.u = x }
+func (v *setVisitor) Float64(x float64) { v.f = x }
+func (v *setVisitor) Bool(x bool) { v.b = x }
+func (v *setVisitor) Duration(x time.Duration) { v.d = x }
+func (v *setVisitor) Any(x any) { v.a = x }
+
+// When dispatching on all types, the "As" functions are slightly slower
+// than switching on the kind and then calling a function that checks
+// the kind again. See BenchmarkDispatch above.
+
+func (a Value) AsString() (string, bool) {
+ if a.Kind() == KindString {
+ return a.str(), true
+ }
+ return "", false
+}
+
+func (a Value) AsInt64() (int64, bool) {
+ if a.Kind() == KindInt64 {
+ return int64(a.num), true
+ }
+ return 0, false
+}
+
+func (a Value) AsUint64() (uint64, bool) {
+ if a.Kind() == KindUint64 {
+ return a.num, true
+ }
+ return 0, false
+}
+
+func (a Value) AsFloat64() (float64, bool) {
+ if a.Kind() == KindFloat64 {
+ return a.float(), true
+ }
+ return 0, false
+}
+
+func (a Value) AsBool() (bool, bool) {
+ if a.Kind() == KindBool {
+ return a.bool(), true
+ }
+ return false, false
+}
+
+func (a Value) AsDuration() (time.Duration, bool) {
+ if a.Kind() == KindDuration {
+ return a.duration(), true
+ }
+ return 0, false
+}
+
+func (a Value) AsAny() (any, bool) {
+ if a.Kind() == KindAny {
+ return a.any, true
+ }
+ return nil, false
+}
+
+// Problem: adding a type means adding a method, which is a breaking change.
+// Using an unexported method to force embedding will make programs compile,
+// But they will panic at runtime when we call the new method.
+type Visitor interface {
+ String(string)
+ Int64(int64)
+ Uint64(uint64)
+ Float64(float64)
+ Bool(bool)
+ Duration(time.Duration)
+ Any(any)
+}
+
+func (a Value) Visit(v Visitor) {
+ switch a.Kind() {
+ case KindString:
+ v.String(a.str())
+ case KindInt64:
+ v.Int64(int64(a.num))
+ case KindUint64:
+ v.Uint64(a.num)
+ case KindBool:
+ v.Bool(a.bool())
+ case KindFloat64:
+ v.Float64(a.float())
+ case KindDuration:
+ v.Duration(a.duration())
+ case KindAny:
+ v.Any(a.any)
+ default:
+ panic("bad kind")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/slog/value_test.go b/platform/dbops/binaries/go/go/src/log/slog/value_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..923a4e0cccfb430b1ff03cb911c76be210120b83
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/slog/value_test.go
@@ -0,0 +1,276 @@
+// 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 slog
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+ "unsafe"
+)
+
+func TestKindString(t *testing.T) {
+ if got, want := KindGroup.String(), "Group"; got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
+func TestValueEqual(t *testing.T) {
+ var x, y int
+ vals := []Value{
+ {},
+ Int64Value(1),
+ Int64Value(2),
+ Float64Value(3.5),
+ Float64Value(3.7),
+ BoolValue(true),
+ BoolValue(false),
+ TimeValue(testTime),
+ AnyValue(&x),
+ AnyValue(&y),
+ GroupValue(Bool("b", true), Int("i", 3)),
+ }
+ for i, v1 := range vals {
+ for j, v2 := range vals {
+ got := v1.Equal(v2)
+ want := i == j
+ if got != want {
+ t.Errorf("%v.Equal(%v): got %t, want %t", v1, v2, got, want)
+ }
+ }
+ }
+}
+
+func panics(f func()) (b bool) {
+ defer func() {
+ if x := recover(); x != nil {
+ b = true
+ }
+ }()
+ f()
+ return false
+}
+
+func TestValueString(t *testing.T) {
+ for _, test := range []struct {
+ v Value
+ want string
+ }{
+ {Int64Value(-3), "-3"},
+ {Uint64Value(1), "1"},
+ {Float64Value(.15), "0.15"},
+ {BoolValue(true), "true"},
+ {StringValue("foo"), "foo"},
+ {TimeValue(testTime), "2000-01-02 03:04:05 +0000 UTC"},
+ {AnyValue(time.Duration(3 * time.Second)), "3s"},
+ {GroupValue(Int("a", 1), Bool("b", true)), "[a=1 b=true]"},
+ } {
+ if got := test.v.String(); got != test.want {
+ t.Errorf("%#v:\ngot %q\nwant %q", test.v, got, test.want)
+ }
+ }
+}
+
+func TestValueNoAlloc(t *testing.T) {
+ // Assign values just to make sure the compiler doesn't optimize away the statements.
+ var (
+ i int64
+ u uint64
+ f float64
+ b bool
+ s string
+ x any
+ p = &i
+ d time.Duration
+ tm time.Time
+ )
+ a := int(testing.AllocsPerRun(5, func() {
+ i = Int64Value(1).Int64()
+ u = Uint64Value(1).Uint64()
+ f = Float64Value(1).Float64()
+ b = BoolValue(true).Bool()
+ s = StringValue("foo").String()
+ d = DurationValue(d).Duration()
+ tm = TimeValue(testTime).Time()
+ x = AnyValue(p).Any()
+ }))
+ if a != 0 {
+ t.Errorf("got %d allocs, want zero", a)
+ }
+ _ = u
+ _ = f
+ _ = b
+ _ = s
+ _ = x
+ _ = tm
+}
+
+func TestAnyLevelAlloc(t *testing.T) {
+ // Because typical Levels are small integers,
+ // they are zero-alloc.
+ var a Value
+ x := LevelDebug + 100
+ wantAllocs(t, 0, func() { a = AnyValue(x) })
+ _ = a
+}
+
+func TestAnyValue(t *testing.T) {
+ for _, test := range []struct {
+ in any
+ want Value
+ }{
+ {1, IntValue(1)},
+ {1.5, Float64Value(1.5)},
+ {float32(2.5), Float64Value(2.5)},
+ {"s", StringValue("s")},
+ {true, BoolValue(true)},
+ {testTime, TimeValue(testTime)},
+ {time.Hour, DurationValue(time.Hour)},
+ {[]Attr{Int("i", 3)}, GroupValue(Int("i", 3))},
+ {IntValue(4), IntValue(4)},
+ {uint(2), Uint64Value(2)},
+ {uint8(3), Uint64Value(3)},
+ {uint16(4), Uint64Value(4)},
+ {uint32(5), Uint64Value(5)},
+ {uint64(6), Uint64Value(6)},
+ {uintptr(7), Uint64Value(7)},
+ {int8(8), Int64Value(8)},
+ {int16(9), Int64Value(9)},
+ {int32(10), Int64Value(10)},
+ {int64(11), Int64Value(11)},
+ } {
+ got := AnyValue(test.in)
+ if !got.Equal(test.want) {
+ t.Errorf("%v (%[1]T): got %v (kind %s), want %v (kind %s)",
+ test.in, got, got.Kind(), test.want, test.want.Kind())
+ }
+ }
+}
+
+func TestValueAny(t *testing.T) {
+ for _, want := range []any{
+ nil,
+ LevelDebug + 100,
+ time.UTC, // time.Locations treated specially...
+ KindBool, // ...as are Kinds
+ []Attr{Int("a", 1)},
+ int64(2),
+ uint64(3),
+ true,
+ time.Minute,
+ time.Time{},
+ 3.14,
+ } {
+ v := AnyValue(want)
+ got := v.Any()
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+ }
+}
+
+func TestLogValue(t *testing.T) {
+ want := "replaced"
+ r := &replace{StringValue(want)}
+ v := AnyValue(r)
+ if g, w := v.Kind(), KindLogValuer; g != w {
+ t.Errorf("got %s, want %s", g, w)
+ }
+ got := v.LogValuer().LogValue().Any()
+ if got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+
+ // Test Resolve.
+ got = v.Resolve().Any()
+ if got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+
+ // Test Resolve max iteration.
+ r.v = AnyValue(r) // create a cycle
+ got = AnyValue(r).Resolve().Any()
+ if _, ok := got.(error); !ok {
+ t.Errorf("expected error, got %T", got)
+ }
+
+ // Groups are not recursively resolved.
+ c := Any("c", &replace{StringValue("d")})
+ v = AnyValue(&replace{GroupValue(Int("a", 1), Group("b", c))})
+ got2 := v.Resolve().Any().([]Attr)
+ want2 := []Attr{Int("a", 1), Group("b", c)}
+ if !attrsEqual(got2, want2) {
+ t.Errorf("got %v, want %v", got2, want2)
+ }
+
+ // Verify that panics in Resolve are caught and turn into errors.
+ v = AnyValue(panickingLogValue{})
+ got = v.Resolve().Any()
+ gotErr, ok := got.(error)
+ if !ok {
+ t.Errorf("expected error, got %T", got)
+ }
+ // The error should provide some context information.
+ // We'll just check that this function name appears in it.
+ if got, want := gotErr.Error(), "TestLogValue"; !strings.Contains(got, want) {
+ t.Errorf("got %q, want substring %q", got, want)
+ }
+}
+
+func TestZeroTime(t *testing.T) {
+ z := time.Time{}
+ got := TimeValue(z).Time()
+ if !got.IsZero() {
+ t.Errorf("got %s (%#[1]v), not zero time (%#v)", got, z)
+ }
+}
+
+func TestEmptyGroup(t *testing.T) {
+ g := GroupValue(
+ Int("a", 1),
+ Group("g1", Group("g2")),
+ Group("g3", Group("g4", Int("b", 2))))
+ got := g.Group()
+ want := []Attr{Int("a", 1), Group("g3", Group("g4", Int("b", 2)))}
+ if !attrsEqual(got, want) {
+ t.Errorf("\ngot %v\nwant %v", got, want)
+ }
+}
+
+type replace struct {
+ v Value
+}
+
+func (r *replace) LogValue() Value { return r.v }
+
+type panickingLogValue struct{}
+
+func (panickingLogValue) LogValue() Value { panic("bad") }
+
+// A Value with "unsafe" strings is significantly faster:
+// safe: 1785 ns/op, 0 allocs
+// unsafe: 690 ns/op, 0 allocs
+
+// Run this with and without -tags unsafe_kvs to compare.
+func BenchmarkUnsafeStrings(b *testing.B) {
+ b.ReportAllocs()
+ dst := make([]Value, 100)
+ src := make([]Value, len(dst))
+ b.Logf("Value size = %d", unsafe.Sizeof(Value{}))
+ for i := range src {
+ src[i] = StringValue(fmt.Sprintf("string#%d", i))
+ }
+ b.ResetTimer()
+ var d string
+ for i := 0; i < b.N; i++ {
+ copy(dst, src)
+ for _, a := range dst {
+ d = a.String()
+ }
+ }
+ _ = d
+}
diff --git a/platform/dbops/binaries/go/go/src/log/syslog/doc.go b/platform/dbops/binaries/go/go/src/log/syslog/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..9a33eeb5d576453b4b22bd557ee7b2501b3480ba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/syslog/doc.go
@@ -0,0 +1,24 @@
+// 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 syslog provides a simple interface to the system log
+// service. It can send messages to the syslog daemon using UNIX
+// domain sockets, UDP or TCP.
+//
+// Only one call to Dial is necessary. On write failures,
+// the syslog client will attempt to reconnect to the server
+// and write again.
+//
+// The syslog package is frozen and is not accepting new features.
+// Some external packages provide more functionality. See:
+//
+// https://godoc.org/?q=syslog
+package syslog
+
+// BUG(brainman): This package is not implemented on Windows. As the
+// syslog package is frozen, Windows users are encouraged to
+// use a package outside of the standard library. For background,
+// see https://golang.org/issue/1108.
+
+// BUG(akumar): This package is not implemented on Plan 9.
diff --git a/platform/dbops/binaries/go/go/src/log/syslog/example_test.go b/platform/dbops/binaries/go/go/src/log/syslog/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4df29c0af0bfe22643ecf6ab72eb59a3f99079c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/syslog/example_test.go
@@ -0,0 +1,23 @@
+// 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 !windows && !plan9
+
+package syslog_test
+
+import (
+ "fmt"
+ "log"
+ "log/syslog"
+)
+
+func ExampleDial() {
+ sysLog, err := syslog.Dial("tcp", "localhost:1234",
+ syslog.LOG_WARNING|syslog.LOG_DAEMON, "demotag")
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Fprintf(sysLog, "This is a daemon warning with demotag.")
+ sysLog.Emerg("And this is a daemon emergency with demotag.")
+}
diff --git a/platform/dbops/binaries/go/go/src/log/syslog/syslog.go b/platform/dbops/binaries/go/go/src/log/syslog/syslog.go
new file mode 100644
index 0000000000000000000000000000000000000000..362dd950ba29b08b9432e5003dee74d31489dc84
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/syslog/syslog.go
@@ -0,0 +1,318 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !windows && !plan9
+
+package syslog
+
+import (
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "strings"
+ "sync"
+ "time"
+)
+
+// The Priority is a combination of the syslog facility and
+// severity. For example, [LOG_ALERT] | [LOG_FTP] sends an alert severity
+// message from the FTP facility. The default severity is [LOG_EMERG];
+// the default facility is [LOG_KERN].
+type Priority int
+
+const severityMask = 0x07
+const facilityMask = 0xf8
+
+const (
+ // Severity.
+
+ // From /usr/include/sys/syslog.h.
+ // These are the same on Linux, BSD, and OS X.
+ LOG_EMERG Priority = iota
+ LOG_ALERT
+ LOG_CRIT
+ LOG_ERR
+ LOG_WARNING
+ LOG_NOTICE
+ LOG_INFO
+ LOG_DEBUG
+)
+
+const (
+ // Facility.
+
+ // From /usr/include/sys/syslog.h.
+ // These are the same up to LOG_FTP on Linux, BSD, and OS X.
+ LOG_KERN Priority = iota << 3
+ LOG_USER
+ LOG_MAIL
+ LOG_DAEMON
+ LOG_AUTH
+ LOG_SYSLOG
+ LOG_LPR
+ LOG_NEWS
+ LOG_UUCP
+ LOG_CRON
+ LOG_AUTHPRIV
+ LOG_FTP
+ _ // unused
+ _ // unused
+ _ // unused
+ _ // unused
+ LOG_LOCAL0
+ LOG_LOCAL1
+ LOG_LOCAL2
+ LOG_LOCAL3
+ LOG_LOCAL4
+ LOG_LOCAL5
+ LOG_LOCAL6
+ LOG_LOCAL7
+)
+
+// A Writer is a connection to a syslog server.
+type Writer struct {
+ priority Priority
+ tag string
+ hostname string
+ network string
+ raddr string
+
+ mu sync.Mutex // guards conn
+ conn serverConn
+}
+
+// This interface and the separate syslog_unix.go file exist for
+// Solaris support as implemented by gccgo. On Solaris you cannot
+// simply open a TCP connection to the syslog daemon. The gccgo
+// sources have a syslog_solaris.go file that implements unixSyslog to
+// return a type that satisfies this interface and simply calls the C
+// library syslog function.
+type serverConn interface {
+ writeString(p Priority, hostname, tag, s, nl string) error
+ close() error
+}
+
+type netConn struct {
+ local bool
+ conn net.Conn
+}
+
+// New establishes a new connection to the system log daemon. Each
+// write to the returned writer sends a log message with the given
+// priority (a combination of the syslog facility and severity) and
+// prefix tag. If tag is empty, the [os.Args][0] is used.
+func New(priority Priority, tag string) (*Writer, error) {
+ return Dial("", "", priority, tag)
+}
+
+// Dial establishes a connection to a log daemon by connecting to
+// address raddr on the specified network. Each write to the returned
+// writer sends a log message with the facility and severity
+// (from priority) and tag. If tag is empty, the [os.Args][0] is used.
+// If network is empty, Dial will connect to the local syslog server.
+// Otherwise, see the documentation for net.Dial for valid values
+// of network and raddr.
+func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) {
+ if priority < 0 || priority > LOG_LOCAL7|LOG_DEBUG {
+ return nil, errors.New("log/syslog: invalid priority")
+ }
+
+ if tag == "" {
+ tag = os.Args[0]
+ }
+ hostname, _ := os.Hostname()
+
+ w := &Writer{
+ priority: priority,
+ tag: tag,
+ hostname: hostname,
+ network: network,
+ raddr: raddr,
+ }
+
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ err := w.connect()
+ if err != nil {
+ return nil, err
+ }
+ return w, err
+}
+
+// connect makes a connection to the syslog server.
+// It must be called with w.mu held.
+func (w *Writer) connect() (err error) {
+ if w.conn != nil {
+ // ignore err from close, it makes sense to continue anyway
+ w.conn.close()
+ w.conn = nil
+ }
+
+ if w.network == "" {
+ w.conn, err = unixSyslog()
+ if w.hostname == "" {
+ w.hostname = "localhost"
+ }
+ } else {
+ var c net.Conn
+ c, err = net.Dial(w.network, w.raddr)
+ if err == nil {
+ w.conn = &netConn{
+ conn: c,
+ local: w.network == "unixgram" || w.network == "unix",
+ }
+ if w.hostname == "" {
+ w.hostname = c.LocalAddr().String()
+ }
+ }
+ }
+ return
+}
+
+// Write sends a log message to the syslog daemon.
+func (w *Writer) Write(b []byte) (int, error) {
+ return w.writeAndRetry(w.priority, string(b))
+}
+
+// Close closes a connection to the syslog daemon.
+func (w *Writer) Close() error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ if w.conn != nil {
+ err := w.conn.close()
+ w.conn = nil
+ return err
+ }
+ return nil
+}
+
+// Emerg logs a message with severity [LOG_EMERG], ignoring the severity
+// passed to New.
+func (w *Writer) Emerg(m string) error {
+ _, err := w.writeAndRetry(LOG_EMERG, m)
+ return err
+}
+
+// Alert logs a message with severity [LOG_ALERT], ignoring the severity
+// passed to New.
+func (w *Writer) Alert(m string) error {
+ _, err := w.writeAndRetry(LOG_ALERT, m)
+ return err
+}
+
+// Crit logs a message with severity [LOG_CRIT], ignoring the severity
+// passed to New.
+func (w *Writer) Crit(m string) error {
+ _, err := w.writeAndRetry(LOG_CRIT, m)
+ return err
+}
+
+// Err logs a message with severity [LOG_ERR], ignoring the severity
+// passed to New.
+func (w *Writer) Err(m string) error {
+ _, err := w.writeAndRetry(LOG_ERR, m)
+ return err
+}
+
+// Warning logs a message with severity [LOG_WARNING], ignoring the
+// severity passed to New.
+func (w *Writer) Warning(m string) error {
+ _, err := w.writeAndRetry(LOG_WARNING, m)
+ return err
+}
+
+// Notice logs a message with severity [LOG_NOTICE], ignoring the
+// severity passed to New.
+func (w *Writer) Notice(m string) error {
+ _, err := w.writeAndRetry(LOG_NOTICE, m)
+ return err
+}
+
+// Info logs a message with severity [LOG_INFO], ignoring the severity
+// passed to New.
+func (w *Writer) Info(m string) error {
+ _, err := w.writeAndRetry(LOG_INFO, m)
+ return err
+}
+
+// Debug logs a message with severity [LOG_DEBUG], ignoring the severity
+// passed to New.
+func (w *Writer) Debug(m string) error {
+ _, err := w.writeAndRetry(LOG_DEBUG, m)
+ return err
+}
+
+func (w *Writer) writeAndRetry(p Priority, s string) (int, error) {
+ pr := (w.priority & facilityMask) | (p & severityMask)
+
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ if w.conn != nil {
+ if n, err := w.write(pr, s); err == nil {
+ return n, nil
+ }
+ }
+ if err := w.connect(); err != nil {
+ return 0, err
+ }
+ return w.write(pr, s)
+}
+
+// write generates and writes a syslog formatted string. The
+// format is as follows: TIMESTAMP HOSTNAME TAG[PID]: MSG
+func (w *Writer) write(p Priority, msg string) (int, error) {
+ // ensure it ends in a \n
+ nl := ""
+ if !strings.HasSuffix(msg, "\n") {
+ nl = "\n"
+ }
+
+ err := w.conn.writeString(p, w.hostname, w.tag, msg, nl)
+ if err != nil {
+ return 0, err
+ }
+ // Note: return the length of the input, not the number of
+ // bytes printed by Fprintf, because this must behave like
+ // an io.Writer.
+ return len(msg), nil
+}
+
+func (n *netConn) writeString(p Priority, hostname, tag, msg, nl string) error {
+ if n.local {
+ // Compared to the network form below, the changes are:
+ // 1. Use time.Stamp instead of time.RFC3339.
+ // 2. Drop the hostname field from the Fprintf.
+ timestamp := time.Now().Format(time.Stamp)
+ _, err := fmt.Fprintf(n.conn, "<%d>%s %s[%d]: %s%s",
+ p, timestamp,
+ tag, os.Getpid(), msg, nl)
+ return err
+ }
+ timestamp := time.Now().Format(time.RFC3339)
+ _, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s%s",
+ p, timestamp, hostname,
+ tag, os.Getpid(), msg, nl)
+ return err
+}
+
+func (n *netConn) close() error {
+ return n.conn.Close()
+}
+
+// NewLogger creates a [log.Logger] whose output is written to the
+// system log service with the specified priority, a combination of
+// the syslog facility and severity. The logFlag argument is the flag
+// set passed through to [log.New] to create the Logger.
+func NewLogger(p Priority, logFlag int) (*log.Logger, error) {
+ s, err := New(p, "")
+ if err != nil {
+ return nil, err
+ }
+ return log.New(s, "", logFlag), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/log/syslog/syslog_test.go b/platform/dbops/binaries/go/go/src/log/syslog/syslog_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cec225f75131f2cd0fe1e3fee1f783231eb95097
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/syslog/syslog_test.go
@@ -0,0 +1,432 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !windows && !plan9 && !js && !wasip1
+
+package syslog
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+)
+
+func runPktSyslog(c net.PacketConn, done chan<- string) {
+ var buf [4096]byte
+ var rcvd string
+ ct := 0
+ for {
+ var n int
+ var err error
+
+ c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
+ n, _, err = c.ReadFrom(buf[:])
+ rcvd += string(buf[:n])
+ if err != nil {
+ if oe, ok := err.(*net.OpError); ok {
+ if ct < 3 && oe.Temporary() {
+ ct++
+ continue
+ }
+ }
+ break
+ }
+ }
+ c.Close()
+ done <- rcvd
+}
+
+var crashy = false
+
+func testableNetwork(network string) bool {
+ switch network {
+ case "unix", "unixgram":
+ switch runtime.GOOS {
+ case "ios", "android":
+ return false
+ }
+ }
+ return true
+}
+
+func runStreamSyslog(l net.Listener, done chan<- string, wg *sync.WaitGroup) {
+ for {
+ var c net.Conn
+ var err error
+ if c, err = l.Accept(); err != nil {
+ return
+ }
+ wg.Add(1)
+ go func(c net.Conn) {
+ defer wg.Done()
+ c.SetReadDeadline(time.Now().Add(5 * time.Second))
+ b := bufio.NewReader(c)
+ for ct := 1; !crashy || ct&7 != 0; ct++ {
+ s, err := b.ReadString('\n')
+ if err != nil {
+ break
+ }
+ done <- s
+ }
+ c.Close()
+ }(c)
+ }
+}
+
+func startServer(t *testing.T, n, la string, done chan<- string) (addr string, sock io.Closer, wg *sync.WaitGroup) {
+ if n == "udp" || n == "tcp" {
+ la = "127.0.0.1:0"
+ } else {
+ // unix and unixgram: choose an address if none given.
+ if la == "" {
+ // The address must be short to fit in the sun_path field of the
+ // sockaddr_un passed to the underlying system calls, so we use
+ // os.MkdirTemp instead of t.TempDir: t.TempDir generally includes all or
+ // part of the test name in the directory, which can be much more verbose
+ // and risks running up against the limit.
+ dir, err := os.MkdirTemp("", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(dir); err != nil {
+ t.Errorf("failed to remove socket temp directory: %v", err)
+ }
+ })
+ la = filepath.Join(dir, "sock")
+ }
+ }
+
+ wg = new(sync.WaitGroup)
+ if n == "udp" || n == "unixgram" {
+ l, e := net.ListenPacket(n, la)
+ if e != nil {
+ t.Helper()
+ t.Fatalf("startServer failed: %v", e)
+ }
+ addr = l.LocalAddr().String()
+ sock = l
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ runPktSyslog(l, done)
+ }()
+ } else {
+ l, e := net.Listen(n, la)
+ if e != nil {
+ t.Helper()
+ t.Fatalf("startServer failed: %v", e)
+ }
+ addr = l.Addr().String()
+ sock = l
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ runStreamSyslog(l, done, wg)
+ }()
+ }
+ return
+}
+
+func TestWithSimulated(t *testing.T) {
+ t.Parallel()
+
+ msg := "Test 123"
+ for _, tr := range []string{"unix", "unixgram", "udp", "tcp"} {
+ if !testableNetwork(tr) {
+ continue
+ }
+
+ tr := tr
+ t.Run(tr, func(t *testing.T) {
+ t.Parallel()
+
+ done := make(chan string)
+ addr, sock, srvWG := startServer(t, tr, "", done)
+ defer srvWG.Wait()
+ defer sock.Close()
+ if tr == "unix" || tr == "unixgram" {
+ defer os.Remove(addr)
+ }
+ s, err := Dial(tr, addr, LOG_INFO|LOG_USER, "syslog_test")
+ if err != nil {
+ t.Fatalf("Dial() failed: %v", err)
+ }
+ err = s.Info(msg)
+ if err != nil {
+ t.Fatalf("log failed: %v", err)
+ }
+ check(t, msg, <-done, tr)
+ s.Close()
+ })
+ }
+}
+
+func TestFlap(t *testing.T) {
+ net := "unix"
+ if !testableNetwork(net) {
+ t.Skipf("skipping on %s/%s; 'unix' is not supported", runtime.GOOS, runtime.GOARCH)
+ }
+
+ done := make(chan string)
+ addr, sock, srvWG := startServer(t, net, "", done)
+ defer srvWG.Wait()
+ defer os.Remove(addr)
+ defer sock.Close()
+
+ s, err := Dial(net, addr, LOG_INFO|LOG_USER, "syslog_test")
+ if err != nil {
+ t.Fatalf("Dial() failed: %v", err)
+ }
+ msg := "Moo 2"
+ err = s.Info(msg)
+ if err != nil {
+ t.Fatalf("log failed: %v", err)
+ }
+ check(t, msg, <-done, net)
+
+ // restart the server
+ if err := os.Remove(addr); err != nil {
+ t.Fatal(err)
+ }
+ _, sock2, srvWG2 := startServer(t, net, addr, done)
+ defer srvWG2.Wait()
+ defer sock2.Close()
+
+ // and try retransmitting
+ msg = "Moo 3"
+ err = s.Info(msg)
+ if err != nil {
+ t.Fatalf("log failed: %v", err)
+ }
+ check(t, msg, <-done, net)
+
+ s.Close()
+}
+
+func TestNew(t *testing.T) {
+ if LOG_LOCAL7 != 23<<3 {
+ t.Fatalf("LOG_LOCAL7 has wrong value")
+ }
+ if testing.Short() {
+ // Depends on syslog daemon running, and sometimes it's not.
+ t.Skip("skipping syslog test during -short")
+ }
+
+ s, err := New(LOG_INFO|LOG_USER, "the_tag")
+ if err != nil {
+ if err.Error() == "Unix syslog delivery error" {
+ t.Skip("skipping: syslogd not running")
+ }
+ t.Fatalf("New() failed: %s", err)
+ }
+ // Don't send any messages.
+ s.Close()
+}
+
+func TestNewLogger(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping syslog test during -short")
+ }
+ f, err := NewLogger(LOG_USER|LOG_INFO, 0)
+ if f == nil {
+ if err.Error() == "Unix syslog delivery error" {
+ t.Skip("skipping: syslogd not running")
+ }
+ t.Error(err)
+ }
+}
+
+func TestDial(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping syslog test during -short")
+ }
+ f, err := Dial("", "", (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test")
+ if f != nil {
+ t.Fatalf("Should have trapped bad priority")
+ }
+ f, err = Dial("", "", -1, "syslog_test")
+ if f != nil {
+ t.Fatalf("Should have trapped bad priority")
+ }
+ l, err := Dial("", "", LOG_USER|LOG_ERR, "syslog_test")
+ if err != nil {
+ if err.Error() == "Unix syslog delivery error" {
+ t.Skip("skipping: syslogd not running")
+ }
+ t.Fatalf("Dial() failed: %s", err)
+ }
+ l.Close()
+}
+
+func check(t *testing.T, in, out, transport string) {
+ hostname, err := os.Hostname()
+ if err != nil {
+ t.Errorf("Error retrieving hostname: %v", err)
+ return
+ }
+
+ if transport == "unixgram" || transport == "unix" {
+ var month, date, ts string
+ var pid int
+ tmpl := fmt.Sprintf("<%d>%%s %%s %%s syslog_test[%%d]: %s\n", LOG_USER+LOG_INFO, in)
+ n, err := fmt.Sscanf(out, tmpl, &month, &date, &ts, &pid)
+ if n != 4 || err != nil {
+ t.Errorf("Got %q, does not match template %q (%d %s)", out, tmpl, n, err)
+ }
+ return
+ }
+
+ // Non-UNIX domain transports.
+ var parsedHostname, timestamp string
+ var pid int
+ tmpl := fmt.Sprintf("<%d>%%s %%s syslog_test[%%d]: %s\n", LOG_USER+LOG_INFO, in)
+ n, err := fmt.Sscanf(out, tmpl, ×tamp, &parsedHostname, &pid)
+ if n != 3 || err != nil {
+ t.Errorf("Got %q, does not match template %q (%d %s)", out, tmpl, n, err)
+ }
+ if hostname != parsedHostname {
+ t.Errorf("Hostname got %q want %q in %q", parsedHostname, hostname, out)
+ }
+}
+
+func TestWrite(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ pri Priority
+ pre string
+ msg string
+ exp string
+ }{
+ {LOG_USER | LOG_ERR, "syslog_test", "", "%s %s syslog_test[%d]: \n"},
+ {LOG_USER | LOG_ERR, "syslog_test", "write test", "%s %s syslog_test[%d]: write test\n"},
+ // Write should not add \n if there already is one
+ {LOG_USER | LOG_ERR, "syslog_test", "write test 2\n", "%s %s syslog_test[%d]: write test 2\n"},
+ }
+
+ if hostname, err := os.Hostname(); err != nil {
+ t.Fatalf("Error retrieving hostname")
+ } else {
+ for _, test := range tests {
+ done := make(chan string)
+ addr, sock, srvWG := startServer(t, "udp", "", done)
+ defer srvWG.Wait()
+ defer sock.Close()
+ l, err := Dial("udp", addr, test.pri, test.pre)
+ if err != nil {
+ t.Fatalf("syslog.Dial() failed: %v", err)
+ }
+ defer l.Close()
+ _, err = io.WriteString(l, test.msg)
+ if err != nil {
+ t.Fatalf("WriteString() failed: %v", err)
+ }
+ rcvd := <-done
+ test.exp = fmt.Sprintf("<%d>", test.pri) + test.exp
+ var parsedHostname, timestamp string
+ var pid int
+ if n, err := fmt.Sscanf(rcvd, test.exp, ×tamp, &parsedHostname, &pid); n != 3 || err != nil || hostname != parsedHostname {
+ t.Errorf("s.Info() = '%q', didn't match '%q' (%d %s)", rcvd, test.exp, n, err)
+ }
+ }
+ }
+}
+
+func TestConcurrentWrite(t *testing.T) {
+ addr, sock, srvWG := startServer(t, "udp", "", make(chan string, 1))
+ defer srvWG.Wait()
+ defer sock.Close()
+ w, err := Dial("udp", addr, LOG_USER|LOG_ERR, "how's it going?")
+ if err != nil {
+ t.Fatalf("syslog.Dial() failed: %v", err)
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < 10; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ err := w.Info("test")
+ if err != nil {
+ t.Errorf("Info() failed: %v", err)
+ return
+ }
+ }()
+ }
+ wg.Wait()
+}
+
+func TestConcurrentReconnect(t *testing.T) {
+ crashy = true
+ defer func() { crashy = false }()
+
+ const N = 10
+ const M = 100
+ net := "unix"
+ if !testableNetwork(net) {
+ net = "tcp"
+ if !testableNetwork(net) {
+ t.Skipf("skipping on %s/%s; neither 'unix' or 'tcp' is supported", runtime.GOOS, runtime.GOARCH)
+ }
+ }
+ done := make(chan string, N*M)
+ addr, sock, srvWG := startServer(t, net, "", done)
+ if net == "unix" {
+ defer os.Remove(addr)
+ }
+
+ // count all the messages arriving
+ count := make(chan int, 1)
+ go func() {
+ ct := 0
+ for range done {
+ ct++
+ // we are looking for 500 out of 1000 events
+ // here because lots of log messages are lost
+ // in buffers (kernel and/or bufio)
+ if ct > N*M/2 {
+ break
+ }
+ }
+ count <- ct
+ }()
+
+ var wg sync.WaitGroup
+ wg.Add(N)
+ for i := 0; i < N; i++ {
+ go func() {
+ defer wg.Done()
+ w, err := Dial(net, addr, LOG_USER|LOG_ERR, "tag")
+ if err != nil {
+ t.Errorf("syslog.Dial() failed: %v", err)
+ return
+ }
+ defer w.Close()
+ for i := 0; i < M; i++ {
+ err := w.Info("test")
+ if err != nil {
+ t.Errorf("Info() failed: %v", err)
+ return
+ }
+ }
+ }()
+ }
+ wg.Wait()
+ sock.Close()
+ srvWG.Wait()
+ close(done)
+
+ select {
+ case <-count:
+ case <-time.After(100 * time.Millisecond):
+ t.Error("timeout in concurrent reconnect")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/syslog/syslog_unix.go b/platform/dbops/binaries/go/go/src/log/syslog/syslog_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f9cdcdc273493d6834776fcd2330d472721ea6f6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/syslog/syslog_unix.go
@@ -0,0 +1,29 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !windows && !plan9
+
+package syslog
+
+import (
+ "errors"
+ "net"
+)
+
+// unixSyslog opens a connection to the syslog daemon running on the
+// local machine using a Unix domain socket.
+
+func unixSyslog() (conn serverConn, err error) {
+ logTypes := []string{"unixgram", "unix"}
+ logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
+ for _, network := range logTypes {
+ for _, path := range logPaths {
+ conn, err := net.Dial(network, path)
+ if err == nil {
+ return &netConn{conn: conn, local: true}, nil
+ }
+ }
+ }
+ return nil, errors.New("Unix syslog delivery error")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/accuracy_string.go b/platform/dbops/binaries/go/go/src/math/big/accuracy_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..aae923829df220894c61df64aa51723c2b369440
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/accuracy_string.go
@@ -0,0 +1,26 @@
+// Code generated by "stringer -type=Accuracy"; DO NOT EDIT.
+
+package big
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[Below - -1]
+ _ = x[Exact-0]
+ _ = x[Above-1]
+}
+
+const _Accuracy_name = "BelowExactAbove"
+
+var _Accuracy_index = [...]uint8{0, 5, 10, 15}
+
+func (i Accuracy) String() string {
+ i -= -1
+ if i < 0 || i >= Accuracy(len(_Accuracy_index)-1) {
+ return "Accuracy(" + strconv.FormatInt(int64(i+-1), 10) + ")"
+ }
+ return _Accuracy_name[_Accuracy_index[i]:_Accuracy_index[i+1]]
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/alias_test.go b/platform/dbops/binaries/go/go/src/math/big/alias_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..36c37fb0656e1d5aca0306c01e39490e71f57ed4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/alias_test.go
@@ -0,0 +1,312 @@
+// 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 big_test
+
+import (
+ cryptorand "crypto/rand"
+ "math/big"
+ "math/rand"
+ "reflect"
+ "testing"
+ "testing/quick"
+)
+
+func equal(z, x *big.Int) bool {
+ return z.Cmp(x) == 0
+}
+
+type bigInt struct {
+ *big.Int
+}
+
+func generatePositiveInt(rand *rand.Rand, size int) *big.Int {
+ n := big.NewInt(1)
+ n.Lsh(n, uint(rand.Intn(size*8)))
+ n.Rand(rand, n)
+ return n
+}
+
+func (bigInt) Generate(rand *rand.Rand, size int) reflect.Value {
+ n := generatePositiveInt(rand, size)
+ if rand.Intn(4) == 0 {
+ n.Neg(n)
+ }
+ return reflect.ValueOf(bigInt{n})
+}
+
+type notZeroInt struct {
+ *big.Int
+}
+
+func (notZeroInt) Generate(rand *rand.Rand, size int) reflect.Value {
+ n := generatePositiveInt(rand, size)
+ if rand.Intn(4) == 0 {
+ n.Neg(n)
+ }
+ if n.Sign() == 0 {
+ n.SetInt64(1)
+ }
+ return reflect.ValueOf(notZeroInt{n})
+}
+
+type positiveInt struct {
+ *big.Int
+}
+
+func (positiveInt) Generate(rand *rand.Rand, size int) reflect.Value {
+ n := generatePositiveInt(rand, size)
+ return reflect.ValueOf(positiveInt{n})
+}
+
+type prime struct {
+ *big.Int
+}
+
+func (prime) Generate(r *rand.Rand, size int) reflect.Value {
+ n, err := cryptorand.Prime(r, r.Intn(size*8-2)+2)
+ if err != nil {
+ panic(err)
+ }
+ return reflect.ValueOf(prime{n})
+}
+
+type zeroOrOne struct {
+ uint
+}
+
+func (zeroOrOne) Generate(rand *rand.Rand, size int) reflect.Value {
+ return reflect.ValueOf(zeroOrOne{uint(rand.Intn(2))})
+}
+
+type smallUint struct {
+ uint
+}
+
+func (smallUint) Generate(rand *rand.Rand, size int) reflect.Value {
+ return reflect.ValueOf(smallUint{uint(rand.Intn(1024))})
+}
+
+// checkAliasingOneArg checks if f returns a correct result when v and x alias.
+//
+// f is a function that takes x as an argument, doesn't modify it, sets v to the
+// result, and returns v. It is the function signature of unbound methods like
+//
+// func (v *big.Int) m(x *big.Int) *big.Int
+//
+// v and x are two random Int values. v is randomized even if it will be
+// overwritten to test for improper buffer reuse.
+func checkAliasingOneArg(t *testing.T, f func(v, x *big.Int) *big.Int, v, x *big.Int) bool {
+ x1, v1 := new(big.Int).Set(x), new(big.Int).Set(x)
+
+ // Calculate a reference f(x) without aliasing.
+ if out := f(v, x); out != v {
+ return false
+ }
+
+ // Test aliasing the argument and the receiver.
+ if out := f(v1, v1); out != v1 || !equal(v1, v) {
+ t.Logf("f(v, x) != f(x, x)")
+ return false
+ }
+
+ // Ensure the arguments was not modified.
+ return equal(x, x1)
+}
+
+// checkAliasingTwoArgs checks if f returns a correct result when any
+// combination of v, x and y alias.
+//
+// f is a function that takes x and y as arguments, doesn't modify them, sets v
+// to the result, and returns v. It is the function signature of unbound methods
+// like
+//
+// func (v *big.Int) m(x, y *big.Int) *big.Int
+//
+// v, x and y are random Int values. v is randomized even if it will be
+// overwritten to test for improper buffer reuse.
+func checkAliasingTwoArgs(t *testing.T, f func(v, x, y *big.Int) *big.Int, v, x, y *big.Int) bool {
+ x1, y1, v1 := new(big.Int).Set(x), new(big.Int).Set(y), new(big.Int).Set(v)
+
+ // Calculate a reference f(x, y) without aliasing.
+ if out := f(v, x, y); out == nil {
+ // Certain functions like ModInverse return nil for certain inputs.
+ // Check that receiver and arguments were unchanged and move on.
+ return equal(x, x1) && equal(y, y1) && equal(v, v1)
+ } else if out != v {
+ return false
+ }
+
+ // Test aliasing the first argument and the receiver.
+ v1.Set(x)
+ if out := f(v1, v1, y); out != v1 || !equal(v1, v) {
+ t.Logf("f(v, x, y) != f(x, x, y)")
+ return false
+ }
+ // Test aliasing the second argument and the receiver.
+ v1.Set(y)
+ if out := f(v1, x, v1); out != v1 || !equal(v1, v) {
+ t.Logf("f(v, x, y) != f(y, x, y)")
+ return false
+ }
+
+ // Calculate a reference f(y, y) without aliasing.
+ // We use y because it's the one that commonly has restrictions
+ // like being prime or non-zero.
+ v1.Set(v)
+ y2 := new(big.Int).Set(y)
+ if out := f(v, y, y2); out == nil {
+ return equal(y, y1) && equal(y2, y1) && equal(v, v1)
+ } else if out != v {
+ return false
+ }
+
+ // Test aliasing the two arguments.
+ if out := f(v1, y, y); out != v1 || !equal(v1, v) {
+ t.Logf("f(v, y1, y2) != f(v, y, y)")
+ return false
+ }
+ // Test aliasing the two arguments and the receiver.
+ v1.Set(y)
+ if out := f(v1, v1, v1); out != v1 || !equal(v1, v) {
+ t.Logf("f(v, y1, y2) != f(y, y, y)")
+ return false
+ }
+
+ // Ensure the arguments were not modified.
+ return equal(x, x1) && equal(y, y1)
+}
+
+func TestAliasing(t *testing.T) {
+ for name, f := range map[string]interface{}{
+ "Abs": func(v, x bigInt) bool {
+ return checkAliasingOneArg(t, (*big.Int).Abs, v.Int, x.Int)
+ },
+ "Add": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Add, v.Int, x.Int, y.Int)
+ },
+ "And": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).And, v.Int, x.Int, y.Int)
+ },
+ "AndNot": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).AndNot, v.Int, x.Int, y.Int)
+ },
+ "Div": func(v, x bigInt, y notZeroInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Div, v.Int, x.Int, y.Int)
+ },
+ "Exp-XY": func(v, x, y bigInt, z notZeroInt) bool {
+ return checkAliasingTwoArgs(t, func(v, x, y *big.Int) *big.Int {
+ return v.Exp(x, y, z.Int)
+ }, v.Int, x.Int, y.Int)
+ },
+ "Exp-XZ": func(v, x, y bigInt, z notZeroInt) bool {
+ return checkAliasingTwoArgs(t, func(v, x, z *big.Int) *big.Int {
+ return v.Exp(x, y.Int, z)
+ }, v.Int, x.Int, z.Int)
+ },
+ "Exp-YZ": func(v, x, y bigInt, z notZeroInt) bool {
+ return checkAliasingTwoArgs(t, func(v, y, z *big.Int) *big.Int {
+ return v.Exp(x.Int, y, z)
+ }, v.Int, y.Int, z.Int)
+ },
+ "GCD": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, func(v, x, y *big.Int) *big.Int {
+ return v.GCD(nil, nil, x, y)
+ }, v.Int, x.Int, y.Int)
+ },
+ "GCD-X": func(v, x, y bigInt) bool {
+ a, b := new(big.Int), new(big.Int)
+ return checkAliasingTwoArgs(t, func(v, x, y *big.Int) *big.Int {
+ a.GCD(v, b, x, y)
+ return v
+ }, v.Int, x.Int, y.Int)
+ },
+ "GCD-Y": func(v, x, y bigInt) bool {
+ a, b := new(big.Int), new(big.Int)
+ return checkAliasingTwoArgs(t, func(v, x, y *big.Int) *big.Int {
+ a.GCD(b, v, x, y)
+ return v
+ }, v.Int, x.Int, y.Int)
+ },
+ "Lsh": func(v, x bigInt, n smallUint) bool {
+ return checkAliasingOneArg(t, func(v, x *big.Int) *big.Int {
+ return v.Lsh(x, n.uint)
+ }, v.Int, x.Int)
+ },
+ "Mod": func(v, x bigInt, y notZeroInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Mod, v.Int, x.Int, y.Int)
+ },
+ "ModInverse": func(v, x bigInt, y notZeroInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).ModInverse, v.Int, x.Int, y.Int)
+ },
+ "ModSqrt": func(v, x bigInt, p prime) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).ModSqrt, v.Int, x.Int, p.Int)
+ },
+ "Mul": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Mul, v.Int, x.Int, y.Int)
+ },
+ "Neg": func(v, x bigInt) bool {
+ return checkAliasingOneArg(t, (*big.Int).Neg, v.Int, x.Int)
+ },
+ "Not": func(v, x bigInt) bool {
+ return checkAliasingOneArg(t, (*big.Int).Not, v.Int, x.Int)
+ },
+ "Or": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Or, v.Int, x.Int, y.Int)
+ },
+ "Quo": func(v, x bigInt, y notZeroInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Quo, v.Int, x.Int, y.Int)
+ },
+ "Rand": func(v, x bigInt, seed int64) bool {
+ return checkAliasingOneArg(t, func(v, x *big.Int) *big.Int {
+ rnd := rand.New(rand.NewSource(seed))
+ return v.Rand(rnd, x)
+ }, v.Int, x.Int)
+ },
+ "Rem": func(v, x bigInt, y notZeroInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Rem, v.Int, x.Int, y.Int)
+ },
+ "Rsh": func(v, x bigInt, n smallUint) bool {
+ return checkAliasingOneArg(t, func(v, x *big.Int) *big.Int {
+ return v.Rsh(x, n.uint)
+ }, v.Int, x.Int)
+ },
+ "Set": func(v, x bigInt) bool {
+ return checkAliasingOneArg(t, (*big.Int).Set, v.Int, x.Int)
+ },
+ "SetBit": func(v, x bigInt, i smallUint, b zeroOrOne) bool {
+ return checkAliasingOneArg(t, func(v, x *big.Int) *big.Int {
+ return v.SetBit(x, int(i.uint), b.uint)
+ }, v.Int, x.Int)
+ },
+ "Sqrt": func(v bigInt, x positiveInt) bool {
+ return checkAliasingOneArg(t, (*big.Int).Sqrt, v.Int, x.Int)
+ },
+ "Sub": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Sub, v.Int, x.Int, y.Int)
+ },
+ "Xor": func(v, x, y bigInt) bool {
+ return checkAliasingTwoArgs(t, (*big.Int).Xor, v.Int, x.Int, y.Int)
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ scale := 1.0
+ switch name {
+ case "ModInverse", "GCD-Y", "GCD-X":
+ scale /= 5
+ case "Rand":
+ scale /= 10
+ case "Exp-XZ", "Exp-XY", "Exp-YZ":
+ scale /= 50
+ case "ModSqrt":
+ scale /= 500
+ }
+ if err := quick.Check(f, &quick.Config{
+ MaxCountScale: scale,
+ }); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith.go b/platform/dbops/binaries/go/go/src/math/big/arith.go
new file mode 100644
index 0000000000000000000000000000000000000000..06e63e2574f31db43bc2769c4f719c99539a81db
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith.go
@@ -0,0 +1,277 @@
+// 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.
+
+// This file provides Go implementations of elementary multi-precision
+// arithmetic operations on word vectors. These have the suffix _g.
+// These are needed for platforms without assembly implementations of these routines.
+// This file also contains elementary operations that can be implemented
+// sufficiently efficiently in Go.
+
+package big
+
+import "math/bits"
+
+// A Word represents a single digit of a multi-precision unsigned integer.
+type Word uint
+
+const (
+ _S = _W / 8 // word size in bytes
+
+ _W = bits.UintSize // word size in bits
+ _B = 1 << _W // digit base
+ _M = _B - 1 // digit mask
+)
+
+// Many of the loops in this file are of the form
+// for i := 0; i < len(z) && i < len(x) && i < len(y); i++
+// i < len(z) is the real condition.
+// However, checking i < len(x) && i < len(y) as well is faster than
+// having the compiler do a bounds check in the body of the loop;
+// remarkably it is even faster than hoisting the bounds check
+// out of the loop, by doing something like
+// _, _ = x[len(z)-1], y[len(z)-1]
+// There are other ways to hoist the bounds check out of the loop,
+// but the compiler's BCE isn't powerful enough for them (yet?).
+// See the discussion in CL 164966.
+
+// ----------------------------------------------------------------------------
+// Elementary operations on words
+//
+// These operations are used by the vector operations below.
+
+// z1<<_W + z0 = x*y
+func mulWW(x, y Word) (z1, z0 Word) {
+ hi, lo := bits.Mul(uint(x), uint(y))
+ return Word(hi), Word(lo)
+}
+
+// z1<<_W + z0 = x*y + c
+func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
+ hi, lo := bits.Mul(uint(x), uint(y))
+ var cc uint
+ lo, cc = bits.Add(lo, uint(c), 0)
+ return Word(hi + cc), Word(lo)
+}
+
+// nlz returns the number of leading zeros in x.
+// Wraps bits.LeadingZeros call for convenience.
+func nlz(x Word) uint {
+ return uint(bits.LeadingZeros(uint(x)))
+}
+
+// The resulting carry c is either 0 or 1.
+func addVV_g(z, x, y []Word) (c Word) {
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x) && i < len(y); i++ {
+ zi, cc := bits.Add(uint(x[i]), uint(y[i]), uint(c))
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+// The resulting carry c is either 0 or 1.
+func subVV_g(z, x, y []Word) (c Word) {
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x) && i < len(y); i++ {
+ zi, cc := bits.Sub(uint(x[i]), uint(y[i]), uint(c))
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+// The resulting carry c is either 0 or 1.
+func addVW_g(z, x []Word, y Word) (c Word) {
+ c = y
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ zi, cc := bits.Add(uint(x[i]), uint(c), 0)
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+// addVWlarge is addVW, but intended for large z.
+// The only difference is that we check on every iteration
+// whether we are done with carries,
+// and if so, switch to a much faster copy instead.
+// This is only a good idea for large z,
+// because the overhead of the check and the function call
+// outweigh the benefits when z is small.
+func addVWlarge(z, x []Word, y Word) (c Word) {
+ c = y
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ if c == 0 {
+ copy(z[i:], x[i:])
+ return
+ }
+ zi, cc := bits.Add(uint(x[i]), uint(c), 0)
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+func subVW_g(z, x []Word, y Word) (c Word) {
+ c = y
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ zi, cc := bits.Sub(uint(x[i]), uint(c), 0)
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+// subVWlarge is to subVW as addVWlarge is to addVW.
+func subVWlarge(z, x []Word, y Word) (c Word) {
+ c = y
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ if c == 0 {
+ copy(z[i:], x[i:])
+ return
+ }
+ zi, cc := bits.Sub(uint(x[i]), uint(c), 0)
+ z[i] = Word(zi)
+ c = Word(cc)
+ }
+ return
+}
+
+func shlVU_g(z, x []Word, s uint) (c Word) {
+ if s == 0 {
+ copy(z, x)
+ return
+ }
+ if len(z) == 0 {
+ return
+ }
+ s &= _W - 1 // hint to the compiler that shifts by s don't need guard code
+ ŝ := _W - s
+ ŝ &= _W - 1 // ditto
+ c = x[len(z)-1] >> ŝ
+ for i := len(z) - 1; i > 0; i-- {
+ z[i] = x[i]<>ŝ
+ }
+ z[0] = x[0] << s
+ return
+}
+
+func shrVU_g(z, x []Word, s uint) (c Word) {
+ if s == 0 {
+ copy(z, x)
+ return
+ }
+ if len(z) == 0 {
+ return
+ }
+ if len(x) != len(z) {
+ // This is an invariant guaranteed by the caller.
+ panic("len(x) != len(z)")
+ }
+ s &= _W - 1 // hint to the compiler that shifts by s don't need guard code
+ ŝ := _W - s
+ ŝ &= _W - 1 // ditto
+ c = x[0] << ŝ
+ for i := 1; i < len(z); i++ {
+ z[i-1] = x[i-1]>>s | x[i]<<ŝ
+ }
+ z[len(z)-1] = x[len(z)-1] >> s
+ return
+}
+
+func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
+ c = r
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ c, z[i] = mulAddWWW_g(x[i], y, c)
+ }
+ return
+}
+
+func addMulVVW_g(z, x []Word, y Word) (c Word) {
+ // The comment near the top of this file discusses this for loop condition.
+ for i := 0; i < len(z) && i < len(x); i++ {
+ z1, z0 := mulAddWWW_g(x[i], y, z[i])
+ lo, cc := bits.Add(uint(z0), uint(c), 0)
+ c, z[i] = Word(cc), Word(lo)
+ c += z1
+ }
+ return
+}
+
+// q = ( x1 << _W + x0 - r)/y. m = floor(( _B^2 - 1 ) / d - _B). Requiring x1>(_W-s)
+ x0 <<= s
+ y <<= s
+ }
+ d := uint(y)
+ // We know that
+ // m = ⎣(B^2-1)/d⎦-B
+ // ⎣(B^2-1)/d⎦ = m+B
+ // (B^2-1)/d = m+B+delta1 0 <= delta1 <= (d-1)/d
+ // B^2/d = m+B+delta2 0 <= delta2 <= 1
+ // The quotient we're trying to compute is
+ // quotient = ⎣(x1*B+x0)/d⎦
+ // = ⎣(x1*B*(B^2/d)+x0*(B^2/d))/B^2⎦
+ // = ⎣(x1*B*(m+B+delta2)+x0*(m+B+delta2))/B^2⎦
+ // = ⎣(x1*m+x1*B+x0)/B + x0*m/B^2 + delta2*(x1*B+x0)/B^2⎦
+ // The latter two terms of this three-term sum are between 0 and 1.
+ // So we can compute just the first term, and we will be low by at most 2.
+ t1, t0 := bits.Mul(uint(m), uint(x1))
+ _, c := bits.Add(t0, uint(x0), 0)
+ t1, _ = bits.Add(t1, uint(x1), c)
+ // The quotient is either t1, t1+1, or t1+2.
+ // We'll try t1 and adjust if needed.
+ qq := t1
+ // compute remainder r=x-d*q.
+ dq1, dq0 := bits.Mul(d, qq)
+ r0, b := bits.Sub(uint(x0), dq0, 0)
+ r1, _ := bits.Sub(uint(x1), dq1, b)
+ // The remainder we just computed is bounded above by B+d:
+ // r = x1*B + x0 - d*q.
+ // = x1*B + x0 - d*⎣(x1*m+x1*B+x0)/B⎦
+ // = x1*B + x0 - d*((x1*m+x1*B+x0)/B-alpha) 0 <= alpha < 1
+ // = x1*B + x0 - x1*d/B*m - x1*d - x0*d/B + d*alpha
+ // = x1*B + x0 - x1*d/B*⎣(B^2-1)/d-B⎦ - x1*d - x0*d/B + d*alpha
+ // = x1*B + x0 - x1*d/B*⎣(B^2-1)/d-B⎦ - x1*d - x0*d/B + d*alpha
+ // = x1*B + x0 - x1*d/B*((B^2-1)/d-B-beta) - x1*d - x0*d/B + d*alpha 0 <= beta < 1
+ // = x1*B + x0 - x1*B + x1/B + x1*d + x1*d/B*beta - x1*d - x0*d/B + d*alpha
+ // = x0 + x1/B + x1*d/B*beta - x0*d/B + d*alpha
+ // = x0*(1-d/B) + x1*(1+d*beta)/B + d*alpha
+ // < B*(1-d/B) + d*B/B + d because x00), x1= d {
+ qq++
+ r0 -= d
+ }
+ return Word(qq), Word(r0 >> s)
+}
+
+// reciprocalWord return the reciprocal of the divisor. rec = floor(( _B^2 - 1 ) / u - _B). u = d1 << nlz(d1).
+func reciprocalWord(d1 Word) Word {
+ u := uint(d1 << nlz(d1))
+ x1 := ^u
+ x0 := uint(_M)
+ rec, _ := bits.Div(x1, x0, u) // (_B^2-1)/U-_B = (_B*(_M-C)+_M)/U
+ return Word(rec)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_386.s b/platform/dbops/binaries/go/go/src/math/big/arith_386.s
new file mode 100644
index 0000000000000000000000000000000000000000..90f6a8c70e1d5381a95408dc9a01b2bcc972ecd3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_386.s
@@ -0,0 +1,235 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !math_big_pure_go
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// func addVV(z, x, y []Word) (c Word)
+TEXT ·addVV(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), CX
+ MOVL z_len+4(FP), BP
+ MOVL $0, BX // i = 0
+ MOVL $0, DX // c = 0
+ JMP E1
+
+L1: MOVL (SI)(BX*4), AX
+ ADDL DX, DX // restore CF
+ ADCL (CX)(BX*4), AX
+ SBBL DX, DX // save CF
+ MOVL AX, (DI)(BX*4)
+ ADDL $1, BX // i++
+
+E1: CMPL BX, BP // i < n
+ JL L1
+
+ NEGL DX
+ MOVL DX, c+36(FP)
+ RET
+
+
+// func subVV(z, x, y []Word) (c Word)
+// (same as addVV except for SBBL instead of ADCL and label names)
+TEXT ·subVV(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), CX
+ MOVL z_len+4(FP), BP
+ MOVL $0, BX // i = 0
+ MOVL $0, DX // c = 0
+ JMP E2
+
+L2: MOVL (SI)(BX*4), AX
+ ADDL DX, DX // restore CF
+ SBBL (CX)(BX*4), AX
+ SBBL DX, DX // save CF
+ MOVL AX, (DI)(BX*4)
+ ADDL $1, BX // i++
+
+E2: CMPL BX, BP // i < n
+ JL L2
+
+ NEGL DX
+ MOVL DX, c+36(FP)
+ RET
+
+
+// func addVW(z, x []Word, y Word) (c Word)
+TEXT ·addVW(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), AX // c = y
+ MOVL z_len+4(FP), BP
+ MOVL $0, BX // i = 0
+ JMP E3
+
+L3: ADDL (SI)(BX*4), AX
+ MOVL AX, (DI)(BX*4)
+ SBBL AX, AX // save CF
+ NEGL AX
+ ADDL $1, BX // i++
+
+E3: CMPL BX, BP // i < n
+ JL L3
+
+ MOVL AX, c+28(FP)
+ RET
+
+
+// func subVW(z, x []Word, y Word) (c Word)
+TEXT ·subVW(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), AX // c = y
+ MOVL z_len+4(FP), BP
+ MOVL $0, BX // i = 0
+ JMP E4
+
+L4: MOVL (SI)(BX*4), DX
+ SUBL AX, DX
+ MOVL DX, (DI)(BX*4)
+ SBBL AX, AX // save CF
+ NEGL AX
+ ADDL $1, BX // i++
+
+E4: CMPL BX, BP // i < n
+ JL L4
+
+ MOVL AX, c+28(FP)
+ RET
+
+
+// func shlVU(z, x []Word, s uint) (c Word)
+TEXT ·shlVU(SB),NOSPLIT,$0
+ MOVL z_len+4(FP), BX // i = z
+ SUBL $1, BX // i--
+ JL X8b // i < 0 (n <= 0)
+
+ // n > 0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL s+24(FP), CX
+ MOVL (SI)(BX*4), AX // w1 = x[n-1]
+ MOVL $0, DX
+ SHLL CX, AX, DX // w1>>ŝ
+ MOVL DX, c+28(FP)
+
+ CMPL BX, $0
+ JLE X8a // i <= 0
+
+ // i > 0
+L8: MOVL AX, DX // w = w1
+ MOVL -4(SI)(BX*4), AX // w1 = x[i-1]
+ SHLL CX, AX, DX // w<>ŝ
+ MOVL DX, (DI)(BX*4) // z[i] = w<>ŝ
+ SUBL $1, BX // i--
+ JG L8 // i > 0
+
+ // i <= 0
+X8a: SHLL CX, AX // w1< 0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL s+24(FP), CX
+ MOVL (SI), AX // w1 = x[0]
+ MOVL $0, DX
+ SHRL CX, AX, DX // w1<<ŝ
+ MOVL DX, c+28(FP)
+
+ MOVL $0, BX // i = 0
+ JMP E9
+
+ // i < n-1
+L9: MOVL AX, DX // w = w1
+ MOVL 4(SI)(BX*4), AX // w1 = x[i+1]
+ SHRL CX, AX, DX // w>>s | w1<<ŝ
+ MOVL DX, (DI)(BX*4) // z[i] = w>>s | w1<<ŝ
+ ADDL $1, BX // i++
+
+E9: CMPL BX, BP
+ JL L9 // i < n-1
+
+ // i >= n-1
+X9a: SHRL CX, AX // w1>>s
+ MOVL AX, (DI)(BP*4) // z[n-1] = w1>>s
+ RET
+
+X9b: MOVL $0, c+28(FP)
+ RET
+
+
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), BP
+ MOVL r+28(FP), CX // c = r
+ MOVL z_len+4(FP), BX
+ LEAL (DI)(BX*4), DI
+ LEAL (SI)(BX*4), SI
+ NEGL BX // i = -n
+ JMP E5
+
+L5: MOVL (SI)(BX*4), AX
+ MULL BP
+ ADDL CX, AX
+ ADCL $0, DX
+ MOVL AX, (DI)(BX*4)
+ MOVL DX, CX
+ ADDL $1, BX // i++
+
+E5: CMPL BX, $0 // i < 0
+ JL L5
+
+ MOVL CX, c+32(FP)
+ RET
+
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ MOVL z+0(FP), DI
+ MOVL x+12(FP), SI
+ MOVL y+24(FP), BP
+ MOVL z_len+4(FP), BX
+ LEAL (DI)(BX*4), DI
+ LEAL (SI)(BX*4), SI
+ NEGL BX // i = -n
+ MOVL $0, CX // c = 0
+ JMP E6
+
+L6: MOVL (SI)(BX*4), AX
+ MULL BP
+ ADDL CX, AX
+ ADCL $0, DX
+ ADDL AX, (DI)(BX*4)
+ ADCL $0, DX
+ MOVL DX, CX
+ ADDL $1, BX // i++
+
+E6: CMPL BX, $0 // i < 0
+ JL L6
+
+ MOVL CX, c+28(FP)
+ RET
+
+
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_amd64.go b/platform/dbops/binaries/go/go/src/math/big/arith_amd64.go
new file mode 100644
index 0000000000000000000000000000000000000000..3db72582bbc0dde5c9b541900e1791b7a3229b86
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_amd64.go
@@ -0,0 +1,11 @@
+// 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 !math_big_pure_go
+
+package big
+
+import "internal/cpu"
+
+var support_adx = cpu.X86.HasADX && cpu.X86.HasBMI2
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_amd64.s b/platform/dbops/binaries/go/go/src/math/big/arith_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..a5b65b1d3c75f6b6f7a532469b3b4c52b78df47c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_amd64.s
@@ -0,0 +1,515 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !math_big_pure_go
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// The carry bit is saved with SBBQ Rx, Rx: if the carry was set, Rx is -1, otherwise it is 0.
+// It is restored with ADDQ Rx, Rx: if Rx was -1 the carry is set, otherwise it is cleared.
+// This is faster than using rotate instructions.
+
+// func addVV(z, x, y []Word) (c Word)
+TEXT ·addVV(SB),NOSPLIT,$0
+ MOVQ z_len+8(FP), DI
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), R9
+ MOVQ z+0(FP), R10
+
+ MOVQ $0, CX // c = 0
+ MOVQ $0, SI // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUBQ $4, DI // n -= 4
+ JL V1 // if n < 0 goto V1
+
+U1: // n >= 0
+ // regular loop body unrolled 4x
+ ADDQ CX, CX // restore CF
+ MOVQ 0(R8)(SI*8), R11
+ MOVQ 8(R8)(SI*8), R12
+ MOVQ 16(R8)(SI*8), R13
+ MOVQ 24(R8)(SI*8), R14
+ ADCQ 0(R9)(SI*8), R11
+ ADCQ 8(R9)(SI*8), R12
+ ADCQ 16(R9)(SI*8), R13
+ ADCQ 24(R9)(SI*8), R14
+ MOVQ R11, 0(R10)(SI*8)
+ MOVQ R12, 8(R10)(SI*8)
+ MOVQ R13, 16(R10)(SI*8)
+ MOVQ R14, 24(R10)(SI*8)
+ SBBQ CX, CX // save CF
+
+ ADDQ $4, SI // i += 4
+ SUBQ $4, DI // n -= 4
+ JGE U1 // if n >= 0 goto U1
+
+V1: ADDQ $4, DI // n += 4
+ JLE E1 // if n <= 0 goto E1
+
+L1: // n > 0
+ ADDQ CX, CX // restore CF
+ MOVQ 0(R8)(SI*8), R11
+ ADCQ 0(R9)(SI*8), R11
+ MOVQ R11, 0(R10)(SI*8)
+ SBBQ CX, CX // save CF
+
+ ADDQ $1, SI // i++
+ SUBQ $1, DI // n--
+ JG L1 // if n > 0 goto L1
+
+E1: NEGQ CX
+ MOVQ CX, c+72(FP) // return c
+ RET
+
+
+// func subVV(z, x, y []Word) (c Word)
+// (same as addVV except for SBBQ instead of ADCQ and label names)
+TEXT ·subVV(SB),NOSPLIT,$0
+ MOVQ z_len+8(FP), DI
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), R9
+ MOVQ z+0(FP), R10
+
+ MOVQ $0, CX // c = 0
+ MOVQ $0, SI // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUBQ $4, DI // n -= 4
+ JL V2 // if n < 0 goto V2
+
+U2: // n >= 0
+ // regular loop body unrolled 4x
+ ADDQ CX, CX // restore CF
+ MOVQ 0(R8)(SI*8), R11
+ MOVQ 8(R8)(SI*8), R12
+ MOVQ 16(R8)(SI*8), R13
+ MOVQ 24(R8)(SI*8), R14
+ SBBQ 0(R9)(SI*8), R11
+ SBBQ 8(R9)(SI*8), R12
+ SBBQ 16(R9)(SI*8), R13
+ SBBQ 24(R9)(SI*8), R14
+ MOVQ R11, 0(R10)(SI*8)
+ MOVQ R12, 8(R10)(SI*8)
+ MOVQ R13, 16(R10)(SI*8)
+ MOVQ R14, 24(R10)(SI*8)
+ SBBQ CX, CX // save CF
+
+ ADDQ $4, SI // i += 4
+ SUBQ $4, DI // n -= 4
+ JGE U2 // if n >= 0 goto U2
+
+V2: ADDQ $4, DI // n += 4
+ JLE E2 // if n <= 0 goto E2
+
+L2: // n > 0
+ ADDQ CX, CX // restore CF
+ MOVQ 0(R8)(SI*8), R11
+ SBBQ 0(R9)(SI*8), R11
+ MOVQ R11, 0(R10)(SI*8)
+ SBBQ CX, CX // save CF
+
+ ADDQ $1, SI // i++
+ SUBQ $1, DI // n--
+ JG L2 // if n > 0 goto L2
+
+E2: NEGQ CX
+ MOVQ CX, c+72(FP) // return c
+ RET
+
+
+// func addVW(z, x []Word, y Word) (c Word)
+TEXT ·addVW(SB),NOSPLIT,$0
+ MOVQ z_len+8(FP), DI
+ CMPQ DI, $32
+ JG large
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), CX // c = y
+ MOVQ z+0(FP), R10
+
+ MOVQ $0, SI // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUBQ $4, DI // n -= 4
+ JL V3 // if n < 4 goto V3
+
+U3: // n >= 0
+ // regular loop body unrolled 4x
+ MOVQ 0(R8)(SI*8), R11
+ MOVQ 8(R8)(SI*8), R12
+ MOVQ 16(R8)(SI*8), R13
+ MOVQ 24(R8)(SI*8), R14
+ ADDQ CX, R11
+ ADCQ $0, R12
+ ADCQ $0, R13
+ ADCQ $0, R14
+ SBBQ CX, CX // save CF
+ NEGQ CX
+ MOVQ R11, 0(R10)(SI*8)
+ MOVQ R12, 8(R10)(SI*8)
+ MOVQ R13, 16(R10)(SI*8)
+ MOVQ R14, 24(R10)(SI*8)
+
+ ADDQ $4, SI // i += 4
+ SUBQ $4, DI // n -= 4
+ JGE U3 // if n >= 0 goto U3
+
+V3: ADDQ $4, DI // n += 4
+ JLE E3 // if n <= 0 goto E3
+
+L3: // n > 0
+ ADDQ 0(R8)(SI*8), CX
+ MOVQ CX, 0(R10)(SI*8)
+ SBBQ CX, CX // save CF
+ NEGQ CX
+
+ ADDQ $1, SI // i++
+ SUBQ $1, DI // n--
+ JG L3 // if n > 0 goto L3
+
+E3: MOVQ CX, c+56(FP) // return c
+ RET
+large:
+ JMP ·addVWlarge(SB)
+
+
+// func subVW(z, x []Word, y Word) (c Word)
+// (same as addVW except for SUBQ/SBBQ instead of ADDQ/ADCQ and label names)
+TEXT ·subVW(SB),NOSPLIT,$0
+ MOVQ z_len+8(FP), DI
+ CMPQ DI, $32
+ JG large
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), CX // c = y
+ MOVQ z+0(FP), R10
+
+ MOVQ $0, SI // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUBQ $4, DI // n -= 4
+ JL V4 // if n < 4 goto V4
+
+U4: // n >= 0
+ // regular loop body unrolled 4x
+ MOVQ 0(R8)(SI*8), R11
+ MOVQ 8(R8)(SI*8), R12
+ MOVQ 16(R8)(SI*8), R13
+ MOVQ 24(R8)(SI*8), R14
+ SUBQ CX, R11
+ SBBQ $0, R12
+ SBBQ $0, R13
+ SBBQ $0, R14
+ SBBQ CX, CX // save CF
+ NEGQ CX
+ MOVQ R11, 0(R10)(SI*8)
+ MOVQ R12, 8(R10)(SI*8)
+ MOVQ R13, 16(R10)(SI*8)
+ MOVQ R14, 24(R10)(SI*8)
+
+ ADDQ $4, SI // i += 4
+ SUBQ $4, DI // n -= 4
+ JGE U4 // if n >= 0 goto U4
+
+V4: ADDQ $4, DI // n += 4
+ JLE E4 // if n <= 0 goto E4
+
+L4: // n > 0
+ MOVQ 0(R8)(SI*8), R11
+ SUBQ CX, R11
+ MOVQ R11, 0(R10)(SI*8)
+ SBBQ CX, CX // save CF
+ NEGQ CX
+
+ ADDQ $1, SI // i++
+ SUBQ $1, DI // n--
+ JG L4 // if n > 0 goto L4
+
+E4: MOVQ CX, c+56(FP) // return c
+ RET
+large:
+ JMP ·subVWlarge(SB)
+
+
+// func shlVU(z, x []Word, s uint) (c Word)
+TEXT ·shlVU(SB),NOSPLIT,$0
+ MOVQ z_len+8(FP), BX // i = z
+ SUBQ $1, BX // i--
+ JL X8b // i < 0 (n <= 0)
+
+ // n > 0
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ MOVQ s+48(FP), CX
+ MOVQ (R8)(BX*8), AX // w1 = x[n-1]
+ MOVQ $0, DX
+ SHLQ CX, AX, DX // w1>>ŝ
+ MOVQ DX, c+56(FP)
+
+ CMPQ BX, $0
+ JLE X8a // i <= 0
+
+ // i > 0
+L8: MOVQ AX, DX // w = w1
+ MOVQ -8(R8)(BX*8), AX // w1 = x[i-1]
+ SHLQ CX, AX, DX // w<>ŝ
+ MOVQ DX, (R10)(BX*8) // z[i] = w<>ŝ
+ SUBQ $1, BX // i--
+ JG L8 // i > 0
+
+ // i <= 0
+X8a: SHLQ CX, AX // w1< 0
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ MOVQ s+48(FP), CX
+ MOVQ (R8), AX // w1 = x[0]
+ MOVQ $0, DX
+ SHRQ CX, AX, DX // w1<<ŝ
+ MOVQ DX, c+56(FP)
+
+ MOVQ $0, BX // i = 0
+ JMP E9
+
+ // i < n-1
+L9: MOVQ AX, DX // w = w1
+ MOVQ 8(R8)(BX*8), AX // w1 = x[i+1]
+ SHRQ CX, AX, DX // w>>s | w1<<ŝ
+ MOVQ DX, (R10)(BX*8) // z[i] = w>>s | w1<<ŝ
+ ADDQ $1, BX // i++
+
+E9: CMPQ BX, R11
+ JL L9 // i < n-1
+
+ // i >= n-1
+X9a: SHRQ CX, AX // w1>>s
+ MOVQ AX, (R10)(R11*8) // z[n-1] = w1>>s
+ RET
+
+X9b: MOVQ $0, c+56(FP)
+ RET
+
+
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), R9
+ MOVQ r+56(FP), CX // c = r
+ MOVQ z_len+8(FP), R11
+ MOVQ $0, BX // i = 0
+
+ CMPQ R11, $4
+ JL E5
+
+U5: // i+4 <= n
+ // regular loop body unrolled 4x
+ MOVQ (0*8)(R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ AX, (0*8)(R10)(BX*8)
+ MOVQ DX, CX
+ MOVQ (1*8)(R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ AX, (1*8)(R10)(BX*8)
+ MOVQ DX, CX
+ MOVQ (2*8)(R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ AX, (2*8)(R10)(BX*8)
+ MOVQ DX, CX
+ MOVQ (3*8)(R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ AX, (3*8)(R10)(BX*8)
+ MOVQ DX, CX
+ ADDQ $4, BX // i += 4
+
+ LEAQ 4(BX), DX
+ CMPQ DX, R11
+ JLE U5
+ JMP E5
+
+L5: MOVQ (R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ AX, (R10)(BX*8)
+ MOVQ DX, CX
+ ADDQ $1, BX // i++
+
+E5: CMPQ BX, R11 // i < n
+ JL L5
+
+ MOVQ CX, c+64(FP)
+ RET
+
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ CMPB ·support_adx(SB), $1
+ JEQ adx
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), R9
+ MOVQ z_len+8(FP), R11
+ MOVQ $0, BX // i = 0
+ MOVQ $0, CX // c = 0
+ MOVQ R11, R12
+ ANDQ $-2, R12
+ CMPQ R11, $2
+ JAE A6
+ JMP E6
+
+A6:
+ MOVQ (R8)(BX*8), AX
+ MULQ R9
+ ADDQ (R10)(BX*8), AX
+ ADCQ $0, DX
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ DX, CX
+ MOVQ AX, (R10)(BX*8)
+
+ MOVQ (8)(R8)(BX*8), AX
+ MULQ R9
+ ADDQ (8)(R10)(BX*8), AX
+ ADCQ $0, DX
+ ADDQ CX, AX
+ ADCQ $0, DX
+ MOVQ DX, CX
+ MOVQ AX, (8)(R10)(BX*8)
+
+ ADDQ $2, BX
+ CMPQ BX, R12
+ JL A6
+ JMP E6
+
+L6: MOVQ (R8)(BX*8), AX
+ MULQ R9
+ ADDQ CX, AX
+ ADCQ $0, DX
+ ADDQ AX, (R10)(BX*8)
+ ADCQ $0, DX
+ MOVQ DX, CX
+ ADDQ $1, BX // i++
+
+E6: CMPQ BX, R11 // i < n
+ JL L6
+
+ MOVQ CX, c+56(FP)
+ RET
+
+adx:
+ MOVQ z_len+8(FP), R11
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ MOVQ y+48(FP), DX
+ MOVQ $0, BX // i = 0
+ MOVQ $0, CX // carry
+ CMPQ R11, $8
+ JAE adx_loop_header
+ CMPQ BX, R11
+ JL adx_short
+ MOVQ CX, c+56(FP)
+ RET
+
+adx_loop_header:
+ MOVQ R11, R13
+ ANDQ $-8, R13
+adx_loop:
+ XORQ R9, R9 // unset flags
+ MULXQ (R8), SI, DI
+ ADCXQ CX,SI
+ ADOXQ (R10), SI
+ MOVQ SI,(R10)
+
+ MULXQ 8(R8), AX, CX
+ ADCXQ DI, AX
+ ADOXQ 8(R10), AX
+ MOVQ AX, 8(R10)
+
+ MULXQ 16(R8), SI, DI
+ ADCXQ CX, SI
+ ADOXQ 16(R10), SI
+ MOVQ SI, 16(R10)
+
+ MULXQ 24(R8), AX, CX
+ ADCXQ DI, AX
+ ADOXQ 24(R10), AX
+ MOVQ AX, 24(R10)
+
+ MULXQ 32(R8), SI, DI
+ ADCXQ CX, SI
+ ADOXQ 32(R10), SI
+ MOVQ SI, 32(R10)
+
+ MULXQ 40(R8), AX, CX
+ ADCXQ DI, AX
+ ADOXQ 40(R10), AX
+ MOVQ AX, 40(R10)
+
+ MULXQ 48(R8), SI, DI
+ ADCXQ CX, SI
+ ADOXQ 48(R10), SI
+ MOVQ SI, 48(R10)
+
+ MULXQ 56(R8), AX, CX
+ ADCXQ DI, AX
+ ADOXQ 56(R10), AX
+ MOVQ AX, 56(R10)
+
+ ADCXQ R9, CX
+ ADOXQ R9, CX
+
+ ADDQ $64, R8
+ ADDQ $64, R10
+ ADDQ $8, BX
+
+ CMPQ BX, R13
+ JL adx_loop
+ MOVQ z+0(FP), R10
+ MOVQ x+24(FP), R8
+ CMPQ BX, R11
+ JL adx_short
+ MOVQ CX, c+56(FP)
+ RET
+
+adx_short:
+ MULXQ (R8)(BX*8), SI, DI
+ ADDQ CX, SI
+ ADCQ $0, DI
+ ADDQ SI, (R10)(BX*8)
+ ADCQ $0, DI
+ MOVQ DI, CX
+ ADDQ $1, BX // i++
+
+ CMPQ BX, R11
+ JL adx_short
+
+ MOVQ CX, c+56(FP)
+ RET
+
+
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_arm.s b/platform/dbops/binaries/go/go/src/math/big/arith_arm.s
new file mode 100644
index 0000000000000000000000000000000000000000..ece3a96f51246b066b165d7b2ed69261642076da
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_arm.s
@@ -0,0 +1,272 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build !math_big_pure_go
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// func addVV(z, x, y []Word) (c Word)
+TEXT ·addVV(SB),NOSPLIT,$0
+ ADD.S $0, R0 // clear carry flag
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R4
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ ADD R4<<2, R1, R4
+ B E1
+L1:
+ MOVW.P 4(R2), R5
+ MOVW.P 4(R3), R6
+ ADC.S R6, R5
+ MOVW.P R5, 4(R1)
+E1:
+ TEQ R1, R4
+ BNE L1
+
+ MOVW $0, R0
+ MOVW.CS $1, R0
+ MOVW R0, c+36(FP)
+ RET
+
+
+// func subVV(z, x, y []Word) (c Word)
+// (same as addVV except for SBC instead of ADC and label names)
+TEXT ·subVV(SB),NOSPLIT,$0
+ SUB.S $0, R0 // clear borrow flag
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R4
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ ADD R4<<2, R1, R4
+ B E2
+L2:
+ MOVW.P 4(R2), R5
+ MOVW.P 4(R3), R6
+ SBC.S R6, R5
+ MOVW.P R5, 4(R1)
+E2:
+ TEQ R1, R4
+ BNE L2
+
+ MOVW $0, R0
+ MOVW.CC $1, R0
+ MOVW R0, c+36(FP)
+ RET
+
+
+// func addVW(z, x []Word, y Word) (c Word)
+TEXT ·addVW(SB),NOSPLIT,$0
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R4
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ ADD R4<<2, R1, R4
+ TEQ R1, R4
+ BNE L3a
+ MOVW R3, c+28(FP)
+ RET
+L3a:
+ MOVW.P 4(R2), R5
+ ADD.S R3, R5
+ MOVW.P R5, 4(R1)
+ B E3
+L3:
+ MOVW.P 4(R2), R5
+ ADC.S $0, R5
+ MOVW.P R5, 4(R1)
+E3:
+ TEQ R1, R4
+ BNE L3
+
+ MOVW $0, R0
+ MOVW.CS $1, R0
+ MOVW R0, c+28(FP)
+ RET
+
+
+// func subVW(z, x []Word, y Word) (c Word)
+TEXT ·subVW(SB),NOSPLIT,$0
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R4
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ ADD R4<<2, R1, R4
+ TEQ R1, R4
+ BNE L4a
+ MOVW R3, c+28(FP)
+ RET
+L4a:
+ MOVW.P 4(R2), R5
+ SUB.S R3, R5
+ MOVW.P R5, 4(R1)
+ B E4
+L4:
+ MOVW.P 4(R2), R5
+ SBC.S $0, R5
+ MOVW.P R5, 4(R1)
+E4:
+ TEQ R1, R4
+ BNE L4
+
+ MOVW $0, R0
+ MOVW.CC $1, R0
+ MOVW R0, c+28(FP)
+ RET
+
+
+// func shlVU(z, x []Word, s uint) (c Word)
+TEXT ·shlVU(SB),NOSPLIT,$0
+ MOVW z_len+4(FP), R5
+ TEQ $0, R5
+ BEQ X7
+
+ MOVW z+0(FP), R1
+ MOVW x+12(FP), R2
+ ADD R5<<2, R2, R2
+ ADD R5<<2, R1, R5
+ MOVW s+24(FP), R3
+ TEQ $0, R3 // shift 0 is special
+ BEQ Y7
+ ADD $4, R1 // stop one word early
+ MOVW $32, R4
+ SUB R3, R4
+ MOVW $0, R7
+
+ MOVW.W -4(R2), R6
+ MOVW R6<>R4, R6
+ MOVW R6, c+28(FP)
+ B E7
+
+L7:
+ MOVW.W -4(R2), R6
+ ORR R6>>R4, R7
+ MOVW.W R7, -4(R5)
+ MOVW R6<>R3, R7
+ MOVW R6<>R3, R7
+E6:
+ TEQ R1, R5
+ BNE L6
+
+ MOVW R7, 0(R1)
+ RET
+
+Y6: // copy loop, because shift 0 == shift 32
+ MOVW.P 4(R2), R6
+ MOVW.P R6, 4(R1)
+ TEQ R1, R5
+ BNE Y6
+
+X6:
+ MOVW $0, R1
+ MOVW R1, c+28(FP)
+ RET
+
+
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ MOVW $0, R0
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R5
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ MOVW r+28(FP), R4
+ ADD R5<<2, R1, R5
+ B E8
+
+ // word loop
+L8:
+ MOVW.P 4(R2), R6
+ MULLU R6, R3, (R7, R6)
+ ADD.S R4, R6
+ ADC R0, R7
+ MOVW.P R6, 4(R1)
+ MOVW R7, R4
+E8:
+ TEQ R1, R5
+ BNE L8
+
+ MOVW R4, c+32(FP)
+ RET
+
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ MOVW $0, R0
+ MOVW z+0(FP), R1
+ MOVW z_len+4(FP), R5
+ MOVW x+12(FP), R2
+ MOVW y+24(FP), R3
+ ADD R5<<2, R1, R5
+ MOVW $0, R4
+ B E9
+
+ // word loop
+L9:
+ MOVW.P 4(R2), R6
+ MULLU R6, R3, (R7, R6)
+ ADD.S R4, R6
+ ADC R0, R7
+ MOVW 0(R1), R4
+ ADD.S R4, R6
+ ADC R0, R7
+ MOVW.P R6, 4(R1)
+ MOVW R7, R4
+E9:
+ TEQ R1, R5
+ BNE L9
+
+ MOVW R4, c+28(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_arm64.s b/platform/dbops/binaries/go/go/src/math/big/arith_arm64.s
new file mode 100644
index 0000000000000000000000000000000000000000..204006e01dcfe393fe7c775a243d9c47d6b0ee72
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_arm64.s
@@ -0,0 +1,572 @@
+// 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 !math_big_pure_go
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// TODO: Consider re-implementing using Advanced SIMD
+// once the assembler supports those instructions.
+
+// func addVV(z, x, y []Word) (c Word)
+TEXT ·addVV(SB),NOSPLIT,$0
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R10
+ ADDS $0, R0 // clear carry flag
+ TBZ $0, R0, two
+ MOVD.P 8(R8), R11
+ MOVD.P 8(R9), R15
+ ADCS R15, R11
+ MOVD.P R11, 8(R10)
+ SUB $1, R0
+two:
+ TBZ $1, R0, loop
+ LDP.P 16(R8), (R11, R12)
+ LDP.P 16(R9), (R15, R16)
+ ADCS R15, R11
+ ADCS R16, R12
+ STP.P (R11, R12), 16(R10)
+ SUB $2, R0
+loop:
+ CBZ R0, done // careful not to touch the carry flag
+ LDP.P 32(R8), (R11, R12)
+ LDP -16(R8), (R13, R14)
+ LDP.P 32(R9), (R15, R16)
+ LDP -16(R9), (R17, R19)
+ ADCS R15, R11
+ ADCS R16, R12
+ ADCS R17, R13
+ ADCS R19, R14
+ STP.P (R11, R12), 32(R10)
+ STP (R13, R14), -16(R10)
+ SUB $4, R0
+ B loop
+done:
+ CSET HS, R0 // extract carry flag
+ MOVD R0, c+72(FP)
+ RET
+
+
+// func subVV(z, x, y []Word) (c Word)
+TEXT ·subVV(SB),NOSPLIT,$0
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R10
+ CMP R0, R0 // set carry flag
+ TBZ $0, R0, two
+ MOVD.P 8(R8), R11
+ MOVD.P 8(R9), R15
+ SBCS R15, R11
+ MOVD.P R11, 8(R10)
+ SUB $1, R0
+two:
+ TBZ $1, R0, loop
+ LDP.P 16(R8), (R11, R12)
+ LDP.P 16(R9), (R15, R16)
+ SBCS R15, R11
+ SBCS R16, R12
+ STP.P (R11, R12), 16(R10)
+ SUB $2, R0
+loop:
+ CBZ R0, done // careful not to touch the carry flag
+ LDP.P 32(R8), (R11, R12)
+ LDP -16(R8), (R13, R14)
+ LDP.P 32(R9), (R15, R16)
+ LDP -16(R9), (R17, R19)
+ SBCS R15, R11
+ SBCS R16, R12
+ SBCS R17, R13
+ SBCS R19, R14
+ STP.P (R11, R12), 32(R10)
+ STP (R13, R14), -16(R10)
+ SUB $4, R0
+ B loop
+done:
+ CSET LO, R0 // extract carry flag
+ MOVD R0, c+72(FP)
+ RET
+
+#define vwOneOp(instr, op1) \
+ MOVD.P 8(R1), R4; \
+ instr op1, R4; \
+ MOVD.P R4, 8(R3);
+
+// handle the first 1~4 elements before starting iteration in addVW/subVW
+#define vwPreIter(instr1, instr2, counter, target) \
+ vwOneOp(instr1, R2); \
+ SUB $1, counter; \
+ CBZ counter, target; \
+ vwOneOp(instr2, $0); \
+ SUB $1, counter; \
+ CBZ counter, target; \
+ vwOneOp(instr2, $0); \
+ SUB $1, counter; \
+ CBZ counter, target; \
+ vwOneOp(instr2, $0);
+
+// do one iteration of add or sub in addVW/subVW
+#define vwOneIter(instr, counter, exit) \
+ CBZ counter, exit; \ // careful not to touch the carry flag
+ LDP.P 32(R1), (R4, R5); \
+ LDP -16(R1), (R6, R7); \
+ instr $0, R4, R8; \
+ instr $0, R5, R9; \
+ instr $0, R6, R10; \
+ instr $0, R7, R11; \
+ STP.P (R8, R9), 32(R3); \
+ STP (R10, R11), -16(R3); \
+ SUB $4, counter;
+
+// do one iteration of copy in addVW/subVW
+#define vwOneIterCopy(counter, exit) \
+ CBZ counter, exit; \
+ LDP.P 32(R1), (R4, R5); \
+ LDP -16(R1), (R6, R7); \
+ STP.P (R4, R5), 32(R3); \
+ STP (R6, R7), -16(R3); \
+ SUB $4, counter;
+
+// func addVW(z, x []Word, y Word) (c Word)
+// The 'large' branch handles large 'z'. It checks the carry flag on every iteration
+// and switches to copy if we are done with carries. The copying is skipped as well
+// if 'x' and 'z' happen to share the same underlying storage.
+// The overhead of the checking and branching is visible when 'z' are small (~5%),
+// so set a threshold of 32, and remain the small-sized part entirely untouched.
+TEXT ·addVW(SB),NOSPLIT,$0
+ MOVD z+0(FP), R3
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R1
+ MOVD y+48(FP), R2
+ CMP $32, R0
+ BGE large // large-sized 'z' and 'x'
+ CBZ R0, len0 // the length of z is 0
+ MOVD.P 8(R1), R4
+ ADDS R2, R4 // z[0] = x[0] + y, set carry
+ MOVD.P R4, 8(R3)
+ SUB $1, R0
+ CBZ R0, len1 // the length of z is 1
+ TBZ $0, R0, two
+ MOVD.P 8(R1), R4 // do it once
+ ADCS $0, R4
+ MOVD.P R4, 8(R3)
+ SUB $1, R0
+two: // do it twice
+ TBZ $1, R0, loop
+ LDP.P 16(R1), (R4, R5)
+ ADCS $0, R4, R8 // c, z[i] = x[i] + c
+ ADCS $0, R5, R9
+ STP.P (R8, R9), 16(R3)
+ SUB $2, R0
+loop: // do four times per round
+ vwOneIter(ADCS, R0, len1)
+ B loop
+len1:
+ CSET HS, R2 // extract carry flag
+len0:
+ MOVD R2, c+56(FP)
+done:
+ RET
+large:
+ AND $0x3, R0, R10
+ AND $~0x3, R0
+ // unrolling for the first 1~4 elements to avoid saving the carry
+ // flag in each step, adjust $R0 if we unrolled 4 elements
+ vwPreIter(ADDS, ADCS, R10, add4)
+ SUB $4, R0
+add4:
+ BCC copy
+ vwOneIter(ADCS, R0, len1)
+ B add4
+copy:
+ MOVD ZR, c+56(FP)
+ CMP R1, R3
+ BEQ done
+copy_4: // no carry flag, copy the rest
+ vwOneIterCopy(R0, done)
+ B copy_4
+
+// func subVW(z, x []Word, y Word) (c Word)
+// The 'large' branch handles large 'z'. It checks the carry flag on every iteration
+// and switches to copy if we are done with carries. The copying is skipped as well
+// if 'x' and 'z' happen to share the same underlying storage.
+// The overhead of the checking and branching is visible when 'z' are small (~5%),
+// so set a threshold of 32, and remain the small-sized part entirely untouched.
+TEXT ·subVW(SB),NOSPLIT,$0
+ MOVD z+0(FP), R3
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R1
+ MOVD y+48(FP), R2
+ CMP $32, R0
+ BGE large // large-sized 'z' and 'x'
+ CBZ R0, len0 // the length of z is 0
+ MOVD.P 8(R1), R4
+ SUBS R2, R4 // z[0] = x[0] - y, set carry
+ MOVD.P R4, 8(R3)
+ SUB $1, R0
+ CBZ R0, len1 // the length of z is 1
+ TBZ $0, R0, two // do it once
+ MOVD.P 8(R1), R4
+ SBCS $0, R4
+ MOVD.P R4, 8(R3)
+ SUB $1, R0
+two: // do it twice
+ TBZ $1, R0, loop
+ LDP.P 16(R1), (R4, R5)
+ SBCS $0, R4, R8 // c, z[i] = x[i] + c
+ SBCS $0, R5, R9
+ STP.P (R8, R9), 16(R3)
+ SUB $2, R0
+loop: // do four times per round
+ vwOneIter(SBCS, R0, len1)
+ B loop
+len1:
+ CSET LO, R2 // extract carry flag
+len0:
+ MOVD R2, c+56(FP)
+done:
+ RET
+large:
+ AND $0x3, R0, R10
+ AND $~0x3, R0
+ // unrolling for the first 1~4 elements to avoid saving the carry
+ // flag in each step, adjust $R0 if we unrolled 4 elements
+ vwPreIter(SUBS, SBCS, R10, sub4)
+ SUB $4, R0
+sub4:
+ BCS copy
+ vwOneIter(SBCS, R0, len1)
+ B sub4
+copy:
+ MOVD ZR, c+56(FP)
+ CMP R1, R3
+ BEQ done
+copy_4: // no carry flag, copy the rest
+ vwOneIterCopy(R0, done)
+ B copy_4
+
+// func shlVU(z, x []Word, s uint) (c Word)
+// This implementation handles the shift operation from the high word to the low word,
+// which may be an error for the case where the low word of x overlaps with the high
+// word of z. When calling this function directly, you need to pay attention to this
+// situation.
+TEXT ·shlVU(SB),NOSPLIT,$0
+ LDP z+0(FP), (R0, R1) // R0 = z.ptr, R1 = len(z)
+ MOVD x+24(FP), R2
+ MOVD s+48(FP), R3
+ ADD R1<<3, R0 // R0 = &z[n]
+ ADD R1<<3, R2 // R2 = &x[n]
+ CBZ R1, len0
+ CBZ R3, copy // if the number of shift is 0, just copy x to z
+ MOVD $64, R4
+ SUB R3, R4
+ // handling the most significant element x[n-1]
+ MOVD.W -8(R2), R6
+ LSR R4, R6, R5 // return value
+ LSL R3, R6, R8 // x[i] << s
+ SUB $1, R1
+one: TBZ $0, R1, two
+ MOVD.W -8(R2), R6
+ LSR R4, R6, R7
+ ORR R8, R7
+ LSL R3, R6, R8
+ SUB $1, R1
+ MOVD.W R7, -8(R0)
+two:
+ TBZ $1, R1, loop
+ LDP.W -16(R2), (R6, R7)
+ LSR R4, R7, R10
+ ORR R8, R10
+ LSL R3, R7
+ LSR R4, R6, R9
+ ORR R7, R9
+ LSL R3, R6, R8
+ SUB $2, R1
+ STP.W (R9, R10), -16(R0)
+loop:
+ CBZ R1, done
+ LDP.W -32(R2), (R10, R11)
+ LDP 16(R2), (R12, R13)
+ LSR R4, R13, R23
+ ORR R8, R23 // z[i] = (x[i] << s) | (x[i-1] >> (64 - s))
+ LSL R3, R13
+ LSR R4, R12, R22
+ ORR R13, R22
+ LSL R3, R12
+ LSR R4, R11, R21
+ ORR R12, R21
+ LSL R3, R11
+ LSR R4, R10, R20
+ ORR R11, R20
+ LSL R3, R10, R8
+ STP.W (R20, R21), -32(R0)
+ STP (R22, R23), 16(R0)
+ SUB $4, R1
+ B loop
+done:
+ MOVD.W R8, -8(R0) // the first element x[0]
+ MOVD R5, c+56(FP) // the part moved out from x[n-1]
+ RET
+copy:
+ CMP R0, R2
+ BEQ len0
+ TBZ $0, R1, ctwo
+ MOVD.W -8(R2), R4
+ MOVD.W R4, -8(R0)
+ SUB $1, R1
+ctwo:
+ TBZ $1, R1, cloop
+ LDP.W -16(R2), (R4, R5)
+ STP.W (R4, R5), -16(R0)
+ SUB $2, R1
+cloop:
+ CBZ R1, len0
+ LDP.W -32(R2), (R4, R5)
+ LDP 16(R2), (R6, R7)
+ STP.W (R4, R5), -32(R0)
+ STP (R6, R7), 16(R0)
+ SUB $4, R1
+ B cloop
+len0:
+ MOVD $0, c+56(FP)
+ RET
+
+// func shrVU(z, x []Word, s uint) (c Word)
+// This implementation handles the shift operation from the low word to the high word,
+// which may be an error for the case where the high word of x overlaps with the low
+// word of z. When calling this function directly, you need to pay attention to this
+// situation.
+TEXT ·shrVU(SB),NOSPLIT,$0
+ MOVD z+0(FP), R0
+ MOVD z_len+8(FP), R1
+ MOVD x+24(FP), R2
+ MOVD s+48(FP), R3
+ MOVD $0, R8
+ MOVD $64, R4
+ SUB R3, R4
+ CBZ R1, len0
+ CBZ R3, copy // if the number of shift is 0, just copy x to z
+
+ MOVD.P 8(R2), R20
+ LSR R3, R20, R8
+ LSL R4, R20
+ MOVD R20, c+56(FP) // deal with the first element
+ SUB $1, R1
+
+ TBZ $0, R1, two
+ MOVD.P 8(R2), R6
+ LSL R4, R6, R20
+ ORR R8, R20
+ LSR R3, R6, R8
+ MOVD.P R20, 8(R0)
+ SUB $1, R1
+two:
+ TBZ $1, R1, loop
+ LDP.P 16(R2), (R6, R7)
+ LSL R4, R6, R20
+ LSR R3, R6
+ ORR R8, R20
+ LSL R4, R7, R21
+ LSR R3, R7, R8
+ ORR R6, R21
+ STP.P (R20, R21), 16(R0)
+ SUB $2, R1
+loop:
+ CBZ R1, done
+ LDP.P 32(R2), (R10, R11)
+ LDP -16(R2), (R12, R13)
+ LSL R4, R10, R20
+ LSR R3, R10
+ ORR R8, R20 // z[i] = (x[i] >> s) | (x[i+1] << (64 - s))
+ LSL R4, R11, R21
+ LSR R3, R11
+ ORR R10, R21
+ LSL R4, R12, R22
+ LSR R3, R12
+ ORR R11, R22
+ LSL R4, R13, R23
+ LSR R3, R13, R8
+ ORR R12, R23
+ STP.P (R20, R21), 32(R0)
+ STP (R22, R23), -16(R0)
+ SUB $4, R1
+ B loop
+done:
+ MOVD R8, (R0) // deal with the last element
+ RET
+copy:
+ CMP R0, R2
+ BEQ len0
+ TBZ $0, R1, ctwo
+ MOVD.P 8(R2), R3
+ MOVD.P R3, 8(R0)
+ SUB $1, R1
+ctwo:
+ TBZ $1, R1, cloop
+ LDP.P 16(R2), (R4, R5)
+ STP.P (R4, R5), 16(R0)
+ SUB $2, R1
+cloop:
+ CBZ R1, len0
+ LDP.P 32(R2), (R4, R5)
+ LDP -16(R2), (R6, R7)
+ STP.P (R4, R5), 32(R0)
+ STP (R6, R7), -16(R0)
+ SUB $4, R1
+ B cloop
+len0:
+ MOVD $0, c+56(FP)
+ RET
+
+
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ MOVD z+0(FP), R1
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R2
+ MOVD y+48(FP), R3
+ MOVD r+56(FP), R4
+ // c, z = x * y + r
+ TBZ $0, R0, two
+ MOVD.P 8(R2), R5
+ MUL R3, R5, R7
+ UMULH R3, R5, R8
+ ADDS R4, R7
+ ADC $0, R8, R4 // c, z[i] = x[i] * y + r
+ MOVD.P R7, 8(R1)
+ SUB $1, R0
+two:
+ TBZ $1, R0, loop
+ LDP.P 16(R2), (R5, R6)
+ MUL R3, R5, R10
+ UMULH R3, R5, R11
+ ADDS R4, R10
+ MUL R3, R6, R12
+ UMULH R3, R6, R13
+ ADCS R12, R11
+ ADC $0, R13, R4
+
+ STP.P (R10, R11), 16(R1)
+ SUB $2, R0
+loop:
+ CBZ R0, done
+ LDP.P 32(R2), (R5, R6)
+ LDP -16(R2), (R7, R8)
+
+ MUL R3, R5, R10
+ UMULH R3, R5, R11
+ ADDS R4, R10
+ MUL R3, R6, R12
+ UMULH R3, R6, R13
+ ADCS R11, R12
+
+ MUL R3, R7, R14
+ UMULH R3, R7, R15
+ ADCS R13, R14
+ MUL R3, R8, R16
+ UMULH R3, R8, R17
+ ADCS R15, R16
+ ADC $0, R17, R4
+
+ STP.P (R10, R12), 32(R1)
+ STP (R14, R16), -16(R1)
+ SUB $4, R0
+ B loop
+done:
+ MOVD R4, c+64(FP)
+ RET
+
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ MOVD z+0(FP), R1
+ MOVD z_len+8(FP), R0
+ MOVD x+24(FP), R2
+ MOVD y+48(FP), R3
+ MOVD $0, R4
+
+ TBZ $0, R0, two
+
+ MOVD.P 8(R2), R5
+ MOVD (R1), R6
+
+ MUL R5, R3, R7
+ UMULH R5, R3, R8
+
+ ADDS R7, R6
+ ADC $0, R8, R4
+
+ MOVD.P R6, 8(R1)
+ SUB $1, R0
+
+two:
+ TBZ $1, R0, loop
+
+ LDP.P 16(R2), (R5, R10)
+ LDP (R1), (R6, R11)
+
+ MUL R10, R3, R13
+ UMULH R10, R3, R12
+
+ MUL R5, R3, R7
+ UMULH R5, R3, R8
+
+ ADDS R4, R6
+ ADCS R13, R11
+ ADC $0, R12
+
+ ADDS R7, R6
+ ADCS R8, R11
+ ADC $0, R12, R4
+
+ STP.P (R6, R11), 16(R1)
+ SUB $2, R0
+
+// The main loop of this code operates on a block of 4 words every iteration
+// performing [R4:R12:R11:R10:R9] = R4 + R3 * [R8:R7:R6:R5] + [R12:R11:R10:R9]
+// where R4 is carried from the previous iteration, R8:R7:R6:R5 hold the next
+// 4 words of x, R3 is y and R12:R11:R10:R9 are part of the result z.
+loop:
+ CBZ R0, done
+
+ LDP.P 16(R2), (R5, R6)
+ LDP.P 16(R2), (R7, R8)
+
+ LDP (R1), (R9, R10)
+ ADDS R4, R9
+ MUL R6, R3, R14
+ ADCS R14, R10
+ MUL R7, R3, R15
+ LDP 16(R1), (R11, R12)
+ ADCS R15, R11
+ MUL R8, R3, R16
+ ADCS R16, R12
+ UMULH R8, R3, R20
+ ADC $0, R20
+
+ MUL R5, R3, R13
+ ADDS R13, R9
+ UMULH R5, R3, R17
+ ADCS R17, R10
+ UMULH R6, R3, R21
+ STP.P (R9, R10), 16(R1)
+ ADCS R21, R11
+ UMULH R7, R3, R19
+ ADCS R19, R12
+ STP.P (R11, R12), 16(R1)
+ ADC $0, R20, R4
+
+ SUB $4, R0
+ B loop
+
+done:
+ MOVD R4, c+56(FP)
+ RET
+
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_decl.go b/platform/dbops/binaries/go/go/src/math/big/arith_decl.go
new file mode 100644
index 0000000000000000000000000000000000000000..f14f8d6794ee0a22c26d01326f4221d44fd1d11c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_decl.go
@@ -0,0 +1,33 @@
+// 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.
+
+//go:build !math_big_pure_go
+
+package big
+
+// implemented in arith_$GOARCH.s
+
+//go:noescape
+func addVV(z, x, y []Word) (c Word)
+
+//go:noescape
+func subVV(z, x, y []Word) (c Word)
+
+//go:noescape
+func addVW(z, x []Word, y Word) (c Word)
+
+//go:noescape
+func subVW(z, x []Word, y Word) (c Word)
+
+//go:noescape
+func shlVU(z, x []Word, s uint) (c Word)
+
+//go:noescape
+func shrVU(z, x []Word, s uint) (c Word)
+
+//go:noescape
+func mulAddVWW(z, x []Word, y, r Word) (c Word)
+
+//go:noescape
+func addMulVVW(z, x []Word, y Word) (c Word)
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_decl_pure.go b/platform/dbops/binaries/go/go/src/math/big/arith_decl_pure.go
new file mode 100644
index 0000000000000000000000000000000000000000..4d7bbc8771633148d11e7a249342dacda92cb0a1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_decl_pure.go
@@ -0,0 +1,49 @@
+// 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.
+
+//go:build math_big_pure_go
+
+package big
+
+func addVV(z, x, y []Word) (c Word) {
+ return addVV_g(z, x, y)
+}
+
+func subVV(z, x, y []Word) (c Word) {
+ return subVV_g(z, x, y)
+}
+
+func addVW(z, x []Word, y Word) (c Word) {
+ // TODO: remove indirect function call when golang.org/issue/30548 is fixed
+ fn := addVW_g
+ if len(z) > 32 {
+ fn = addVWlarge
+ }
+ return fn(z, x, y)
+}
+
+func subVW(z, x []Word, y Word) (c Word) {
+ // TODO: remove indirect function call when golang.org/issue/30548 is fixed
+ fn := subVW_g
+ if len(z) > 32 {
+ fn = subVWlarge
+ }
+ return fn(z, x, y)
+}
+
+func shlVU(z, x []Word, s uint) (c Word) {
+ return shlVU_g(z, x, s)
+}
+
+func shrVU(z, x []Word, s uint) (c Word) {
+ return shrVU_g(z, x, s)
+}
+
+func mulAddVWW(z, x []Word, y, r Word) (c Word) {
+ return mulAddVWW_g(z, x, y, r)
+}
+
+func addMulVVW(z, x []Word, y Word) (c Word) {
+ return addMulVVW_g(z, x, y)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_decl_s390x.go b/platform/dbops/binaries/go/go/src/math/big/arith_decl_s390x.go
new file mode 100644
index 0000000000000000000000000000000000000000..653916687812bf98aadb01f8b37c447bad4d19c9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_decl_s390x.go
@@ -0,0 +1,18 @@
+// 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 !math_big_pure_go
+
+package big
+
+import "internal/cpu"
+
+func addVV_check(z, x, y []Word) (c Word)
+func addVV_vec(z, x, y []Word) (c Word)
+func addVV_novec(z, x, y []Word) (c Word)
+func subVV_check(z, x, y []Word) (c Word)
+func subVV_vec(z, x, y []Word) (c Word)
+func subVV_novec(z, x, y []Word) (c Word)
+
+var hasVX = cpu.S390X.HasVX
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_loong64.s b/platform/dbops/binaries/go/go/src/math/big/arith_loong64.s
new file mode 100644
index 0000000000000000000000000000000000000000..847e3127fbf41036dd1aab570b5d17bcc1817496
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_loong64.s
@@ -0,0 +1,34 @@
+// 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 !math_big_pure_go && loong64
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+TEXT ·addVV(SB),NOSPLIT,$0
+ JMP ·addVV_g(SB)
+
+TEXT ·subVV(SB),NOSPLIT,$0
+ JMP ·subVV_g(SB)
+
+TEXT ·addVW(SB),NOSPLIT,$0
+ JMP ·addVW_g(SB)
+
+TEXT ·subVW(SB),NOSPLIT,$0
+ JMP ·subVW_g(SB)
+
+TEXT ·shlVU(SB),NOSPLIT,$0
+ JMP ·shlVU_g(SB)
+
+TEXT ·shrVU(SB),NOSPLIT,$0
+ JMP ·shrVU_g(SB)
+
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ JMP ·mulAddVWW_g(SB)
+
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ JMP ·addMulVVW_g(SB)
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_mips64x.s b/platform/dbops/binaries/go/go/src/math/big/arith_mips64x.s
new file mode 100644
index 0000000000000000000000000000000000000000..393a3efb9bcef2ce57fa3c70066ba1d6fd3a0d58
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_mips64x.s
@@ -0,0 +1,35 @@
+// 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 !math_big_pure_go && (mips64 || mips64le)
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+TEXT ·addVV(SB),NOSPLIT,$0
+ JMP ·addVV_g(SB)
+
+TEXT ·subVV(SB),NOSPLIT,$0
+ JMP ·subVV_g(SB)
+
+TEXT ·addVW(SB),NOSPLIT,$0
+ JMP ·addVW_g(SB)
+
+TEXT ·subVW(SB),NOSPLIT,$0
+ JMP ·subVW_g(SB)
+
+TEXT ·shlVU(SB),NOSPLIT,$0
+ JMP ·shlVU_g(SB)
+
+TEXT ·shrVU(SB),NOSPLIT,$0
+ JMP ·shrVU_g(SB)
+
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ JMP ·mulAddVWW_g(SB)
+
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ JMP ·addMulVVW_g(SB)
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_mipsx.s b/platform/dbops/binaries/go/go/src/math/big/arith_mipsx.s
new file mode 100644
index 0000000000000000000000000000000000000000..cdb4bbcab63336efe34709ab3c3cfe109791e541
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_mipsx.s
@@ -0,0 +1,35 @@
+// 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 !math_big_pure_go && (mips || mipsle)
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+TEXT ·addVV(SB),NOSPLIT,$0
+ JMP ·addVV_g(SB)
+
+TEXT ·subVV(SB),NOSPLIT,$0
+ JMP ·subVV_g(SB)
+
+TEXT ·addVW(SB),NOSPLIT,$0
+ JMP ·addVW_g(SB)
+
+TEXT ·subVW(SB),NOSPLIT,$0
+ JMP ·subVW_g(SB)
+
+TEXT ·shlVU(SB),NOSPLIT,$0
+ JMP ·shlVU_g(SB)
+
+TEXT ·shrVU(SB),NOSPLIT,$0
+ JMP ·shrVU_g(SB)
+
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ JMP ·mulAddVWW_g(SB)
+
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ JMP ·addMulVVW_g(SB)
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_ppc64x.s b/platform/dbops/binaries/go/go/src/math/big/arith_ppc64x.s
new file mode 100644
index 0000000000000000000000000000000000000000..9512a12270d42386db75bcca97e21741cec40f9b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_ppc64x.s
@@ -0,0 +1,631 @@
+// 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 !math_big_pure_go && (ppc64 || ppc64le)
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// func addVV(z, y, y []Word) (c Word)
+// z[i] = x[i] + y[i] for all i, carrying
+TEXT ·addVV(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R7 // R7 = z_len
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R9 // R9 = y[]
+ MOVD z+0(FP), R10 // R10 = z[]
+
+ // If z_len = 0, we are done
+ CMP R0, R7
+ MOVD R0, R4
+ BEQ done
+
+ // Process the first iteration out of the loop so we can
+ // use MOVDU and avoid 3 index registers updates.
+ MOVD 0(R8), R11 // R11 = x[i]
+ MOVD 0(R9), R12 // R12 = y[i]
+ ADD $-1, R7 // R7 = z_len - 1
+ ADDC R12, R11, R15 // R15 = x[i] + y[i], set CA
+ CMP R0, R7
+ MOVD R15, 0(R10) // z[i]
+ BEQ final // If z_len was 1, we are done
+
+ SRD $2, R7, R5 // R5 = z_len/4
+ CMP R0, R5
+ MOVD R5, CTR // Set up loop counter
+ BEQ tail // If R5 = 0, we can't use the loop
+
+ // Process 4 elements per iteration. Unrolling this loop
+ // means a performance trade-off: we will lose performance
+ // for small values of z_len (0.90x in the worst case), but
+ // gain significant performance as z_len increases (up to
+ // 1.45x).
+
+ PCALIGN $16
+loop:
+ MOVD 8(R8), R11 // R11 = x[i]
+ MOVD 16(R8), R12 // R12 = x[i+1]
+ MOVD 24(R8), R14 // R14 = x[i+2]
+ MOVDU 32(R8), R15 // R15 = x[i+3]
+ MOVD 8(R9), R16 // R16 = y[i]
+ MOVD 16(R9), R17 // R17 = y[i+1]
+ MOVD 24(R9), R18 // R18 = y[i+2]
+ MOVDU 32(R9), R19 // R19 = y[i+3]
+ ADDE R11, R16, R20 // R20 = x[i] + y[i] + CA
+ ADDE R12, R17, R21 // R21 = x[i+1] + y[i+1] + CA
+ ADDE R14, R18, R22 // R22 = x[i+2] + y[i+2] + CA
+ ADDE R15, R19, R23 // R23 = x[i+3] + y[i+3] + CA
+ MOVD R20, 8(R10) // z[i]
+ MOVD R21, 16(R10) // z[i+1]
+ MOVD R22, 24(R10) // z[i+2]
+ MOVDU R23, 32(R10) // z[i+3]
+ ADD $-4, R7 // R7 = z_len - 4
+ BC 16, 0, loop // bdnz
+
+ // We may have more elements to read
+ CMP R0, R7
+ BEQ final
+
+ // Process the remaining elements, one at a time
+tail:
+ MOVDU 8(R8), R11 // R11 = x[i]
+ MOVDU 8(R9), R16 // R16 = y[i]
+ ADD $-1, R7 // R7 = z_len - 1
+ ADDE R11, R16, R20 // R20 = x[i] + y[i] + CA
+ CMP R0, R7
+ MOVDU R20, 8(R10) // z[i]
+ BEQ final // If R7 = 0, we are done
+
+ MOVDU 8(R8), R11
+ MOVDU 8(R9), R16
+ ADD $-1, R7
+ ADDE R11, R16, R20
+ CMP R0, R7
+ MOVDU R20, 8(R10)
+ BEQ final
+
+ MOVD 8(R8), R11
+ MOVD 8(R9), R16
+ ADDE R11, R16, R20
+ MOVD R20, 8(R10)
+
+final:
+ ADDZE R4 // Capture CA
+
+done:
+ MOVD R4, c+72(FP)
+ RET
+
+// func subVV(z, x, y []Word) (c Word)
+// z[i] = x[i] - y[i] for all i, carrying
+TEXT ·subVV(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R7 // R7 = z_len
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R9 // R9 = y[]
+ MOVD z+0(FP), R10 // R10 = z[]
+
+ // If z_len = 0, we are done
+ CMP R0, R7
+ MOVD R0, R4
+ BEQ done
+
+ // Process the first iteration out of the loop so we can
+ // use MOVDU and avoid 3 index registers updates.
+ MOVD 0(R8), R11 // R11 = x[i]
+ MOVD 0(R9), R12 // R12 = y[i]
+ ADD $-1, R7 // R7 = z_len - 1
+ SUBC R12, R11, R15 // R15 = x[i] - y[i], set CA
+ CMP R0, R7
+ MOVD R15, 0(R10) // z[i]
+ BEQ final // If z_len was 1, we are done
+
+ SRD $2, R7, R5 // R5 = z_len/4
+ CMP R0, R5
+ MOVD R5, CTR // Set up loop counter
+ BEQ tail // If R5 = 0, we can't use the loop
+
+ // Process 4 elements per iteration. Unrolling this loop
+ // means a performance trade-off: we will lose performance
+ // for small values of z_len (0.92x in the worst case), but
+ // gain significant performance as z_len increases (up to
+ // 1.45x).
+
+ PCALIGN $16
+loop:
+ MOVD 8(R8), R11 // R11 = x[i]
+ MOVD 16(R8), R12 // R12 = x[i+1]
+ MOVD 24(R8), R14 // R14 = x[i+2]
+ MOVDU 32(R8), R15 // R15 = x[i+3]
+ MOVD 8(R9), R16 // R16 = y[i]
+ MOVD 16(R9), R17 // R17 = y[i+1]
+ MOVD 24(R9), R18 // R18 = y[i+2]
+ MOVDU 32(R9), R19 // R19 = y[i+3]
+ SUBE R16, R11, R20 // R20 = x[i] - y[i] + CA
+ SUBE R17, R12, R21 // R21 = x[i+1] - y[i+1] + CA
+ SUBE R18, R14, R22 // R22 = x[i+2] - y[i+2] + CA
+ SUBE R19, R15, R23 // R23 = x[i+3] - y[i+3] + CA
+ MOVD R20, 8(R10) // z[i]
+ MOVD R21, 16(R10) // z[i+1]
+ MOVD R22, 24(R10) // z[i+2]
+ MOVDU R23, 32(R10) // z[i+3]
+ ADD $-4, R7 // R7 = z_len - 4
+ BC 16, 0, loop // bdnz
+
+ // We may have more elements to read
+ CMP R0, R7
+ BEQ final
+
+ // Process the remaining elements, one at a time
+tail:
+ MOVDU 8(R8), R11 // R11 = x[i]
+ MOVDU 8(R9), R16 // R16 = y[i]
+ ADD $-1, R7 // R7 = z_len - 1
+ SUBE R16, R11, R20 // R20 = x[i] - y[i] + CA
+ CMP R0, R7
+ MOVDU R20, 8(R10) // z[i]
+ BEQ final // If R7 = 0, we are done
+
+ MOVDU 8(R8), R11
+ MOVDU 8(R9), R16
+ ADD $-1, R7
+ SUBE R16, R11, R20
+ CMP R0, R7
+ MOVDU R20, 8(R10)
+ BEQ final
+
+ MOVD 8(R8), R11
+ MOVD 8(R9), R16
+ SUBE R16, R11, R20
+ MOVD R20, 8(R10)
+
+final:
+ ADDZE R4
+ XOR $1, R4
+
+done:
+ MOVD R4, c+72(FP)
+ RET
+
+// func addVW(z, x []Word, y Word) (c Word)
+TEXT ·addVW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R10 // R10 = z[]
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R4 // R4 = y = c
+ MOVD z_len+8(FP), R11 // R11 = z_len
+
+ CMP R0, R11 // If z_len is zero, return
+ BEQ done
+
+ // We will process the first iteration out of the loop so we capture
+ // the value of c. In the subsequent iterations, we will rely on the
+ // value of CA set here.
+ MOVD 0(R8), R20 // R20 = x[i]
+ ADD $-1, R11 // R11 = z_len - 1
+ ADDC R20, R4, R6 // R6 = x[i] + c
+ CMP R0, R11 // If z_len was 1, we are done
+ MOVD R6, 0(R10) // z[i]
+ BEQ final
+
+ // We will read 4 elements per iteration
+ SRD $2, R11, R9 // R9 = z_len/4
+ DCBT (R8)
+ CMP R0, R9
+ MOVD R9, CTR // Set up the loop counter
+ BEQ tail // If R9 = 0, we can't use the loop
+ PCALIGN $16
+
+loop:
+ MOVD 8(R8), R20 // R20 = x[i]
+ MOVD 16(R8), R21 // R21 = x[i+1]
+ MOVD 24(R8), R22 // R22 = x[i+2]
+ MOVDU 32(R8), R23 // R23 = x[i+3]
+ ADDZE R20, R24 // R24 = x[i] + CA
+ ADDZE R21, R25 // R25 = x[i+1] + CA
+ ADDZE R22, R26 // R26 = x[i+2] + CA
+ ADDZE R23, R27 // R27 = x[i+3] + CA
+ MOVD R24, 8(R10) // z[i]
+ MOVD R25, 16(R10) // z[i+1]
+ MOVD R26, 24(R10) // z[i+2]
+ MOVDU R27, 32(R10) // z[i+3]
+ ADD $-4, R11 // R11 = z_len - 4
+ BC 16, 0, loop // bdnz
+
+ // We may have some elements to read
+ CMP R0, R11
+ BEQ final
+
+tail:
+ MOVDU 8(R8), R20
+ ADDZE R20, R24
+ ADD $-1, R11
+ MOVDU R24, 8(R10)
+ CMP R0, R11
+ BEQ final
+
+ MOVDU 8(R8), R20
+ ADDZE R20, R24
+ ADD $-1, R11
+ MOVDU R24, 8(R10)
+ CMP R0, R11
+ BEQ final
+
+ MOVD 8(R8), R20
+ ADDZE R20, R24
+ MOVD R24, 8(R10)
+
+final:
+ ADDZE R0, R4 // c = CA
+done:
+ MOVD R4, c+56(FP)
+ RET
+
+// func subVW(z, x []Word, y Word) (c Word)
+TEXT ·subVW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R10 // R10 = z[]
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R4 // R4 = y = c
+ MOVD z_len+8(FP), R11 // R11 = z_len
+
+ CMP R0, R11 // If z_len is zero, return
+ BEQ done
+
+ // We will process the first iteration out of the loop so we capture
+ // the value of c. In the subsequent iterations, we will rely on the
+ // value of CA set here.
+ MOVD 0(R8), R20 // R20 = x[i]
+ ADD $-1, R11 // R11 = z_len - 1
+ SUBC R4, R20, R6 // R6 = x[i] - c
+ CMP R0, R11 // If z_len was 1, we are done
+ MOVD R6, 0(R10) // z[i]
+ BEQ final
+
+ // We will read 4 elements per iteration
+ SRD $2, R11, R9 // R9 = z_len/4
+ DCBT (R8)
+ CMP R0, R9
+ MOVD R9, CTR // Set up the loop counter
+ BEQ tail // If R9 = 0, we can't use the loop
+
+ // The loop here is almost the same as the one used in s390x, but
+ // we don't need to capture CA every iteration because we've already
+ // done that above.
+
+ PCALIGN $16
+loop:
+ MOVD 8(R8), R20
+ MOVD 16(R8), R21
+ MOVD 24(R8), R22
+ MOVDU 32(R8), R23
+ SUBE R0, R20
+ SUBE R0, R21
+ SUBE R0, R22
+ SUBE R0, R23
+ MOVD R20, 8(R10)
+ MOVD R21, 16(R10)
+ MOVD R22, 24(R10)
+ MOVDU R23, 32(R10)
+ ADD $-4, R11
+ BC 16, 0, loop // bdnz
+
+ // We may have some elements to read
+ CMP R0, R11
+ BEQ final
+
+tail:
+ MOVDU 8(R8), R20
+ SUBE R0, R20
+ ADD $-1, R11
+ MOVDU R20, 8(R10)
+ CMP R0, R11
+ BEQ final
+
+ MOVDU 8(R8), R20
+ SUBE R0, R20
+ ADD $-1, R11
+ MOVDU R20, 8(R10)
+ CMP R0, R11
+ BEQ final
+
+ MOVD 8(R8), R20
+ SUBE R0, R20
+ MOVD R20, 8(R10)
+
+final:
+ // Capture CA
+ SUBE R4, R4
+ NEG R4, R4
+
+done:
+ MOVD R4, c+56(FP)
+ RET
+
+//func shlVU(z, x []Word, s uint) (c Word)
+TEXT ·shlVU(SB), NOSPLIT, $0
+ MOVD z+0(FP), R3
+ MOVD x+24(FP), R6
+ MOVD s+48(FP), R9
+ MOVD z_len+8(FP), R4
+ MOVD x_len+32(FP), R7
+ CMP R9, R0 // s==0 copy(z,x)
+ BEQ zeroshift
+ CMP R4, R0 // len(z)==0 return
+ BEQ done
+
+ ADD $-1, R4, R5 // len(z)-1
+ SUBC R9, $64, R4 // ŝ=_W-s, we skip & by _W-1 as the caller ensures s < _W(64)
+ SLD $3, R5, R7
+ ADD R6, R7, R15 // save starting address &x[len(z)-1]
+ ADD R3, R7, R16 // save starting address &z[len(z)-1]
+ MOVD (R6)(R7), R14
+ SRD R4, R14, R7 // compute x[len(z)-1]>>ŝ into R7
+ CMP R5, R0 // iterate from i=len(z)-1 to 0
+ BEQ loopexit // Already at end?
+ MOVD 0(R15),R10 // x[i]
+ PCALIGN $16
+shloop:
+ SLD R9, R10, R10 // x[i]<>ŝ
+ OR R11, R10, R10
+ MOVD R10, 0(R16) // z[i-1]=x[i]<>ŝ
+ MOVD R14, R10 // reuse x[i-1] for next iteration
+ ADD $-8, R16 // i--
+ CMP R15, R6 // &x[i-1]>&x[0]?
+ BGT shloop
+loopexit:
+ MOVD 0(R6), R4
+ SLD R9, R4, R4
+ MOVD R4, 0(R3) // z[0]=x[0]<>ŝ into c
+ RET
+
+zeroshift:
+ CMP R6, R0 // x is null, nothing to copy
+ BEQ done
+ CMP R6, R3 // if x is same as z, nothing to copy
+ BEQ done
+ CMP R7, R4
+ ISEL $0, R7, R4, R7 // Take the lower bound of lengths of x,z
+ SLD $3, R7, R7
+ SUB R6, R3, R11 // dest - src
+ CMPU R11, R7, CR2 // < len?
+ BLT CR2, backward // there is overlap, copy backwards
+ MOVD $0, R14
+ // shlVU processes backwards, but added a forward copy option
+ // since its faster on POWER
+repeat:
+ MOVD (R6)(R14), R15 // Copy 8 bytes at a time
+ MOVD R15, (R3)(R14)
+ ADD $8, R14
+ CMP R14, R7 // More 8 bytes left?
+ BLT repeat
+ BR done
+backward:
+ ADD $-8,R7, R14
+repeatback:
+ MOVD (R6)(R14), R15 // copy x into z backwards
+ MOVD R15, (R3)(R14) // copy 8 bytes at a time
+ SUB $8, R14
+ CMP R14, $-8 // More 8 bytes left?
+ BGT repeatback
+
+done:
+ MOVD R0, c+56(FP) // c=0
+ RET
+
+//func shrVU(z, x []Word, s uint) (c Word)
+TEXT ·shrVU(SB), NOSPLIT, $0
+ MOVD z+0(FP), R3
+ MOVD x+24(FP), R6
+ MOVD s+48(FP), R9
+ MOVD z_len+8(FP), R4
+ MOVD x_len+32(FP), R7
+
+ CMP R9, R0 // s==0, copy(z,x)
+ BEQ zeroshift
+ CMP R4, R0 // len(z)==0 return
+ BEQ done
+ SUBC R9, $64, R5 // ŝ=_W-s, we skip & by _W-1 as the caller ensures s < _W(64)
+
+ MOVD 0(R6), R7
+ SLD R5, R7, R7 // compute x[0]<<ŝ
+ MOVD $1, R8 // iterate from i=1 to i=3, else jump to scalar loop
+ CMP R4, $3
+ BLT scalar
+ MTVSRD R9, VS38 // s
+ VSPLTB $7, V6, V4
+ MTVSRD R5, VS39 // ŝ
+ VSPLTB $7, V7, V2
+ ADD $-2, R4, R16
+ PCALIGN $16
+loopback:
+ ADD $-1, R8, R10
+ SLD $3, R10
+ LXVD2X (R6)(R10), VS32 // load x[i-1], x[i]
+ SLD $3, R8, R12
+ LXVD2X (R6)(R12), VS33 // load x[i], x[i+1]
+
+ VSRD V0, V4, V3 // x[i-1]>>s, x[i]>>s
+ VSLD V1, V2, V5 // x[i]<<ŝ, x[i+1]<<ŝ
+ VOR V3, V5, V5 // Or(|) the two registers together
+ STXVD2X VS37, (R3)(R10) // store into z[i-1] and z[i]
+ ADD $2, R8 // Done processing 2 entries, i and i+1
+ CMP R8, R16 // Are there at least a couple of more entries left?
+ BLE loopback
+ CMP R8, R4 // Are we at the last element?
+ BEQ loopexit
+scalar:
+ ADD $-1, R8, R10
+ SLD $3, R10
+ MOVD (R6)(R10),R11
+ SRD R9, R11, R11 // x[len(z)-2] >> s
+ SLD $3, R8, R12
+ MOVD (R6)(R12), R12
+ SLD R5, R12, R12 // x[len(z)-1]<<ŝ
+ OR R12, R11, R11 // x[len(z)-2]>>s | x[len(z)-1]<<ŝ
+ MOVD R11, (R3)(R10) // z[len(z)-2]=x[len(z)-2]>>s | x[len(z)-1]<<ŝ
+loopexit:
+ ADD $-1, R4
+ SLD $3, R4
+ MOVD (R6)(R4), R5
+ SRD R9, R5, R5 // x[len(z)-1]>>s
+ MOVD R5, (R3)(R4) // z[len(z)-1]=x[len(z)-1]>>s
+ MOVD R7, c+56(FP) // store pre-computed x[0]<<ŝ into c
+ RET
+
+zeroshift:
+ CMP R6, R0 // x is null, nothing to copy
+ BEQ done
+ CMP R6, R3 // if x is same as z, nothing to copy
+ BEQ done
+ CMP R7, R4
+ ISEL $0, R7, R4, R7 // Take the lower bounds of lengths of x, z
+ SLD $3, R7, R7
+ MOVD $0, R14
+repeat:
+ MOVD (R6)(R14), R15 // copy 8 bytes at a time
+ MOVD R15, (R3)(R14) // shrVU processes bytes only forwards
+ ADD $8, R14
+ CMP R14, R7 // More 8 bytes left?
+ BLT repeat
+done:
+ MOVD R0, c+56(FP)
+ RET
+
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R10 // R10 = z[]
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R9 // R9 = y
+ MOVD r+56(FP), R4 // R4 = r = c
+ MOVD z_len+8(FP), R11 // R11 = z_len
+
+ CMP R0, R11
+ BEQ done
+
+ MOVD 0(R8), R20
+ ADD $-1, R11
+ MULLD R9, R20, R6 // R6 = z0 = Low-order(x[i]*y)
+ MULHDU R9, R20, R7 // R7 = z1 = High-order(x[i]*y)
+ ADDC R4, R6 // R6 = z0 + r
+ ADDZE R7 // R7 = z1 + CA
+ CMP R0, R11
+ MOVD R7, R4 // R4 = c
+ MOVD R6, 0(R10) // z[i]
+ BEQ done
+
+ // We will read 4 elements per iteration
+ SRD $2, R11, R14 // R14 = z_len/4
+ DCBT (R8)
+ CMP R0, R14
+ MOVD R14, CTR // Set up the loop counter
+ BEQ tail // If R9 = 0, we can't use the loop
+ PCALIGN $16
+
+loop:
+ MOVD 8(R8), R20 // R20 = x[i]
+ MOVD 16(R8), R21 // R21 = x[i+1]
+ MOVD 24(R8), R22 // R22 = x[i+2]
+ MOVDU 32(R8), R23 // R23 = x[i+3]
+ MULLD R9, R20, R24 // R24 = z0[i]
+ MULHDU R9, R20, R20 // R20 = z1[i]
+ ADDC R4, R24 // R24 = z0[i] + c
+ ADDZE R20 // R7 = z1[i] + CA
+ MULLD R9, R21, R25
+ MULHDU R9, R21, R21
+ ADDC R20, R25
+ ADDZE R21
+ MULLD R9, R22, R26
+ MULHDU R9, R22, R22
+ MULLD R9, R23, R27
+ MULHDU R9, R23, R23
+ ADDC R21, R26
+ ADDZE R22
+ MOVD R24, 8(R10) // z[i]
+ MOVD R25, 16(R10) // z[i+1]
+ ADDC R22, R27
+ ADDZE R23,R4 // update carry
+ MOVD R26, 24(R10) // z[i+2]
+ MOVDU R27, 32(R10) // z[i+3]
+ ADD $-4, R11 // R11 = z_len - 4
+ BC 16, 0, loop // bdnz
+
+ // We may have some elements to read
+ CMP R0, R11
+ BEQ done
+
+ // Process the remaining elements, one at a time
+tail:
+ MOVDU 8(R8), R20 // R20 = x[i]
+ MULLD R9, R20, R24 // R24 = z0[i]
+ MULHDU R9, R20, R25 // R25 = z1[i]
+ ADD $-1, R11 // R11 = z_len - 1
+ ADDC R4, R24
+ ADDZE R25
+ MOVDU R24, 8(R10) // z[i]
+ CMP R0, R11
+ MOVD R25, R4 // R4 = c
+ BEQ done // If R11 = 0, we are done
+
+ MOVDU 8(R8), R20
+ MULLD R9, R20, R24
+ MULHDU R9, R20, R25
+ ADD $-1, R11
+ ADDC R4, R24
+ ADDZE R25
+ MOVDU R24, 8(R10)
+ CMP R0, R11
+ MOVD R25, R4
+ BEQ done
+
+ MOVD 8(R8), R20
+ MULLD R9, R20, R24
+ MULHDU R9, R20, R25
+ ADD $-1, R11
+ ADDC R4, R24
+ ADDZE R25
+ MOVD R24, 8(R10)
+ MOVD R25, R4
+
+done:
+ MOVD R4, c+64(FP)
+ RET
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+TEXT ·addMulVVW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R10 // R10 = z[]
+ MOVD x+24(FP), R8 // R8 = x[]
+ MOVD y+48(FP), R9 // R9 = y
+ MOVD z_len+8(FP), R22 // R22 = z_len
+
+ MOVD R0, R3 // R3 will be the index register
+ CMP R0, R22
+ MOVD R0, R4 // R4 = c = 0
+ MOVD R22, CTR // Initialize loop counter
+ BEQ done
+ PCALIGN $16
+
+loop:
+ MOVD (R8)(R3), R20 // Load x[i]
+ MOVD (R10)(R3), R21 // Load z[i]
+ MULLD R9, R20, R6 // R6 = Low-order(x[i]*y)
+ MULHDU R9, R20, R7 // R7 = High-order(x[i]*y)
+ ADDC R21, R6 // R6 = z0
+ ADDZE R7 // R7 = z1
+ ADDC R4, R6 // R6 = z0 + c + 0
+ ADDZE R7, R4 // c += z1
+ MOVD R6, (R10)(R3) // Store z[i]
+ ADD $8, R3
+ BC 16, 0, loop // bdnz
+
+done:
+ MOVD R4, c+56(FP)
+ RET
+
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_riscv64.s b/platform/dbops/binaries/go/go/src/math/big/arith_riscv64.s
new file mode 100644
index 0000000000000000000000000000000000000000..bad32497b71c6739e7013199e2368355b8dc8686
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_riscv64.s
@@ -0,0 +1,35 @@
+// 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 !math_big_pure_go && riscv64
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+TEXT ·addVV(SB),NOSPLIT,$0
+ JMP ·addVV_g(SB)
+
+TEXT ·subVV(SB),NOSPLIT,$0
+ JMP ·subVV_g(SB)
+
+TEXT ·addVW(SB),NOSPLIT,$0
+ JMP ·addVW_g(SB)
+
+TEXT ·subVW(SB),NOSPLIT,$0
+ JMP ·subVW_g(SB)
+
+TEXT ·shlVU(SB),NOSPLIT,$0
+ JMP ·shlVU_g(SB)
+
+TEXT ·shrVU(SB),NOSPLIT,$0
+ JMP ·shrVU_g(SB)
+
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ JMP ·mulAddVWW_g(SB)
+
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ JMP ·addMulVVW_g(SB)
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_s390x.s b/platform/dbops/binaries/go/go/src/math/big/arith_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..01a7bb2d51262962bc3c6d6deb991b205c0a7b21
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_s390x.s
@@ -0,0 +1,786 @@
+// 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 !math_big_pure_go
+
+#include "textflag.h"
+
+// This file provides fast assembly versions for the elementary
+// arithmetic operations on vectors implemented in arith.go.
+
+// DI = R3, CX = R4, SI = r10, r8 = r8, r9=r9, r10 = r2, r11 = r5, r12 = r6, r13 = r7, r14 = r1 (R0 set to 0) + use R11
+// func addVV(z, x, y []Word) (c Word)
+
+TEXT ·addVV(SB), NOSPLIT, $0
+ MOVD addvectorfacility+0x00(SB), R1
+ BR (R1)
+
+TEXT ·addVV_check(SB), NOSPLIT, $0
+ MOVB ·hasVX(SB), R1
+ CMPBEQ R1, $1, vectorimpl // vectorfacility = 1, vector supported
+ MOVD $addvectorfacility+0x00(SB), R1
+ MOVD $·addVV_novec(SB), R2
+ MOVD R2, 0(R1)
+
+ // MOVD $·addVV_novec(SB), 0(R1)
+ BR ·addVV_novec(SB)
+
+vectorimpl:
+ MOVD $addvectorfacility+0x00(SB), R1
+ MOVD $·addVV_vec(SB), R2
+ MOVD R2, 0(R1)
+
+ // MOVD $·addVV_vec(SB), 0(R1)
+ BR ·addVV_vec(SB)
+
+GLOBL addvectorfacility+0x00(SB), NOPTR, $8
+DATA addvectorfacility+0x00(SB)/8, $·addVV_check(SB)
+
+TEXT ·addVV_vec(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R3
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R2
+
+ MOVD $0, R4 // c = 0
+ MOVD $0, R0 // make sure it's zero
+ MOVD $0, R10 // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUB $4, R3
+ BLT v1
+ SUB $12, R3 // n -= 16
+ BLT A1 // if n < 0 goto A1
+
+ MOVD R8, R5
+ MOVD R9, R6
+ MOVD R2, R7
+
+ // n >= 0
+ // regular loop body unrolled 16x
+ VZERO V0 // c = 0
+
+UU1:
+ VLM 0(R5), V1, V4 // 64-bytes into V1..V8
+ ADD $64, R5
+ VPDI $0x4, V1, V1, V1 // flip the doublewords to big-endian order
+ VPDI $0x4, V2, V2, V2 // flip the doublewords to big-endian order
+
+ VLM 0(R6), V9, V12 // 64-bytes into V9..V16
+ ADD $64, R6
+ VPDI $0x4, V9, V9, V9 // flip the doublewords to big-endian order
+ VPDI $0x4, V10, V10, V10 // flip the doublewords to big-endian order
+
+ VACCCQ V1, V9, V0, V25
+ VACQ V1, V9, V0, V17
+ VACCCQ V2, V10, V25, V26
+ VACQ V2, V10, V25, V18
+
+ VLM 0(R5), V5, V6 // 32-bytes into V1..V8
+ VLM 0(R6), V13, V14 // 32-bytes into V9..V16
+ ADD $32, R5
+ ADD $32, R6
+
+ VPDI $0x4, V3, V3, V3 // flip the doublewords to big-endian order
+ VPDI $0x4, V4, V4, V4 // flip the doublewords to big-endian order
+ VPDI $0x4, V11, V11, V11 // flip the doublewords to big-endian order
+ VPDI $0x4, V12, V12, V12 // flip the doublewords to big-endian order
+
+ VACCCQ V3, V11, V26, V27
+ VACQ V3, V11, V26, V19
+ VACCCQ V4, V12, V27, V28
+ VACQ V4, V12, V27, V20
+
+ VLM 0(R5), V7, V8 // 32-bytes into V1..V8
+ VLM 0(R6), V15, V16 // 32-bytes into V9..V16
+ ADD $32, R5
+ ADD $32, R6
+
+ VPDI $0x4, V5, V5, V5 // flip the doublewords to big-endian order
+ VPDI $0x4, V6, V6, V6 // flip the doublewords to big-endian order
+ VPDI $0x4, V13, V13, V13 // flip the doublewords to big-endian order
+ VPDI $0x4, V14, V14, V14 // flip the doublewords to big-endian order
+
+ VACCCQ V5, V13, V28, V29
+ VACQ V5, V13, V28, V21
+ VACCCQ V6, V14, V29, V30
+ VACQ V6, V14, V29, V22
+
+ VPDI $0x4, V7, V7, V7 // flip the doublewords to big-endian order
+ VPDI $0x4, V8, V8, V8 // flip the doublewords to big-endian order
+ VPDI $0x4, V15, V15, V15 // flip the doublewords to big-endian order
+ VPDI $0x4, V16, V16, V16 // flip the doublewords to big-endian order
+
+ VACCCQ V7, V15, V30, V31
+ VACQ V7, V15, V30, V23
+ VACCCQ V8, V16, V31, V0 // V0 has carry-over
+ VACQ V8, V16, V31, V24
+
+ VPDI $0x4, V17, V17, V17 // flip the doublewords to big-endian order
+ VPDI $0x4, V18, V18, V18 // flip the doublewords to big-endian order
+ VPDI $0x4, V19, V19, V19 // flip the doublewords to big-endian order
+ VPDI $0x4, V20, V20, V20 // flip the doublewords to big-endian order
+ VPDI $0x4, V21, V21, V21 // flip the doublewords to big-endian order
+ VPDI $0x4, V22, V22, V22 // flip the doublewords to big-endian order
+ VPDI $0x4, V23, V23, V23 // flip the doublewords to big-endian order
+ VPDI $0x4, V24, V24, V24 // flip the doublewords to big-endian order
+ VSTM V17, V24, 0(R7) // 128-bytes into z
+ ADD $128, R7
+ ADD $128, R10 // i += 16
+ SUB $16, R3 // n -= 16
+ BGE UU1 // if n >= 0 goto U1
+ VLGVG $1, V0, R4 // put cf into R4
+ NEG R4, R4 // save cf
+
+A1:
+ ADD $12, R3 // n += 16
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ BLT v1 // if n < 0 goto v1
+
+U1: // n >= 0
+ // regular loop body unrolled 4x
+ MOVD 0(R8)(R10*1), R5
+ MOVD 8(R8)(R10*1), R6
+ MOVD 16(R8)(R10*1), R7
+ MOVD 24(R8)(R10*1), R1
+ ADDC R4, R4 // restore CF
+ MOVD 0(R9)(R10*1), R11
+ ADDE R11, R5
+ MOVD 8(R9)(R10*1), R11
+ ADDE R11, R6
+ MOVD 16(R9)(R10*1), R11
+ ADDE R11, R7
+ MOVD 24(R9)(R10*1), R11
+ ADDE R11, R1
+ MOVD R0, R4
+ ADDE R4, R4 // save CF
+ NEG R4, R4
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R6, 8(R2)(R10*1)
+ MOVD R7, 16(R2)(R10*1)
+ MOVD R1, 24(R2)(R10*1)
+
+ ADD $32, R10 // i += 4
+ SUB $4, R3 // n -= 4
+ BGE U1 // if n >= 0 goto U1
+
+v1:
+ ADD $4, R3 // n += 4
+ BLE E1 // if n <= 0 goto E1
+
+L1: // n > 0
+ ADDC R4, R4 // restore CF
+ MOVD 0(R8)(R10*1), R5
+ MOVD 0(R9)(R10*1), R11
+ ADDE R11, R5
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R0, R4
+ ADDE R4, R4 // save CF
+ NEG R4, R4
+
+ ADD $8, R10 // i++
+ SUB $1, R3 // n--
+ BGT L1 // if n > 0 goto L1
+
+E1:
+ NEG R4, R4
+ MOVD R4, c+72(FP) // return c
+ RET
+
+TEXT ·addVV_novec(SB), NOSPLIT, $0
+novec:
+ MOVD z_len+8(FP), R3
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R2
+
+ MOVD $0, R4 // c = 0
+ MOVD $0, R0 // make sure it's zero
+ MOVD $0, R10 // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUB $4, R3 // n -= 4
+ BLT v1n // if n < 0 goto v1n
+
+U1n: // n >= 0
+ // regular loop body unrolled 4x
+ MOVD 0(R8)(R10*1), R5
+ MOVD 8(R8)(R10*1), R6
+ MOVD 16(R8)(R10*1), R7
+ MOVD 24(R8)(R10*1), R1
+ ADDC R4, R4 // restore CF
+ MOVD 0(R9)(R10*1), R11
+ ADDE R11, R5
+ MOVD 8(R9)(R10*1), R11
+ ADDE R11, R6
+ MOVD 16(R9)(R10*1), R11
+ ADDE R11, R7
+ MOVD 24(R9)(R10*1), R11
+ ADDE R11, R1
+ MOVD R0, R4
+ ADDE R4, R4 // save CF
+ NEG R4, R4
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R6, 8(R2)(R10*1)
+ MOVD R7, 16(R2)(R10*1)
+ MOVD R1, 24(R2)(R10*1)
+
+ ADD $32, R10 // i += 4
+ SUB $4, R3 // n -= 4
+ BGE U1n // if n >= 0 goto U1n
+
+v1n:
+ ADD $4, R3 // n += 4
+ BLE E1n // if n <= 0 goto E1n
+
+L1n: // n > 0
+ ADDC R4, R4 // restore CF
+ MOVD 0(R8)(R10*1), R5
+ MOVD 0(R9)(R10*1), R11
+ ADDE R11, R5
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R0, R4
+ ADDE R4, R4 // save CF
+ NEG R4, R4
+
+ ADD $8, R10 // i++
+ SUB $1, R3 // n--
+ BGT L1n // if n > 0 goto L1n
+
+E1n:
+ NEG R4, R4
+ MOVD R4, c+72(FP) // return c
+ RET
+
+TEXT ·subVV(SB), NOSPLIT, $0
+ MOVD subvectorfacility+0x00(SB), R1
+ BR (R1)
+
+TEXT ·subVV_check(SB), NOSPLIT, $0
+ MOVB ·hasVX(SB), R1
+ CMPBEQ R1, $1, vectorimpl // vectorfacility = 1, vector supported
+ MOVD $subvectorfacility+0x00(SB), R1
+ MOVD $·subVV_novec(SB), R2
+ MOVD R2, 0(R1)
+
+ // MOVD $·subVV_novec(SB), 0(R1)
+ BR ·subVV_novec(SB)
+
+vectorimpl:
+ MOVD $subvectorfacility+0x00(SB), R1
+ MOVD $·subVV_vec(SB), R2
+ MOVD R2, 0(R1)
+
+ // MOVD $·subVV_vec(SB), 0(R1)
+ BR ·subVV_vec(SB)
+
+GLOBL subvectorfacility+0x00(SB), NOPTR, $8
+DATA subvectorfacility+0x00(SB)/8, $·subVV_check(SB)
+
+// DI = R3, CX = R4, SI = r10, r8 = r8, r9=r9, r10 = r2, r11 = r5, r12 = r6, r13 = r7, r14 = r1 (R0 set to 0) + use R11
+// func subVV(z, x, y []Word) (c Word)
+// (same as addVV except for SUBC/SUBE instead of ADDC/ADDE and label names)
+TEXT ·subVV_vec(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R3
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R2
+ MOVD $0, R4 // c = 0
+ MOVD $0, R0 // make sure it's zero
+ MOVD $0, R10 // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUB $4, R3 // n -= 4
+ BLT v1 // if n < 0 goto v1
+ SUB $12, R3 // n -= 16
+ BLT A1 // if n < 0 goto A1
+
+ MOVD R8, R5
+ MOVD R9, R6
+ MOVD R2, R7
+
+ // n >= 0
+ // regular loop body unrolled 16x
+ VZERO V0 // cf = 0
+ MOVD $1, R4 // for 390 subtraction cf starts as 1 (no borrow)
+ VLVGG $1, R4, V0 // put carry into V0
+
+UU1:
+ VLM 0(R5), V1, V4 // 64-bytes into V1..V8
+ ADD $64, R5
+ VPDI $0x4, V1, V1, V1 // flip the doublewords to big-endian order
+ VPDI $0x4, V2, V2, V2 // flip the doublewords to big-endian order
+
+ VLM 0(R6), V9, V12 // 64-bytes into V9..V16
+ ADD $64, R6
+ VPDI $0x4, V9, V9, V9 // flip the doublewords to big-endian order
+ VPDI $0x4, V10, V10, V10 // flip the doublewords to big-endian order
+
+ VSBCBIQ V1, V9, V0, V25
+ VSBIQ V1, V9, V0, V17
+ VSBCBIQ V2, V10, V25, V26
+ VSBIQ V2, V10, V25, V18
+
+ VLM 0(R5), V5, V6 // 32-bytes into V1..V8
+ VLM 0(R6), V13, V14 // 32-bytes into V9..V16
+ ADD $32, R5
+ ADD $32, R6
+
+ VPDI $0x4, V3, V3, V3 // flip the doublewords to big-endian order
+ VPDI $0x4, V4, V4, V4 // flip the doublewords to big-endian order
+ VPDI $0x4, V11, V11, V11 // flip the doublewords to big-endian order
+ VPDI $0x4, V12, V12, V12 // flip the doublewords to big-endian order
+
+ VSBCBIQ V3, V11, V26, V27
+ VSBIQ V3, V11, V26, V19
+ VSBCBIQ V4, V12, V27, V28
+ VSBIQ V4, V12, V27, V20
+
+ VLM 0(R5), V7, V8 // 32-bytes into V1..V8
+ VLM 0(R6), V15, V16 // 32-bytes into V9..V16
+ ADD $32, R5
+ ADD $32, R6
+
+ VPDI $0x4, V5, V5, V5 // flip the doublewords to big-endian order
+ VPDI $0x4, V6, V6, V6 // flip the doublewords to big-endian order
+ VPDI $0x4, V13, V13, V13 // flip the doublewords to big-endian order
+ VPDI $0x4, V14, V14, V14 // flip the doublewords to big-endian order
+
+ VSBCBIQ V5, V13, V28, V29
+ VSBIQ V5, V13, V28, V21
+ VSBCBIQ V6, V14, V29, V30
+ VSBIQ V6, V14, V29, V22
+
+ VPDI $0x4, V7, V7, V7 // flip the doublewords to big-endian order
+ VPDI $0x4, V8, V8, V8 // flip the doublewords to big-endian order
+ VPDI $0x4, V15, V15, V15 // flip the doublewords to big-endian order
+ VPDI $0x4, V16, V16, V16 // flip the doublewords to big-endian order
+
+ VSBCBIQ V7, V15, V30, V31
+ VSBIQ V7, V15, V30, V23
+ VSBCBIQ V8, V16, V31, V0 // V0 has carry-over
+ VSBIQ V8, V16, V31, V24
+
+ VPDI $0x4, V17, V17, V17 // flip the doublewords to big-endian order
+ VPDI $0x4, V18, V18, V18 // flip the doublewords to big-endian order
+ VPDI $0x4, V19, V19, V19 // flip the doublewords to big-endian order
+ VPDI $0x4, V20, V20, V20 // flip the doublewords to big-endian order
+ VPDI $0x4, V21, V21, V21 // flip the doublewords to big-endian order
+ VPDI $0x4, V22, V22, V22 // flip the doublewords to big-endian order
+ VPDI $0x4, V23, V23, V23 // flip the doublewords to big-endian order
+ VPDI $0x4, V24, V24, V24 // flip the doublewords to big-endian order
+ VSTM V17, V24, 0(R7) // 128-bytes into z
+ ADD $128, R7
+ ADD $128, R10 // i += 16
+ SUB $16, R3 // n -= 16
+ BGE UU1 // if n >= 0 goto U1
+ VLGVG $1, V0, R4 // put cf into R4
+ SUB $1, R4 // save cf
+
+A1:
+ ADD $12, R3 // n += 16
+ BLT v1 // if n < 0 goto v1
+
+U1: // n >= 0
+ // regular loop body unrolled 4x
+ MOVD 0(R8)(R10*1), R5
+ MOVD 8(R8)(R10*1), R6
+ MOVD 16(R8)(R10*1), R7
+ MOVD 24(R8)(R10*1), R1
+ MOVD R0, R11
+ SUBC R4, R11 // restore CF
+ MOVD 0(R9)(R10*1), R11
+ SUBE R11, R5
+ MOVD 8(R9)(R10*1), R11
+ SUBE R11, R6
+ MOVD 16(R9)(R10*1), R11
+ SUBE R11, R7
+ MOVD 24(R9)(R10*1), R11
+ SUBE R11, R1
+ MOVD R0, R4
+ SUBE R4, R4 // save CF
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R6, 8(R2)(R10*1)
+ MOVD R7, 16(R2)(R10*1)
+ MOVD R1, 24(R2)(R10*1)
+
+ ADD $32, R10 // i += 4
+ SUB $4, R3 // n -= 4
+ BGE U1 // if n >= 0 goto U1n
+
+v1:
+ ADD $4, R3 // n += 4
+ BLE E1 // if n <= 0 goto E1
+
+L1: // n > 0
+ MOVD R0, R11
+ SUBC R4, R11 // restore CF
+ MOVD 0(R8)(R10*1), R5
+ MOVD 0(R9)(R10*1), R11
+ SUBE R11, R5
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R0, R4
+ SUBE R4, R4 // save CF
+
+ ADD $8, R10 // i++
+ SUB $1, R3 // n--
+ BGT L1 // if n > 0 goto L1n
+
+E1:
+ NEG R4, R4
+ MOVD R4, c+72(FP) // return c
+ RET
+
+// DI = R3, CX = R4, SI = r10, r8 = r8, r9=r9, r10 = r2, r11 = r5, r12 = r6, r13 = r7, r14 = r1 (R0 set to 0) + use R11
+// func subVV(z, x, y []Word) (c Word)
+// (same as addVV except for SUBC/SUBE instead of ADDC/ADDE and label names)
+TEXT ·subVV_novec(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R3
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z+0(FP), R2
+
+ MOVD $0, R4 // c = 0
+ MOVD $0, R0 // make sure it's zero
+ MOVD $0, R10 // i = 0
+
+ // s/JL/JMP/ below to disable the unrolled loop
+ SUB $4, R3 // n -= 4
+ BLT v1 // if n < 0 goto v1
+
+U1: // n >= 0
+ // regular loop body unrolled 4x
+ MOVD 0(R8)(R10*1), R5
+ MOVD 8(R8)(R10*1), R6
+ MOVD 16(R8)(R10*1), R7
+ MOVD 24(R8)(R10*1), R1
+ MOVD R0, R11
+ SUBC R4, R11 // restore CF
+ MOVD 0(R9)(R10*1), R11
+ SUBE R11, R5
+ MOVD 8(R9)(R10*1), R11
+ SUBE R11, R6
+ MOVD 16(R9)(R10*1), R11
+ SUBE R11, R7
+ MOVD 24(R9)(R10*1), R11
+ SUBE R11, R1
+ MOVD R0, R4
+ SUBE R4, R4 // save CF
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R6, 8(R2)(R10*1)
+ MOVD R7, 16(R2)(R10*1)
+ MOVD R1, 24(R2)(R10*1)
+
+ ADD $32, R10 // i += 4
+ SUB $4, R3 // n -= 4
+ BGE U1 // if n >= 0 goto U1
+
+v1:
+ ADD $4, R3 // n += 4
+ BLE E1 // if n <= 0 goto E1
+
+L1: // n > 0
+ MOVD R0, R11
+ SUBC R4, R11 // restore CF
+ MOVD 0(R8)(R10*1), R5
+ MOVD 0(R9)(R10*1), R11
+ SUBE R11, R5
+ MOVD R5, 0(R2)(R10*1)
+ MOVD R0, R4
+ SUBE R4, R4 // save CF
+
+ ADD $8, R10 // i++
+ SUB $1, R3 // n--
+ BGT L1 // if n > 0 goto L1
+
+E1:
+ NEG R4, R4
+ MOVD R4, c+72(FP) // return c
+ RET
+
+TEXT ·addVW(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R5 // length of z
+ MOVD x+24(FP), R6
+ MOVD y+48(FP), R7 // c = y
+ MOVD z+0(FP), R8
+
+ CMPBEQ R5, $0, returnC // if len(z) == 0, we can have an early return
+
+ // Add the first two words, and determine which path (copy path or loop path) to take based on the carry flag.
+ ADDC 0(R6), R7
+ MOVD R7, 0(R8)
+ CMPBEQ R5, $1, returnResult // len(z) == 1
+ MOVD $0, R9
+ ADDE 8(R6), R9
+ MOVD R9, 8(R8)
+ CMPBEQ R5, $2, returnResult // len(z) == 2
+
+ // Update the counters
+ MOVD $16, R12 // i = 2
+ MOVD $-2(R5), R5 // n = n - 2
+
+loopOverEachWord:
+ BRC $12, copySetup // carry = 0, copy the rest
+ MOVD $1, R9
+
+ // Originally we used the carry flag generated in the previous iteration
+ // (i.e: ADDE could be used here to do the addition). However, since we
+ // already know carry is 1 (otherwise we will go to copy section), we can use
+ // ADDC here so the current iteration does not depend on the carry flag
+ // generated in the previous iteration. This could be useful when branch prediction happens.
+ ADDC 0(R6)(R12*1), R9
+ MOVD R9, 0(R8)(R12*1) // z[i] = x[i] + c
+
+ MOVD $8(R12), R12 // i++
+ BRCTG R5, loopOverEachWord // n--
+
+// Return the current carry value
+returnResult:
+ MOVD $0, R0
+ ADDE R0, R0
+ MOVD R0, c+56(FP)
+ RET
+
+// Update position of x(R6) and z(R8) based on the current counter value and perform copying.
+// With the assumption that x and z will not overlap with each other or x and z will
+// point to same memory region, we can use a faster version of copy using only MVC here.
+// In the following implementation, we have three copy loops, each copying a word, 4 words, and
+// 32 words at a time. Via benchmarking, this implementation is faster than calling runtime·memmove.
+copySetup:
+ ADD R12, R6
+ ADD R12, R8
+
+ CMPBGE R5, $4, mediumLoop
+
+smallLoop: // does a loop unrolling to copy word when n < 4
+ CMPBEQ R5, $0, returnZero
+ MVC $8, 0(R6), 0(R8)
+ CMPBEQ R5, $1, returnZero
+ MVC $8, 8(R6), 8(R8)
+ CMPBEQ R5, $2, returnZero
+ MVC $8, 16(R6), 16(R8)
+
+returnZero:
+ MOVD $0, c+56(FP) // return 0 as carry
+ RET
+
+mediumLoop:
+ CMPBLT R5, $4, smallLoop
+ CMPBLT R5, $32, mediumLoopBody
+
+largeLoop: // Copying 256 bytes at a time.
+ MVC $256, 0(R6), 0(R8)
+ MOVD $256(R6), R6
+ MOVD $256(R8), R8
+ MOVD $-32(R5), R5
+ CMPBGE R5, $32, largeLoop
+ BR mediumLoop
+
+mediumLoopBody: // Copying 32 bytes at a time
+ MVC $32, 0(R6), 0(R8)
+ MOVD $32(R6), R6
+ MOVD $32(R8), R8
+ MOVD $-4(R5), R5
+ CMPBGE R5, $4, mediumLoopBody
+ BR smallLoop
+
+returnC:
+ MOVD R7, c+56(FP)
+ RET
+
+TEXT ·subVW(SB), NOSPLIT, $0
+ MOVD z_len+8(FP), R5
+ MOVD x+24(FP), R6
+ MOVD y+48(FP), R7 // The borrow bit passed in
+ MOVD z+0(FP), R8
+ MOVD $0, R0 // R0 is a temporary variable used during computation. Ensure it has zero in it.
+
+ CMPBEQ R5, $0, returnC // len(z) == 0, have an early return
+
+ // Subtract the first two words, and determine which path (copy path or loop path) to take based on the borrow flag
+ MOVD 0(R6), R9
+ SUBC R7, R9
+ MOVD R9, 0(R8)
+ CMPBEQ R5, $1, returnResult
+ MOVD 8(R6), R9
+ SUBE R0, R9
+ MOVD R9, 8(R8)
+ CMPBEQ R5, $2, returnResult
+
+ // Update the counters
+ MOVD $16, R12 // i = 2
+ MOVD $-2(R5), R5 // n = n - 2
+
+loopOverEachWord:
+ BRC $3, copySetup // no borrow, copy the rest
+ MOVD 0(R6)(R12*1), R9
+
+ // Originally we used the borrow flag generated in the previous iteration
+ // (i.e: SUBE could be used here to do the subtraction). However, since we
+ // already know borrow is 1 (otherwise we will go to copy section), we can
+ // use SUBC here so the current iteration does not depend on the borrow flag
+ // generated in the previous iteration. This could be useful when branch prediction happens.
+ SUBC $1, R9
+ MOVD R9, 0(R8)(R12*1) // z[i] = x[i] - 1
+
+ MOVD $8(R12), R12 // i++
+ BRCTG R5, loopOverEachWord // n--
+
+// return the current borrow value
+returnResult:
+ SUBE R0, R0
+ NEG R0, R0
+ MOVD R0, c+56(FP)
+ RET
+
+// Update position of x(R6) and z(R8) based on the current counter value and perform copying.
+// With the assumption that x and z will not overlap with each other or x and z will
+// point to same memory region, we can use a faster version of copy using only MVC here.
+// In the following implementation, we have three copy loops, each copying a word, 4 words, and
+// 32 words at a time. Via benchmarking, this implementation is faster than calling runtime·memmove.
+copySetup:
+ ADD R12, R6
+ ADD R12, R8
+
+ CMPBGE R5, $4, mediumLoop
+
+smallLoop: // does a loop unrolling to copy word when n < 4
+ CMPBEQ R5, $0, returnZero
+ MVC $8, 0(R6), 0(R8)
+ CMPBEQ R5, $1, returnZero
+ MVC $8, 8(R6), 8(R8)
+ CMPBEQ R5, $2, returnZero
+ MVC $8, 16(R6), 16(R8)
+
+returnZero:
+ MOVD $0, c+56(FP) // return 0 as borrow
+ RET
+
+mediumLoop:
+ CMPBLT R5, $4, smallLoop
+ CMPBLT R5, $32, mediumLoopBody
+
+largeLoop: // Copying 256 bytes at a time
+ MVC $256, 0(R6), 0(R8)
+ MOVD $256(R6), R6
+ MOVD $256(R8), R8
+ MOVD $-32(R5), R5
+ CMPBGE R5, $32, largeLoop
+ BR mediumLoop
+
+mediumLoopBody: // Copying 32 bytes at a time
+ MVC $32, 0(R6), 0(R8)
+ MOVD $32(R6), R6
+ MOVD $32(R8), R8
+ MOVD $-4(R5), R5
+ CMPBGE R5, $4, mediumLoopBody
+ BR smallLoop
+
+returnC:
+ MOVD R7, c+56(FP)
+ RET
+
+// func shlVU(z, x []Word, s uint) (c Word)
+TEXT ·shlVU(SB), NOSPLIT, $0
+ BR ·shlVU_g(SB)
+
+// func shrVU(z, x []Word, s uint) (c Word)
+TEXT ·shrVU(SB), NOSPLIT, $0
+ BR ·shrVU_g(SB)
+
+// CX = R4, r8 = r8, r9=r9, r10 = r2, r11 = r5, DX = r3, AX = r6, BX = R1, (R0 set to 0) + use R11 + use R7 for i
+// func mulAddVWW(z, x []Word, y, r Word) (c Word)
+TEXT ·mulAddVWW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R2
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD r+56(FP), R4 // c = r
+ MOVD z_len+8(FP), R5
+ MOVD $0, R1 // i = 0
+ MOVD $0, R7 // i*8 = 0
+ MOVD $0, R0 // make sure it's zero
+ BR E5
+
+L5:
+ MOVD (R8)(R1*1), R6
+ MULHDU R9, R6
+ ADDC R4, R11 // add to low order bits
+ ADDE R0, R6
+ MOVD R11, (R2)(R1*1)
+ MOVD R6, R4
+ ADD $8, R1 // i*8 + 8
+ ADD $1, R7 // i++
+
+E5:
+ CMPBLT R7, R5, L5 // i < n
+
+ MOVD R4, c+64(FP)
+ RET
+
+// func addMulVVW(z, x []Word, y Word) (c Word)
+// CX = R4, r8 = r8, r9=r9, r10 = r2, r11 = r5, AX = r11, DX = R6, r12=r12, BX = R1, (R0 set to 0) + use R11 + use R7 for i
+TEXT ·addMulVVW(SB), NOSPLIT, $0
+ MOVD z+0(FP), R2
+ MOVD x+24(FP), R8
+ MOVD y+48(FP), R9
+ MOVD z_len+8(FP), R5
+
+ MOVD $0, R1 // i*8 = 0
+ MOVD $0, R7 // i = 0
+ MOVD $0, R0 // make sure it's zero
+ MOVD $0, R4 // c = 0
+
+ MOVD R5, R12
+ AND $-2, R12
+ CMPBGE R5, $2, A6
+ BR E6
+
+A6:
+ MOVD (R8)(R1*1), R6
+ MULHDU R9, R6
+ MOVD (R2)(R1*1), R10
+ ADDC R10, R11 // add to low order bits
+ ADDE R0, R6
+ ADDC R4, R11
+ ADDE R0, R6
+ MOVD R6, R4
+ MOVD R11, (R2)(R1*1)
+
+ MOVD (8)(R8)(R1*1), R6
+ MULHDU R9, R6
+ MOVD (8)(R2)(R1*1), R10
+ ADDC R10, R11 // add to low order bits
+ ADDE R0, R6
+ ADDC R4, R11
+ ADDE R0, R6
+ MOVD R6, R4
+ MOVD R11, (8)(R2)(R1*1)
+
+ ADD $16, R1 // i*8 + 8
+ ADD $2, R7 // i++
+
+ CMPBLT R7, R12, A6
+ BR E6
+
+L6:
+ MOVD (R8)(R1*1), R6
+ MULHDU R9, R6
+ MOVD (R2)(R1*1), R10
+ ADDC R10, R11 // add to low order bits
+ ADDE R0, R6
+ ADDC R4, R11
+ ADDE R0, R6
+ MOVD R6, R4
+ MOVD R11, (R2)(R1*1)
+
+ ADD $8, R1 // i*8 + 8
+ ADD $1, R7 // i++
+
+E6:
+ CMPBLT R7, R5, L6 // i < n
+
+ MOVD R4, c+56(FP)
+ RET
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_s390x_test.go b/platform/dbops/binaries/go/go/src/math/big/arith_s390x_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b91cc1393fb285a792969b18b72f6bbb1377dad
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_s390x_test.go
@@ -0,0 +1,32 @@
+// 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 s390x && !math_big_pure_go
+
+package big
+
+import (
+ "testing"
+)
+
+// Tests whether the non vector routines are working, even when the tests are run on a
+// vector-capable machine
+
+func TestFunVVnovec(t *testing.T) {
+ if hasVX {
+ for _, a := range sumVV {
+ arg := a
+ testFunVV(t, "addVV_novec", addVV_novec, arg)
+
+ arg = argVV{a.z, a.y, a.x, a.c}
+ testFunVV(t, "addVV_novec symmetric", addVV_novec, arg)
+
+ arg = argVV{a.x, a.z, a.y, a.c}
+ testFunVV(t, "subVV_novec", subVV_novec, arg)
+
+ arg = argVV{a.y, a.z, a.x, a.c}
+ testFunVV(t, "subVV_novec symmetric", subVV_novec, arg)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_test.go b/platform/dbops/binaries/go/go/src/math/big/arith_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..64225bbd53661ce9ad1fd034c5d135bf6c4caafa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_test.go
@@ -0,0 +1,697 @@
+// 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 big
+
+import (
+ "fmt"
+ "internal/testenv"
+ "math/bits"
+ "math/rand"
+ "strings"
+ "testing"
+)
+
+var isRaceBuilder = strings.HasSuffix(testenv.Builder(), "-race")
+
+type funVV func(z, x, y []Word) (c Word)
+type argVV struct {
+ z, x, y nat
+ c Word
+}
+
+var sumVV = []argVV{
+ {},
+ {nat{0}, nat{0}, nat{0}, 0},
+ {nat{1}, nat{1}, nat{0}, 0},
+ {nat{0}, nat{_M}, nat{1}, 1},
+ {nat{80235}, nat{12345}, nat{67890}, 0},
+ {nat{_M - 1}, nat{_M}, nat{_M}, 1},
+ {nat{0, 0, 0, 0}, nat{_M, _M, _M, _M}, nat{1, 0, 0, 0}, 1},
+ {nat{0, 0, 0, _M}, nat{_M, _M, _M, _M - 1}, nat{1, 0, 0, 0}, 0},
+ {nat{0, 0, 0, 0}, nat{_M, 0, _M, 0}, nat{1, _M, 0, _M}, 1},
+}
+
+func testFunVV(t *testing.T, msg string, f funVV, a argVV) {
+ z := make(nat, len(a.z))
+ c := f(z, a.x, a.y)
+ for i, zi := range z {
+ if zi != a.z[i] {
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
+ }
+ }
+ if c != a.c {
+ t.Errorf("%s%+v\n\tgot c = %#x; want %#x", msg, a, c, a.c)
+ }
+}
+
+func TestFunVV(t *testing.T) {
+ for _, a := range sumVV {
+ arg := a
+ testFunVV(t, "addVV_g", addVV_g, arg)
+ testFunVV(t, "addVV", addVV, arg)
+
+ arg = argVV{a.z, a.y, a.x, a.c}
+ testFunVV(t, "addVV_g symmetric", addVV_g, arg)
+ testFunVV(t, "addVV symmetric", addVV, arg)
+
+ arg = argVV{a.x, a.z, a.y, a.c}
+ testFunVV(t, "subVV_g", subVV_g, arg)
+ testFunVV(t, "subVV", subVV, arg)
+
+ arg = argVV{a.y, a.z, a.x, a.c}
+ testFunVV(t, "subVV_g symmetric", subVV_g, arg)
+ testFunVV(t, "subVV symmetric", subVV, arg)
+ }
+}
+
+// Always the same seed for reproducible results.
+var rnd = rand.New(rand.NewSource(0))
+
+func rndW() Word {
+ return Word(rnd.Int63()<<1 | rnd.Int63n(2))
+}
+
+func rndV(n int) []Word {
+ v := make([]Word, n)
+ for i := range v {
+ v[i] = rndW()
+ }
+ return v
+}
+
+var benchSizes = []int{1, 2, 3, 4, 5, 1e1, 1e2, 1e3, 1e4, 1e5}
+
+func BenchmarkAddVV(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndV(n)
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ for i := 0; i < b.N; i++ {
+ addVV(z, x, y)
+ }
+ })
+ }
+}
+
+func BenchmarkSubVV(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndV(n)
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ for i := 0; i < b.N; i++ {
+ subVV(z, x, y)
+ }
+ })
+ }
+}
+
+type funVW func(z, x []Word, y Word) (c Word)
+type argVW struct {
+ z, x nat
+ y Word
+ c Word
+}
+
+var sumVW = []argVW{
+ {},
+ {nil, nil, 2, 2},
+ {nat{0}, nat{0}, 0, 0},
+ {nat{1}, nat{0}, 1, 0},
+ {nat{1}, nat{1}, 0, 0},
+ {nat{0}, nat{_M}, 1, 1},
+ {nat{0, 0, 0, 0}, nat{_M, _M, _M, _M}, 1, 1},
+ {nat{585}, nat{314}, 271, 0},
+}
+
+var lshVW = []argVW{
+ {},
+ {nat{0}, nat{0}, 0, 0},
+ {nat{0}, nat{0}, 1, 0},
+ {nat{0}, nat{0}, 20, 0},
+
+ {nat{_M}, nat{_M}, 0, 0},
+ {nat{_M << 1 & _M}, nat{_M}, 1, 1},
+ {nat{_M << 20 & _M}, nat{_M}, 20, _M >> (_W - 20)},
+
+ {nat{_M, _M, _M}, nat{_M, _M, _M}, 0, 0},
+ {nat{_M << 1 & _M, _M, _M}, nat{_M, _M, _M}, 1, 1},
+ {nat{_M << 20 & _M, _M, _M}, nat{_M, _M, _M}, 20, _M >> (_W - 20)},
+}
+
+var rshVW = []argVW{
+ {},
+ {nat{0}, nat{0}, 0, 0},
+ {nat{0}, nat{0}, 1, 0},
+ {nat{0}, nat{0}, 20, 0},
+
+ {nat{_M}, nat{_M}, 0, 0},
+ {nat{_M >> 1}, nat{_M}, 1, _M << (_W - 1) & _M},
+ {nat{_M >> 20}, nat{_M}, 20, _M << (_W - 20) & _M},
+
+ {nat{_M, _M, _M}, nat{_M, _M, _M}, 0, 0},
+ {nat{_M, _M, _M >> 1}, nat{_M, _M, _M}, 1, _M << (_W - 1) & _M},
+ {nat{_M, _M, _M >> 20}, nat{_M, _M, _M}, 20, _M << (_W - 20) & _M},
+}
+
+func testFunVW(t *testing.T, msg string, f funVW, a argVW) {
+ z := make(nat, len(a.z))
+ c := f(z, a.x, a.y)
+ for i, zi := range z {
+ if zi != a.z[i] {
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
+ }
+ }
+ if c != a.c {
+ t.Errorf("%s%+v\n\tgot c = %#x; want %#x", msg, a, c, a.c)
+ }
+}
+
+func testFunVWext(t *testing.T, msg string, f funVW, f_g funVW, a argVW) {
+ // using the result of addVW_g/subVW_g as golden
+ z_g := make(nat, len(a.z))
+ c_g := f_g(z_g, a.x, a.y)
+ c := f(a.z, a.x, a.y)
+
+ for i, zi := range a.z {
+ if zi != z_g[i] {
+ t.Errorf("%s\n\tgot z[%d] = %#x; want %#x", msg, i, zi, z_g[i])
+ break
+ }
+ }
+ if c != c_g {
+ t.Errorf("%s\n\tgot c = %#x; want %#x", msg, c, c_g)
+ }
+}
+
+func makeFunVW(f func(z, x []Word, s uint) (c Word)) funVW {
+ return func(z, x []Word, s Word) (c Word) {
+ return f(z, x, uint(s))
+ }
+}
+
+func TestFunVW(t *testing.T) {
+ for _, a := range sumVW {
+ arg := a
+ testFunVW(t, "addVW_g", addVW_g, arg)
+ testFunVW(t, "addVW", addVW, arg)
+
+ arg = argVW{a.x, a.z, a.y, a.c}
+ testFunVW(t, "subVW_g", subVW_g, arg)
+ testFunVW(t, "subVW", subVW, arg)
+ }
+
+ shlVW_g := makeFunVW(shlVU_g)
+ shlVW := makeFunVW(shlVU)
+ for _, a := range lshVW {
+ arg := a
+ testFunVW(t, "shlVU_g", shlVW_g, arg)
+ testFunVW(t, "shlVU", shlVW, arg)
+ }
+
+ shrVW_g := makeFunVW(shrVU_g)
+ shrVW := makeFunVW(shrVU)
+ for _, a := range rshVW {
+ arg := a
+ testFunVW(t, "shrVU_g", shrVW_g, arg)
+ testFunVW(t, "shrVU", shrVW, arg)
+ }
+}
+
+// Construct a vector comprising the same word, usually '0' or 'maximum uint'
+func makeWordVec(e Word, n int) []Word {
+ v := make([]Word, n)
+ for i := range v {
+ v[i] = e
+ }
+ return v
+}
+
+// Extended testing to addVW and subVW using various kinds of input data.
+// We utilize the results of addVW_g and subVW_g as golden reference to check
+// correctness.
+func TestFunVWExt(t *testing.T) {
+ // 32 is the current threshold that triggers an optimized version of
+ // calculation for large-sized vector, ensure we have sizes around it tested.
+ var vwSizes = []int{0, 1, 3, 4, 5, 8, 9, 23, 31, 32, 33, 34, 35, 36, 50, 120}
+ for _, n := range vwSizes {
+ // vector of random numbers, using the result of addVW_g/subVW_g as golden
+ x := rndV(n)
+ y := rndW()
+ z := make(nat, n)
+ arg := argVW{z, x, y, 0}
+ testFunVWext(t, "addVW, random inputs", addVW, addVW_g, arg)
+ testFunVWext(t, "subVW, random inputs", subVW, subVW_g, arg)
+
+ // vector of random numbers, but make 'x' and 'z' share storage
+ arg = argVW{x, x, y, 0}
+ testFunVWext(t, "addVW, random inputs, sharing storage", addVW, addVW_g, arg)
+ testFunVWext(t, "subVW, random inputs, sharing storage", subVW, subVW_g, arg)
+
+ // vector of maximum uint, to force carry flag set in each 'add'
+ y = ^Word(0)
+ x = makeWordVec(y, n)
+ arg = argVW{z, x, y, 0}
+ testFunVWext(t, "addVW, vector of max uint", addVW, addVW_g, arg)
+
+ // vector of '0', to force carry flag set in each 'sub'
+ x = makeWordVec(0, n)
+ arg = argVW{z, x, 1, 0}
+ testFunVWext(t, "subVW, vector of zero", subVW, subVW_g, arg)
+ }
+}
+
+type argVU struct {
+ d []Word // d is a Word slice, the input parameters x and z come from this array.
+ l uint // l is the length of the input parameters x and z.
+ xp uint // xp is the starting position of the input parameter x, x := d[xp:xp+l].
+ zp uint // zp is the starting position of the input parameter z, z := d[zp:zp+l].
+ s uint // s is the shift number.
+ r []Word // r is the expected output result z.
+ c Word // c is the expected return value.
+ m string // message.
+}
+
+var argshlVUIn = []Word{1, 2, 4, 8, 16, 32, 64, 0, 0, 0}
+var argshlVUr0 = []Word{1, 2, 4, 8, 16, 32, 64}
+var argshlVUr1 = []Word{2, 4, 8, 16, 32, 64, 128}
+var argshlVUrWm1 = []Word{1 << (_W - 1), 0, 1, 2, 4, 8, 16}
+
+var argshlVU = []argVU{
+ // test cases for shlVU
+ {[]Word{1, _M, _M, _M, _M, _M, 3 << (_W - 2), 0}, 7, 0, 0, 1, []Word{2, _M - 1, _M, _M, _M, _M, 1<<(_W-1) + 1}, 1, "complete overlap of shlVU"},
+ {[]Word{1, _M, _M, _M, _M, _M, 3 << (_W - 2), 0, 0, 0, 0}, 7, 0, 3, 1, []Word{2, _M - 1, _M, _M, _M, _M, 1<<(_W-1) + 1}, 1, "partial overlap by half of shlVU"},
+ {[]Word{1, _M, _M, _M, _M, _M, 3 << (_W - 2), 0, 0, 0, 0, 0, 0, 0}, 7, 0, 6, 1, []Word{2, _M - 1, _M, _M, _M, _M, 1<<(_W-1) + 1}, 1, "partial overlap by 1 Word of shlVU"},
+ {[]Word{1, _M, _M, _M, _M, _M, 3 << (_W - 2), 0, 0, 0, 0, 0, 0, 0, 0}, 7, 0, 7, 1, []Word{2, _M - 1, _M, _M, _M, _M, 1<<(_W-1) + 1}, 1, "no overlap of shlVU"},
+ // additional test cases with shift values of 0, 1 and (_W-1)
+ {argshlVUIn, 7, 0, 0, 0, argshlVUr0, 0, "complete overlap of shlVU and shift of 0"},
+ {argshlVUIn, 7, 0, 0, 1, argshlVUr1, 0, "complete overlap of shlVU and shift of 1"},
+ {argshlVUIn, 7, 0, 0, _W - 1, argshlVUrWm1, 32, "complete overlap of shlVU and shift of _W - 1"},
+ {argshlVUIn, 7, 0, 1, 0, argshlVUr0, 0, "partial overlap by 6 Words of shlVU and shift of 0"},
+ {argshlVUIn, 7, 0, 1, 1, argshlVUr1, 0, "partial overlap by 6 Words of shlVU and shift of 1"},
+ {argshlVUIn, 7, 0, 1, _W - 1, argshlVUrWm1, 32, "partial overlap by 6 Words of shlVU and shift of _W - 1"},
+ {argshlVUIn, 7, 0, 2, 0, argshlVUr0, 0, "partial overlap by 5 Words of shlVU and shift of 0"},
+ {argshlVUIn, 7, 0, 2, 1, argshlVUr1, 0, "partial overlap by 5 Words of shlVU and shift of 1"},
+ {argshlVUIn, 7, 0, 2, _W - 1, argshlVUrWm1, 32, "partial overlap by 5 Words of shlVU abd shift of _W - 1"},
+ {argshlVUIn, 7, 0, 3, 0, argshlVUr0, 0, "partial overlap by 4 Words of shlVU and shift of 0"},
+ {argshlVUIn, 7, 0, 3, 1, argshlVUr1, 0, "partial overlap by 4 Words of shlVU and shift of 1"},
+ {argshlVUIn, 7, 0, 3, _W - 1, argshlVUrWm1, 32, "partial overlap by 4 Words of shlVU and shift of _W - 1"},
+}
+
+var argshrVUIn = []Word{0, 0, 0, 1, 2, 4, 8, 16, 32, 64}
+var argshrVUr0 = []Word{1, 2, 4, 8, 16, 32, 64}
+var argshrVUr1 = []Word{0, 1, 2, 4, 8, 16, 32}
+var argshrVUrWm1 = []Word{4, 8, 16, 32, 64, 128, 0}
+
+var argshrVU = []argVU{
+ // test cases for shrVU
+ {[]Word{0, 3, _M, _M, _M, _M, _M, 1 << (_W - 1)}, 7, 1, 1, 1, []Word{1<<(_W-1) + 1, _M, _M, _M, _M, _M >> 1, 1 << (_W - 2)}, 1 << (_W - 1), "complete overlap of shrVU"},
+ {[]Word{0, 0, 0, 0, 3, _M, _M, _M, _M, _M, 1 << (_W - 1)}, 7, 4, 1, 1, []Word{1<<(_W-1) + 1, _M, _M, _M, _M, _M >> 1, 1 << (_W - 2)}, 1 << (_W - 1), "partial overlap by half of shrVU"},
+ {[]Word{0, 0, 0, 0, 0, 0, 0, 3, _M, _M, _M, _M, _M, 1 << (_W - 1)}, 7, 7, 1, 1, []Word{1<<(_W-1) + 1, _M, _M, _M, _M, _M >> 1, 1 << (_W - 2)}, 1 << (_W - 1), "partial overlap by 1 Word of shrVU"},
+ {[]Word{0, 0, 0, 0, 0, 0, 0, 0, 3, _M, _M, _M, _M, _M, 1 << (_W - 1)}, 7, 8, 1, 1, []Word{1<<(_W-1) + 1, _M, _M, _M, _M, _M >> 1, 1 << (_W - 2)}, 1 << (_W - 1), "no overlap of shrVU"},
+ // additional test cases with shift values of 0, 1 and (_W-1)
+ {argshrVUIn, 7, 3, 3, 0, argshrVUr0, 0, "complete overlap of shrVU and shift of 0"},
+ {argshrVUIn, 7, 3, 3, 1, argshrVUr1, 1 << (_W - 1), "complete overlap of shrVU and shift of 1"},
+ {argshrVUIn, 7, 3, 3, _W - 1, argshrVUrWm1, 2, "complete overlap of shrVU and shift of _W - 1"},
+ {argshrVUIn, 7, 3, 2, 0, argshrVUr0, 0, "partial overlap by 6 Words of shrVU and shift of 0"},
+ {argshrVUIn, 7, 3, 2, 1, argshrVUr1, 1 << (_W - 1), "partial overlap by 6 Words of shrVU and shift of 1"},
+ {argshrVUIn, 7, 3, 2, _W - 1, argshrVUrWm1, 2, "partial overlap by 6 Words of shrVU and shift of _W - 1"},
+ {argshrVUIn, 7, 3, 1, 0, argshrVUr0, 0, "partial overlap by 5 Words of shrVU and shift of 0"},
+ {argshrVUIn, 7, 3, 1, 1, argshrVUr1, 1 << (_W - 1), "partial overlap by 5 Words of shrVU and shift of 1"},
+ {argshrVUIn, 7, 3, 1, _W - 1, argshrVUrWm1, 2, "partial overlap by 5 Words of shrVU and shift of _W - 1"},
+ {argshrVUIn, 7, 3, 0, 0, argshrVUr0, 0, "partial overlap by 4 Words of shrVU and shift of 0"},
+ {argshrVUIn, 7, 3, 0, 1, argshrVUr1, 1 << (_W - 1), "partial overlap by 4 Words of shrVU and shift of 1"},
+ {argshrVUIn, 7, 3, 0, _W - 1, argshrVUrWm1, 2, "partial overlap by 4 Words of shrVU and shift of _W - 1"},
+}
+
+func testShiftFunc(t *testing.T, f func(z, x []Word, s uint) Word, a argVU) {
+ // work on copy of a.d to preserve the original data.
+ b := make([]Word, len(a.d))
+ copy(b, a.d)
+ z := b[a.zp : a.zp+a.l]
+ x := b[a.xp : a.xp+a.l]
+ c := f(z, x, a.s)
+ for i, zi := range z {
+ if zi != a.r[i] {
+ t.Errorf("d := %v, %s(d[%d:%d], d[%d:%d], %d)\n\tgot z[%d] = %#x; want %#x", a.d, a.m, a.zp, a.zp+a.l, a.xp, a.xp+a.l, a.s, i, zi, a.r[i])
+ break
+ }
+ }
+ if c != a.c {
+ t.Errorf("d := %v, %s(d[%d:%d], d[%d:%d], %d)\n\tgot c = %#x; want %#x", a.d, a.m, a.zp, a.zp+a.l, a.xp, a.xp+a.l, a.s, c, a.c)
+ }
+}
+
+func TestShiftOverlap(t *testing.T) {
+ for _, a := range argshlVU {
+ arg := a
+ testShiftFunc(t, shlVU, arg)
+ }
+
+ for _, a := range argshrVU {
+ arg := a
+ testShiftFunc(t, shrVU, arg)
+ }
+}
+
+func TestIssue31084(t *testing.T) {
+ // compute 10^n via 5^n << n.
+ const n = 165
+ p := nat(nil).expNN(nat{5}, nat{n}, nil, false)
+ p = p.shl(p, n)
+ got := string(p.utoa(10))
+ want := "1" + strings.Repeat("0", n)
+ if got != want {
+ t.Errorf("shl(%v, %v)\n\tgot %s\n\twant %s", p, n, got, want)
+ }
+}
+
+const issue42838Value = "159309191113245227702888039776771180559110455519261878607388585338616290151305816094308987472018268594098344692611135542392730712890625"
+
+func TestIssue42838(t *testing.T) {
+ const s = 192
+ z, _, _, _ := nat(nil).scan(strings.NewReader(issue42838Value), 0, false)
+ z = z.shl(z, s)
+ got := string(z.utoa(10))
+ want := "1" + strings.Repeat("0", s)
+ if got != want {
+ t.Errorf("shl(%v, %v)\n\tgot %s\n\twant %s", z, s, got, want)
+ }
+}
+
+func BenchmarkAddVW(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndW()
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _S))
+ for i := 0; i < b.N; i++ {
+ addVW(z, x, y)
+ }
+ })
+ }
+}
+
+// Benchmarking addVW using vector of maximum uint to force carry flag set
+func BenchmarkAddVWext(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ y := ^Word(0)
+ x := makeWordVec(y, n)
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _S))
+ for i := 0; i < b.N; i++ {
+ addVW(z, x, y)
+ }
+ })
+ }
+}
+
+func BenchmarkSubVW(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndW()
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _S))
+ for i := 0; i < b.N; i++ {
+ subVW(z, x, y)
+ }
+ })
+ }
+}
+
+// Benchmarking subVW using vector of zero to force carry flag set
+func BenchmarkSubVWext(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := makeWordVec(0, n)
+ y := Word(1)
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _S))
+ for i := 0; i < b.N; i++ {
+ subVW(z, x, y)
+ }
+ })
+ }
+}
+
+type funVWW func(z, x []Word, y, r Word) (c Word)
+type argVWW struct {
+ z, x nat
+ y, r Word
+ c Word
+}
+
+var prodVWW = []argVWW{
+ {},
+ {nat{0}, nat{0}, 0, 0, 0},
+ {nat{991}, nat{0}, 0, 991, 0},
+ {nat{0}, nat{_M}, 0, 0, 0},
+ {nat{991}, nat{_M}, 0, 991, 0},
+ {nat{0}, nat{0}, _M, 0, 0},
+ {nat{991}, nat{0}, _M, 991, 0},
+ {nat{1}, nat{1}, 1, 0, 0},
+ {nat{992}, nat{1}, 1, 991, 0},
+ {nat{22793}, nat{991}, 23, 0, 0},
+ {nat{22800}, nat{991}, 23, 7, 0},
+ {nat{0, 0, 0, 22793}, nat{0, 0, 0, 991}, 23, 0, 0},
+ {nat{7, 0, 0, 22793}, nat{0, 0, 0, 991}, 23, 7, 0},
+ {nat{0, 0, 0, 0}, nat{7893475, 7395495, 798547395, 68943}, 0, 0, 0},
+ {nat{991, 0, 0, 0}, nat{7893475, 7395495, 798547395, 68943}, 0, 991, 0},
+ {nat{0, 0, 0, 0}, nat{0, 0, 0, 0}, 894375984, 0, 0},
+ {nat{991, 0, 0, 0}, nat{0, 0, 0, 0}, 894375984, 991, 0},
+ {nat{_M << 1 & _M}, nat{_M}, 1 << 1, 0, _M >> (_W - 1)},
+ {nat{_M<<1&_M + 1}, nat{_M}, 1 << 1, 1, _M >> (_W - 1)},
+ {nat{_M << 7 & _M}, nat{_M}, 1 << 7, 0, _M >> (_W - 7)},
+ {nat{_M<<7&_M + 1<<6}, nat{_M}, 1 << 7, 1 << 6, _M >> (_W - 7)},
+ {nat{_M << 7 & _M, _M, _M, _M}, nat{_M, _M, _M, _M}, 1 << 7, 0, _M >> (_W - 7)},
+ {nat{_M<<7&_M + 1<<6, _M, _M, _M}, nat{_M, _M, _M, _M}, 1 << 7, 1 << 6, _M >> (_W - 7)},
+}
+
+func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) {
+ z := make(nat, len(a.z))
+ c := f(z, a.x, a.y, a.r)
+ for i, zi := range z {
+ if zi != a.z[i] {
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
+ }
+ }
+ if c != a.c {
+ t.Errorf("%s%+v\n\tgot c = %#x; want %#x", msg, a, c, a.c)
+ }
+}
+
+// TODO(gri) mulAddVWW and divWVW are symmetric operations but
+// their signature is not symmetric. Try to unify.
+
+type funWVW func(z []Word, xn Word, x []Word, y Word) (r Word)
+type argWVW struct {
+ z nat
+ xn Word
+ x nat
+ y Word
+ r Word
+}
+
+func testFunWVW(t *testing.T, msg string, f funWVW, a argWVW) {
+ z := make(nat, len(a.z))
+ r := f(z, a.xn, a.x, a.y)
+ for i, zi := range z {
+ if zi != a.z[i] {
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
+ }
+ }
+ if r != a.r {
+ t.Errorf("%s%+v\n\tgot r = %#x; want %#x", msg, a, r, a.r)
+ }
+}
+
+func TestFunVWW(t *testing.T) {
+ for _, a := range prodVWW {
+ arg := a
+ testFunVWW(t, "mulAddVWW_g", mulAddVWW_g, arg)
+ testFunVWW(t, "mulAddVWW", mulAddVWW, arg)
+
+ if a.y != 0 && a.r < a.y {
+ arg := argWVW{a.x, a.c, a.z, a.y, a.r}
+ testFunWVW(t, "divWVW", divWVW, arg)
+ }
+ }
+}
+
+var mulWWTests = []struct {
+ x, y Word
+ q, r Word
+}{
+ {_M, _M, _M - 1, 1},
+ // 32 bit only: {0xc47dfa8c, 50911, 0x98a4, 0x998587f4},
+}
+
+func TestMulWW(t *testing.T) {
+ for i, test := range mulWWTests {
+ q, r := mulWW(test.x, test.y)
+ if q != test.q || r != test.r {
+ t.Errorf("#%d got (%x, %x) want (%x, %x)", i, q, r, test.q, test.r)
+ }
+ }
+}
+
+var mulAddWWWTests = []struct {
+ x, y, c Word
+ q, r Word
+}{
+ // TODO(agl): These will only work on 64-bit platforms.
+ // {15064310297182388543, 0xe7df04d2d35d5d80, 13537600649892366549, 13644450054494335067, 10832252001440893781},
+ // {15064310297182388543, 0xdab2f18048baa68d, 13644450054494335067, 12869334219691522700, 14233854684711418382},
+ {_M, _M, 0, _M - 1, 1},
+ {_M, _M, _M, _M, 0},
+}
+
+func TestMulAddWWW(t *testing.T) {
+ for i, test := range mulAddWWWTests {
+ q, r := mulAddWWW_g(test.x, test.y, test.c)
+ if q != test.q || r != test.r {
+ t.Errorf("#%d got (%x, %x) want (%x, %x)", i, q, r, test.q, test.r)
+ }
+ }
+}
+
+var divWWTests = []struct {
+ x1, x0, y Word
+ q, r Word
+}{
+ {_M >> 1, 0, _M, _M >> 1, _M >> 1},
+ {_M - (1 << (_W - 2)), _M, 3 << (_W - 2), _M, _M - (1 << (_W - 2))},
+}
+
+const testsNumber = 1 << 16
+
+func TestDivWW(t *testing.T) {
+ i := 0
+ for i, test := range divWWTests {
+ rec := reciprocalWord(test.y)
+ q, r := divWW(test.x1, test.x0, test.y, rec)
+ if q != test.q || r != test.r {
+ t.Errorf("#%d got (%x, %x) want (%x, %x)", i, q, r, test.q, test.r)
+ }
+ }
+ //random tests
+ for ; i < testsNumber; i++ {
+ x1 := rndW()
+ x0 := rndW()
+ y := rndW()
+ if x1 >= y {
+ continue
+ }
+ rec := reciprocalWord(y)
+ qGot, rGot := divWW(x1, x0, y, rec)
+ qWant, rWant := bits.Div(uint(x1), uint(x0), uint(y))
+ if uint(qGot) != qWant || uint(rGot) != rWant {
+ t.Errorf("#%d got (%x, %x) want (%x, %x)", i, qGot, rGot, qWant, rWant)
+ }
+ }
+}
+
+func BenchmarkMulAddVWW(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ z := make([]Word, n+1)
+ x := rndV(n)
+ y := rndW()
+ r := rndW()
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ for i := 0; i < b.N; i++ {
+ mulAddVWW(z, x, y, r)
+ }
+ })
+ }
+}
+
+func BenchmarkAddMulVVW(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndW()
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ for i := 0; i < b.N; i++ {
+ addMulVVW(z, x, y)
+ }
+ })
+ }
+}
+func BenchmarkDivWVW(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ y := rndW()
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ for i := 0; i < b.N; i++ {
+ divWVW(z, 0, x, y)
+ }
+ })
+ }
+}
+
+func BenchmarkNonZeroShifts(b *testing.B) {
+ for _, n := range benchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ x := rndV(n)
+ s := uint(rand.Int63n(_W-2)) + 1 // avoid 0 and over-large shifts
+ z := make([]Word, n)
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ b.SetBytes(int64(n * _W))
+ b.Run("shrVU", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _ = shrVU(z, x, s)
+ }
+ })
+ b.Run("shlVU", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _ = shlVU(z, x, s)
+ }
+ })
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/arith_wasm.s b/platform/dbops/binaries/go/go/src/math/big/arith_wasm.s
new file mode 100644
index 0000000000000000000000000000000000000000..fd51031d8a02461f46e30378c5778e95c71c9b36
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/arith_wasm.s
@@ -0,0 +1,32 @@
+// 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 !math_big_pure_go
+
+#include "textflag.h"
+
+TEXT ·addVV(SB),NOSPLIT,$0
+ JMP ·addVV_g(SB)
+
+TEXT ·subVV(SB),NOSPLIT,$0
+ JMP ·subVV_g(SB)
+
+TEXT ·addVW(SB),NOSPLIT,$0
+ JMP ·addVW_g(SB)
+
+TEXT ·subVW(SB),NOSPLIT,$0
+ JMP ·subVW_g(SB)
+
+TEXT ·shlVU(SB),NOSPLIT,$0
+ JMP ·shlVU_g(SB)
+
+TEXT ·shrVU(SB),NOSPLIT,$0
+ JMP ·shrVU_g(SB)
+
+TEXT ·mulAddVWW(SB),NOSPLIT,$0
+ JMP ·mulAddVWW_g(SB)
+
+TEXT ·addMulVVW(SB),NOSPLIT,$0
+ JMP ·addMulVVW_g(SB)
+
diff --git a/platform/dbops/binaries/go/go/src/math/big/bits_test.go b/platform/dbops/binaries/go/go/src/math/big/bits_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..985b60bd4b742708775ac39c532e91ccefdcd8bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/bits_test.go
@@ -0,0 +1,224 @@
+// 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 the Bits type used for testing Float operations
+// via an independent (albeit slower) representations for floating-point
+// numbers.
+
+package big
+
+import (
+ "fmt"
+ "sort"
+ "testing"
+)
+
+// A Bits value b represents a finite floating-point number x of the form
+//
+// x = 2**b[0] + 2**b[1] + ... 2**b[len(b)-1]
+//
+// The order of slice elements is not significant. Negative elements may be
+// used to form fractions. A Bits value is normalized if each b[i] occurs at
+// most once. For instance Bits{0, 0, 1} is not normalized but represents the
+// same floating-point number as Bits{2}, which is normalized. The zero (nil)
+// value of Bits is a ready to use Bits value and represents the value 0.
+type Bits []int
+
+func (x Bits) add(y Bits) Bits {
+ return append(x, y...)
+}
+
+func (x Bits) mul(y Bits) Bits {
+ var p Bits
+ for _, x := range x {
+ for _, y := range y {
+ p = append(p, x+y)
+ }
+ }
+ return p
+}
+
+func TestMulBits(t *testing.T) {
+ for _, test := range []struct {
+ x, y, want Bits
+ }{
+ {nil, nil, nil},
+ {Bits{}, Bits{}, nil},
+ {Bits{0}, Bits{0}, Bits{0}},
+ {Bits{0}, Bits{1}, Bits{1}},
+ {Bits{1}, Bits{1, 2, 3}, Bits{2, 3, 4}},
+ {Bits{-1}, Bits{1}, Bits{0}},
+ {Bits{-10, -1, 0, 1, 10}, Bits{1, 2, 3}, Bits{-9, -8, -7, 0, 1, 2, 1, 2, 3, 2, 3, 4, 11, 12, 13}},
+ } {
+ got := fmt.Sprintf("%v", test.x.mul(test.y))
+ want := fmt.Sprintf("%v", test.want)
+ if got != want {
+ t.Errorf("%v * %v = %s; want %s", test.x, test.y, got, want)
+ }
+
+ }
+}
+
+// norm returns the normalized bits for x: It removes multiple equal entries
+// by treating them as an addition (e.g., Bits{5, 5} => Bits{6}), and it sorts
+// the result list for reproducible results.
+func (x Bits) norm() Bits {
+ m := make(map[int]bool)
+ for _, b := range x {
+ for m[b] {
+ m[b] = false
+ b++
+ }
+ m[b] = true
+ }
+ var z Bits
+ for b, set := range m {
+ if set {
+ z = append(z, b)
+ }
+ }
+ sort.Ints([]int(z))
+ return z
+}
+
+func TestNormBits(t *testing.T) {
+ for _, test := range []struct {
+ x, want Bits
+ }{
+ {nil, nil},
+ {Bits{}, Bits{}},
+ {Bits{0}, Bits{0}},
+ {Bits{0, 0}, Bits{1}},
+ {Bits{3, 1, 1}, Bits{2, 3}},
+ {Bits{10, 9, 8, 7, 6, 6}, Bits{11}},
+ } {
+ got := fmt.Sprintf("%v", test.x.norm())
+ want := fmt.Sprintf("%v", test.want)
+ if got != want {
+ t.Errorf("normBits(%v) = %s; want %s", test.x, got, want)
+ }
+
+ }
+}
+
+// round returns the Float value corresponding to x after rounding x
+// to prec bits according to mode.
+func (x Bits) round(prec uint, mode RoundingMode) *Float {
+ x = x.norm()
+
+ // determine range
+ var min, max int
+ for i, b := range x {
+ if i == 0 || b < min {
+ min = b
+ }
+ if i == 0 || b > max {
+ max = b
+ }
+ }
+ prec0 := uint(max + 1 - min)
+ if prec >= prec0 {
+ return x.Float()
+ }
+ // prec < prec0
+
+ // determine bit 0, rounding, and sticky bit, and result bits z
+ var bit0, rbit, sbit uint
+ var z Bits
+ r := max - int(prec)
+ for _, b := range x {
+ switch {
+ case b == r:
+ rbit = 1
+ case b < r:
+ sbit = 1
+ default:
+ // b > r
+ if b == r+1 {
+ bit0 = 1
+ }
+ z = append(z, b)
+ }
+ }
+
+ // round
+ f := z.Float() // rounded to zero
+ if mode == ToNearestAway {
+ panic("not yet implemented")
+ }
+ if mode == ToNearestEven && rbit == 1 && (sbit == 1 || sbit == 0 && bit0 != 0) || mode == AwayFromZero {
+ // round away from zero
+ f.SetMode(ToZero).SetPrec(prec)
+ f.Add(f, Bits{int(r) + 1}.Float())
+ }
+ return f
+}
+
+// Float returns the *Float z of the smallest possible precision such that
+// z = sum(2**bits[i]), with i = range bits. If multiple bits[i] are equal,
+// they are added: Bits{0, 1, 0}.Float() == 2**0 + 2**1 + 2**0 = 4.
+func (bits Bits) Float() *Float {
+ // handle 0
+ if len(bits) == 0 {
+ return new(Float)
+ }
+ // len(bits) > 0
+
+ // determine lsb exponent
+ var min int
+ for i, b := range bits {
+ if i == 0 || b < min {
+ min = b
+ }
+ }
+
+ // create bit pattern
+ x := NewInt(0)
+ for _, b := range bits {
+ badj := b - min
+ // propagate carry if necessary
+ for x.Bit(badj) != 0 {
+ x.SetBit(x, badj, 0)
+ badj++
+ }
+ x.SetBit(x, badj, 1)
+ }
+
+ // create corresponding float
+ z := new(Float).SetInt(x) // normalized
+ if e := int64(z.exp) + int64(min); MinExp <= e && e <= MaxExp {
+ z.exp = int32(e)
+ } else {
+ // this should never happen for our test cases
+ panic("exponent out of range")
+ }
+ return z
+}
+
+func TestFromBits(t *testing.T) {
+ for _, test := range []struct {
+ bits Bits
+ want string
+ }{
+ // all different bit numbers
+ {nil, "0"},
+ {Bits{0}, "0x.8p+1"},
+ {Bits{1}, "0x.8p+2"},
+ {Bits{-1}, "0x.8p+0"},
+ {Bits{63}, "0x.8p+64"},
+ {Bits{33, -30}, "0x.8000000000000001p+34"},
+ {Bits{255, 0}, "0x.8000000000000000000000000000000000000000000000000000000000000001p+256"},
+
+ // multiple equal bit numbers
+ {Bits{0, 0}, "0x.8p+2"},
+ {Bits{0, 0, 0, 0}, "0x.8p+3"},
+ {Bits{0, 1, 0}, "0x.8p+3"},
+ {append(Bits{2, 1, 0} /* 7 */, Bits{3, 1} /* 10 */ ...), "0x.88p+5" /* 17 */},
+ } {
+ f := test.bits.Float()
+ if got := f.Text('p', 0); got != test.want {
+ t.Errorf("setBits(%v) = %s; want %s", test.bits, got, test.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/calibrate_test.go b/platform/dbops/binaries/go/go/src/math/big/calibrate_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d85833aedef619937716a943f5ed2058009c868d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/calibrate_test.go
@@ -0,0 +1,173 @@
+// 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.
+
+// Calibration used to determine thresholds for using
+// different algorithms. Ideally, this would be converted
+// to go generate to create thresholds.go
+
+// This file prints execution times for the Mul benchmark
+// given different Karatsuba thresholds. The result may be
+// used to manually fine-tune the threshold constant. The
+// results are somewhat fragile; use repeated runs to get
+// a clear picture.
+
+// Calculates lower and upper thresholds for when basicSqr
+// is faster than standard multiplication.
+
+// Usage: go test -run='^TestCalibrate$' -v -calibrate
+
+package big
+
+import (
+ "flag"
+ "fmt"
+ "testing"
+ "time"
+)
+
+var calibrate = flag.Bool("calibrate", false, "run calibration test")
+
+const (
+ sqrModeMul = "mul(x, x)"
+ sqrModeBasic = "basicSqr(x)"
+ sqrModeKaratsuba = "karatsubaSqr(x)"
+)
+
+func TestCalibrate(t *testing.T) {
+ if !*calibrate {
+ return
+ }
+
+ computeKaratsubaThresholds()
+
+ // compute basicSqrThreshold where overhead becomes negligible
+ minSqr := computeSqrThreshold(10, 30, 1, 3, sqrModeMul, sqrModeBasic)
+ // compute karatsubaSqrThreshold where karatsuba is faster
+ maxSqr := computeSqrThreshold(200, 500, 10, 3, sqrModeBasic, sqrModeKaratsuba)
+ if minSqr != 0 {
+ fmt.Printf("found basicSqrThreshold = %d\n", minSqr)
+ } else {
+ fmt.Println("no basicSqrThreshold found")
+ }
+ if maxSqr != 0 {
+ fmt.Printf("found karatsubaSqrThreshold = %d\n", maxSqr)
+ } else {
+ fmt.Println("no karatsubaSqrThreshold found")
+ }
+}
+
+func karatsubaLoad(b *testing.B) {
+ BenchmarkMul(b)
+}
+
+// measureKaratsuba returns the time to run a Karatsuba-relevant benchmark
+// given Karatsuba threshold th.
+func measureKaratsuba(th int) time.Duration {
+ th, karatsubaThreshold = karatsubaThreshold, th
+ res := testing.Benchmark(karatsubaLoad)
+ karatsubaThreshold = th
+ return time.Duration(res.NsPerOp())
+}
+
+func computeKaratsubaThresholds() {
+ fmt.Printf("Multiplication times for varying Karatsuba thresholds\n")
+ fmt.Printf("(run repeatedly for good results)\n")
+
+ // determine Tk, the work load execution time using basic multiplication
+ Tb := measureKaratsuba(1e9) // th == 1e9 => Karatsuba multiplication disabled
+ fmt.Printf("Tb = %10s\n", Tb)
+
+ // thresholds
+ th := 4
+ th1 := -1
+ th2 := -1
+
+ var deltaOld time.Duration
+ for count := -1; count != 0 && th < 128; count-- {
+ // determine Tk, the work load execution time using Karatsuba multiplication
+ Tk := measureKaratsuba(th)
+
+ // improvement over Tb
+ delta := (Tb - Tk) * 100 / Tb
+
+ fmt.Printf("th = %3d Tk = %10s %4d%%", th, Tk, delta)
+
+ // determine break-even point
+ if Tk < Tb && th1 < 0 {
+ th1 = th
+ fmt.Print(" break-even point")
+ }
+
+ // determine diminishing return
+ if 0 < delta && delta < deltaOld && th2 < 0 {
+ th2 = th
+ fmt.Print(" diminishing return")
+ }
+ deltaOld = delta
+
+ fmt.Println()
+
+ // trigger counter
+ if th1 >= 0 && th2 >= 0 && count < 0 {
+ count = 10 // this many extra measurements after we got both thresholds
+ }
+
+ th++
+ }
+}
+
+func measureSqr(words, nruns int, mode string) time.Duration {
+ // more runs for better statistics
+ initBasicSqr, initKaratsubaSqr := basicSqrThreshold, karatsubaSqrThreshold
+
+ switch mode {
+ case sqrModeMul:
+ basicSqrThreshold = words + 1
+ case sqrModeBasic:
+ basicSqrThreshold, karatsubaSqrThreshold = words-1, words+1
+ case sqrModeKaratsuba:
+ karatsubaSqrThreshold = words - 1
+ }
+
+ var testval int64
+ for i := 0; i < nruns; i++ {
+ res := testing.Benchmark(func(b *testing.B) { benchmarkNatSqr(b, words) })
+ testval += res.NsPerOp()
+ }
+ testval /= int64(nruns)
+
+ basicSqrThreshold, karatsubaSqrThreshold = initBasicSqr, initKaratsubaSqr
+
+ return time.Duration(testval)
+}
+
+func computeSqrThreshold(from, to, step, nruns int, lower, upper string) int {
+ fmt.Printf("Calibrating threshold between %s and %s\n", lower, upper)
+ fmt.Printf("Looking for a timing difference for x between %d - %d words by %d step\n", from, to, step)
+ var initPos bool
+ var threshold int
+ for i := from; i <= to; i += step {
+ baseline := measureSqr(i, nruns, lower)
+ testval := measureSqr(i, nruns, upper)
+ pos := baseline > testval
+ delta := baseline - testval
+ percent := delta * 100 / baseline
+ fmt.Printf("words = %3d deltaT = %10s (%4d%%) is %s better: %v", i, delta, percent, upper, pos)
+ if i == from {
+ initPos = pos
+ }
+ if threshold == 0 && pos != initPos {
+ threshold = i
+ fmt.Printf(" threshold found")
+ }
+ fmt.Println()
+
+ }
+ if threshold != 0 {
+ fmt.Printf("Found threshold = %d between %d - %d\n", threshold, from, to)
+ } else {
+ fmt.Printf("Found NO threshold between %d - %d\n", from, to)
+ }
+ return threshold
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/decimal.go b/platform/dbops/binaries/go/go/src/math/big/decimal.go
new file mode 100644
index 0000000000000000000000000000000000000000..716f03bfa43398019aa67d65958b5c28ac141ee1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/decimal.go
@@ -0,0 +1,270 @@
+// 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 multi-precision decimal numbers.
+// The implementation is for float to decimal conversion only;
+// not general purpose use.
+// The only operations are precise conversion from binary to
+// decimal and rounding.
+//
+// The key observation and some code (shr) is borrowed from
+// strconv/decimal.go: conversion of binary fractional values can be done
+// precisely in multi-precision decimal because 2 divides 10 (required for
+// >> of mantissa); but conversion of decimal floating-point values cannot
+// be done precisely in binary representation.
+//
+// In contrast to strconv/decimal.go, only right shift is implemented in
+// decimal format - left shift can be done precisely in binary format.
+
+package big
+
+// A decimal represents an unsigned floating-point number in decimal representation.
+// The value of a non-zero decimal d is d.mant * 10**d.exp with 0.1 <= d.mant < 1,
+// with the most-significant mantissa digit at index 0. For the zero decimal, the
+// mantissa length and exponent are 0.
+// The zero value for decimal represents a ready-to-use 0.0.
+type decimal struct {
+ mant []byte // mantissa ASCII digits, big-endian
+ exp int // exponent
+}
+
+// at returns the i'th mantissa digit, starting with the most significant digit at 0.
+func (d *decimal) at(i int) byte {
+ if 0 <= i && i < len(d.mant) {
+ return d.mant[i]
+ }
+ return '0'
+}
+
+// Maximum shift amount that can be done in one pass without overflow.
+// A Word has _W bits and (1<= 0), or m >> -shift (for shift < 0).
+func (x *decimal) init(m nat, shift int) {
+ // special case 0
+ if len(m) == 0 {
+ x.mant = x.mant[:0]
+ x.exp = 0
+ return
+ }
+
+ // Optimization: If we need to shift right, first remove any trailing
+ // zero bits from m to reduce shift amount that needs to be done in
+ // decimal format (since that is likely slower).
+ if shift < 0 {
+ ntz := m.trailingZeroBits()
+ s := uint(-shift)
+ if s >= ntz {
+ s = ntz // shift at most ntz bits
+ }
+ m = nat(nil).shr(m, s)
+ shift += int(s)
+ }
+
+ // Do any shift left in binary representation.
+ if shift > 0 {
+ m = nat(nil).shl(m, uint(shift))
+ shift = 0
+ }
+
+ // Convert mantissa into decimal representation.
+ s := m.utoa(10)
+ n := len(s)
+ x.exp = n
+ // Trim trailing zeros; instead the exponent is tracking
+ // the decimal point independent of the number of digits.
+ for n > 0 && s[n-1] == '0' {
+ n--
+ }
+ x.mant = append(x.mant[:0], s[:n]...)
+
+ // Do any (remaining) shift right in decimal representation.
+ if shift < 0 {
+ for shift < -maxShift {
+ shr(x, maxShift)
+ shift += maxShift
+ }
+ shr(x, uint(-shift))
+ }
+}
+
+// shr implements x >> s, for s <= maxShift.
+func shr(x *decimal, s uint) {
+ // Division by 1<>s == 0 && r < len(x.mant) {
+ ch := Word(x.mant[r])
+ r++
+ n = n*10 + ch - '0'
+ }
+ if n == 0 {
+ // x == 0; shouldn't get here, but handle anyway
+ x.mant = x.mant[:0]
+ return
+ }
+ for n>>s == 0 {
+ r++
+ n *= 10
+ }
+ x.exp += 1 - r
+
+ // read a digit, write a digit
+ w := 0 // write index
+ mask := Word(1)<> s
+ n &= mask // n -= d << s
+ x.mant[w] = byte(d + '0')
+ w++
+ n = n*10 + ch - '0'
+ }
+
+ // write extra digits that still fit
+ for n > 0 && w < len(x.mant) {
+ d := n >> s
+ n &= mask
+ x.mant[w] = byte(d + '0')
+ w++
+ n = n * 10
+ }
+ x.mant = x.mant[:w] // the number may be shorter (e.g. 1024 >> 10)
+
+ // append additional digits that didn't fit
+ for n > 0 {
+ d := n >> s
+ n &= mask
+ x.mant = append(x.mant, byte(d+'0'))
+ n = n * 10
+ }
+
+ trim(x)
+}
+
+func (x *decimal) String() string {
+ if len(x.mant) == 0 {
+ return "0"
+ }
+
+ var buf []byte
+ switch {
+ case x.exp <= 0:
+ // 0.00ddd
+ buf = make([]byte, 0, 2+(-x.exp)+len(x.mant))
+ buf = append(buf, "0."...)
+ buf = appendZeros(buf, -x.exp)
+ buf = append(buf, x.mant...)
+
+ case /* 0 < */ x.exp < len(x.mant):
+ // dd.ddd
+ buf = make([]byte, 0, 1+len(x.mant))
+ buf = append(buf, x.mant[:x.exp]...)
+ buf = append(buf, '.')
+ buf = append(buf, x.mant[x.exp:]...)
+
+ default: // len(x.mant) <= x.exp
+ // ddd00
+ buf = make([]byte, 0, x.exp)
+ buf = append(buf, x.mant...)
+ buf = appendZeros(buf, x.exp-len(x.mant))
+ }
+
+ return string(buf)
+}
+
+// appendZeros appends n 0 digits to buf and returns buf.
+func appendZeros(buf []byte, n int) []byte {
+ for ; n > 0; n-- {
+ buf = append(buf, '0')
+ }
+ return buf
+}
+
+// shouldRoundUp reports if x should be rounded up
+// if shortened to n digits. n must be a valid index
+// for x.mant.
+func shouldRoundUp(x *decimal, n int) bool {
+ if x.mant[n] == '5' && n+1 == len(x.mant) {
+ // exactly halfway - round to even
+ return n > 0 && (x.mant[n-1]-'0')&1 != 0
+ }
+ // not halfway - digit tells all (x.mant has no trailing zeros)
+ return x.mant[n] >= '5'
+}
+
+// round sets x to (at most) n mantissa digits by rounding it
+// to the nearest even value with n (or fever) mantissa digits.
+// If n < 0, x remains unchanged.
+func (x *decimal) round(n int) {
+ if n < 0 || n >= len(x.mant) {
+ return // nothing to do
+ }
+
+ if shouldRoundUp(x, n) {
+ x.roundUp(n)
+ } else {
+ x.roundDown(n)
+ }
+}
+
+func (x *decimal) roundUp(n int) {
+ if n < 0 || n >= len(x.mant) {
+ return // nothing to do
+ }
+ // 0 <= n < len(x.mant)
+
+ // find first digit < '9'
+ for n > 0 && x.mant[n-1] >= '9' {
+ n--
+ }
+
+ if n == 0 {
+ // all digits are '9's => round up to '1' and update exponent
+ x.mant[0] = '1' // ok since len(x.mant) > n
+ x.mant = x.mant[:1]
+ x.exp++
+ return
+ }
+
+ // n > 0 && x.mant[n-1] < '9'
+ x.mant[n-1]++
+ x.mant = x.mant[:n]
+ // x already trimmed
+}
+
+func (x *decimal) roundDown(n int) {
+ if n < 0 || n >= len(x.mant) {
+ return // nothing to do
+ }
+ x.mant = x.mant[:n]
+ trim(x)
+}
+
+// trim cuts off any trailing zeros from x's mantissa;
+// they are meaningless for the value of x.
+func trim(x *decimal) {
+ i := len(x.mant)
+ for i > 0 && x.mant[i-1] == '0' {
+ i--
+ }
+ x.mant = x.mant[:i]
+ if i == 0 {
+ x.exp = 0
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/decimal_test.go b/platform/dbops/binaries/go/go/src/math/big/decimal_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..424811e15af12d9fd1825803fa89dae7cd4436a1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/decimal_test.go
@@ -0,0 +1,134 @@
+// 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.
+
+package big
+
+import (
+ "fmt"
+ "testing"
+)
+
+func TestDecimalString(t *testing.T) {
+ for _, test := range []struct {
+ x decimal
+ want string
+ }{
+ {want: "0"},
+ {decimal{nil, 1000}, "0"}, // exponent of 0 is ignored
+ {decimal{[]byte("12345"), 0}, "0.12345"},
+ {decimal{[]byte("12345"), -3}, "0.00012345"},
+ {decimal{[]byte("12345"), +3}, "123.45"},
+ {decimal{[]byte("12345"), +10}, "1234500000"},
+ } {
+ if got := test.x.String(); got != test.want {
+ t.Errorf("%v == %s; want %s", test.x, got, test.want)
+ }
+ }
+}
+
+func TestDecimalInit(t *testing.T) {
+ for _, test := range []struct {
+ x Word
+ shift int
+ want string
+ }{
+ {0, 0, "0"},
+ {0, -100, "0"},
+ {0, 100, "0"},
+ {1, 0, "1"},
+ {1, 10, "1024"},
+ {1, 100, "1267650600228229401496703205376"},
+ {1, -100, "0.0000000000000000000000000000007888609052210118054117285652827862296732064351090230047702789306640625"},
+ {12345678, 8, "3160493568"},
+ {12345678, -8, "48225.3046875"},
+ {195312, 9, "99999744"},
+ {1953125, 9, "1000000000"},
+ } {
+ var d decimal
+ d.init(nat{test.x}.norm(), test.shift)
+ if got := d.String(); got != test.want {
+ t.Errorf("%d << %d == %s; want %s", test.x, test.shift, got, test.want)
+ }
+ }
+}
+
+func TestDecimalRounding(t *testing.T) {
+ for _, test := range []struct {
+ x uint64
+ n int
+ down, even, up string
+ }{
+ {0, 0, "0", "0", "0"},
+ {0, 1, "0", "0", "0"},
+
+ {1, 0, "0", "0", "10"},
+ {5, 0, "0", "0", "10"},
+ {9, 0, "0", "10", "10"},
+
+ {15, 1, "10", "20", "20"},
+ {45, 1, "40", "40", "50"},
+ {95, 1, "90", "100", "100"},
+
+ {12344999, 4, "12340000", "12340000", "12350000"},
+ {12345000, 4, "12340000", "12340000", "12350000"},
+ {12345001, 4, "12340000", "12350000", "12350000"},
+ {23454999, 4, "23450000", "23450000", "23460000"},
+ {23455000, 4, "23450000", "23460000", "23460000"},
+ {23455001, 4, "23450000", "23460000", "23460000"},
+
+ {99994999, 4, "99990000", "99990000", "100000000"},
+ {99995000, 4, "99990000", "100000000", "100000000"},
+ {99999999, 4, "99990000", "100000000", "100000000"},
+
+ {12994999, 4, "12990000", "12990000", "13000000"},
+ {12995000, 4, "12990000", "13000000", "13000000"},
+ {12999999, 4, "12990000", "13000000", "13000000"},
+ } {
+ x := nat(nil).setUint64(test.x)
+
+ var d decimal
+ d.init(x, 0)
+ d.roundDown(test.n)
+ if got := d.String(); got != test.down {
+ t.Errorf("roundDown(%d, %d) = %s; want %s", test.x, test.n, got, test.down)
+ }
+
+ d.init(x, 0)
+ d.round(test.n)
+ if got := d.String(); got != test.even {
+ t.Errorf("round(%d, %d) = %s; want %s", test.x, test.n, got, test.even)
+ }
+
+ d.init(x, 0)
+ d.roundUp(test.n)
+ if got := d.String(); got != test.up {
+ t.Errorf("roundUp(%d, %d) = %s; want %s", test.x, test.n, got, test.up)
+ }
+ }
+}
+
+var sink string
+
+func BenchmarkDecimalConversion(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for shift := -100; shift <= +100; shift++ {
+ var d decimal
+ d.init(natOne, shift)
+ sink = d.String()
+ }
+ }
+}
+
+func BenchmarkFloatString(b *testing.B) {
+ x := new(Float)
+ for _, prec := range []uint{1e2, 1e3, 1e4, 1e5} {
+ x.SetPrec(prec).SetRat(NewRat(1, 3))
+ b.Run(fmt.Sprintf("%v", prec), func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ sink = x.String()
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/doc.go b/platform/dbops/binaries/go/go/src/math/big/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..2038546fa86ec54fc8e1a60f49a6d47c0e6a6797
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/doc.go
@@ -0,0 +1,98 @@
+// 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 big implements arbitrary-precision arithmetic (big numbers).
+The following numeric types are supported:
+
+ Int signed integers
+ Rat rational numbers
+ Float floating-point numbers
+
+The zero value for an [Int], [Rat], or [Float] correspond to 0. Thus, new
+values can be declared in the usual ways and denote 0 without further
+initialization:
+
+ var x Int // &x is an *Int of value 0
+ var r = &Rat{} // r is a *Rat of value 0
+ y := new(Float) // y is a *Float of value 0
+
+Alternatively, new values can be allocated and initialized with factory
+functions of the form:
+
+ func NewT(v V) *T
+
+For instance, [NewInt](x) returns an *[Int] set to the value of the int64
+argument x, [NewRat](a, b) returns a *[Rat] set to the fraction a/b where
+a and b are int64 values, and [NewFloat](f) returns a *[Float] initialized
+to the float64 argument f. More flexibility is provided with explicit
+setters, for instance:
+
+ var z1 Int
+ z1.SetUint64(123) // z1 := 123
+ z2 := new(Rat).SetFloat64(1.25) // z2 := 5/4
+ z3 := new(Float).SetInt(z1) // z3 := 123.0
+
+Setters, numeric operations and predicates are represented as methods of
+the form:
+
+ func (z *T) SetV(v V) *T // z = v
+ func (z *T) Unary(x *T) *T // z = unary x
+ func (z *T) Binary(x, y *T) *T // z = x binary y
+ func (x *T) Pred() P // p = pred(x)
+
+with T one of [Int], [Rat], or [Float]. For unary and binary operations, the
+result is the receiver (usually named z in that case; see below); if it
+is one of the operands x or y it may be safely overwritten (and its memory
+reused).
+
+Arithmetic expressions are typically written as a sequence of individual
+method calls, with each call corresponding to an operation. The receiver
+denotes the result and the method arguments are the operation's operands.
+For instance, given three *Int values a, b and c, the invocation
+
+ c.Add(a, b)
+
+computes the sum a + b and stores the result in c, overwriting whatever
+value was held in c before. Unless specified otherwise, operations permit
+aliasing of parameters, so it is perfectly ok to write
+
+ sum.Add(sum, x)
+
+to accumulate values x in a sum.
+
+(By always passing in a result value via the receiver, memory use can be
+much better controlled. Instead of having to allocate new memory for each
+result, an operation can reuse the space allocated for the result value,
+and overwrite that value with the new result in the process.)
+
+Notational convention: Incoming method parameters (including the receiver)
+are named consistently in the API to clarify their use. Incoming operands
+are usually named x, y, a, b, and so on, but never z. A parameter specifying
+the result is named z (typically the receiver).
+
+For instance, the arguments for (*Int).Add are named x and y, and because
+the receiver specifies the result destination, it is called z:
+
+ func (z *Int) Add(x, y *Int) *Int
+
+Methods of this form typically return the incoming receiver as well, to
+enable simple call chaining.
+
+Methods which don't require a result value to be passed in (for instance,
+[Int.Sign]), simply return the result. In this case, the receiver is typically
+the first operand, named x:
+
+ func (x *Int) Sign() int
+
+Various methods support conversions between strings and corresponding
+numeric values, and vice versa: *[Int], *[Rat], and *[Float] values implement
+the Stringer interface for a (default) string representation of the value,
+but also provide SetString methods to initialize a value from a string in
+a variety of supported formats (see the respective SetString documentation).
+
+Finally, *[Int], *[Rat], and *[Float] satisfy [fmt.Scanner] for scanning
+and (except for *[Rat]) the Formatter interface for formatted printing.
+*/
+package big
diff --git a/platform/dbops/binaries/go/go/src/math/big/example_rat_test.go b/platform/dbops/binaries/go/go/src/math/big/example_rat_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dc67430980172b70bcc1fab2baa4325cca3fd762
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/example_rat_test.go
@@ -0,0 +1,68 @@
+// 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.
+
+package big_test
+
+import (
+ "fmt"
+ "math/big"
+)
+
+// Use the classic continued fraction for e
+//
+// e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...]
+//
+// i.e., for the nth term, use
+//
+// 1 if n mod 3 != 1
+// (n-1)/3 * 2 if n mod 3 == 1
+func recur(n, lim int64) *big.Rat {
+ term := new(big.Rat)
+ if n%3 != 1 {
+ term.SetInt64(1)
+ } else {
+ term.SetInt64((n - 1) / 3 * 2)
+ }
+
+ if n > lim {
+ return term
+ }
+
+ // Directly initialize frac as the fractional
+ // inverse of the result of recur.
+ frac := new(big.Rat).Inv(recur(n+1, lim))
+
+ return term.Add(term, frac)
+}
+
+// This example demonstrates how to use big.Rat to compute the
+// first 15 terms in the sequence of rational convergents for
+// the constant e (base of natural logarithm).
+func Example_eConvergents() {
+ for i := 1; i <= 15; i++ {
+ r := recur(0, int64(i))
+
+ // Print r both as a fraction and as a floating-point number.
+ // Since big.Rat implements fmt.Formatter, we can use %-13s to
+ // get a left-aligned string representation of the fraction.
+ fmt.Printf("%-13s = %s\n", r, r.FloatString(8))
+ }
+
+ // Output:
+ // 2/1 = 2.00000000
+ // 3/1 = 3.00000000
+ // 8/3 = 2.66666667
+ // 11/4 = 2.75000000
+ // 19/7 = 2.71428571
+ // 87/32 = 2.71875000
+ // 106/39 = 2.71794872
+ // 193/71 = 2.71830986
+ // 1264/465 = 2.71827957
+ // 1457/536 = 2.71828358
+ // 2721/1001 = 2.71828172
+ // 23225/8544 = 2.71828184
+ // 25946/9545 = 2.71828182
+ // 49171/18089 = 2.71828183
+ // 517656/190435 = 2.71828183
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/example_test.go b/platform/dbops/binaries/go/go/src/math/big/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..31ca784154c2cf660ca8062971ab35b6532a2985
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/example_test.go
@@ -0,0 +1,148 @@
+// 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 big_test
+
+import (
+ "fmt"
+ "log"
+ "math"
+ "math/big"
+)
+
+func ExampleRat_SetString() {
+ r := new(big.Rat)
+ r.SetString("355/113")
+ fmt.Println(r.FloatString(3))
+ // Output: 3.142
+}
+
+func ExampleInt_SetString() {
+ i := new(big.Int)
+ i.SetString("644", 8) // octal
+ fmt.Println(i)
+ // Output: 420
+}
+
+func ExampleFloat_SetString() {
+ f := new(big.Float)
+ f.SetString("3.14159")
+ fmt.Println(f)
+ // Output: 3.14159
+}
+
+func ExampleRat_Scan() {
+ // The Scan function is rarely used directly;
+ // the fmt package recognizes it as an implementation of fmt.Scanner.
+ r := new(big.Rat)
+ _, err := fmt.Sscan("1.5000", r)
+ if err != nil {
+ log.Println("error scanning value:", err)
+ } else {
+ fmt.Println(r)
+ }
+ // Output: 3/2
+}
+
+func ExampleInt_Scan() {
+ // The Scan function is rarely used directly;
+ // the fmt package recognizes it as an implementation of fmt.Scanner.
+ i := new(big.Int)
+ _, err := fmt.Sscan("18446744073709551617", i)
+ if err != nil {
+ log.Println("error scanning value:", err)
+ } else {
+ fmt.Println(i)
+ }
+ // Output: 18446744073709551617
+}
+
+func ExampleFloat_Scan() {
+ // The Scan function is rarely used directly;
+ // the fmt package recognizes it as an implementation of fmt.Scanner.
+ f := new(big.Float)
+ _, err := fmt.Sscan("1.19282e99", f)
+ if err != nil {
+ log.Println("error scanning value:", err)
+ } else {
+ fmt.Println(f)
+ }
+ // Output: 1.19282e+99
+}
+
+// This example demonstrates how to use big.Int to compute the smallest
+// Fibonacci number with 100 decimal digits and to test whether it is prime.
+func Example_fibonacci() {
+ // Initialize two big ints with the first two numbers in the sequence.
+ a := big.NewInt(0)
+ b := big.NewInt(1)
+
+ // Initialize limit as 10^99, the smallest integer with 100 digits.
+ var limit big.Int
+ limit.Exp(big.NewInt(10), big.NewInt(99), nil)
+
+ // Loop while a is smaller than 1e100.
+ for a.Cmp(&limit) < 0 {
+ // Compute the next Fibonacci number, storing it in a.
+ a.Add(a, b)
+ // Swap a and b so that b is the next number in the sequence.
+ a, b = b, a
+ }
+ fmt.Println(a) // 100-digit Fibonacci number
+
+ // Test a for primality.
+ // (ProbablyPrimes' argument sets the number of Miller-Rabin
+ // rounds to be performed. 20 is a good value.)
+ fmt.Println(a.ProbablyPrime(20))
+
+ // Output:
+ // 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
+ // false
+}
+
+// This example shows how to use big.Float to compute the square root of 2 with
+// a precision of 200 bits, and how to print the result as a decimal number.
+func Example_sqrt2() {
+ // We'll do computations with 200 bits of precision in the mantissa.
+ const prec = 200
+
+ // Compute the square root of 2 using Newton's Method. We start with
+ // an initial estimate for sqrt(2), and then iterate:
+ // x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
+
+ // Since Newton's Method doubles the number of correct digits at each
+ // iteration, we need at least log_2(prec) steps.
+ steps := int(math.Log2(prec))
+
+ // Initialize values we need for the computation.
+ two := new(big.Float).SetPrec(prec).SetInt64(2)
+ half := new(big.Float).SetPrec(prec).SetFloat64(0.5)
+
+ // Use 1 as the initial estimate.
+ x := new(big.Float).SetPrec(prec).SetInt64(1)
+
+ // We use t as a temporary variable. There's no need to set its precision
+ // since big.Float values with unset (== 0) precision automatically assume
+ // the largest precision of the arguments when used as the result (receiver)
+ // of a big.Float operation.
+ t := new(big.Float)
+
+ // Iterate.
+ for i := 0; i <= steps; i++ {
+ t.Quo(two, x) // t = 2.0 / x_n
+ t.Add(x, t) // t = x_n + (2.0 / x_n)
+ x.Mul(half, t) // x_{n+1} = 0.5 * t
+ }
+
+ // We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatter
+ fmt.Printf("sqrt(2) = %.50f\n", x)
+
+ // Print the error between 2 and x*x.
+ t.Mul(x, x) // t = x*x
+ fmt.Printf("error = %e\n", t.Sub(two, t))
+
+ // Output:
+ // sqrt(2) = 1.41421356237309504880168872420969807856967187537695
+ // error = 0.000000e+00
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/float.go b/platform/dbops/binaries/go/go/src/math/big/float.go
new file mode 100644
index 0000000000000000000000000000000000000000..1c97ec98c004f2455125fe3901d29707cf181ae9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/float.go
@@ -0,0 +1,1736 @@
+// Copyright 2014 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 multi-precision floating-point numbers.
+// Like in the GNU MPFR library (https://www.mpfr.org/), operands
+// can be of mixed precision. Unlike MPFR, the rounding mode is
+// not specified with each operation, but with each operand. The
+// rounding mode of the result operand determines the rounding
+// mode of an operation. This is a from-scratch implementation.
+
+package big
+
+import (
+ "fmt"
+ "math"
+ "math/bits"
+)
+
+const debugFloat = false // enable for debugging
+
+// A nonzero finite Float represents a multi-precision floating point number
+//
+// sign × mantissa × 2**exponent
+//
+// with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp.
+// A Float may also be zero (+0, -0) or infinite (+Inf, -Inf).
+// All Floats are ordered, and the ordering of two Floats x and y
+// is defined by x.Cmp(y).
+//
+// Each Float value also has a precision, rounding mode, and accuracy.
+// The precision is the maximum number of mantissa bits available to
+// represent the value. The rounding mode specifies how a result should
+// be rounded to fit into the mantissa bits, and accuracy describes the
+// rounding error with respect to the exact result.
+//
+// Unless specified otherwise, all operations (including setters) that
+// specify a *Float variable for the result (usually via the receiver
+// with the exception of [Float.MantExp]), round the numeric result according
+// to the precision and rounding mode of the result variable.
+//
+// If the provided result precision is 0 (see below), it is set to the
+// precision of the argument with the largest precision value before any
+// rounding takes place, and the rounding mode remains unchanged. Thus,
+// uninitialized Floats provided as result arguments will have their
+// precision set to a reasonable value determined by the operands, and
+// their mode is the zero value for RoundingMode (ToNearestEven).
+//
+// By setting the desired precision to 24 or 53 and using matching rounding
+// mode (typically [ToNearestEven]), Float operations produce the same results
+// as the corresponding float32 or float64 IEEE-754 arithmetic for operands
+// that correspond to normal (i.e., not denormal) float32 or float64 numbers.
+// Exponent underflow and overflow lead to a 0 or an Infinity for different
+// values than IEEE-754 because Float exponents have a much larger range.
+//
+// The zero (uninitialized) value for a Float is ready to use and represents
+// the number +0.0 exactly, with precision 0 and rounding mode [ToNearestEven].
+//
+// Operations always take pointer arguments (*Float) rather
+// than Float values, and each unique Float value requires
+// its own unique *Float pointer. To "copy" a Float value,
+// an existing (or newly allocated) Float must be set to
+// a new value using the [Float.Set] method; shallow copies
+// of Floats are not supported and may lead to errors.
+type Float struct {
+ prec uint32
+ mode RoundingMode
+ acc Accuracy
+ form form
+ neg bool
+ mant nat
+ exp int32
+}
+
+// An ErrNaN panic is raised by a [Float] operation that would lead to
+// a NaN under IEEE-754 rules. An ErrNaN implements the error interface.
+type ErrNaN struct {
+ msg string
+}
+
+func (err ErrNaN) Error() string {
+ return err.msg
+}
+
+// NewFloat allocates and returns a new [Float] set to x,
+// with precision 53 and rounding mode [ToNearestEven].
+// NewFloat panics with [ErrNaN] if x is a NaN.
+func NewFloat(x float64) *Float {
+ if math.IsNaN(x) {
+ panic(ErrNaN{"NewFloat(NaN)"})
+ }
+ return new(Float).SetFloat64(x)
+}
+
+// Exponent and precision limits.
+const (
+ MaxExp = math.MaxInt32 // largest supported exponent
+ MinExp = math.MinInt32 // smallest supported exponent
+ MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited
+)
+
+// Internal representation: The mantissa bits x.mant of a nonzero finite
+// Float x are stored in a nat slice long enough to hold up to x.prec bits;
+// the slice may (but doesn't have to) be shorter if the mantissa contains
+// trailing 0 bits. x.mant is normalized if the msb of x.mant == 1 (i.e.,
+// the msb is shifted all the way "to the left"). Thus, if the mantissa has
+// trailing 0 bits or x.prec is not a multiple of the Word size _W,
+// x.mant[0] has trailing zero bits. The msb of the mantissa corresponds
+// to the value 0.5; the exponent x.exp shifts the binary point as needed.
+//
+// A zero or non-finite Float x ignores x.mant and x.exp.
+//
+// x form neg mant exp
+// ----------------------------------------------------------
+// ±0 zero sign - -
+// 0 < |x| < +Inf finite sign mantissa exponent
+// ±Inf inf sign - -
+
+// A form value describes the internal representation.
+type form byte
+
+// The form value order is relevant - do not change!
+const (
+ zero form = iota
+ finite
+ inf
+)
+
+// RoundingMode determines how a [Float] value is rounded to the
+// desired precision. Rounding may change the [Float] value; the
+// rounding error is described by the [Float]'s [Accuracy].
+type RoundingMode byte
+
+// These constants define supported rounding modes.
+const (
+ ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
+ ToNearestAway // == IEEE 754-2008 roundTiesToAway
+ ToZero // == IEEE 754-2008 roundTowardZero
+ AwayFromZero // no IEEE 754-2008 equivalent
+ ToNegativeInf // == IEEE 754-2008 roundTowardNegative
+ ToPositiveInf // == IEEE 754-2008 roundTowardPositive
+)
+
+//go:generate stringer -type=RoundingMode
+
+// Accuracy describes the rounding error produced by the most recent
+// operation that generated a [Float] value, relative to the exact value.
+type Accuracy int8
+
+// Constants describing the [Accuracy] of a [Float].
+const (
+ Below Accuracy = -1
+ Exact Accuracy = 0
+ Above Accuracy = +1
+)
+
+//go:generate stringer -type=Accuracy
+
+// SetPrec sets z's precision to prec and returns the (possibly) rounded
+// value of z. Rounding occurs according to z's rounding mode if the mantissa
+// cannot be represented in prec bits without loss of precision.
+// SetPrec(0) maps all finite values to ±0; infinite values remain unchanged.
+// If prec > [MaxPrec], it is set to [MaxPrec].
+func (z *Float) SetPrec(prec uint) *Float {
+ z.acc = Exact // optimistically assume no rounding is needed
+
+ // special case
+ if prec == 0 {
+ z.prec = 0
+ if z.form == finite {
+ // truncate z to 0
+ z.acc = makeAcc(z.neg)
+ z.form = zero
+ }
+ return z
+ }
+
+ // general case
+ if prec > MaxPrec {
+ prec = MaxPrec
+ }
+ old := z.prec
+ z.prec = uint32(prec)
+ if z.prec < old {
+ z.round(0)
+ }
+ return z
+}
+
+func makeAcc(above bool) Accuracy {
+ if above {
+ return Above
+ }
+ return Below
+}
+
+// SetMode sets z's rounding mode to mode and returns an exact z.
+// z remains unchanged otherwise.
+// z.SetMode(z.Mode()) is a cheap way to set z's accuracy to [Exact].
+func (z *Float) SetMode(mode RoundingMode) *Float {
+ z.mode = mode
+ z.acc = Exact
+ return z
+}
+
+// Prec returns the mantissa precision of x in bits.
+// The result may be 0 for |x| == 0 and |x| == Inf.
+func (x *Float) Prec() uint {
+ return uint(x.prec)
+}
+
+// MinPrec returns the minimum precision required to represent x exactly
+// (i.e., the smallest prec before x.SetPrec(prec) would start rounding x).
+// The result is 0 for |x| == 0 and |x| == Inf.
+func (x *Float) MinPrec() uint {
+ if x.form != finite {
+ return 0
+ }
+ return uint(len(x.mant))*_W - x.mant.trailingZeroBits()
+}
+
+// Mode returns the rounding mode of x.
+func (x *Float) Mode() RoundingMode {
+ return x.mode
+}
+
+// Acc returns the accuracy of x produced by the most recent
+// operation, unless explicitly documented otherwise by that
+// operation.
+func (x *Float) Acc() Accuracy {
+ return x.acc
+}
+
+// Sign returns:
+//
+// -1 if x < 0
+// 0 if x is ±0
+// +1 if x > 0
+func (x *Float) Sign() int {
+ if debugFloat {
+ x.validate()
+ }
+ if x.form == zero {
+ return 0
+ }
+ if x.neg {
+ return -1
+ }
+ return 1
+}
+
+// MantExp breaks x into its mantissa and exponent components
+// and returns the exponent. If a non-nil mant argument is
+// provided its value is set to the mantissa of x, with the
+// same precision and rounding mode as x. The components
+// satisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0.
+// Calling MantExp with a nil argument is an efficient way to
+// get the exponent of the receiver.
+//
+// Special cases are:
+//
+// ( ±0).MantExp(mant) = 0, with mant set to ±0
+// (±Inf).MantExp(mant) = 0, with mant set to ±Inf
+//
+// x and mant may be the same in which case x is set to its
+// mantissa value.
+func (x *Float) MantExp(mant *Float) (exp int) {
+ if debugFloat {
+ x.validate()
+ }
+ if x.form == finite {
+ exp = int(x.exp)
+ }
+ if mant != nil {
+ mant.Copy(x)
+ if mant.form == finite {
+ mant.exp = 0
+ }
+ }
+ return
+}
+
+func (z *Float) setExpAndRound(exp int64, sbit uint) {
+ if exp < MinExp {
+ // underflow
+ z.acc = makeAcc(z.neg)
+ z.form = zero
+ return
+ }
+
+ if exp > MaxExp {
+ // overflow
+ z.acc = makeAcc(!z.neg)
+ z.form = inf
+ return
+ }
+
+ z.form = finite
+ z.exp = int32(exp)
+ z.round(sbit)
+}
+
+// SetMantExp sets z to mant × 2**exp and returns z.
+// The result z has the same precision and rounding mode
+// as mant. SetMantExp is an inverse of [Float.MantExp] but does
+// not require 0.5 <= |mant| < 1.0. Specifically, for a
+// given x of type *[Float], SetMantExp relates to [Float.MantExp]
+// as follows:
+//
+// mant := new(Float)
+// new(Float).SetMantExp(mant, x.MantExp(mant)).Cmp(x) == 0
+//
+// Special cases are:
+//
+// z.SetMantExp( ±0, exp) = ±0
+// z.SetMantExp(±Inf, exp) = ±Inf
+//
+// z and mant may be the same in which case z's exponent
+// is set to exp.
+func (z *Float) SetMantExp(mant *Float, exp int) *Float {
+ if debugFloat {
+ z.validate()
+ mant.validate()
+ }
+ z.Copy(mant)
+
+ if z.form == finite {
+ // 0 < |mant| < +Inf
+ z.setExpAndRound(int64(z.exp)+int64(exp), 0)
+ }
+ return z
+}
+
+// Signbit reports whether x is negative or negative zero.
+func (x *Float) Signbit() bool {
+ return x.neg
+}
+
+// IsInf reports whether x is +Inf or -Inf.
+func (x *Float) IsInf() bool {
+ return x.form == inf
+}
+
+// IsInt reports whether x is an integer.
+// ±Inf values are not integers.
+func (x *Float) IsInt() bool {
+ if debugFloat {
+ x.validate()
+ }
+ // special cases
+ if x.form != finite {
+ return x.form == zero
+ }
+ // x.form == finite
+ if x.exp <= 0 {
+ return false
+ }
+ // x.exp > 0
+ return x.prec <= uint32(x.exp) || x.MinPrec() <= uint(x.exp) // not enough bits for fractional mantissa
+}
+
+// debugging support
+func (x *Float) validate() {
+ if !debugFloat {
+ // avoid performance bugs
+ panic("validate called but debugFloat is not set")
+ }
+ if msg := x.validate0(); msg != "" {
+ panic(msg)
+ }
+}
+
+func (x *Float) validate0() string {
+ if x.form != finite {
+ return ""
+ }
+ m := len(x.mant)
+ if m == 0 {
+ return "nonzero finite number with empty mantissa"
+ }
+ const msb = 1 << (_W - 1)
+ if x.mant[m-1]&msb == 0 {
+ return fmt.Sprintf("msb not set in last word %#x of %s", x.mant[m-1], x.Text('p', 0))
+ }
+ if x.prec == 0 {
+ return "zero precision finite number"
+ }
+ return ""
+}
+
+// round rounds z according to z.mode to z.prec bits and sets z.acc accordingly.
+// sbit must be 0 or 1 and summarizes any "sticky bit" information one might
+// have before calling round. z's mantissa must be normalized (with the msb set)
+// or empty.
+//
+// CAUTION: The rounding modes ToNegativeInf, ToPositiveInf are affected by the
+// sign of z. For correct rounding, the sign of z must be set correctly before
+// calling round.
+func (z *Float) round(sbit uint) {
+ if debugFloat {
+ z.validate()
+ }
+
+ z.acc = Exact
+ if z.form != finite {
+ // ±0 or ±Inf => nothing left to do
+ return
+ }
+ // z.form == finite && len(z.mant) > 0
+ // m > 0 implies z.prec > 0 (checked by validate)
+
+ m := uint32(len(z.mant)) // present mantissa length in words
+ bits := m * _W // present mantissa bits; bits > 0
+ if bits <= z.prec {
+ // mantissa fits => nothing to do
+ return
+ }
+ // bits > z.prec
+
+ // Rounding is based on two bits: the rounding bit (rbit) and the
+ // sticky bit (sbit). The rbit is the bit immediately before the
+ // z.prec leading mantissa bits (the "0.5"). The sbit is set if any
+ // of the bits before the rbit are set (the "0.25", "0.125", etc.):
+ //
+ // rbit sbit => "fractional part"
+ //
+ // 0 0 == 0
+ // 0 1 > 0 , < 0.5
+ // 1 0 == 0.5
+ // 1 1 > 0.5, < 1.0
+
+ // bits > z.prec: mantissa too large => round
+ r := uint(bits - z.prec - 1) // rounding bit position; r >= 0
+ rbit := z.mant.bit(r) & 1 // rounding bit; be safe and ensure it's a single bit
+ // The sticky bit is only needed for rounding ToNearestEven
+ // or when the rounding bit is zero. Avoid computation otherwise.
+ if sbit == 0 && (rbit == 0 || z.mode == ToNearestEven) {
+ sbit = z.mant.sticky(r)
+ }
+ sbit &= 1 // be safe and ensure it's a single bit
+
+ // cut off extra words
+ n := (z.prec + (_W - 1)) / _W // mantissa length in words for desired precision
+ if m > n {
+ copy(z.mant, z.mant[m-n:]) // move n last words to front
+ z.mant = z.mant[:n]
+ }
+
+ // determine number of trailing zero bits (ntz) and compute lsb mask of mantissa's least-significant word
+ ntz := n*_W - z.prec // 0 <= ntz < _W
+ lsb := Word(1) << ntz
+
+ // round if result is inexact
+ if rbit|sbit != 0 {
+ // Make rounding decision: The result mantissa is truncated ("rounded down")
+ // by default. Decide if we need to increment, or "round up", the (unsigned)
+ // mantissa.
+ inc := false
+ switch z.mode {
+ case ToNegativeInf:
+ inc = z.neg
+ case ToZero:
+ // nothing to do
+ case ToNearestEven:
+ inc = rbit != 0 && (sbit != 0 || z.mant[0]&lsb != 0)
+ case ToNearestAway:
+ inc = rbit != 0
+ case AwayFromZero:
+ inc = true
+ case ToPositiveInf:
+ inc = !z.neg
+ default:
+ panic("unreachable")
+ }
+
+ // A positive result (!z.neg) is Above the exact result if we increment,
+ // and it's Below if we truncate (Exact results require no rounding).
+ // For a negative result (z.neg) it is exactly the opposite.
+ z.acc = makeAcc(inc != z.neg)
+
+ if inc {
+ // add 1 to mantissa
+ if addVW(z.mant, z.mant, lsb) != 0 {
+ // mantissa overflow => adjust exponent
+ if z.exp >= MaxExp {
+ // exponent overflow
+ z.form = inf
+ return
+ }
+ z.exp++
+ // adjust mantissa: divide by 2 to compensate for exponent adjustment
+ shrVU(z.mant, z.mant, 1)
+ // set msb == carry == 1 from the mantissa overflow above
+ const msb = 1 << (_W - 1)
+ z.mant[n-1] |= msb
+ }
+ }
+ }
+
+ // zero out trailing bits in least-significant word
+ z.mant[0] &^= lsb - 1
+
+ if debugFloat {
+ z.validate()
+ }
+}
+
+func (z *Float) setBits64(neg bool, x uint64) *Float {
+ if z.prec == 0 {
+ z.prec = 64
+ }
+ z.acc = Exact
+ z.neg = neg
+ if x == 0 {
+ z.form = zero
+ return z
+ }
+ // x != 0
+ z.form = finite
+ s := bits.LeadingZeros64(x)
+ z.mant = z.mant.setUint64(x << uint(s))
+ z.exp = int32(64 - s) // always fits
+ if z.prec < 64 {
+ z.round(0)
+ }
+ return z
+}
+
+// SetUint64 sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to 64 (and rounding will have
+// no effect).
+func (z *Float) SetUint64(x uint64) *Float {
+ return z.setBits64(false, x)
+}
+
+// SetInt64 sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to 64 (and rounding will have
+// no effect).
+func (z *Float) SetInt64(x int64) *Float {
+ u := x
+ if u < 0 {
+ u = -u
+ }
+ // We cannot simply call z.SetUint64(uint64(u)) and change
+ // the sign afterwards because the sign affects rounding.
+ return z.setBits64(x < 0, uint64(u))
+}
+
+// SetFloat64 sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to 53 (and rounding will have
+// no effect). SetFloat64 panics with [ErrNaN] if x is a NaN.
+func (z *Float) SetFloat64(x float64) *Float {
+ if z.prec == 0 {
+ z.prec = 53
+ }
+ if math.IsNaN(x) {
+ panic(ErrNaN{"Float.SetFloat64(NaN)"})
+ }
+ z.acc = Exact
+ z.neg = math.Signbit(x) // handle -0, -Inf correctly
+ if x == 0 {
+ z.form = zero
+ return z
+ }
+ if math.IsInf(x, 0) {
+ z.form = inf
+ return z
+ }
+ // normalized x != 0
+ z.form = finite
+ fmant, exp := math.Frexp(x) // get normalized mantissa
+ z.mant = z.mant.setUint64(1<<63 | math.Float64bits(fmant)<<11)
+ z.exp = int32(exp) // always fits
+ if z.prec < 53 {
+ z.round(0)
+ }
+ return z
+}
+
+// fnorm normalizes mantissa m by shifting it to the left
+// such that the msb of the most-significant word (msw) is 1.
+// It returns the shift amount. It assumes that len(m) != 0.
+func fnorm(m nat) int64 {
+ if debugFloat && (len(m) == 0 || m[len(m)-1] == 0) {
+ panic("msw of mantissa is 0")
+ }
+ s := nlz(m[len(m)-1])
+ if s > 0 {
+ c := shlVU(m, m, s)
+ if debugFloat && c != 0 {
+ panic("nlz or shlVU incorrect")
+ }
+ }
+ return int64(s)
+}
+
+// SetInt sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to the larger of x.BitLen()
+// or 64 (and rounding will have no effect).
+func (z *Float) SetInt(x *Int) *Float {
+ // TODO(gri) can be more efficient if z.prec > 0
+ // but small compared to the size of x, or if there
+ // are many trailing 0's.
+ bits := uint32(x.BitLen())
+ if z.prec == 0 {
+ z.prec = umax32(bits, 64)
+ }
+ z.acc = Exact
+ z.neg = x.neg
+ if len(x.abs) == 0 {
+ z.form = zero
+ return z
+ }
+ // x != 0
+ z.mant = z.mant.set(x.abs)
+ fnorm(z.mant)
+ z.setExpAndRound(int64(bits), 0)
+ return z
+}
+
+// SetRat sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to the largest of a.BitLen(),
+// b.BitLen(), or 64; with x = a/b.
+func (z *Float) SetRat(x *Rat) *Float {
+ if x.IsInt() {
+ return z.SetInt(x.Num())
+ }
+ var a, b Float
+ a.SetInt(x.Num())
+ b.SetInt(x.Denom())
+ if z.prec == 0 {
+ z.prec = umax32(a.prec, b.prec)
+ }
+ return z.Quo(&a, &b)
+}
+
+// SetInf sets z to the infinite Float -Inf if signbit is
+// set, or +Inf if signbit is not set, and returns z. The
+// precision of z is unchanged and the result is always
+// [Exact].
+func (z *Float) SetInf(signbit bool) *Float {
+ z.acc = Exact
+ z.form = inf
+ z.neg = signbit
+ return z
+}
+
+// Set sets z to the (possibly rounded) value of x and returns z.
+// If z's precision is 0, it is changed to the precision of x
+// before setting z (and rounding will have no effect).
+// Rounding is performed according to z's precision and rounding
+// mode; and z's accuracy reports the result error relative to the
+// exact (not rounded) result.
+func (z *Float) Set(x *Float) *Float {
+ if debugFloat {
+ x.validate()
+ }
+ z.acc = Exact
+ if z != x {
+ z.form = x.form
+ z.neg = x.neg
+ if x.form == finite {
+ z.exp = x.exp
+ z.mant = z.mant.set(x.mant)
+ }
+ if z.prec == 0 {
+ z.prec = x.prec
+ } else if z.prec < x.prec {
+ z.round(0)
+ }
+ }
+ return z
+}
+
+// Copy sets z to x, with the same precision, rounding mode, and
+// accuracy as x, and returns z. x is not changed even if z and
+// x are the same.
+func (z *Float) Copy(x *Float) *Float {
+ if debugFloat {
+ x.validate()
+ }
+ if z != x {
+ z.prec = x.prec
+ z.mode = x.mode
+ z.acc = x.acc
+ z.form = x.form
+ z.neg = x.neg
+ if z.form == finite {
+ z.mant = z.mant.set(x.mant)
+ z.exp = x.exp
+ }
+ }
+ return z
+}
+
+// msb32 returns the 32 most significant bits of x.
+func msb32(x nat) uint32 {
+ i := len(x) - 1
+ if i < 0 {
+ return 0
+ }
+ if debugFloat && x[i]&(1<<(_W-1)) == 0 {
+ panic("x not normalized")
+ }
+ switch _W {
+ case 32:
+ return uint32(x[i])
+ case 64:
+ return uint32(x[i] >> 32)
+ }
+ panic("unreachable")
+}
+
+// msb64 returns the 64 most significant bits of x.
+func msb64(x nat) uint64 {
+ i := len(x) - 1
+ if i < 0 {
+ return 0
+ }
+ if debugFloat && x[i]&(1<<(_W-1)) == 0 {
+ panic("x not normalized")
+ }
+ switch _W {
+ case 32:
+ v := uint64(x[i]) << 32
+ if i > 0 {
+ v |= uint64(x[i-1])
+ }
+ return v
+ case 64:
+ return uint64(x[i])
+ }
+ panic("unreachable")
+}
+
+// Uint64 returns the unsigned integer resulting from truncating x
+// towards zero. If 0 <= x <= math.MaxUint64, the result is [Exact]
+// if x is an integer and [Below] otherwise.
+// The result is (0, [Above]) for x < 0, and ([math.MaxUint64], [Below])
+// for x > [math.MaxUint64].
+func (x *Float) Uint64() (uint64, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ switch x.form {
+ case finite:
+ if x.neg {
+ return 0, Above
+ }
+ // 0 < x < +Inf
+ if x.exp <= 0 {
+ // 0 < x < 1
+ return 0, Below
+ }
+ // 1 <= x < Inf
+ if x.exp <= 64 {
+ // u = trunc(x) fits into a uint64
+ u := msb64(x.mant) >> (64 - uint32(x.exp))
+ if x.MinPrec() <= 64 {
+ return u, Exact
+ }
+ return u, Below // x truncated
+ }
+ // x too large
+ return math.MaxUint64, Below
+
+ case zero:
+ return 0, Exact
+
+ case inf:
+ if x.neg {
+ return 0, Above
+ }
+ return math.MaxUint64, Below
+ }
+
+ panic("unreachable")
+}
+
+// Int64 returns the integer resulting from truncating x towards zero.
+// If [math.MinInt64] <= x <= [math.MaxInt64], the result is [Exact] if x is
+// an integer, and [Above] (x < 0) or [Below] (x > 0) otherwise.
+// The result is ([math.MinInt64], [Above]) for x < [math.MinInt64],
+// and ([math.MaxInt64], [Below]) for x > [math.MaxInt64].
+func (x *Float) Int64() (int64, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ switch x.form {
+ case finite:
+ // 0 < |x| < +Inf
+ acc := makeAcc(x.neg)
+ if x.exp <= 0 {
+ // 0 < |x| < 1
+ return 0, acc
+ }
+ // x.exp > 0
+
+ // 1 <= |x| < +Inf
+ if x.exp <= 63 {
+ // i = trunc(x) fits into an int64 (excluding math.MinInt64)
+ i := int64(msb64(x.mant) >> (64 - uint32(x.exp)))
+ if x.neg {
+ i = -i
+ }
+ if x.MinPrec() <= uint(x.exp) {
+ return i, Exact
+ }
+ return i, acc // x truncated
+ }
+ if x.neg {
+ // check for special case x == math.MinInt64 (i.e., x == -(0.5 << 64))
+ if x.exp == 64 && x.MinPrec() == 1 {
+ acc = Exact
+ }
+ return math.MinInt64, acc
+ }
+ // x too large
+ return math.MaxInt64, Below
+
+ case zero:
+ return 0, Exact
+
+ case inf:
+ if x.neg {
+ return math.MinInt64, Above
+ }
+ return math.MaxInt64, Below
+ }
+
+ panic("unreachable")
+}
+
+// Float32 returns the float32 value nearest to x. If x is too small to be
+// represented by a float32 (|x| < [math.SmallestNonzeroFloat32]), the result
+// is (0, [Below]) or (-0, [Above]), respectively, depending on the sign of x.
+// If x is too large to be represented by a float32 (|x| > [math.MaxFloat32]),
+// the result is (+Inf, [Above]) or (-Inf, [Below]), depending on the sign of x.
+func (x *Float) Float32() (float32, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ switch x.form {
+ case finite:
+ // 0 < |x| < +Inf
+
+ const (
+ fbits = 32 // float size
+ mbits = 23 // mantissa size (excluding implicit msb)
+ ebits = fbits - mbits - 1 // 8 exponent size
+ bias = 1<<(ebits-1) - 1 // 127 exponent bias
+ dmin = 1 - bias - mbits // -149 smallest unbiased exponent (denormal)
+ emin = 1 - bias // -126 smallest unbiased exponent (normal)
+ emax = bias // 127 largest unbiased exponent (normal)
+ )
+
+ // Float mantissa m is 0.5 <= m < 1.0; compute exponent e for float32 mantissa.
+ e := x.exp - 1 // exponent for normal mantissa m with 1.0 <= m < 2.0
+
+ // Compute precision p for float32 mantissa.
+ // If the exponent is too small, we have a denormal number before
+ // rounding and fewer than p mantissa bits of precision available
+ // (the exponent remains fixed but the mantissa gets shifted right).
+ p := mbits + 1 // precision of normal float
+ if e < emin {
+ // recompute precision
+ p = mbits + 1 - emin + int(e)
+ // If p == 0, the mantissa of x is shifted so much to the right
+ // that its msb falls immediately to the right of the float32
+ // mantissa space. In other words, if the smallest denormal is
+ // considered "1.0", for p == 0, the mantissa value m is >= 0.5.
+ // If m > 0.5, it is rounded up to 1.0; i.e., the smallest denormal.
+ // If m == 0.5, it is rounded down to even, i.e., 0.0.
+ // If p < 0, the mantissa value m is <= "0.25" which is never rounded up.
+ if p < 0 /* m <= 0.25 */ || p == 0 && x.mant.sticky(uint(len(x.mant))*_W-1) == 0 /* m == 0.5 */ {
+ // underflow to ±0
+ if x.neg {
+ var z float32
+ return -z, Above
+ }
+ return 0.0, Below
+ }
+ // otherwise, round up
+ // We handle p == 0 explicitly because it's easy and because
+ // Float.round doesn't support rounding to 0 bits of precision.
+ if p == 0 {
+ if x.neg {
+ return -math.SmallestNonzeroFloat32, Below
+ }
+ return math.SmallestNonzeroFloat32, Above
+ }
+ }
+ // p > 0
+
+ // round
+ var r Float
+ r.prec = uint32(p)
+ r.Set(x)
+ e = r.exp - 1
+
+ // Rounding may have caused r to overflow to ±Inf
+ // (rounding never causes underflows to 0).
+ // If the exponent is too large, also overflow to ±Inf.
+ if r.form == inf || e > emax {
+ // overflow
+ if x.neg {
+ return float32(math.Inf(-1)), Below
+ }
+ return float32(math.Inf(+1)), Above
+ }
+ // e <= emax
+
+ // Determine sign, biased exponent, and mantissa.
+ var sign, bexp, mant uint32
+ if x.neg {
+ sign = 1 << (fbits - 1)
+ }
+
+ // Rounding may have caused a denormal number to
+ // become normal. Check again.
+ if e < emin {
+ // denormal number: recompute precision
+ // Since rounding may have at best increased precision
+ // and we have eliminated p <= 0 early, we know p > 0.
+ // bexp == 0 for denormals
+ p = mbits + 1 - emin + int(e)
+ mant = msb32(r.mant) >> uint(fbits-p)
+ } else {
+ // normal number: emin <= e <= emax
+ bexp = uint32(e+bias) << mbits
+ mant = msb32(r.mant) >> ebits & (1< [math.MaxFloat64]),
+// the result is (+Inf, [Above]) or (-Inf, [Below]), depending on the sign of x.
+func (x *Float) Float64() (float64, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ switch x.form {
+ case finite:
+ // 0 < |x| < +Inf
+
+ const (
+ fbits = 64 // float size
+ mbits = 52 // mantissa size (excluding implicit msb)
+ ebits = fbits - mbits - 1 // 11 exponent size
+ bias = 1<<(ebits-1) - 1 // 1023 exponent bias
+ dmin = 1 - bias - mbits // -1074 smallest unbiased exponent (denormal)
+ emin = 1 - bias // -1022 smallest unbiased exponent (normal)
+ emax = bias // 1023 largest unbiased exponent (normal)
+ )
+
+ // Float mantissa m is 0.5 <= m < 1.0; compute exponent e for float64 mantissa.
+ e := x.exp - 1 // exponent for normal mantissa m with 1.0 <= m < 2.0
+
+ // Compute precision p for float64 mantissa.
+ // If the exponent is too small, we have a denormal number before
+ // rounding and fewer than p mantissa bits of precision available
+ // (the exponent remains fixed but the mantissa gets shifted right).
+ p := mbits + 1 // precision of normal float
+ if e < emin {
+ // recompute precision
+ p = mbits + 1 - emin + int(e)
+ // If p == 0, the mantissa of x is shifted so much to the right
+ // that its msb falls immediately to the right of the float64
+ // mantissa space. In other words, if the smallest denormal is
+ // considered "1.0", for p == 0, the mantissa value m is >= 0.5.
+ // If m > 0.5, it is rounded up to 1.0; i.e., the smallest denormal.
+ // If m == 0.5, it is rounded down to even, i.e., 0.0.
+ // If p < 0, the mantissa value m is <= "0.25" which is never rounded up.
+ if p < 0 /* m <= 0.25 */ || p == 0 && x.mant.sticky(uint(len(x.mant))*_W-1) == 0 /* m == 0.5 */ {
+ // underflow to ±0
+ if x.neg {
+ var z float64
+ return -z, Above
+ }
+ return 0.0, Below
+ }
+ // otherwise, round up
+ // We handle p == 0 explicitly because it's easy and because
+ // Float.round doesn't support rounding to 0 bits of precision.
+ if p == 0 {
+ if x.neg {
+ return -math.SmallestNonzeroFloat64, Below
+ }
+ return math.SmallestNonzeroFloat64, Above
+ }
+ }
+ // p > 0
+
+ // round
+ var r Float
+ r.prec = uint32(p)
+ r.Set(x)
+ e = r.exp - 1
+
+ // Rounding may have caused r to overflow to ±Inf
+ // (rounding never causes underflows to 0).
+ // If the exponent is too large, also overflow to ±Inf.
+ if r.form == inf || e > emax {
+ // overflow
+ if x.neg {
+ return math.Inf(-1), Below
+ }
+ return math.Inf(+1), Above
+ }
+ // e <= emax
+
+ // Determine sign, biased exponent, and mantissa.
+ var sign, bexp, mant uint64
+ if x.neg {
+ sign = 1 << (fbits - 1)
+ }
+
+ // Rounding may have caused a denormal number to
+ // become normal. Check again.
+ if e < emin {
+ // denormal number: recompute precision
+ // Since rounding may have at best increased precision
+ // and we have eliminated p <= 0 early, we know p > 0.
+ // bexp == 0 for denormals
+ p = mbits + 1 - emin + int(e)
+ mant = msb64(r.mant) >> uint(fbits-p)
+ } else {
+ // normal number: emin <= e <= emax
+ bexp = uint64(e+bias) << mbits
+ mant = msb64(r.mant) >> ebits & (1< 0, and [Above] for x < 0.
+// If a non-nil *[Int] argument z is provided, [Int] stores
+// the result in z instead of allocating a new [Int].
+func (x *Float) Int(z *Int) (*Int, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ if z == nil && x.form <= finite {
+ z = new(Int)
+ }
+
+ switch x.form {
+ case finite:
+ // 0 < |x| < +Inf
+ acc := makeAcc(x.neg)
+ if x.exp <= 0 {
+ // 0 < |x| < 1
+ return z.SetInt64(0), acc
+ }
+ // x.exp > 0
+
+ // 1 <= |x| < +Inf
+ // determine minimum required precision for x
+ allBits := uint(len(x.mant)) * _W
+ exp := uint(x.exp)
+ if x.MinPrec() <= exp {
+ acc = Exact
+ }
+ // shift mantissa as needed
+ if z == nil {
+ z = new(Int)
+ }
+ z.neg = x.neg
+ switch {
+ case exp > allBits:
+ z.abs = z.abs.shl(x.mant, exp-allBits)
+ default:
+ z.abs = z.abs.set(x.mant)
+ case exp < allBits:
+ z.abs = z.abs.shr(x.mant, allBits-exp)
+ }
+ return z, acc
+
+ case zero:
+ return z.SetInt64(0), Exact
+
+ case inf:
+ return nil, makeAcc(x.neg)
+ }
+
+ panic("unreachable")
+}
+
+// Rat returns the rational number corresponding to x;
+// or nil if x is an infinity.
+// The result is [Exact] if x is not an Inf.
+// If a non-nil *[Rat] argument z is provided, [Rat] stores
+// the result in z instead of allocating a new [Rat].
+func (x *Float) Rat(z *Rat) (*Rat, Accuracy) {
+ if debugFloat {
+ x.validate()
+ }
+
+ if z == nil && x.form <= finite {
+ z = new(Rat)
+ }
+
+ switch x.form {
+ case finite:
+ // 0 < |x| < +Inf
+ allBits := int32(len(x.mant)) * _W
+ // build up numerator and denominator
+ z.a.neg = x.neg
+ switch {
+ case x.exp > allBits:
+ z.a.abs = z.a.abs.shl(x.mant, uint(x.exp-allBits))
+ z.b.abs = z.b.abs[:0] // == 1 (see Rat)
+ // z already in normal form
+ default:
+ z.a.abs = z.a.abs.set(x.mant)
+ z.b.abs = z.b.abs[:0] // == 1 (see Rat)
+ // z already in normal form
+ case x.exp < allBits:
+ z.a.abs = z.a.abs.set(x.mant)
+ t := z.b.abs.setUint64(1)
+ z.b.abs = t.shl(t, uint(allBits-x.exp))
+ z.norm()
+ }
+ return z, Exact
+
+ case zero:
+ return z.SetInt64(0), Exact
+
+ case inf:
+ return nil, makeAcc(x.neg)
+ }
+
+ panic("unreachable")
+}
+
+// Abs sets z to the (possibly rounded) value |x| (the absolute value of x)
+// and returns z.
+func (z *Float) Abs(x *Float) *Float {
+ z.Set(x)
+ z.neg = false
+ return z
+}
+
+// Neg sets z to the (possibly rounded) value of x with its sign negated,
+// and returns z.
+func (z *Float) Neg(x *Float) *Float {
+ z.Set(x)
+ z.neg = !z.neg
+ return z
+}
+
+func validateBinaryOperands(x, y *Float) {
+ if !debugFloat {
+ // avoid performance bugs
+ panic("validateBinaryOperands called but debugFloat is not set")
+ }
+ if len(x.mant) == 0 {
+ panic("empty mantissa for x")
+ }
+ if len(y.mant) == 0 {
+ panic("empty mantissa for y")
+ }
+}
+
+// z = x + y, ignoring signs of x and y for the addition
+// but using the sign of z for rounding the result.
+// x and y must have a non-empty mantissa and valid exponent.
+func (z *Float) uadd(x, y *Float) {
+ // Note: This implementation requires 2 shifts most of the
+ // time. It is also inefficient if exponents or precisions
+ // differ by wide margins. The following article describes
+ // an efficient (but much more complicated) implementation
+ // compatible with the internal representation used here:
+ //
+ // Vincent Lefèvre: "The Generic Multiple-Precision Floating-
+ // Point Addition With Exact Rounding (as in the MPFR Library)"
+ // http://www.vinc17.net/research/papers/rnc6.pdf
+
+ if debugFloat {
+ validateBinaryOperands(x, y)
+ }
+
+ // compute exponents ex, ey for mantissa with "binary point"
+ // on the right (mantissa.0) - use int64 to avoid overflow
+ ex := int64(x.exp) - int64(len(x.mant))*_W
+ ey := int64(y.exp) - int64(len(y.mant))*_W
+
+ al := alias(z.mant, x.mant) || alias(z.mant, y.mant)
+
+ // TODO(gri) having a combined add-and-shift primitive
+ // could make this code significantly faster
+ switch {
+ case ex < ey:
+ if al {
+ t := nat(nil).shl(y.mant, uint(ey-ex))
+ z.mant = z.mant.add(x.mant, t)
+ } else {
+ z.mant = z.mant.shl(y.mant, uint(ey-ex))
+ z.mant = z.mant.add(x.mant, z.mant)
+ }
+ default:
+ // ex == ey, no shift needed
+ z.mant = z.mant.add(x.mant, y.mant)
+ case ex > ey:
+ if al {
+ t := nat(nil).shl(x.mant, uint(ex-ey))
+ z.mant = z.mant.add(t, y.mant)
+ } else {
+ z.mant = z.mant.shl(x.mant, uint(ex-ey))
+ z.mant = z.mant.add(z.mant, y.mant)
+ }
+ ex = ey
+ }
+ // len(z.mant) > 0
+
+ z.setExpAndRound(ex+int64(len(z.mant))*_W-fnorm(z.mant), 0)
+}
+
+// z = x - y for |x| > |y|, ignoring signs of x and y for the subtraction
+// but using the sign of z for rounding the result.
+// x and y must have a non-empty mantissa and valid exponent.
+func (z *Float) usub(x, y *Float) {
+ // This code is symmetric to uadd.
+ // We have not factored the common code out because
+ // eventually uadd (and usub) should be optimized
+ // by special-casing, and the code will diverge.
+
+ if debugFloat {
+ validateBinaryOperands(x, y)
+ }
+
+ ex := int64(x.exp) - int64(len(x.mant))*_W
+ ey := int64(y.exp) - int64(len(y.mant))*_W
+
+ al := alias(z.mant, x.mant) || alias(z.mant, y.mant)
+
+ switch {
+ case ex < ey:
+ if al {
+ t := nat(nil).shl(y.mant, uint(ey-ex))
+ z.mant = t.sub(x.mant, t)
+ } else {
+ z.mant = z.mant.shl(y.mant, uint(ey-ex))
+ z.mant = z.mant.sub(x.mant, z.mant)
+ }
+ default:
+ // ex == ey, no shift needed
+ z.mant = z.mant.sub(x.mant, y.mant)
+ case ex > ey:
+ if al {
+ t := nat(nil).shl(x.mant, uint(ex-ey))
+ z.mant = t.sub(t, y.mant)
+ } else {
+ z.mant = z.mant.shl(x.mant, uint(ex-ey))
+ z.mant = z.mant.sub(z.mant, y.mant)
+ }
+ ex = ey
+ }
+
+ // operands may have canceled each other out
+ if len(z.mant) == 0 {
+ z.acc = Exact
+ z.form = zero
+ z.neg = false
+ return
+ }
+ // len(z.mant) > 0
+
+ z.setExpAndRound(ex+int64(len(z.mant))*_W-fnorm(z.mant), 0)
+}
+
+// z = x * y, ignoring signs of x and y for the multiplication
+// but using the sign of z for rounding the result.
+// x and y must have a non-empty mantissa and valid exponent.
+func (z *Float) umul(x, y *Float) {
+ if debugFloat {
+ validateBinaryOperands(x, y)
+ }
+
+ // Note: This is doing too much work if the precision
+ // of z is less than the sum of the precisions of x
+ // and y which is often the case (e.g., if all floats
+ // have the same precision).
+ // TODO(gri) Optimize this for the common case.
+
+ e := int64(x.exp) + int64(y.exp)
+ if x == y {
+ z.mant = z.mant.sqr(x.mant)
+ } else {
+ z.mant = z.mant.mul(x.mant, y.mant)
+ }
+ z.setExpAndRound(e-fnorm(z.mant), 0)
+}
+
+// z = x / y, ignoring signs of x and y for the division
+// but using the sign of z for rounding the result.
+// x and y must have a non-empty mantissa and valid exponent.
+func (z *Float) uquo(x, y *Float) {
+ if debugFloat {
+ validateBinaryOperands(x, y)
+ }
+
+ // mantissa length in words for desired result precision + 1
+ // (at least one extra bit so we get the rounding bit after
+ // the division)
+ n := int(z.prec/_W) + 1
+
+ // compute adjusted x.mant such that we get enough result precision
+ xadj := x.mant
+ if d := n - len(x.mant) + len(y.mant); d > 0 {
+ // d extra words needed => add d "0 digits" to x
+ xadj = make(nat, len(x.mant)+d)
+ copy(xadj[d:], x.mant)
+ }
+ // TODO(gri): If we have too many digits (d < 0), we should be able
+ // to shorten x for faster division. But we must be extra careful
+ // with rounding in that case.
+
+ // Compute d before division since there may be aliasing of x.mant
+ // (via xadj) or y.mant with z.mant.
+ d := len(xadj) - len(y.mant)
+
+ // divide
+ var r nat
+ z.mant, r = z.mant.div(nil, xadj, y.mant)
+ e := int64(x.exp) - int64(y.exp) - int64(d-len(z.mant))*_W
+
+ // The result is long enough to include (at least) the rounding bit.
+ // If there's a non-zero remainder, the corresponding fractional part
+ // (if it were computed), would have a non-zero sticky bit (if it were
+ // zero, it couldn't have a non-zero remainder).
+ var sbit uint
+ if len(r) > 0 {
+ sbit = 1
+ }
+
+ z.setExpAndRound(e-fnorm(z.mant), sbit)
+}
+
+// ucmp returns -1, 0, or +1, depending on whether
+// |x| < |y|, |x| == |y|, or |x| > |y|.
+// x and y must have a non-empty mantissa and valid exponent.
+func (x *Float) ucmp(y *Float) int {
+ if debugFloat {
+ validateBinaryOperands(x, y)
+ }
+
+ switch {
+ case x.exp < y.exp:
+ return -1
+ case x.exp > y.exp:
+ return +1
+ }
+ // x.exp == y.exp
+
+ // compare mantissas
+ i := len(x.mant)
+ j := len(y.mant)
+ for i > 0 || j > 0 {
+ var xm, ym Word
+ if i > 0 {
+ i--
+ xm = x.mant[i]
+ }
+ if j > 0 {
+ j--
+ ym = y.mant[j]
+ }
+ switch {
+ case xm < ym:
+ return -1
+ case xm > ym:
+ return +1
+ }
+ }
+
+ return 0
+}
+
+// Handling of sign bit as defined by IEEE 754-2008, section 6.3:
+//
+// When neither the inputs nor result are NaN, the sign of a product or
+// quotient is the exclusive OR of the operands’ signs; the sign of a sum,
+// or of a difference x−y regarded as a sum x+(−y), differs from at most
+// one of the addends’ signs; and the sign of the result of conversions,
+// the quantize operation, the roundToIntegral operations, and the
+// roundToIntegralExact (see 5.3.1) is the sign of the first or only operand.
+// These rules shall apply even when operands or results are zero or infinite.
+//
+// When the sum of two operands with opposite signs (or the difference of
+// two operands with like signs) is exactly zero, the sign of that sum (or
+// difference) shall be +0 in all rounding-direction attributes except
+// roundTowardNegative; under that attribute, the sign of an exact zero
+// sum (or difference) shall be −0. However, x+x = x−(−x) retains the same
+// sign as x even when x is zero.
+//
+// See also: https://play.golang.org/p/RtH3UCt5IH
+
+// Add sets z to the rounded sum x+y and returns z. If z's precision is 0,
+// it is changed to the larger of x's or y's precision before the operation.
+// Rounding is performed according to z's precision and rounding mode; and
+// z's accuracy reports the result error relative to the exact (not rounded)
+// result. Add panics with [ErrNaN] if x and y are infinities with opposite
+// signs. The value of z is undefined in that case.
+func (z *Float) Add(x, y *Float) *Float {
+ if debugFloat {
+ x.validate()
+ y.validate()
+ }
+
+ if z.prec == 0 {
+ z.prec = umax32(x.prec, y.prec)
+ }
+
+ if x.form == finite && y.form == finite {
+ // x + y (common case)
+
+ // Below we set z.neg = x.neg, and when z aliases y this will
+ // change the y operand's sign. This is fine, because if an
+ // operand aliases the receiver it'll be overwritten, but we still
+ // want the original x.neg and y.neg values when we evaluate
+ // x.neg != y.neg, so we need to save y.neg before setting z.neg.
+ yneg := y.neg
+
+ z.neg = x.neg
+ if x.neg == yneg {
+ // x + y == x + y
+ // (-x) + (-y) == -(x + y)
+ z.uadd(x, y)
+ } else {
+ // x + (-y) == x - y == -(y - x)
+ // (-x) + y == y - x == -(x - y)
+ if x.ucmp(y) > 0 {
+ z.usub(x, y)
+ } else {
+ z.neg = !z.neg
+ z.usub(y, x)
+ }
+ }
+ if z.form == zero && z.mode == ToNegativeInf && z.acc == Exact {
+ z.neg = true
+ }
+ return z
+ }
+
+ if x.form == inf && y.form == inf && x.neg != y.neg {
+ // +Inf + -Inf
+ // -Inf + +Inf
+ // value of z is undefined but make sure it's valid
+ z.acc = Exact
+ z.form = zero
+ z.neg = false
+ panic(ErrNaN{"addition of infinities with opposite signs"})
+ }
+
+ if x.form == zero && y.form == zero {
+ // ±0 + ±0
+ z.acc = Exact
+ z.form = zero
+ z.neg = x.neg && y.neg // -0 + -0 == -0
+ return z
+ }
+
+ if x.form == inf || y.form == zero {
+ // ±Inf + y
+ // x + ±0
+ return z.Set(x)
+ }
+
+ // ±0 + y
+ // x + ±Inf
+ return z.Set(y)
+}
+
+// Sub sets z to the rounded difference x-y and returns z.
+// Precision, rounding, and accuracy reporting are as for [Float.Add].
+// Sub panics with [ErrNaN] if x and y are infinities with equal
+// signs. The value of z is undefined in that case.
+func (z *Float) Sub(x, y *Float) *Float {
+ if debugFloat {
+ x.validate()
+ y.validate()
+ }
+
+ if z.prec == 0 {
+ z.prec = umax32(x.prec, y.prec)
+ }
+
+ if x.form == finite && y.form == finite {
+ // x - y (common case)
+ yneg := y.neg
+ z.neg = x.neg
+ if x.neg != yneg {
+ // x - (-y) == x + y
+ // (-x) - y == -(x + y)
+ z.uadd(x, y)
+ } else {
+ // x - y == x - y == -(y - x)
+ // (-x) - (-y) == y - x == -(x - y)
+ if x.ucmp(y) > 0 {
+ z.usub(x, y)
+ } else {
+ z.neg = !z.neg
+ z.usub(y, x)
+ }
+ }
+ if z.form == zero && z.mode == ToNegativeInf && z.acc == Exact {
+ z.neg = true
+ }
+ return z
+ }
+
+ if x.form == inf && y.form == inf && x.neg == y.neg {
+ // +Inf - +Inf
+ // -Inf - -Inf
+ // value of z is undefined but make sure it's valid
+ z.acc = Exact
+ z.form = zero
+ z.neg = false
+ panic(ErrNaN{"subtraction of infinities with equal signs"})
+ }
+
+ if x.form == zero && y.form == zero {
+ // ±0 - ±0
+ z.acc = Exact
+ z.form = zero
+ z.neg = x.neg && !y.neg // -0 - +0 == -0
+ return z
+ }
+
+ if x.form == inf || y.form == zero {
+ // ±Inf - y
+ // x - ±0
+ return z.Set(x)
+ }
+
+ // ±0 - y
+ // x - ±Inf
+ return z.Neg(y)
+}
+
+// Mul sets z to the rounded product x*y and returns z.
+// Precision, rounding, and accuracy reporting are as for [Float.Add].
+// Mul panics with [ErrNaN] if one operand is zero and the other
+// operand an infinity. The value of z is undefined in that case.
+func (z *Float) Mul(x, y *Float) *Float {
+ if debugFloat {
+ x.validate()
+ y.validate()
+ }
+
+ if z.prec == 0 {
+ z.prec = umax32(x.prec, y.prec)
+ }
+
+ z.neg = x.neg != y.neg
+
+ if x.form == finite && y.form == finite {
+ // x * y (common case)
+ z.umul(x, y)
+ return z
+ }
+
+ z.acc = Exact
+ if x.form == zero && y.form == inf || x.form == inf && y.form == zero {
+ // ±0 * ±Inf
+ // ±Inf * ±0
+ // value of z is undefined but make sure it's valid
+ z.form = zero
+ z.neg = false
+ panic(ErrNaN{"multiplication of zero with infinity"})
+ }
+
+ if x.form == inf || y.form == inf {
+ // ±Inf * y
+ // x * ±Inf
+ z.form = inf
+ return z
+ }
+
+ // ±0 * y
+ // x * ±0
+ z.form = zero
+ return z
+}
+
+// Quo sets z to the rounded quotient x/y and returns z.
+// Precision, rounding, and accuracy reporting are as for [Float.Add].
+// Quo panics with [ErrNaN] if both operands are zero or infinities.
+// The value of z is undefined in that case.
+func (z *Float) Quo(x, y *Float) *Float {
+ if debugFloat {
+ x.validate()
+ y.validate()
+ }
+
+ if z.prec == 0 {
+ z.prec = umax32(x.prec, y.prec)
+ }
+
+ z.neg = x.neg != y.neg
+
+ if x.form == finite && y.form == finite {
+ // x / y (common case)
+ z.uquo(x, y)
+ return z
+ }
+
+ z.acc = Exact
+ if x.form == zero && y.form == zero || x.form == inf && y.form == inf {
+ // ±0 / ±0
+ // ±Inf / ±Inf
+ // value of z is undefined but make sure it's valid
+ z.form = zero
+ z.neg = false
+ panic(ErrNaN{"division of zero by zero or infinity by infinity"})
+ }
+
+ if x.form == zero || y.form == inf {
+ // ±0 / y
+ // x / ±Inf
+ z.form = zero
+ return z
+ }
+
+ // x / ±0
+ // ±Inf / y
+ z.form = inf
+ return z
+}
+
+// Cmp compares x and y and returns:
+//
+// -1 if x < y
+// 0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
+// +1 if x > y
+func (x *Float) Cmp(y *Float) int {
+ if debugFloat {
+ x.validate()
+ y.validate()
+ }
+
+ mx := x.ord()
+ my := y.ord()
+ switch {
+ case mx < my:
+ return -1
+ case mx > my:
+ return +1
+ }
+ // mx == my
+
+ // only if |mx| == 1 we have to compare the mantissae
+ switch mx {
+ case -1:
+ return y.ucmp(x)
+ case +1:
+ return x.ucmp(y)
+ }
+
+ return 0
+}
+
+// ord classifies x and returns:
+//
+// -2 if -Inf == x
+// -1 if -Inf < x < 0
+// 0 if x == 0 (signed or unsigned)
+// +1 if 0 < x < +Inf
+// +2 if x == +Inf
+func (x *Float) ord() int {
+ var m int
+ switch x.form {
+ case finite:
+ m = 1
+ case zero:
+ return 0
+ case inf:
+ m = 2
+ }
+ if x.neg {
+ m = -m
+ }
+ return m
+}
+
+func umax32(x, y uint32) uint32 {
+ if x > y {
+ return x
+ }
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/float_test.go b/platform/dbops/binaries/go/go/src/math/big/float_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bb045a0b48fceb04be9745d77afe027651ab881a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/float_test.go
@@ -0,0 +1,1856 @@
+// Copyright 2014 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 big
+
+import (
+ "flag"
+ "fmt"
+ "math"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// Verify that ErrNaN implements the error interface.
+var _ error = ErrNaN{}
+
+func (x *Float) uint64() uint64 {
+ u, acc := x.Uint64()
+ if acc != Exact {
+ panic(fmt.Sprintf("%s is not a uint64", x.Text('g', 10)))
+ }
+ return u
+}
+
+func (x *Float) int64() int64 {
+ i, acc := x.Int64()
+ if acc != Exact {
+ panic(fmt.Sprintf("%s is not an int64", x.Text('g', 10)))
+ }
+ return i
+}
+
+func TestFloatZeroValue(t *testing.T) {
+ // zero (uninitialized) value is a ready-to-use 0.0
+ var x Float
+ if s := x.Text('f', 1); s != "0.0" {
+ t.Errorf("zero value = %s; want 0.0", s)
+ }
+
+ // zero value has precision 0
+ if prec := x.Prec(); prec != 0 {
+ t.Errorf("prec = %d; want 0", prec)
+ }
+
+ // zero value can be used in any and all positions of binary operations
+ make := func(x int) *Float {
+ var f Float
+ if x != 0 {
+ f.SetInt64(int64(x))
+ }
+ // x == 0 translates into the zero value
+ return &f
+ }
+ for _, test := range []struct {
+ z, x, y, want int
+ opname rune
+ op func(z, x, y *Float) *Float
+ }{
+ {0, 0, 0, 0, '+', (*Float).Add},
+ {0, 1, 2, 3, '+', (*Float).Add},
+ {1, 2, 0, 2, '+', (*Float).Add},
+ {2, 0, 1, 1, '+', (*Float).Add},
+
+ {0, 0, 0, 0, '-', (*Float).Sub},
+ {0, 1, 2, -1, '-', (*Float).Sub},
+ {1, 2, 0, 2, '-', (*Float).Sub},
+ {2, 0, 1, -1, '-', (*Float).Sub},
+
+ {0, 0, 0, 0, '*', (*Float).Mul},
+ {0, 1, 2, 2, '*', (*Float).Mul},
+ {1, 2, 0, 0, '*', (*Float).Mul},
+ {2, 0, 1, 0, '*', (*Float).Mul},
+
+ // {0, 0, 0, 0, '/', (*Float).Quo}, // panics
+ {0, 2, 1, 2, '/', (*Float).Quo},
+ {1, 2, 0, 0, '/', (*Float).Quo}, // = +Inf
+ {2, 0, 1, 0, '/', (*Float).Quo},
+ } {
+ z := make(test.z)
+ test.op(z, make(test.x), make(test.y))
+ got := 0
+ if !z.IsInf() {
+ got = int(z.int64())
+ }
+ if got != test.want {
+ t.Errorf("%d %c %d = %d; want %d", test.x, test.opname, test.y, got, test.want)
+ }
+ }
+
+ // TODO(gri) test how precision is set for zero value results
+}
+
+func makeFloat(s string) *Float {
+ x, _, err := ParseFloat(s, 0, 1000, ToNearestEven)
+ if err != nil {
+ panic(err)
+ }
+ return x
+}
+
+func TestFloatSetPrec(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ prec uint
+ want string
+ acc Accuracy
+ }{
+ // prec 0
+ {"0", 0, "0", Exact},
+ {"-0", 0, "-0", Exact},
+ {"-Inf", 0, "-Inf", Exact},
+ {"+Inf", 0, "+Inf", Exact},
+ {"123", 0, "0", Below},
+ {"-123", 0, "-0", Above},
+
+ // prec at upper limit
+ {"0", MaxPrec, "0", Exact},
+ {"-0", MaxPrec, "-0", Exact},
+ {"-Inf", MaxPrec, "-Inf", Exact},
+ {"+Inf", MaxPrec, "+Inf", Exact},
+
+ // just a few regular cases - general rounding is tested elsewhere
+ {"1.5", 1, "2", Above},
+ {"-1.5", 1, "-2", Below},
+ {"123", 1e6, "123", Exact},
+ {"-123", 1e6, "-123", Exact},
+ } {
+ x := makeFloat(test.x).SetPrec(test.prec)
+ prec := test.prec
+ if prec > MaxPrec {
+ prec = MaxPrec
+ }
+ if got := x.Prec(); got != prec {
+ t.Errorf("%s.SetPrec(%d).Prec() == %d; want %d", test.x, test.prec, got, prec)
+ }
+ if got, acc := x.String(), x.Acc(); got != test.want || acc != test.acc {
+ t.Errorf("%s.SetPrec(%d) = %s (%s); want %s (%s)", test.x, test.prec, got, acc, test.want, test.acc)
+ }
+ }
+}
+
+func TestFloatMinPrec(t *testing.T) {
+ const max = 100
+ for _, test := range []struct {
+ x string
+ want uint
+ }{
+ {"0", 0},
+ {"-0", 0},
+ {"+Inf", 0},
+ {"-Inf", 0},
+ {"1", 1},
+ {"2", 1},
+ {"3", 2},
+ {"0x8001", 16},
+ {"0x8001p-1000", 16},
+ {"0x8001p+1000", 16},
+ {"0.1", max},
+ } {
+ x := makeFloat(test.x).SetPrec(max)
+ if got := x.MinPrec(); got != test.want {
+ t.Errorf("%s.MinPrec() = %d; want %d", test.x, got, test.want)
+ }
+ }
+}
+
+func TestFloatSign(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ s int
+ }{
+ {"-Inf", -1},
+ {"-1", -1},
+ {"-0", 0},
+ {"+0", 0},
+ {"+1", +1},
+ {"+Inf", +1},
+ } {
+ x := makeFloat(test.x)
+ s := x.Sign()
+ if s != test.s {
+ t.Errorf("%s.Sign() = %d; want %d", test.x, s, test.s)
+ }
+ }
+}
+
+// alike(x, y) is like x.Cmp(y) == 0 but also considers the sign of 0 (0 != -0).
+func alike(x, y *Float) bool {
+ return x.Cmp(y) == 0 && x.Signbit() == y.Signbit()
+}
+
+func alike32(x, y float32) bool {
+ // we can ignore NaNs
+ return x == y && math.Signbit(float64(x)) == math.Signbit(float64(y))
+}
+
+func alike64(x, y float64) bool {
+ // we can ignore NaNs
+ return x == y && math.Signbit(x) == math.Signbit(y)
+}
+
+func TestFloatMantExp(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ mant string
+ exp int
+ }{
+ {"0", "0", 0},
+ {"+0", "0", 0},
+ {"-0", "-0", 0},
+ {"Inf", "+Inf", 0},
+ {"+Inf", "+Inf", 0},
+ {"-Inf", "-Inf", 0},
+ {"1.5", "0.75", 1},
+ {"1.024e3", "0.5", 11},
+ {"-0.125", "-0.5", -2},
+ } {
+ x := makeFloat(test.x)
+ mant := makeFloat(test.mant)
+ m := new(Float)
+ e := x.MantExp(m)
+ if !alike(m, mant) || e != test.exp {
+ t.Errorf("%s.MantExp() = %s, %d; want %s, %d", test.x, m.Text('g', 10), e, test.mant, test.exp)
+ }
+ }
+}
+
+func TestFloatMantExpAliasing(t *testing.T) {
+ x := makeFloat("0.5p10")
+ if e := x.MantExp(x); e != 10 {
+ t.Fatalf("Float.MantExp aliasing error: got %d; want 10", e)
+ }
+ if want := makeFloat("0.5"); !alike(x, want) {
+ t.Fatalf("Float.MantExp aliasing error: got %s; want %s", x.Text('g', 10), want.Text('g', 10))
+ }
+}
+
+func TestFloatSetMantExp(t *testing.T) {
+ for _, test := range []struct {
+ frac string
+ exp int
+ z string
+ }{
+ {"0", 0, "0"},
+ {"+0", 0, "0"},
+ {"-0", 0, "-0"},
+ {"Inf", 1234, "+Inf"},
+ {"+Inf", -1234, "+Inf"},
+ {"-Inf", -1234, "-Inf"},
+ {"0", MinExp, "0"},
+ {"0.25", MinExp, "+0"}, // exponent underflow
+ {"-0.25", MinExp, "-0"}, // exponent underflow
+ {"1", MaxExp, "+Inf"}, // exponent overflow
+ {"2", MaxExp - 1, "+Inf"}, // exponent overflow
+ {"0.75", 1, "1.5"},
+ {"0.5", 11, "1024"},
+ {"-0.5", -2, "-0.125"},
+ {"32", 5, "1024"},
+ {"1024", -10, "1"},
+ } {
+ frac := makeFloat(test.frac)
+ want := makeFloat(test.z)
+ var z Float
+ z.SetMantExp(frac, test.exp)
+ if !alike(&z, want) {
+ t.Errorf("SetMantExp(%s, %d) = %s; want %s", test.frac, test.exp, z.Text('g', 10), test.z)
+ }
+ // test inverse property
+ mant := new(Float)
+ if z.SetMantExp(mant, want.MantExp(mant)).Cmp(want) != 0 {
+ t.Errorf("Inverse property not satisfied: got %s; want %s", z.Text('g', 10), test.z)
+ }
+ }
+}
+
+func TestFloatPredicates(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ sign int
+ signbit, inf bool
+ }{
+ {x: "-Inf", sign: -1, signbit: true, inf: true},
+ {x: "-1", sign: -1, signbit: true},
+ {x: "-0", signbit: true},
+ {x: "0"},
+ {x: "1", sign: 1},
+ {x: "+Inf", sign: 1, inf: true},
+ } {
+ x := makeFloat(test.x)
+ if got := x.Signbit(); got != test.signbit {
+ t.Errorf("(%s).Signbit() = %v; want %v", test.x, got, test.signbit)
+ }
+ if got := x.Sign(); got != test.sign {
+ t.Errorf("(%s).Sign() = %d; want %d", test.x, got, test.sign)
+ }
+ if got := x.IsInf(); got != test.inf {
+ t.Errorf("(%s).IsInf() = %v; want %v", test.x, got, test.inf)
+ }
+ }
+}
+
+func TestFloatIsInt(t *testing.T) {
+ for _, test := range []string{
+ "0 int",
+ "-0 int",
+ "1 int",
+ "-1 int",
+ "0.5",
+ "1.23",
+ "1.23e1",
+ "1.23e2 int",
+ "0.000000001e+8",
+ "0.000000001e+9 int",
+ "1.2345e200 int",
+ "Inf",
+ "+Inf",
+ "-Inf",
+ } {
+ s := strings.TrimSuffix(test, " int")
+ want := s != test
+ if got := makeFloat(s).IsInt(); got != want {
+ t.Errorf("%s.IsInt() == %t", s, got)
+ }
+ }
+}
+
+func fromBinary(s string) int64 {
+ x, err := strconv.ParseInt(s, 2, 64)
+ if err != nil {
+ panic(err)
+ }
+ return x
+}
+
+func toBinary(x int64) string {
+ return strconv.FormatInt(x, 2)
+}
+
+func testFloatRound(t *testing.T, x, r int64, prec uint, mode RoundingMode) {
+ // verify test data
+ var ok bool
+ switch mode {
+ case ToNearestEven, ToNearestAway:
+ ok = true // nothing to do for now
+ case ToZero:
+ if x < 0 {
+ ok = r >= x
+ } else {
+ ok = r <= x
+ }
+ case AwayFromZero:
+ if x < 0 {
+ ok = r <= x
+ } else {
+ ok = r >= x
+ }
+ case ToNegativeInf:
+ ok = r <= x
+ case ToPositiveInf:
+ ok = r >= x
+ default:
+ panic("unreachable")
+ }
+ if !ok {
+ t.Fatalf("incorrect test data for prec = %d, %s: x = %s, r = %s", prec, mode, toBinary(x), toBinary(r))
+ }
+
+ // compute expected accuracy
+ a := Exact
+ switch {
+ case r < x:
+ a = Below
+ case r > x:
+ a = Above
+ }
+
+ // round
+ f := new(Float).SetMode(mode).SetInt64(x).SetPrec(prec)
+
+ // check result
+ r1 := f.int64()
+ p1 := f.Prec()
+ a1 := f.Acc()
+ if r1 != r || p1 != prec || a1 != a {
+ t.Errorf("round %s (%d bits, %s) incorrect: got %s (%d bits, %s); want %s (%d bits, %s)",
+ toBinary(x), prec, mode,
+ toBinary(r1), p1, a1,
+ toBinary(r), prec, a)
+ return
+ }
+
+ // g and f should be the same
+ // (rounding by SetPrec after SetInt64 using default precision
+ // should be the same as rounding by SetInt64 after setting the
+ // precision)
+ g := new(Float).SetMode(mode).SetPrec(prec).SetInt64(x)
+ if !alike(g, f) {
+ t.Errorf("round %s (%d bits, %s) not symmetric: got %s and %s; want %s",
+ toBinary(x), prec, mode,
+ toBinary(g.int64()),
+ toBinary(r1),
+ toBinary(r),
+ )
+ return
+ }
+
+ // h and f should be the same
+ // (repeated rounding should be idempotent)
+ h := new(Float).SetMode(mode).SetPrec(prec).Set(f)
+ if !alike(h, f) {
+ t.Errorf("round %s (%d bits, %s) not idempotent: got %s and %s; want %s",
+ toBinary(x), prec, mode,
+ toBinary(h.int64()),
+ toBinary(r1),
+ toBinary(r),
+ )
+ return
+ }
+}
+
+// TestFloatRound tests basic rounding.
+func TestFloatRound(t *testing.T) {
+ for _, test := range []struct {
+ prec uint
+ x, zero, neven, naway, away string // input, results rounded to prec bits
+ }{
+ {5, "1000", "1000", "1000", "1000", "1000"},
+ {5, "1001", "1001", "1001", "1001", "1001"},
+ {5, "1010", "1010", "1010", "1010", "1010"},
+ {5, "1011", "1011", "1011", "1011", "1011"},
+ {5, "1100", "1100", "1100", "1100", "1100"},
+ {5, "1101", "1101", "1101", "1101", "1101"},
+ {5, "1110", "1110", "1110", "1110", "1110"},
+ {5, "1111", "1111", "1111", "1111", "1111"},
+
+ {4, "1000", "1000", "1000", "1000", "1000"},
+ {4, "1001", "1001", "1001", "1001", "1001"},
+ {4, "1010", "1010", "1010", "1010", "1010"},
+ {4, "1011", "1011", "1011", "1011", "1011"},
+ {4, "1100", "1100", "1100", "1100", "1100"},
+ {4, "1101", "1101", "1101", "1101", "1101"},
+ {4, "1110", "1110", "1110", "1110", "1110"},
+ {4, "1111", "1111", "1111", "1111", "1111"},
+
+ {3, "1000", "1000", "1000", "1000", "1000"},
+ {3, "1001", "1000", "1000", "1010", "1010"},
+ {3, "1010", "1010", "1010", "1010", "1010"},
+ {3, "1011", "1010", "1100", "1100", "1100"},
+ {3, "1100", "1100", "1100", "1100", "1100"},
+ {3, "1101", "1100", "1100", "1110", "1110"},
+ {3, "1110", "1110", "1110", "1110", "1110"},
+ {3, "1111", "1110", "10000", "10000", "10000"},
+
+ {3, "1000001", "1000000", "1000000", "1000000", "1010000"},
+ {3, "1001001", "1000000", "1010000", "1010000", "1010000"},
+ {3, "1010001", "1010000", "1010000", "1010000", "1100000"},
+ {3, "1011001", "1010000", "1100000", "1100000", "1100000"},
+ {3, "1100001", "1100000", "1100000", "1100000", "1110000"},
+ {3, "1101001", "1100000", "1110000", "1110000", "1110000"},
+ {3, "1110001", "1110000", "1110000", "1110000", "10000000"},
+ {3, "1111001", "1110000", "10000000", "10000000", "10000000"},
+
+ {2, "1000", "1000", "1000", "1000", "1000"},
+ {2, "1001", "1000", "1000", "1000", "1100"},
+ {2, "1010", "1000", "1000", "1100", "1100"},
+ {2, "1011", "1000", "1100", "1100", "1100"},
+ {2, "1100", "1100", "1100", "1100", "1100"},
+ {2, "1101", "1100", "1100", "1100", "10000"},
+ {2, "1110", "1100", "10000", "10000", "10000"},
+ {2, "1111", "1100", "10000", "10000", "10000"},
+
+ {2, "1000001", "1000000", "1000000", "1000000", "1100000"},
+ {2, "1001001", "1000000", "1000000", "1000000", "1100000"},
+ {2, "1010001", "1000000", "1100000", "1100000", "1100000"},
+ {2, "1011001", "1000000", "1100000", "1100000", "1100000"},
+ {2, "1100001", "1100000", "1100000", "1100000", "10000000"},
+ {2, "1101001", "1100000", "1100000", "1100000", "10000000"},
+ {2, "1110001", "1100000", "10000000", "10000000", "10000000"},
+ {2, "1111001", "1100000", "10000000", "10000000", "10000000"},
+
+ {1, "1000", "1000", "1000", "1000", "1000"},
+ {1, "1001", "1000", "1000", "1000", "10000"},
+ {1, "1010", "1000", "1000", "1000", "10000"},
+ {1, "1011", "1000", "1000", "1000", "10000"},
+ {1, "1100", "1000", "10000", "10000", "10000"},
+ {1, "1101", "1000", "10000", "10000", "10000"},
+ {1, "1110", "1000", "10000", "10000", "10000"},
+ {1, "1111", "1000", "10000", "10000", "10000"},
+
+ {1, "1000001", "1000000", "1000000", "1000000", "10000000"},
+ {1, "1001001", "1000000", "1000000", "1000000", "10000000"},
+ {1, "1010001", "1000000", "1000000", "1000000", "10000000"},
+ {1, "1011001", "1000000", "1000000", "1000000", "10000000"},
+ {1, "1100001", "1000000", "10000000", "10000000", "10000000"},
+ {1, "1101001", "1000000", "10000000", "10000000", "10000000"},
+ {1, "1110001", "1000000", "10000000", "10000000", "10000000"},
+ {1, "1111001", "1000000", "10000000", "10000000", "10000000"},
+ } {
+ x := fromBinary(test.x)
+ z := fromBinary(test.zero)
+ e := fromBinary(test.neven)
+ n := fromBinary(test.naway)
+ a := fromBinary(test.away)
+ prec := test.prec
+
+ testFloatRound(t, x, z, prec, ToZero)
+ testFloatRound(t, x, e, prec, ToNearestEven)
+ testFloatRound(t, x, n, prec, ToNearestAway)
+ testFloatRound(t, x, a, prec, AwayFromZero)
+
+ testFloatRound(t, x, z, prec, ToNegativeInf)
+ testFloatRound(t, x, a, prec, ToPositiveInf)
+
+ testFloatRound(t, -x, -a, prec, ToNegativeInf)
+ testFloatRound(t, -x, -z, prec, ToPositiveInf)
+ }
+}
+
+// TestFloatRound24 tests that rounding a float64 to 24 bits
+// matches IEEE-754 rounding to nearest when converting a
+// float64 to a float32 (excluding denormal numbers).
+func TestFloatRound24(t *testing.T) {
+ const x0 = 1<<26 - 0x10 // 11...110000 (26 bits)
+ for d := 0; d <= 0x10; d++ {
+ x := float64(x0 + d)
+ f := new(Float).SetPrec(24).SetFloat64(x)
+ got, _ := f.Float32()
+ want := float32(x)
+ if got != want {
+ t.Errorf("Round(%g, 24) = %g; want %g", x, got, want)
+ }
+ }
+}
+
+func TestFloatSetUint64(t *testing.T) {
+ for _, want := range []uint64{
+ 0,
+ 1,
+ 2,
+ 10,
+ 100,
+ 1<<32 - 1,
+ 1 << 32,
+ 1<<64 - 1,
+ } {
+ var f Float
+ f.SetUint64(want)
+ if got := f.uint64(); got != want {
+ t.Errorf("got %#x (%s); want %#x", got, f.Text('p', 0), want)
+ }
+ }
+
+ // test basic rounding behavior (exhaustive rounding testing is done elsewhere)
+ const x uint64 = 0x8765432187654321 // 64 bits needed
+ for prec := uint(1); prec <= 64; prec++ {
+ f := new(Float).SetPrec(prec).SetMode(ToZero).SetUint64(x)
+ got := f.uint64()
+ want := x &^ (1<<(64-prec) - 1) // cut off (round to zero) low 64-prec bits
+ if got != want {
+ t.Errorf("got %#x (%s); want %#x", got, f.Text('p', 0), want)
+ }
+ }
+}
+
+func TestFloatSetInt64(t *testing.T) {
+ for _, want := range []int64{
+ 0,
+ 1,
+ 2,
+ 10,
+ 100,
+ 1<<32 - 1,
+ 1 << 32,
+ 1<<63 - 1,
+ } {
+ for i := range [2]int{} {
+ if i&1 != 0 {
+ want = -want
+ }
+ var f Float
+ f.SetInt64(want)
+ if got := f.int64(); got != want {
+ t.Errorf("got %#x (%s); want %#x", got, f.Text('p', 0), want)
+ }
+ }
+ }
+
+ // test basic rounding behavior (exhaustive rounding testing is done elsewhere)
+ const x int64 = 0x7654321076543210 // 63 bits needed
+ for prec := uint(1); prec <= 63; prec++ {
+ f := new(Float).SetPrec(prec).SetMode(ToZero).SetInt64(x)
+ got := f.int64()
+ want := x &^ (1<<(63-prec) - 1) // cut off (round to zero) low 63-prec bits
+ if got != want {
+ t.Errorf("got %#x (%s); want %#x", got, f.Text('p', 0), want)
+ }
+ }
+}
+
+func TestFloatSetFloat64(t *testing.T) {
+ for _, want := range []float64{
+ 0,
+ 1,
+ 2,
+ 12345,
+ 1e10,
+ 1e100,
+ 3.14159265e10,
+ 2.718281828e-123,
+ 1.0 / 3,
+ math.MaxFloat32,
+ math.MaxFloat64,
+ math.SmallestNonzeroFloat32,
+ math.SmallestNonzeroFloat64,
+ math.Inf(-1),
+ math.Inf(0),
+ -math.Inf(1),
+ } {
+ for i := range [2]int{} {
+ if i&1 != 0 {
+ want = -want
+ }
+ var f Float
+ f.SetFloat64(want)
+ if got, acc := f.Float64(); got != want || acc != Exact {
+ t.Errorf("got %g (%s, %s); want %g (Exact)", got, f.Text('p', 0), acc, want)
+ }
+ }
+ }
+
+ // test basic rounding behavior (exhaustive rounding testing is done elsewhere)
+ const x uint64 = 0x8765432143218 // 53 bits needed
+ for prec := uint(1); prec <= 52; prec++ {
+ f := new(Float).SetPrec(prec).SetMode(ToZero).SetFloat64(float64(x))
+ got, _ := f.Float64()
+ want := float64(x &^ (1<<(52-prec) - 1)) // cut off (round to zero) low 53-prec bits
+ if got != want {
+ t.Errorf("got %g (%s); want %g", got, f.Text('p', 0), want)
+ }
+ }
+
+ // test NaN
+ defer func() {
+ if p, ok := recover().(ErrNaN); !ok {
+ t.Errorf("got %v; want ErrNaN panic", p)
+ }
+ }()
+ var f Float
+ f.SetFloat64(math.NaN())
+ // should not reach here
+ t.Errorf("got %s; want ErrNaN panic", f.Text('p', 0))
+}
+
+func TestFloatSetInt(t *testing.T) {
+ for _, want := range []string{
+ "0",
+ "1",
+ "-1",
+ "1234567890",
+ "123456789012345678901234567890",
+ "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ } {
+ var x Int
+ _, ok := x.SetString(want, 0)
+ if !ok {
+ t.Errorf("invalid integer %s", want)
+ continue
+ }
+ n := x.BitLen()
+
+ var f Float
+ f.SetInt(&x)
+
+ // check precision
+ if n < 64 {
+ n = 64
+ }
+ if prec := f.Prec(); prec != uint(n) {
+ t.Errorf("got prec = %d; want %d", prec, n)
+ }
+
+ // check value
+ got := f.Text('g', 100)
+ if got != want {
+ t.Errorf("got %s (%s); want %s", got, f.Text('p', 0), want)
+ }
+ }
+
+ // TODO(gri) test basic rounding behavior
+}
+
+func TestFloatSetRat(t *testing.T) {
+ for _, want := range []string{
+ "0",
+ "1",
+ "-1",
+ "1234567890",
+ "123456789012345678901234567890",
+ "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ "1.2",
+ "3.14159265",
+ // TODO(gri) expand
+ } {
+ var x Rat
+ _, ok := x.SetString(want)
+ if !ok {
+ t.Errorf("invalid fraction %s", want)
+ continue
+ }
+ n := max(x.Num().BitLen(), x.Denom().BitLen())
+
+ var f1, f2 Float
+ f2.SetPrec(1000)
+ f1.SetRat(&x)
+ f2.SetRat(&x)
+
+ // check precision when set automatically
+ if n < 64 {
+ n = 64
+ }
+ if prec := f1.Prec(); prec != uint(n) {
+ t.Errorf("got prec = %d; want %d", prec, n)
+ }
+
+ got := f2.Text('g', 100)
+ if got != want {
+ t.Errorf("got %s (%s); want %s", got, f2.Text('p', 0), want)
+ }
+ }
+}
+
+func TestFloatSetInf(t *testing.T) {
+ var f Float
+ for _, test := range []struct {
+ signbit bool
+ prec uint
+ want string
+ }{
+ {false, 0, "+Inf"},
+ {true, 0, "-Inf"},
+ {false, 10, "+Inf"},
+ {true, 30, "-Inf"},
+ } {
+ x := f.SetPrec(test.prec).SetInf(test.signbit)
+ if got := x.String(); got != test.want || x.Prec() != test.prec {
+ t.Errorf("SetInf(%v) = %s (prec = %d); want %s (prec = %d)", test.signbit, got, x.Prec(), test.want, test.prec)
+ }
+ }
+}
+
+func TestFloatUint64(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ out uint64
+ acc Accuracy
+ }{
+ {"-Inf", 0, Above},
+ {"-1", 0, Above},
+ {"-1e-1000", 0, Above},
+ {"-0", 0, Exact},
+ {"0", 0, Exact},
+ {"1e-1000", 0, Below},
+ {"1", 1, Exact},
+ {"1.000000000000000000001", 1, Below},
+ {"12345.0", 12345, Exact},
+ {"12345.000000000000000000001", 12345, Below},
+ {"18446744073709551615", 18446744073709551615, Exact},
+ {"18446744073709551615.000000000000000000001", math.MaxUint64, Below},
+ {"18446744073709551616", math.MaxUint64, Below},
+ {"1e10000", math.MaxUint64, Below},
+ {"+Inf", math.MaxUint64, Below},
+ } {
+ x := makeFloat(test.x)
+ out, acc := x.Uint64()
+ if out != test.out || acc != test.acc {
+ t.Errorf("%s: got %d (%s); want %d (%s)", test.x, out, acc, test.out, test.acc)
+ }
+ }
+}
+
+func TestFloatInt64(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ out int64
+ acc Accuracy
+ }{
+ {"-Inf", math.MinInt64, Above},
+ {"-1e10000", math.MinInt64, Above},
+ {"-9223372036854775809", math.MinInt64, Above},
+ {"-9223372036854775808.000000000000000000001", math.MinInt64, Above},
+ {"-9223372036854775808", -9223372036854775808, Exact},
+ {"-9223372036854775807.000000000000000000001", -9223372036854775807, Above},
+ {"-9223372036854775807", -9223372036854775807, Exact},
+ {"-12345.000000000000000000001", -12345, Above},
+ {"-12345.0", -12345, Exact},
+ {"-1.000000000000000000001", -1, Above},
+ {"-1.5", -1, Above},
+ {"-1", -1, Exact},
+ {"-1e-1000", 0, Above},
+ {"0", 0, Exact},
+ {"1e-1000", 0, Below},
+ {"1", 1, Exact},
+ {"1.000000000000000000001", 1, Below},
+ {"1.5", 1, Below},
+ {"12345.0", 12345, Exact},
+ {"12345.000000000000000000001", 12345, Below},
+ {"9223372036854775807", 9223372036854775807, Exact},
+ {"9223372036854775807.000000000000000000001", math.MaxInt64, Below},
+ {"9223372036854775808", math.MaxInt64, Below},
+ {"1e10000", math.MaxInt64, Below},
+ {"+Inf", math.MaxInt64, Below},
+ } {
+ x := makeFloat(test.x)
+ out, acc := x.Int64()
+ if out != test.out || acc != test.acc {
+ t.Errorf("%s: got %d (%s); want %d (%s)", test.x, out, acc, test.out, test.acc)
+ }
+ }
+}
+
+func TestFloatFloat32(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ out float32
+ acc Accuracy
+ }{
+ {"0", 0, Exact},
+
+ // underflow to zero
+ {"1e-1000", 0, Below},
+ {"0x0.000002p-127", 0, Below},
+ {"0x.0000010p-126", 0, Below},
+
+ // denormals
+ {"1.401298464e-45", math.SmallestNonzeroFloat32, Above}, // rounded up to smallest denormal
+ {"0x.ffffff8p-149", math.SmallestNonzeroFloat32, Above}, // rounded up to smallest denormal
+ {"0x.0000018p-126", math.SmallestNonzeroFloat32, Above}, // rounded up to smallest denormal
+ {"0x.0000020p-126", math.SmallestNonzeroFloat32, Exact},
+ {"0x.8p-148", math.SmallestNonzeroFloat32, Exact},
+ {"1p-149", math.SmallestNonzeroFloat32, Exact},
+ {"0x.fffffep-126", math.Float32frombits(0x7fffff), Exact}, // largest denormal
+
+ // special denormal cases (see issues 14553, 14651)
+ {"0x0.0000001p-126", math.Float32frombits(0x00000000), Below}, // underflow to zero
+ {"0x0.0000008p-126", math.Float32frombits(0x00000000), Below}, // underflow to zero
+ {"0x0.0000010p-126", math.Float32frombits(0x00000000), Below}, // rounded down to even
+ {"0x0.0000011p-126", math.Float32frombits(0x00000001), Above}, // rounded up to smallest denormal
+ {"0x0.0000018p-126", math.Float32frombits(0x00000001), Above}, // rounded up to smallest denormal
+
+ {"0x1.0000000p-149", math.Float32frombits(0x00000001), Exact}, // smallest denormal
+ {"0x0.0000020p-126", math.Float32frombits(0x00000001), Exact}, // smallest denormal
+ {"0x0.fffffe0p-126", math.Float32frombits(0x007fffff), Exact}, // largest denormal
+ {"0x1.0000000p-126", math.Float32frombits(0x00800000), Exact}, // smallest normal
+
+ {"0x0.8p-149", math.Float32frombits(0x000000000), Below}, // rounded down to even
+ {"0x0.9p-149", math.Float32frombits(0x000000001), Above}, // rounded up to smallest denormal
+ {"0x0.ap-149", math.Float32frombits(0x000000001), Above}, // rounded up to smallest denormal
+ {"0x0.bp-149", math.Float32frombits(0x000000001), Above}, // rounded up to smallest denormal
+ {"0x0.cp-149", math.Float32frombits(0x000000001), Above}, // rounded up to smallest denormal
+
+ {"0x1.0p-149", math.Float32frombits(0x000000001), Exact}, // smallest denormal
+ {"0x1.7p-149", math.Float32frombits(0x000000001), Below},
+ {"0x1.8p-149", math.Float32frombits(0x000000002), Above},
+ {"0x1.9p-149", math.Float32frombits(0x000000002), Above},
+
+ {"0x2.0p-149", math.Float32frombits(0x000000002), Exact},
+ {"0x2.8p-149", math.Float32frombits(0x000000002), Below}, // rounded down to even
+ {"0x2.9p-149", math.Float32frombits(0x000000003), Above},
+
+ {"0x3.0p-149", math.Float32frombits(0x000000003), Exact},
+ {"0x3.7p-149", math.Float32frombits(0x000000003), Below},
+ {"0x3.8p-149", math.Float32frombits(0x000000004), Above}, // rounded up to even
+
+ {"0x4.0p-149", math.Float32frombits(0x000000004), Exact},
+ {"0x4.8p-149", math.Float32frombits(0x000000004), Below}, // rounded down to even
+ {"0x4.9p-149", math.Float32frombits(0x000000005), Above},
+
+ // specific case from issue 14553
+ {"0x7.7p-149", math.Float32frombits(0x000000007), Below},
+ {"0x7.8p-149", math.Float32frombits(0x000000008), Above},
+ {"0x7.9p-149", math.Float32frombits(0x000000008), Above},
+
+ // normals
+ {"0x.ffffffp-126", math.Float32frombits(0x00800000), Above}, // rounded up to smallest normal
+ {"1p-126", math.Float32frombits(0x00800000), Exact}, // smallest normal
+ {"0x1.fffffep-126", math.Float32frombits(0x00ffffff), Exact},
+ {"0x1.ffffffp-126", math.Float32frombits(0x01000000), Above}, // rounded up
+ {"1", 1, Exact},
+ {"1.000000000000000000001", 1, Below},
+ {"12345.0", 12345, Exact},
+ {"12345.000000000000000000001", 12345, Below},
+ {"0x1.fffffe0p127", math.MaxFloat32, Exact},
+ {"0x1.fffffe8p127", math.MaxFloat32, Below},
+
+ // overflow
+ {"0x1.ffffff0p127", float32(math.Inf(+1)), Above},
+ {"0x1p128", float32(math.Inf(+1)), Above},
+ {"1e10000", float32(math.Inf(+1)), Above},
+ {"0x1.ffffff0p2147483646", float32(math.Inf(+1)), Above}, // overflow in rounding
+
+ // inf
+ {"Inf", float32(math.Inf(+1)), Exact},
+ } {
+ for i := 0; i < 2; i++ {
+ // test both signs
+ tx, tout, tacc := test.x, test.out, test.acc
+ if i != 0 {
+ tx = "-" + tx
+ tout = -tout
+ tacc = -tacc
+ }
+
+ // conversion should match strconv where syntax is agreeable
+ if f, err := strconv.ParseFloat(tx, 32); err == nil && !alike32(float32(f), tout) {
+ t.Errorf("%s: got %g; want %g (incorrect test data)", tx, f, tout)
+ }
+
+ x := makeFloat(tx)
+ out, acc := x.Float32()
+ if !alike32(out, tout) || acc != tacc {
+ t.Errorf("%s: got %g (%#08x, %s); want %g (%#08x, %s)", tx, out, math.Float32bits(out), acc, test.out, math.Float32bits(test.out), tacc)
+ }
+
+ // test that x.SetFloat64(float64(f)).Float32() == f
+ var x2 Float
+ out2, acc2 := x2.SetFloat64(float64(out)).Float32()
+ if !alike32(out2, out) || acc2 != Exact {
+ t.Errorf("idempotency test: got %g (%s); want %g (Exact)", out2, acc2, out)
+ }
+ }
+ }
+}
+
+func TestFloatFloat64(t *testing.T) {
+ const smallestNormalFloat64 = 2.2250738585072014e-308 // 1p-1022
+ for _, test := range []struct {
+ x string
+ out float64
+ acc Accuracy
+ }{
+ {"0", 0, Exact},
+
+ // underflow to zero
+ {"1e-1000", 0, Below},
+ {"0x0.0000000000001p-1023", 0, Below},
+ {"0x0.00000000000008p-1022", 0, Below},
+
+ // denormals
+ {"0x0.0000000000000cp-1022", math.SmallestNonzeroFloat64, Above}, // rounded up to smallest denormal
+ {"0x0.00000000000010p-1022", math.SmallestNonzeroFloat64, Exact}, // smallest denormal
+ {"0x.8p-1073", math.SmallestNonzeroFloat64, Exact},
+ {"1p-1074", math.SmallestNonzeroFloat64, Exact},
+ {"0x.fffffffffffffp-1022", math.Float64frombits(0x000fffffffffffff), Exact}, // largest denormal
+
+ // special denormal cases (see issues 14553, 14651)
+ {"0x0.00000000000001p-1022", math.Float64frombits(0x00000000000000000), Below}, // underflow to zero
+ {"0x0.00000000000004p-1022", math.Float64frombits(0x00000000000000000), Below}, // underflow to zero
+ {"0x0.00000000000008p-1022", math.Float64frombits(0x00000000000000000), Below}, // rounded down to even
+ {"0x0.00000000000009p-1022", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+ {"0x0.0000000000000ap-1022", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+
+ {"0x0.8p-1074", math.Float64frombits(0x00000000000000000), Below}, // rounded down to even
+ {"0x0.9p-1074", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+ {"0x0.ap-1074", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+ {"0x0.bp-1074", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+ {"0x0.cp-1074", math.Float64frombits(0x00000000000000001), Above}, // rounded up to smallest denormal
+
+ {"0x1.0p-1074", math.Float64frombits(0x00000000000000001), Exact},
+ {"0x1.7p-1074", math.Float64frombits(0x00000000000000001), Below},
+ {"0x1.8p-1074", math.Float64frombits(0x00000000000000002), Above},
+ {"0x1.9p-1074", math.Float64frombits(0x00000000000000002), Above},
+
+ {"0x2.0p-1074", math.Float64frombits(0x00000000000000002), Exact},
+ {"0x2.8p-1074", math.Float64frombits(0x00000000000000002), Below}, // rounded down to even
+ {"0x2.9p-1074", math.Float64frombits(0x00000000000000003), Above},
+
+ {"0x3.0p-1074", math.Float64frombits(0x00000000000000003), Exact},
+ {"0x3.7p-1074", math.Float64frombits(0x00000000000000003), Below},
+ {"0x3.8p-1074", math.Float64frombits(0x00000000000000004), Above}, // rounded up to even
+
+ {"0x4.0p-1074", math.Float64frombits(0x00000000000000004), Exact},
+ {"0x4.8p-1074", math.Float64frombits(0x00000000000000004), Below}, // rounded down to even
+ {"0x4.9p-1074", math.Float64frombits(0x00000000000000005), Above},
+
+ // normals
+ {"0x.fffffffffffff8p-1022", math.Float64frombits(0x0010000000000000), Above}, // rounded up to smallest normal
+ {"1p-1022", math.Float64frombits(0x0010000000000000), Exact}, // smallest normal
+ {"1", 1, Exact},
+ {"1.000000000000000000001", 1, Below},
+ {"12345.0", 12345, Exact},
+ {"12345.000000000000000000001", 12345, Below},
+ {"0x1.fffffffffffff0p1023", math.MaxFloat64, Exact},
+ {"0x1.fffffffffffff4p1023", math.MaxFloat64, Below},
+
+ // overflow
+ {"0x1.fffffffffffff8p1023", math.Inf(+1), Above},
+ {"0x1p1024", math.Inf(+1), Above},
+ {"1e10000", math.Inf(+1), Above},
+ {"0x1.fffffffffffff8p2147483646", math.Inf(+1), Above}, // overflow in rounding
+ {"Inf", math.Inf(+1), Exact},
+
+ // selected denormalized values that were handled incorrectly in the past
+ {"0x.fffffffffffffp-1022", smallestNormalFloat64 - math.SmallestNonzeroFloat64, Exact},
+ {"4503599627370495p-1074", smallestNormalFloat64 - math.SmallestNonzeroFloat64, Exact},
+
+ // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/
+ {"2.2250738585072011e-308", 2.225073858507201e-308, Below},
+ // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
+ {"2.2250738585072012e-308", 2.2250738585072014e-308, Above},
+ } {
+ for i := 0; i < 2; i++ {
+ // test both signs
+ tx, tout, tacc := test.x, test.out, test.acc
+ if i != 0 {
+ tx = "-" + tx
+ tout = -tout
+ tacc = -tacc
+ }
+
+ // conversion should match strconv where syntax is agreeable
+ if f, err := strconv.ParseFloat(tx, 64); err == nil && !alike64(f, tout) {
+ t.Errorf("%s: got %g; want %g (incorrect test data)", tx, f, tout)
+ }
+
+ x := makeFloat(tx)
+ out, acc := x.Float64()
+ if !alike64(out, tout) || acc != tacc {
+ t.Errorf("%s: got %g (%#016x, %s); want %g (%#016x, %s)", tx, out, math.Float64bits(out), acc, test.out, math.Float64bits(test.out), tacc)
+ }
+
+ // test that x.SetFloat64(f).Float64() == f
+ var x2 Float
+ out2, acc2 := x2.SetFloat64(out).Float64()
+ if !alike64(out2, out) || acc2 != Exact {
+ t.Errorf("idempotency test: got %g (%s); want %g (Exact)", out2, acc2, out)
+ }
+ }
+ }
+}
+
+func TestFloatInt(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ want string
+ acc Accuracy
+ }{
+ {"0", "0", Exact},
+ {"+0", "0", Exact},
+ {"-0", "0", Exact},
+ {"Inf", "nil", Below},
+ {"+Inf", "nil", Below},
+ {"-Inf", "nil", Above},
+ {"1", "1", Exact},
+ {"-1", "-1", Exact},
+ {"1.23", "1", Below},
+ {"-1.23", "-1", Above},
+ {"123e-2", "1", Below},
+ {"123e-3", "0", Below},
+ {"123e-4", "0", Below},
+ {"1e-1000", "0", Below},
+ {"-1e-1000", "0", Above},
+ {"1e+10", "10000000000", Exact},
+ {"1e+100", "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", Exact},
+ } {
+ x := makeFloat(test.x)
+ res, acc := x.Int(nil)
+ got := "nil"
+ if res != nil {
+ got = res.String()
+ }
+ if got != test.want || acc != test.acc {
+ t.Errorf("%s: got %s (%s); want %s (%s)", test.x, got, acc, test.want, test.acc)
+ }
+ }
+
+ // check that supplied *Int is used
+ for _, f := range []string{"0", "1", "-1", "1234"} {
+ x := makeFloat(f)
+ i := new(Int)
+ if res, _ := x.Int(i); res != i {
+ t.Errorf("(%s).Int is not using supplied *Int", f)
+ }
+ }
+}
+
+func TestFloatRat(t *testing.T) {
+ for _, test := range []struct {
+ x, want string
+ acc Accuracy
+ }{
+ {"0", "0/1", Exact},
+ {"+0", "0/1", Exact},
+ {"-0", "0/1", Exact},
+ {"Inf", "nil", Below},
+ {"+Inf", "nil", Below},
+ {"-Inf", "nil", Above},
+ {"1", "1/1", Exact},
+ {"-1", "-1/1", Exact},
+ {"1.25", "5/4", Exact},
+ {"-1.25", "-5/4", Exact},
+ {"1e10", "10000000000/1", Exact},
+ {"1p10", "1024/1", Exact},
+ {"-1p-10", "-1/1024", Exact},
+ {"3.14159265", "7244019449799623199/2305843009213693952", Exact},
+ } {
+ x := makeFloat(test.x).SetPrec(64)
+ res, acc := x.Rat(nil)
+ got := "nil"
+ if res != nil {
+ got = res.String()
+ }
+ if got != test.want {
+ t.Errorf("%s: got %s; want %s", test.x, got, test.want)
+ continue
+ }
+ if acc != test.acc {
+ t.Errorf("%s: got %s; want %s", test.x, acc, test.acc)
+ continue
+ }
+
+ // inverse conversion
+ if res != nil {
+ got := new(Float).SetPrec(64).SetRat(res)
+ if got.Cmp(x) != 0 {
+ t.Errorf("%s: got %s; want %s", test.x, got, x)
+ }
+ }
+ }
+
+ // check that supplied *Rat is used
+ for _, f := range []string{"0", "1", "-1", "1234"} {
+ x := makeFloat(f)
+ r := new(Rat)
+ if res, _ := x.Rat(r); res != r {
+ t.Errorf("(%s).Rat is not using supplied *Rat", f)
+ }
+ }
+}
+
+func TestFloatAbs(t *testing.T) {
+ for _, test := range []string{
+ "0",
+ "1",
+ "1234",
+ "1.23e-2",
+ "1e-1000",
+ "1e1000",
+ "Inf",
+ } {
+ p := makeFloat(test)
+ a := new(Float).Abs(p)
+ if !alike(a, p) {
+ t.Errorf("%s: got %s; want %s", test, a.Text('g', 10), test)
+ }
+
+ n := makeFloat("-" + test)
+ a.Abs(n)
+ if !alike(a, p) {
+ t.Errorf("-%s: got %s; want %s", test, a.Text('g', 10), test)
+ }
+ }
+}
+
+func TestFloatNeg(t *testing.T) {
+ for _, test := range []string{
+ "0",
+ "1",
+ "1234",
+ "1.23e-2",
+ "1e-1000",
+ "1e1000",
+ "Inf",
+ } {
+ p1 := makeFloat(test)
+ n1 := makeFloat("-" + test)
+ n2 := new(Float).Neg(p1)
+ p2 := new(Float).Neg(n2)
+ if !alike(n2, n1) {
+ t.Errorf("%s: got %s; want %s", test, n2.Text('g', 10), n1.Text('g', 10))
+ }
+ if !alike(p2, p1) {
+ t.Errorf("%s: got %s; want %s", test, p2.Text('g', 10), p1.Text('g', 10))
+ }
+ }
+}
+
+func TestFloatInc(t *testing.T) {
+ const n = 10
+ for _, prec := range precList {
+ if 1< y:
+ want = +1
+ }
+ if got != want {
+ t.Errorf("(%g).Cmp(%g) = %v; want %v", x, y, got, want)
+ }
+ }
+ }
+ }
+}
+
+func BenchmarkFloatAdd(b *testing.B) {
+ x := new(Float)
+ y := new(Float)
+ z := new(Float)
+
+ for _, prec := range []uint{10, 1e2, 1e3, 1e4, 1e5} {
+ x.SetPrec(prec).SetRat(NewRat(1, 3))
+ y.SetPrec(prec).SetRat(NewRat(1, 6))
+ z.SetPrec(prec)
+
+ b.Run(fmt.Sprintf("%v", prec), func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ z.Add(x, y)
+ }
+ })
+ }
+}
+
+func BenchmarkFloatSub(b *testing.B) {
+ x := new(Float)
+ y := new(Float)
+ z := new(Float)
+
+ for _, prec := range []uint{10, 1e2, 1e3, 1e4, 1e5} {
+ x.SetPrec(prec).SetRat(NewRat(1, 3))
+ y.SetPrec(prec).SetRat(NewRat(1, 6))
+ z.SetPrec(prec)
+
+ b.Run(fmt.Sprintf("%v", prec), func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ z.Sub(x, y)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/floatconv.go b/platform/dbops/binaries/go/go/src/math/big/floatconv.go
new file mode 100644
index 0000000000000000000000000000000000000000..d8c69b8b283e0baa876ad17a6fe2a4f9642074e5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/floatconv.go
@@ -0,0 +1,302 @@
+// 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 string-to-Float conversion functions.
+
+package big
+
+import (
+ "fmt"
+ "io"
+ "strings"
+)
+
+var floatZero Float
+
+// SetString sets z to the value of s and returns z and a boolean indicating
+// success. s must be a floating-point number of the same format as accepted
+// by [Float.Parse], with base argument 0. The entire string (not just a prefix) must
+// be valid for success. If the operation failed, the value of z is undefined
+// but the returned value is nil.
+func (z *Float) SetString(s string) (*Float, bool) {
+ if f, _, err := z.Parse(s, 0); err == nil {
+ return f, true
+ }
+ return nil, false
+}
+
+// scan is like Parse but reads the longest possible prefix representing a valid
+// floating point number from an io.ByteScanner rather than a string. It serves
+// as the implementation of Parse. It does not recognize ±Inf and does not expect
+// EOF at the end.
+func (z *Float) scan(r io.ByteScanner, base int) (f *Float, b int, err error) {
+ prec := z.prec
+ if prec == 0 {
+ prec = 64
+ }
+
+ // A reasonable value in case of an error.
+ z.form = zero
+
+ // sign
+ z.neg, err = scanSign(r)
+ if err != nil {
+ return
+ }
+
+ // mantissa
+ var fcount int // fractional digit count; valid if <= 0
+ z.mant, b, fcount, err = z.mant.scan(r, base, true)
+ if err != nil {
+ return
+ }
+
+ // exponent
+ var exp int64
+ var ebase int
+ exp, ebase, err = scanExponent(r, true, base == 0)
+ if err != nil {
+ return
+ }
+
+ // special-case 0
+ if len(z.mant) == 0 {
+ z.prec = prec
+ z.acc = Exact
+ z.form = zero
+ f = z
+ return
+ }
+ // len(z.mant) > 0
+
+ // The mantissa may have a radix point (fcount <= 0) and there
+ // may be a nonzero exponent exp. The radix point amounts to a
+ // division by b**(-fcount). An exponent means multiplication by
+ // ebase**exp. Finally, mantissa normalization (shift left) requires
+ // a correcting multiplication by 2**(-shiftcount). Multiplications
+ // are commutative, so we can apply them in any order as long as there
+ // is no loss of precision. We only have powers of 2 and 10, and
+ // we split powers of 10 into the product of the same powers of
+ // 2 and 5. This reduces the size of the multiplication factor
+ // needed for base-10 exponents.
+
+ // normalize mantissa and determine initial exponent contributions
+ exp2 := int64(len(z.mant))*_W - fnorm(z.mant)
+ exp5 := int64(0)
+
+ // determine binary or decimal exponent contribution of radix point
+ if fcount < 0 {
+ // The mantissa has a radix point ddd.dddd; and
+ // -fcount is the number of digits to the right
+ // of '.'. Adjust relevant exponent accordingly.
+ d := int64(fcount)
+ switch b {
+ case 10:
+ exp5 = d
+ fallthrough // 10**e == 5**e * 2**e
+ case 2:
+ exp2 += d
+ case 8:
+ exp2 += d * 3 // octal digits are 3 bits each
+ case 16:
+ exp2 += d * 4 // hexadecimal digits are 4 bits each
+ default:
+ panic("unexpected mantissa base")
+ }
+ // fcount consumed - not needed anymore
+ }
+
+ // take actual exponent into account
+ switch ebase {
+ case 10:
+ exp5 += exp
+ fallthrough // see fallthrough above
+ case 2:
+ exp2 += exp
+ default:
+ panic("unexpected exponent base")
+ }
+ // exp consumed - not needed anymore
+
+ // apply 2**exp2
+ if MinExp <= exp2 && exp2 <= MaxExp {
+ z.prec = prec
+ z.form = finite
+ z.exp = int32(exp2)
+ f = z
+ } else {
+ err = fmt.Errorf("exponent overflow")
+ return
+ }
+
+ if exp5 == 0 {
+ // no decimal exponent contribution
+ z.round(0)
+ return
+ }
+ // exp5 != 0
+
+ // apply 5**exp5
+ p := new(Float).SetPrec(z.Prec() + 64) // use more bits for p -- TODO(gri) what is the right number?
+ if exp5 < 0 {
+ z.Quo(z, p.pow5(uint64(-exp5)))
+ } else {
+ z.Mul(z, p.pow5(uint64(exp5)))
+ }
+
+ return
+}
+
+// These powers of 5 fit into a uint64.
+//
+// for p, q := uint64(0), uint64(1); p < q; p, q = q, q*5 {
+// fmt.Println(q)
+// }
+var pow5tab = [...]uint64{
+ 1,
+ 5,
+ 25,
+ 125,
+ 625,
+ 3125,
+ 15625,
+ 78125,
+ 390625,
+ 1953125,
+ 9765625,
+ 48828125,
+ 244140625,
+ 1220703125,
+ 6103515625,
+ 30517578125,
+ 152587890625,
+ 762939453125,
+ 3814697265625,
+ 19073486328125,
+ 95367431640625,
+ 476837158203125,
+ 2384185791015625,
+ 11920928955078125,
+ 59604644775390625,
+ 298023223876953125,
+ 1490116119384765625,
+ 7450580596923828125,
+}
+
+// pow5 sets z to 5**n and returns z.
+// n must not be negative.
+func (z *Float) pow5(n uint64) *Float {
+ const m = uint64(len(pow5tab) - 1)
+ if n <= m {
+ return z.SetUint64(pow5tab[n])
+ }
+ // n > m
+
+ z.SetUint64(pow5tab[m])
+ n -= m
+
+ // use more bits for f than for z
+ // TODO(gri) what is the right number?
+ f := new(Float).SetPrec(z.Prec() + 64).SetUint64(5)
+
+ for n > 0 {
+ if n&1 != 0 {
+ z.Mul(z, f)
+ }
+ f.Mul(f, f)
+ n >>= 1
+ }
+
+ return z
+}
+
+// Parse parses s which must contain a text representation of a floating-
+// point number with a mantissa in the given conversion base (the exponent
+// is always a decimal number), or a string representing an infinite value.
+//
+// For base 0, an underscore character “_” may appear between a base
+// prefix and an adjacent digit, and between successive digits; such
+// underscores do not change the value of the number, or the returned
+// digit count. Incorrect placement of underscores is reported as an
+// error if there are no other errors. If base != 0, underscores are
+// not recognized and thus terminate scanning like any other character
+// that is not a valid radix point or digit.
+//
+// It sets z to the (possibly rounded) value of the corresponding floating-
+// point value, and returns z, the actual base b, and an error err, if any.
+// The entire string (not just a prefix) must be consumed for success.
+// If z's precision is 0, it is changed to 64 before rounding takes effect.
+// The number must be of the form:
+//
+// number = [ sign ] ( float | "inf" | "Inf" ) .
+// sign = "+" | "-" .
+// float = ( mantissa | prefix pmantissa ) [ exponent ] .
+// prefix = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
+// mantissa = digits "." [ digits ] | digits | "." digits .
+// pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
+// exponent = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
+// digits = digit { [ "_" ] digit } .
+// digit = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
+//
+// The base argument must be 0, 2, 8, 10, or 16. Providing an invalid base
+// argument will lead to a run-time panic.
+//
+// For base 0, the number prefix determines the actual base: A prefix of
+// “0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and
+// “0x” or “0X” selects base 16. Otherwise, the actual base is 10 and
+// no prefix is accepted. The octal prefix "0" is not supported (a leading
+// "0" is simply considered a "0").
+//
+// A "p" or "P" exponent indicates a base 2 (rather than base 10) exponent;
+// for instance, "0x1.fffffffffffffp1023" (using base 0) represents the
+// maximum float64 value. For hexadecimal mantissae, the exponent character
+// must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator
+// cannot be distinguished from a mantissa digit).
+//
+// The returned *Float f is nil and the value of z is valid but not
+// defined if an error is reported.
+func (z *Float) Parse(s string, base int) (f *Float, b int, err error) {
+ // scan doesn't handle ±Inf
+ if len(s) == 3 && (s == "Inf" || s == "inf") {
+ f = z.SetInf(false)
+ return
+ }
+ if len(s) == 4 && (s[0] == '+' || s[0] == '-') && (s[1:] == "Inf" || s[1:] == "inf") {
+ f = z.SetInf(s[0] == '-')
+ return
+ }
+
+ r := strings.NewReader(s)
+ if f, b, err = z.scan(r, base); err != nil {
+ return
+ }
+
+ // entire string must have been consumed
+ if ch, err2 := r.ReadByte(); err2 == nil {
+ err = fmt.Errorf("expected end of string, found %q", ch)
+ } else if err2 != io.EOF {
+ err = err2
+ }
+
+ return
+}
+
+// ParseFloat is like f.Parse(s, base) with f set to the given precision
+// and rounding mode.
+func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {
+ return new(Float).SetPrec(prec).SetMode(mode).Parse(s, base)
+}
+
+var _ fmt.Scanner = (*Float)(nil) // *Float must implement fmt.Scanner
+
+// Scan is a support routine for [fmt.Scanner]; it sets z to the value of
+// the scanned number. It accepts formats whose verbs are supported by
+// [fmt.Scan] for floating point values, which are:
+// 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'.
+// Scan doesn't handle ±Inf.
+func (z *Float) Scan(s fmt.ScanState, ch rune) error {
+ s.SkipSpace()
+ _, _, err := z.scan(byteReader{s}, 0)
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/floatconv_test.go b/platform/dbops/binaries/go/go/src/math/big/floatconv_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a1cc38a4596c5b3f8d67b9506c4a6329eeb848d6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/floatconv_test.go
@@ -0,0 +1,825 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+ "math"
+ "math/bits"
+ "strconv"
+ "testing"
+)
+
+var zero_ float64
+
+func TestFloatSetFloat64String(t *testing.T) {
+ inf := math.Inf(0)
+ nan := math.NaN()
+
+ for _, test := range []struct {
+ s string
+ x float64 // NaNs represent invalid inputs
+ }{
+ // basics
+ {"0", 0},
+ {"-0", -zero_},
+ {"+0", 0},
+ {"1", 1},
+ {"-1", -1},
+ {"+1", 1},
+ {"1.234", 1.234},
+ {"-1.234", -1.234},
+ {"+1.234", 1.234},
+ {".1", 0.1},
+ {"1.", 1},
+ {"+1.", 1},
+
+ // various zeros
+ {"0e100", 0},
+ {"-0e+100", -zero_},
+ {"+0e-100", 0},
+ {"0E100", 0},
+ {"-0E+100", -zero_},
+ {"+0E-100", 0},
+
+ // various decimal exponent formats
+ {"1.e10", 1e10},
+ {"1e+10", 1e10},
+ {"+1e-10", 1e-10},
+ {"1E10", 1e10},
+ {"1.E+10", 1e10},
+ {"+1E-10", 1e-10},
+
+ // infinities
+ {"Inf", inf},
+ {"+Inf", inf},
+ {"-Inf", -inf},
+ {"inf", inf},
+ {"+inf", inf},
+ {"-inf", -inf},
+
+ // invalid numbers
+ {"", nan},
+ {"-", nan},
+ {"0x", nan},
+ {"0e", nan},
+ {"1.2ef", nan},
+ {"2..3", nan},
+ {"123..", nan},
+ {"infinity", nan},
+ {"foobar", nan},
+
+ // invalid underscores
+ {"_", nan},
+ {"0_", nan},
+ {"1__0", nan},
+ {"123_.", nan},
+ {"123._", nan},
+ {"123._4", nan},
+ {"1_2.3_4_", nan},
+ {"_.123", nan},
+ {"_123.456", nan},
+ {"10._0", nan},
+ {"10.0e_0", nan},
+ {"10.0e0_", nan},
+ {"0P-0__0", nan},
+
+ // misc decimal values
+ {"3.14159265", 3.14159265},
+ {"-687436.79457e-245", -687436.79457e-245},
+ {"-687436.79457E245", -687436.79457e245},
+ {".0000000000000000000000000000000000000001", 1e-40},
+ {"+10000000000000000000000000000000000000000e-0", 1e40},
+
+ // decimal mantissa, binary exponent
+ {"0p0", 0},
+ {"-0p0", -zero_},
+ {"1p10", 1 << 10},
+ {"1p+10", 1 << 10},
+ {"+1p-10", 1.0 / (1 << 10)},
+ {"1024p-12", 0.25},
+ {"-1p10", -1024},
+ {"1.5p1", 3},
+
+ // binary mantissa, decimal exponent
+ {"0b0", 0},
+ {"-0b0", -zero_},
+ {"0b0e+10", 0},
+ {"-0b0e-10", -zero_},
+ {"0b1010", 10},
+ {"0B1010E2", 1000},
+ {"0b.1", 0.5},
+ {"0b.001", 0.125},
+ {"0b.001e3", 125},
+
+ // binary mantissa, binary exponent
+ {"0b0p+10", 0},
+ {"-0b0p-10", -zero_},
+ {"0b.1010p4", 10},
+ {"0b1p-1", 0.5},
+ {"0b001p-3", 0.125},
+ {"0b.001p3", 1},
+ {"0b0.01p2", 1},
+ {"0b0.01P+2", 1},
+
+ // octal mantissa, decimal exponent
+ {"0o0", 0},
+ {"-0o0", -zero_},
+ {"0o0e+10", 0},
+ {"-0o0e-10", -zero_},
+ {"0o12", 10},
+ {"0O12E2", 1000},
+ {"0o.4", 0.5},
+ {"0o.01", 0.015625},
+ {"0o.01e3", 15.625},
+
+ // octal mantissa, binary exponent
+ {"0o0p+10", 0},
+ {"-0o0p-10", -zero_},
+ {"0o.12p6", 10},
+ {"0o4p-3", 0.5},
+ {"0o0014p-6", 0.1875},
+ {"0o.001p9", 1},
+ {"0o0.01p7", 2},
+ {"0O0.01P+2", 0.0625},
+
+ // hexadecimal mantissa and exponent
+ {"0x0", 0},
+ {"-0x0", -zero_},
+ {"0x0p+10", 0},
+ {"-0x0p-10", -zero_},
+ {"0xff", 255},
+ {"0X.8p1", 1},
+ {"-0X0.00008p16", -0.5},
+ {"-0X0.00008P+16", -0.5},
+ {"0x0.0000000000001p-1022", math.SmallestNonzeroFloat64},
+ {"0x1.fffffffffffffp1023", math.MaxFloat64},
+
+ // underscores
+ {"0_0", 0},
+ {"1_000.", 1000},
+ {"1_2_3.4_5_6", 123.456},
+ {"1.0e0_0", 1},
+ {"1p+1_0", 1024},
+ {"0b_1000", 0x8},
+ {"0b_1011_1101", 0xbd},
+ {"0x_f0_0d_1eP+0_8", 0xf00d1e00},
+ } {
+ var x Float
+ x.SetPrec(53)
+ _, ok := x.SetString(test.s)
+ if math.IsNaN(test.x) {
+ // test.s is invalid
+ if ok {
+ t.Errorf("%s: want parse error", test.s)
+ }
+ continue
+ }
+ // test.s is valid
+ if !ok {
+ t.Errorf("%s: got parse error", test.s)
+ continue
+ }
+ f, _ := x.Float64()
+ want := new(Float).SetFloat64(test.x)
+ if x.Cmp(want) != 0 || x.Signbit() != want.Signbit() {
+ t.Errorf("%s: got %v (%v); want %v", test.s, &x, f, test.x)
+ }
+ }
+}
+
+func fdiv(a, b float64) float64 { return a / b }
+
+const (
+ below1e23 = 99999999999999974834176
+ above1e23 = 100000000000000008388608
+)
+
+func TestFloat64Text(t *testing.T) {
+ for _, test := range []struct {
+ x float64
+ format byte
+ prec int
+ want string
+ }{
+ {0, 'f', 0, "0"},
+ {math.Copysign(0, -1), 'f', 0, "-0"},
+ {1, 'f', 0, "1"},
+ {-1, 'f', 0, "-1"},
+
+ {0.001, 'e', 0, "1e-03"},
+ {0.459, 'e', 0, "5e-01"},
+ {1.459, 'e', 0, "1e+00"},
+ {2.459, 'e', 1, "2.5e+00"},
+ {3.459, 'e', 2, "3.46e+00"},
+ {4.459, 'e', 3, "4.459e+00"},
+ {5.459, 'e', 4, "5.4590e+00"},
+
+ {0.001, 'f', 0, "0"},
+ {0.459, 'f', 0, "0"},
+ {1.459, 'f', 0, "1"},
+ {2.459, 'f', 1, "2.5"},
+ {3.459, 'f', 2, "3.46"},
+ {4.459, 'f', 3, "4.459"},
+ {5.459, 'f', 4, "5.4590"},
+
+ {0, 'b', 0, "0"},
+ {math.Copysign(0, -1), 'b', 0, "-0"},
+ {1.0, 'b', 0, "4503599627370496p-52"},
+ {-1.0, 'b', 0, "-4503599627370496p-52"},
+ {4503599627370496, 'b', 0, "4503599627370496p+0"},
+
+ {0, 'p', 0, "0"},
+ {math.Copysign(0, -1), 'p', 0, "-0"},
+ {1024.0, 'p', 0, "0x.8p+11"},
+ {-1024.0, 'p', 0, "-0x.8p+11"},
+
+ // all test cases below from strconv/ftoa_test.go
+ {1, 'e', 5, "1.00000e+00"},
+ {1, 'f', 5, "1.00000"},
+ {1, 'g', 5, "1"},
+ {1, 'g', -1, "1"},
+ {20, 'g', -1, "20"},
+ {1234567.8, 'g', -1, "1.2345678e+06"},
+ {200000, 'g', -1, "200000"},
+ {2000000, 'g', -1, "2e+06"},
+
+ // g conversion and zero suppression
+ {400, 'g', 2, "4e+02"},
+ {40, 'g', 2, "40"},
+ {4, 'g', 2, "4"},
+ {.4, 'g', 2, "0.4"},
+ {.04, 'g', 2, "0.04"},
+ {.004, 'g', 2, "0.004"},
+ {.0004, 'g', 2, "0.0004"},
+ {.00004, 'g', 2, "4e-05"},
+ {.000004, 'g', 2, "4e-06"},
+
+ {0, 'e', 5, "0.00000e+00"},
+ {0, 'f', 5, "0.00000"},
+ {0, 'g', 5, "0"},
+ {0, 'g', -1, "0"},
+
+ {-1, 'e', 5, "-1.00000e+00"},
+ {-1, 'f', 5, "-1.00000"},
+ {-1, 'g', 5, "-1"},
+ {-1, 'g', -1, "-1"},
+
+ {12, 'e', 5, "1.20000e+01"},
+ {12, 'f', 5, "12.00000"},
+ {12, 'g', 5, "12"},
+ {12, 'g', -1, "12"},
+
+ {123456700, 'e', 5, "1.23457e+08"},
+ {123456700, 'f', 5, "123456700.00000"},
+ {123456700, 'g', 5, "1.2346e+08"},
+ {123456700, 'g', -1, "1.234567e+08"},
+
+ {1.2345e6, 'e', 5, "1.23450e+06"},
+ {1.2345e6, 'f', 5, "1234500.00000"},
+ {1.2345e6, 'g', 5, "1.2345e+06"},
+
+ {1e23, 'e', 17, "9.99999999999999916e+22"},
+ {1e23, 'f', 17, "99999999999999991611392.00000000000000000"},
+ {1e23, 'g', 17, "9.9999999999999992e+22"},
+
+ {1e23, 'e', -1, "1e+23"},
+ {1e23, 'f', -1, "100000000000000000000000"},
+ {1e23, 'g', -1, "1e+23"},
+
+ {below1e23, 'e', 17, "9.99999999999999748e+22"},
+ {below1e23, 'f', 17, "99999999999999974834176.00000000000000000"},
+ {below1e23, 'g', 17, "9.9999999999999975e+22"},
+
+ {below1e23, 'e', -1, "9.999999999999997e+22"},
+ {below1e23, 'f', -1, "99999999999999970000000"},
+ {below1e23, 'g', -1, "9.999999999999997e+22"},
+
+ {above1e23, 'e', 17, "1.00000000000000008e+23"},
+ {above1e23, 'f', 17, "100000000000000008388608.00000000000000000"},
+ {above1e23, 'g', 17, "1.0000000000000001e+23"},
+
+ {above1e23, 'e', -1, "1.0000000000000001e+23"},
+ {above1e23, 'f', -1, "100000000000000010000000"},
+ {above1e23, 'g', -1, "1.0000000000000001e+23"},
+
+ {5e-304 / 1e20, 'g', -1, "5e-324"},
+ {-5e-304 / 1e20, 'g', -1, "-5e-324"},
+ {fdiv(5e-304, 1e20), 'g', -1, "5e-324"}, // avoid constant arithmetic
+ {fdiv(-5e-304, 1e20), 'g', -1, "-5e-324"}, // avoid constant arithmetic
+
+ {32, 'g', -1, "32"},
+ {32, 'g', 0, "3e+01"},
+
+ {100, 'x', -1, "0x1.9p+06"},
+
+ // {math.NaN(), 'g', -1, "NaN"}, // Float doesn't support NaNs
+ // {-math.NaN(), 'g', -1, "NaN"}, // Float doesn't support NaNs
+ {math.Inf(0), 'g', -1, "+Inf"},
+ {math.Inf(-1), 'g', -1, "-Inf"},
+ {-math.Inf(0), 'g', -1, "-Inf"},
+
+ {-1, 'b', -1, "-4503599627370496p-52"},
+
+ // fixed bugs
+ {0.9, 'f', 1, "0.9"},
+ {0.09, 'f', 1, "0.1"},
+ {0.0999, 'f', 1, "0.1"},
+ {0.05, 'f', 1, "0.1"},
+ {0.05, 'f', 0, "0"},
+ {0.5, 'f', 1, "0.5"},
+ {0.5, 'f', 0, "0"},
+ {1.5, 'f', 0, "2"},
+
+ // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
+ {2.2250738585072012e-308, 'g', -1, "2.2250738585072014e-308"},
+ // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/
+ {2.2250738585072011e-308, 'g', -1, "2.225073858507201e-308"},
+
+ // Issue 2625.
+ {383260575764816448, 'f', 0, "383260575764816448"},
+ {383260575764816448, 'g', -1, "3.8326057576481645e+17"},
+
+ // Issue 15918.
+ {1, 'f', -10, "1"},
+ {1, 'f', -11, "1"},
+ {1, 'f', -12, "1"},
+ } {
+ // The test cases are from the strconv package which tests float64 values.
+ // When formatting values with prec = -1 (shortest representation),
+ // the actually available mantissa precision matters.
+ // For denormalized values, that precision is < 53 (SetFloat64 default).
+ // Compute and set the actual precision explicitly.
+ f := new(Float).SetPrec(actualPrec(test.x)).SetFloat64(test.x)
+ got := f.Text(test.format, test.prec)
+ if got != test.want {
+ t.Errorf("%v: got %s; want %s", test, got, test.want)
+ continue
+ }
+
+ if test.format == 'b' && test.x == 0 {
+ continue // 'b' format in strconv.Float requires knowledge of bias for 0.0
+ }
+ if test.format == 'p' {
+ continue // 'p' format not supported in strconv.Format
+ }
+
+ // verify that Float format matches strconv format
+ want := strconv.FormatFloat(test.x, test.format, test.prec, 64)
+ if got != want {
+ t.Errorf("%v: got %s; want %s (strconv)", test, got, want)
+ }
+ }
+}
+
+// actualPrec returns the number of actually used mantissa bits.
+func actualPrec(x float64) uint {
+ if mant := math.Float64bits(x); x != 0 && mant&(0x7ff<<52) == 0 {
+ // x is denormalized
+ return 64 - uint(bits.LeadingZeros64(mant&(1<<52-1)))
+ }
+ return 53
+}
+
+func TestFloatText(t *testing.T) {
+ const defaultRound = ^RoundingMode(0)
+
+ for _, test := range []struct {
+ x string
+ round RoundingMode
+ prec uint
+ format byte
+ digits int
+ want string
+ }{
+ {"0", defaultRound, 10, 'f', 0, "0"},
+ {"-0", defaultRound, 10, 'f', 0, "-0"},
+ {"1", defaultRound, 10, 'f', 0, "1"},
+ {"-1", defaultRound, 10, 'f', 0, "-1"},
+
+ {"1.459", defaultRound, 100, 'e', 0, "1e+00"},
+ {"2.459", defaultRound, 100, 'e', 1, "2.5e+00"},
+ {"3.459", defaultRound, 100, 'e', 2, "3.46e+00"},
+ {"4.459", defaultRound, 100, 'e', 3, "4.459e+00"},
+ {"5.459", defaultRound, 100, 'e', 4, "5.4590e+00"},
+
+ {"1.459", defaultRound, 100, 'E', 0, "1E+00"},
+ {"2.459", defaultRound, 100, 'E', 1, "2.5E+00"},
+ {"3.459", defaultRound, 100, 'E', 2, "3.46E+00"},
+ {"4.459", defaultRound, 100, 'E', 3, "4.459E+00"},
+ {"5.459", defaultRound, 100, 'E', 4, "5.4590E+00"},
+
+ {"1.459", defaultRound, 100, 'f', 0, "1"},
+ {"2.459", defaultRound, 100, 'f', 1, "2.5"},
+ {"3.459", defaultRound, 100, 'f', 2, "3.46"},
+ {"4.459", defaultRound, 100, 'f', 3, "4.459"},
+ {"5.459", defaultRound, 100, 'f', 4, "5.4590"},
+
+ {"1.459", defaultRound, 100, 'g', 0, "1"},
+ {"2.459", defaultRound, 100, 'g', 1, "2"},
+ {"3.459", defaultRound, 100, 'g', 2, "3.5"},
+ {"4.459", defaultRound, 100, 'g', 3, "4.46"},
+ {"5.459", defaultRound, 100, 'g', 4, "5.459"},
+
+ {"1459", defaultRound, 53, 'g', 0, "1e+03"},
+ {"2459", defaultRound, 53, 'g', 1, "2e+03"},
+ {"3459", defaultRound, 53, 'g', 2, "3.5e+03"},
+ {"4459", defaultRound, 53, 'g', 3, "4.46e+03"},
+ {"5459", defaultRound, 53, 'g', 4, "5459"},
+
+ {"1459", defaultRound, 53, 'G', 0, "1E+03"},
+ {"2459", defaultRound, 53, 'G', 1, "2E+03"},
+ {"3459", defaultRound, 53, 'G', 2, "3.5E+03"},
+ {"4459", defaultRound, 53, 'G', 3, "4.46E+03"},
+ {"5459", defaultRound, 53, 'G', 4, "5459"},
+
+ {"3", defaultRound, 10, 'e', 40, "3.0000000000000000000000000000000000000000e+00"},
+ {"3", defaultRound, 10, 'f', 40, "3.0000000000000000000000000000000000000000"},
+ {"3", defaultRound, 10, 'g', 40, "3"},
+
+ {"3e40", defaultRound, 100, 'e', 40, "3.0000000000000000000000000000000000000000e+40"},
+ {"3e40", defaultRound, 100, 'f', 4, "30000000000000000000000000000000000000000.0000"},
+ {"3e40", defaultRound, 100, 'g', 40, "3e+40"},
+
+ // make sure "stupid" exponents don't stall the machine
+ {"1e1000000", defaultRound, 64, 'p', 0, "0x.88b3a28a05eade3ap+3321929"},
+ {"1e646456992", defaultRound, 64, 'p', 0, "0x.e883a0c5c8c7c42ap+2147483644"},
+ {"1e646456993", defaultRound, 64, 'p', 0, "+Inf"},
+ {"1e1000000000", defaultRound, 64, 'p', 0, "+Inf"},
+ {"1e-1000000", defaultRound, 64, 'p', 0, "0x.efb4542cc8ca418ap-3321928"},
+ {"1e-646456993", defaultRound, 64, 'p', 0, "0x.e17c8956983d9d59p-2147483647"},
+ {"1e-646456994", defaultRound, 64, 'p', 0, "0"},
+ {"1e-1000000000", defaultRound, 64, 'p', 0, "0"},
+
+ // minimum and maximum values
+ {"1p2147483646", defaultRound, 64, 'p', 0, "0x.8p+2147483647"},
+ {"0x.8p2147483647", defaultRound, 64, 'p', 0, "0x.8p+2147483647"},
+ {"0x.8p-2147483647", defaultRound, 64, 'p', 0, "0x.8p-2147483647"},
+ {"1p-2147483649", defaultRound, 64, 'p', 0, "0x.8p-2147483648"},
+
+ // TODO(gri) need tests for actual large Floats
+
+ {"0", defaultRound, 53, 'b', 0, "0"},
+ {"-0", defaultRound, 53, 'b', 0, "-0"},
+ {"1.0", defaultRound, 53, 'b', 0, "4503599627370496p-52"},
+ {"-1.0", defaultRound, 53, 'b', 0, "-4503599627370496p-52"},
+ {"4503599627370496", defaultRound, 53, 'b', 0, "4503599627370496p+0"},
+
+ // issue 9939
+ {"3", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+ {"03", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+ {"3.", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+ {"3.0", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+ {"3.00", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+ {"3.000", defaultRound, 350, 'b', 0, "1720123961992553633708115671476565205597423741876210842803191629540192157066363606052513914832594264915968p-348"},
+
+ {"3", defaultRound, 350, 'p', 0, "0x.cp+2"},
+ {"03", defaultRound, 350, 'p', 0, "0x.cp+2"},
+ {"3.", defaultRound, 350, 'p', 0, "0x.cp+2"},
+ {"3.0", defaultRound, 350, 'p', 0, "0x.cp+2"},
+ {"3.00", defaultRound, 350, 'p', 0, "0x.cp+2"},
+ {"3.000", defaultRound, 350, 'p', 0, "0x.cp+2"},
+
+ {"0", defaultRound, 64, 'p', 0, "0"},
+ {"-0", defaultRound, 64, 'p', 0, "-0"},
+ {"1024.0", defaultRound, 64, 'p', 0, "0x.8p+11"},
+ {"-1024.0", defaultRound, 64, 'p', 0, "-0x.8p+11"},
+
+ {"0", defaultRound, 64, 'x', -1, "0x0p+00"},
+ {"0", defaultRound, 64, 'x', 0, "0x0p+00"},
+ {"0", defaultRound, 64, 'x', 1, "0x0.0p+00"},
+ {"0", defaultRound, 64, 'x', 5, "0x0.00000p+00"},
+ {"3.25", defaultRound, 64, 'x', 0, "0x1p+02"},
+ {"-3.25", defaultRound, 64, 'x', 0, "-0x1p+02"},
+ {"3.25", defaultRound, 64, 'x', 1, "0x1.ap+01"},
+ {"-3.25", defaultRound, 64, 'x', 1, "-0x1.ap+01"},
+ {"3.25", defaultRound, 64, 'x', -1, "0x1.ap+01"},
+ {"-3.25", defaultRound, 64, 'x', -1, "-0x1.ap+01"},
+ {"1024.0", defaultRound, 64, 'x', 0, "0x1p+10"},
+ {"-1024.0", defaultRound, 64, 'x', 0, "-0x1p+10"},
+ {"1024.0", defaultRound, 64, 'x', 5, "0x1.00000p+10"},
+ {"8191.0", defaultRound, 53, 'x', -1, "0x1.fffp+12"},
+ {"8191.5", defaultRound, 53, 'x', -1, "0x1.fff8p+12"},
+ {"8191.53125", defaultRound, 53, 'x', -1, "0x1.fff88p+12"},
+ {"8191.53125", defaultRound, 53, 'x', 4, "0x1.fff8p+12"},
+ {"8191.53125", defaultRound, 53, 'x', 3, "0x1.000p+13"},
+ {"8191.53125", defaultRound, 53, 'x', 0, "0x1p+13"},
+ {"8191.533203125", defaultRound, 53, 'x', -1, "0x1.fff888p+12"},
+ {"8191.533203125", defaultRound, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.533203125", defaultRound, 53, 'x', 4, "0x1.fff9p+12"},
+
+ {"8191.53125", defaultRound, 53, 'x', -1, "0x1.fff88p+12"},
+ {"8191.53125", ToNearestEven, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.53125", ToNearestAway, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.53125", ToZero, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.53125", AwayFromZero, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.53125", ToNegativeInf, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.53125", ToPositiveInf, 53, 'x', 5, "0x1.fff88p+12"},
+
+ {"8191.53125", defaultRound, 53, 'x', 4, "0x1.fff8p+12"},
+ {"8191.53125", defaultRound, 53, 'x', 3, "0x1.000p+13"},
+ {"8191.53125", defaultRound, 53, 'x', 0, "0x1p+13"},
+ {"8191.533203125", defaultRound, 53, 'x', -1, "0x1.fff888p+12"},
+ {"8191.533203125", defaultRound, 53, 'x', 6, "0x1.fff888p+12"},
+ {"8191.533203125", defaultRound, 53, 'x', 5, "0x1.fff88p+12"},
+ {"8191.533203125", defaultRound, 53, 'x', 4, "0x1.fff9p+12"},
+
+ {"8191.53125", ToNearestEven, 53, 'x', 4, "0x1.fff8p+12"},
+ {"8191.53125", ToNearestAway, 53, 'x', 4, "0x1.fff9p+12"},
+ {"8191.53125", ToZero, 53, 'x', 4, "0x1.fff8p+12"},
+ {"8191.53125", ToZero, 53, 'x', 2, "0x1.ffp+12"},
+ {"8191.53125", AwayFromZero, 53, 'x', 4, "0x1.fff9p+12"},
+ {"8191.53125", ToNegativeInf, 53, 'x', 4, "0x1.fff8p+12"},
+ {"-8191.53125", ToNegativeInf, 53, 'x', 4, "-0x1.fff9p+12"},
+ {"8191.53125", ToPositiveInf, 53, 'x', 4, "0x1.fff9p+12"},
+ {"-8191.53125", ToPositiveInf, 53, 'x', 4, "-0x1.fff8p+12"},
+
+ // issue 34343
+ {"0x.8p-2147483648", ToNearestEven, 4, 'p', -1, "0x.8p-2147483648"},
+ {"0x.8p-2147483648", ToNearestEven, 4, 'x', -1, "0x1p-2147483649"},
+ } {
+ f, _, err := ParseFloat(test.x, 0, test.prec, ToNearestEven)
+ if err != nil {
+ t.Errorf("%v: %s", test, err)
+ continue
+ }
+ if test.round != defaultRound {
+ f.SetMode(test.round)
+ }
+
+ got := f.Text(test.format, test.digits)
+ if got != test.want {
+ t.Errorf("%v: got %s; want %s", test, got, test.want)
+ }
+
+ // compare with strconv.FormatFloat output if possible
+ // ('p' format is not supported by strconv.FormatFloat,
+ // and its output for 0.0 prints a biased exponent value
+ // as in 0p-1074 which makes no sense to emulate here)
+ if test.prec == 53 && test.format != 'p' && f.Sign() != 0 && (test.round == ToNearestEven || test.round == defaultRound) {
+ f64, acc := f.Float64()
+ if acc != Exact {
+ t.Errorf("%v: expected exact conversion to float64", test)
+ continue
+ }
+ got := strconv.FormatFloat(f64, test.format, test.digits, 64)
+ if got != test.want {
+ t.Errorf("%v: got %s; want %s", test, got, test.want)
+ }
+ }
+ }
+}
+
+func TestFloatFormat(t *testing.T) {
+ for _, test := range []struct {
+ format string
+ value any // float32, float64, or string (== 512bit *Float)
+ want string
+ }{
+ // from fmt/fmt_test.go
+ {"%+.3e", 0.0, "+0.000e+00"},
+ {"%+.3e", 1.0, "+1.000e+00"},
+ {"%+.3f", -1.0, "-1.000"},
+ {"%+.3F", -1.0, "-1.000"},
+ {"%+.3F", float32(-1.0), "-1.000"},
+ {"%+07.2f", 1.0, "+001.00"},
+ {"%+07.2f", -1.0, "-001.00"},
+ {"%+10.2f", +1.0, " +1.00"},
+ {"%+10.2f", -1.0, " -1.00"},
+ {"% .3E", -1.0, "-1.000E+00"},
+ {"% .3e", 1.0, " 1.000e+00"},
+ {"%+.3g", 0.0, "+0"},
+ {"%+.3g", 1.0, "+1"},
+ {"%+.3g", -1.0, "-1"},
+ {"% .3g", -1.0, "-1"},
+ {"% .3g", 1.0, " 1"},
+ {"%b", float32(1.0), "8388608p-23"},
+ {"%b", 1.0, "4503599627370496p-52"},
+
+ // from fmt/fmt_test.go: old test/fmt_test.go
+ {"%e", 1.0, "1.000000e+00"},
+ {"%e", 1234.5678e3, "1.234568e+06"},
+ {"%e", 1234.5678e-8, "1.234568e-05"},
+ {"%e", -7.0, "-7.000000e+00"},
+ {"%e", -1e-9, "-1.000000e-09"},
+ {"%f", 1234.5678e3, "1234567.800000"},
+ {"%f", 1234.5678e-8, "0.000012"},
+ {"%f", -7.0, "-7.000000"},
+ {"%f", -1e-9, "-0.000000"},
+ {"%g", 1234.5678e3, "1.2345678e+06"},
+ {"%g", float32(1234.5678e3), "1.2345678e+06"},
+ {"%g", 1234.5678e-8, "1.2345678e-05"},
+ {"%g", -7.0, "-7"},
+ {"%g", -1e-9, "-1e-09"},
+ {"%g", float32(-1e-9), "-1e-09"},
+ {"%E", 1.0, "1.000000E+00"},
+ {"%E", 1234.5678e3, "1.234568E+06"},
+ {"%E", 1234.5678e-8, "1.234568E-05"},
+ {"%E", -7.0, "-7.000000E+00"},
+ {"%E", -1e-9, "-1.000000E-09"},
+ {"%G", 1234.5678e3, "1.2345678E+06"},
+ {"%G", float32(1234.5678e3), "1.2345678E+06"},
+ {"%G", 1234.5678e-8, "1.2345678E-05"},
+ {"%G", -7.0, "-7"},
+ {"%G", -1e-9, "-1E-09"},
+ {"%G", float32(-1e-9), "-1E-09"},
+
+ {"%20.6e", 1.2345e3, " 1.234500e+03"},
+ {"%20.6e", 1.2345e-3, " 1.234500e-03"},
+ {"%20e", 1.2345e3, " 1.234500e+03"},
+ {"%20e", 1.2345e-3, " 1.234500e-03"},
+ {"%20.8e", 1.2345e3, " 1.23450000e+03"},
+ {"%20f", 1.23456789e3, " 1234.567890"},
+ {"%20f", 1.23456789e-3, " 0.001235"},
+ {"%20f", 12345678901.23456789, " 12345678901.234568"},
+ {"%-20f", 1.23456789e3, "1234.567890 "},
+ {"%20.8f", 1.23456789e3, " 1234.56789000"},
+ {"%20.8f", 1.23456789e-3, " 0.00123457"},
+ {"%g", 1.23456789e3, "1234.56789"},
+ {"%g", 1.23456789e-3, "0.00123456789"},
+ {"%g", 1.23456789e20, "1.23456789e+20"},
+ {"%20e", math.Inf(1), " +Inf"},
+ {"%-20f", math.Inf(-1), "-Inf "},
+
+ // from fmt/fmt_test.go: comparison of padding rules with C printf
+ {"%.2f", 1.0, "1.00"},
+ {"%.2f", -1.0, "-1.00"},
+ {"% .2f", 1.0, " 1.00"},
+ {"% .2f", -1.0, "-1.00"},
+ {"%+.2f", 1.0, "+1.00"},
+ {"%+.2f", -1.0, "-1.00"},
+ {"%7.2f", 1.0, " 1.00"},
+ {"%7.2f", -1.0, " -1.00"},
+ {"% 7.2f", 1.0, " 1.00"},
+ {"% 7.2f", -1.0, " -1.00"},
+ {"%+7.2f", 1.0, " +1.00"},
+ {"%+7.2f", -1.0, " -1.00"},
+ {"%07.2f", 1.0, "0001.00"},
+ {"%07.2f", -1.0, "-001.00"},
+ {"% 07.2f", 1.0, " 001.00"},
+ {"% 07.2f", -1.0, "-001.00"},
+ {"%+07.2f", 1.0, "+001.00"},
+ {"%+07.2f", -1.0, "-001.00"},
+
+ // from fmt/fmt_test.go: zero padding does not apply to infinities
+ {"%020f", math.Inf(-1), " -Inf"},
+ {"%020f", math.Inf(+1), " +Inf"},
+ {"% 020f", math.Inf(-1), " -Inf"},
+ {"% 020f", math.Inf(+1), " Inf"},
+ {"%+020f", math.Inf(-1), " -Inf"},
+ {"%+020f", math.Inf(+1), " +Inf"},
+ {"%20f", -1.0, " -1.000000"},
+
+ // handle %v like %g
+ {"%v", 0.0, "0"},
+ {"%v", -7.0, "-7"},
+ {"%v", -1e-9, "-1e-09"},
+ {"%v", float32(-1e-9), "-1e-09"},
+ {"%010v", 0.0, "0000000000"},
+
+ // *Float cases
+ {"%.20f", "1e-20", "0.00000000000000000001"},
+ {"%.20f", "-1e-20", "-0.00000000000000000001"},
+ {"%30.20f", "-1e-20", " -0.00000000000000000001"},
+ {"%030.20f", "-1e-20", "-00000000.00000000000000000001"},
+ {"%030.20f", "+1e-20", "000000000.00000000000000000001"},
+ {"% 030.20f", "+1e-20", " 00000000.00000000000000000001"},
+
+ // erroneous formats
+ {"%s", 1.0, "%!s(*big.Float=1)"},
+ } {
+ value := new(Float)
+ switch v := test.value.(type) {
+ case float32:
+ value.SetPrec(24).SetFloat64(float64(v))
+ case float64:
+ value.SetPrec(53).SetFloat64(v)
+ case string:
+ value.SetPrec(512).Parse(v, 0)
+ default:
+ t.Fatalf("unsupported test value: %v (%T)", v, v)
+ }
+
+ if got := fmt.Sprintf(test.format, value); got != test.want {
+ t.Errorf("%v: got %q; want %q", test, got, test.want)
+ }
+ }
+}
+
+func BenchmarkParseFloatSmallExp(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, s := range []string{
+ "1e0",
+ "1e-1",
+ "1e-2",
+ "1e-3",
+ "1e-4",
+ "1e-5",
+ "1e-10",
+ "1e-20",
+ "1e-50",
+ "1e1",
+ "1e2",
+ "1e3",
+ "1e4",
+ "1e5",
+ "1e10",
+ "1e20",
+ "1e50",
+ } {
+ var x Float
+ _, _, err := x.Parse(s, 0)
+ if err != nil {
+ b.Fatalf("%s: %v", s, err)
+ }
+ }
+ }
+}
+
+func BenchmarkParseFloatLargeExp(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ for _, s := range []string{
+ "1e0",
+ "1e-10",
+ "1e-20",
+ "1e-30",
+ "1e-40",
+ "1e-50",
+ "1e-100",
+ "1e-500",
+ "1e-1000",
+ "1e-5000",
+ "1e-10000",
+ "1e10",
+ "1e20",
+ "1e30",
+ "1e40",
+ "1e50",
+ "1e100",
+ "1e500",
+ "1e1000",
+ "1e5000",
+ "1e10000",
+ } {
+ var x Float
+ _, _, err := x.Parse(s, 0)
+ if err != nil {
+ b.Fatalf("%s: %v", s, err)
+ }
+ }
+ }
+}
+
+func TestFloatScan(t *testing.T) {
+ var floatScanTests = []struct {
+ input string
+ format string
+ output string
+ remaining int
+ wantErr bool
+ }{
+ 0: {"10.0", "%f", "10", 0, false},
+ 1: {"23.98+2.0", "%v", "23.98", 4, false},
+ 2: {"-1+1", "%v", "-1", 2, false},
+ 3: {" 00000", "%v", "0", 0, false},
+ 4: {"-123456p-78", "%b", "-4.084816388e-19", 0, false},
+ 5: {"+123", "%b", "123", 0, false},
+ 6: {"-1.234e+56", "%e", "-1.234e+56", 0, false},
+ 7: {"-1.234E-56", "%E", "-1.234e-56", 0, false},
+ 8: {"-1.234e+567", "%g", "-1.234e+567", 0, false},
+ 9: {"+1234567891011.234", "%G", "1.234567891e+12", 0, false},
+
+ // Scan doesn't handle ±Inf.
+ 10: {"Inf", "%v", "", 3, true},
+ 11: {"-Inf", "%v", "", 3, true},
+ 12: {"-Inf", "%v", "", 3, true},
+ }
+
+ var buf bytes.Buffer
+ for i, test := range floatScanTests {
+ x := new(Float)
+ buf.Reset()
+ buf.WriteString(test.input)
+ _, err := fmt.Fscanf(&buf, test.format, x)
+ if test.wantErr {
+ if err == nil {
+ t.Errorf("#%d want non-nil err", i)
+ }
+ continue
+ }
+
+ if err != nil {
+ t.Errorf("#%d error: %s", i, err)
+ }
+
+ if x.String() != test.output {
+ t.Errorf("#%d got %s; want %s", i, x.String(), test.output)
+ }
+ if buf.Len() != test.remaining {
+ t.Errorf("#%d got %d bytes remaining; want %d", i, buf.Len(), test.remaining)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/floatexample_test.go b/platform/dbops/binaries/go/go/src/math/big/floatexample_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0c6668c93bc592edafc9a826a877f19af1ca35bc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/floatexample_test.go
@@ -0,0 +1,141 @@
+// 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.
+
+package big_test
+
+import (
+ "fmt"
+ "math"
+ "math/big"
+)
+
+func ExampleFloat_Add() {
+ // Operate on numbers of different precision.
+ var x, y, z big.Float
+ x.SetInt64(1000) // x is automatically set to 64bit precision
+ y.SetFloat64(2.718281828) // y is automatically set to 53bit precision
+ z.SetPrec(32)
+ z.Add(&x, &y)
+ fmt.Printf("x = %.10g (%s, prec = %d, acc = %s)\n", &x, x.Text('p', 0), x.Prec(), x.Acc())
+ fmt.Printf("y = %.10g (%s, prec = %d, acc = %s)\n", &y, y.Text('p', 0), y.Prec(), y.Acc())
+ fmt.Printf("z = %.10g (%s, prec = %d, acc = %s)\n", &z, z.Text('p', 0), z.Prec(), z.Acc())
+ // Output:
+ // x = 1000 (0x.fap+10, prec = 64, acc = Exact)
+ // y = 2.718281828 (0x.adf85458248cd8p+2, prec = 53, acc = Exact)
+ // z = 1002.718282 (0x.faadf854p+10, prec = 32, acc = Below)
+}
+
+func ExampleFloat_shift() {
+ // Implement Float "shift" by modifying the (binary) exponents directly.
+ for s := -5; s <= 5; s++ {
+ x := big.NewFloat(0.5)
+ x.SetMantExp(x, x.MantExp(nil)+s) // shift x by s
+ fmt.Println(x)
+ }
+ // Output:
+ // 0.015625
+ // 0.03125
+ // 0.0625
+ // 0.125
+ // 0.25
+ // 0.5
+ // 1
+ // 2
+ // 4
+ // 8
+ // 16
+}
+
+func ExampleFloat_Cmp() {
+ inf := math.Inf(1)
+ zero := 0.0
+
+ operands := []float64{-inf, -1.2, -zero, 0, +1.2, +inf}
+
+ fmt.Println(" x y cmp")
+ fmt.Println("---------------")
+ for _, x64 := range operands {
+ x := big.NewFloat(x64)
+ for _, y64 := range operands {
+ y := big.NewFloat(y64)
+ fmt.Printf("%4g %4g %3d\n", x, y, x.Cmp(y))
+ }
+ fmt.Println()
+ }
+
+ // Output:
+ // x y cmp
+ // ---------------
+ // -Inf -Inf 0
+ // -Inf -1.2 -1
+ // -Inf -0 -1
+ // -Inf 0 -1
+ // -Inf 1.2 -1
+ // -Inf +Inf -1
+ //
+ // -1.2 -Inf 1
+ // -1.2 -1.2 0
+ // -1.2 -0 -1
+ // -1.2 0 -1
+ // -1.2 1.2 -1
+ // -1.2 +Inf -1
+ //
+ // -0 -Inf 1
+ // -0 -1.2 1
+ // -0 -0 0
+ // -0 0 0
+ // -0 1.2 -1
+ // -0 +Inf -1
+ //
+ // 0 -Inf 1
+ // 0 -1.2 1
+ // 0 -0 0
+ // 0 0 0
+ // 0 1.2 -1
+ // 0 +Inf -1
+ //
+ // 1.2 -Inf 1
+ // 1.2 -1.2 1
+ // 1.2 -0 1
+ // 1.2 0 1
+ // 1.2 1.2 0
+ // 1.2 +Inf -1
+ //
+ // +Inf -Inf 1
+ // +Inf -1.2 1
+ // +Inf -0 1
+ // +Inf 0 1
+ // +Inf 1.2 1
+ // +Inf +Inf 0
+}
+
+func ExampleRoundingMode() {
+ operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}
+
+ fmt.Print(" x")
+ for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+ fmt.Printf(" %s", mode)
+ }
+ fmt.Println()
+
+ for _, f64 := range operands {
+ fmt.Printf("%4g", f64)
+ for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+ // sample operands above require 2 bits to represent mantissa
+ // set binary precision to 2 to round them to integer values
+ f := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)
+ fmt.Printf(" %*g", len(mode.String()), f)
+ }
+ fmt.Println()
+ }
+
+ // Output:
+ // x ToNearestEven ToNearestAway ToZero AwayFromZero ToNegativeInf ToPositiveInf
+ // 2.6 3 3 2 3 2 3
+ // 2.5 2 3 2 3 2 3
+ // 2.1 2 2 2 3 2 3
+ // -2.1 -2 -2 -2 -3 -3 -2
+ // -2.5 -2 -3 -2 -3 -3 -2
+ // -2.6 -3 -3 -2 -3 -3 -2
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/floatmarsh.go b/platform/dbops/binaries/go/go/src/math/big/floatmarsh.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a908cef28ab9f7a4bbb588cd45600f25cf1f059
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/floatmarsh.go
@@ -0,0 +1,131 @@
+// 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 encoding/decoding of Floats.
+
+package big
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+)
+
+// Gob codec version. Permits backward-compatible changes to the encoding.
+const floatGobVersion byte = 1
+
+// GobEncode implements the [encoding/gob.GobEncoder] interface.
+// The [Float] value and all its attributes (precision,
+// rounding mode, accuracy) are marshaled.
+func (x *Float) GobEncode() ([]byte, error) {
+ if x == nil {
+ return nil, nil
+ }
+
+ // determine max. space (bytes) required for encoding
+ sz := 1 + 1 + 4 // version + mode|acc|form|neg (3+2+2+1bit) + prec
+ n := 0 // number of mantissa words
+ if x.form == finite {
+ // add space for mantissa and exponent
+ n = int((x.prec + (_W - 1)) / _W) // required mantissa length in words for given precision
+ // actual mantissa slice could be shorter (trailing 0's) or longer (unused bits):
+ // - if shorter, only encode the words present
+ // - if longer, cut off unused words when encoding in bytes
+ // (in practice, this should never happen since rounding
+ // takes care of it, but be safe and do it always)
+ if len(x.mant) < n {
+ n = len(x.mant)
+ }
+ // len(x.mant) >= n
+ sz += 4 + n*_S // exp + mant
+ }
+ buf := make([]byte, sz)
+
+ buf[0] = floatGobVersion
+ b := byte(x.mode&7)<<5 | byte((x.acc+1)&3)<<3 | byte(x.form&3)<<1
+ if x.neg {
+ b |= 1
+ }
+ buf[1] = b
+ binary.BigEndian.PutUint32(buf[2:], x.prec)
+
+ if x.form == finite {
+ binary.BigEndian.PutUint32(buf[6:], uint32(x.exp))
+ x.mant[len(x.mant)-n:].bytes(buf[10:]) // cut off unused trailing words
+ }
+
+ return buf, nil
+}
+
+// GobDecode implements the [encoding/gob.GobDecoder] interface.
+// The result is rounded per the precision and rounding mode of
+// z unless z's precision is 0, in which case z is set exactly
+// to the decoded value.
+func (z *Float) GobDecode(buf []byte) error {
+ if len(buf) == 0 {
+ // Other side sent a nil or default value.
+ *z = Float{}
+ return nil
+ }
+ if len(buf) < 6 {
+ return errors.New("Float.GobDecode: buffer too small")
+ }
+
+ if buf[0] != floatGobVersion {
+ return fmt.Errorf("Float.GobDecode: encoding version %d not supported", buf[0])
+ }
+
+ oldPrec := z.prec
+ oldMode := z.mode
+
+ b := buf[1]
+ z.mode = RoundingMode((b >> 5) & 7)
+ z.acc = Accuracy((b>>3)&3) - 1
+ z.form = form((b >> 1) & 3)
+ z.neg = b&1 != 0
+ z.prec = binary.BigEndian.Uint32(buf[2:])
+
+ if z.form == finite {
+ if len(buf) < 10 {
+ return errors.New("Float.GobDecode: buffer too small for finite form float")
+ }
+ z.exp = int32(binary.BigEndian.Uint32(buf[6:]))
+ z.mant = z.mant.setBytes(buf[10:])
+ }
+
+ if oldPrec != 0 {
+ z.mode = oldMode
+ z.SetPrec(uint(oldPrec))
+ }
+
+ if msg := z.validate0(); msg != "" {
+ return errors.New("Float.GobDecode: " + msg)
+ }
+
+ return nil
+}
+
+// MarshalText implements the [encoding.TextMarshaler] interface.
+// Only the [Float] value is marshaled (in full precision), other
+// attributes such as precision or accuracy are ignored.
+func (x *Float) MarshalText() (text []byte, err error) {
+ if x == nil {
+ return []byte(""), nil
+ }
+ var buf []byte
+ return x.Append(buf, 'g', -1), nil
+}
+
+// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
+// The result is rounded per the precision and rounding mode of z.
+// If z's precision is 0, it is changed to 64 before rounding takes
+// effect.
+func (z *Float) UnmarshalText(text []byte) error {
+ // TODO(gri): get rid of the []byte/string conversion
+ _, _, err := z.Parse(string(text), 0)
+ if err != nil {
+ err = fmt.Errorf("math/big: cannot unmarshal %q into a *big.Float (%v)", text, err)
+ }
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/floatmarsh_test.go b/platform/dbops/binaries/go/go/src/math/big/floatmarsh_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..20def68a6d3c613a4ae89362fc8943837195b185
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/floatmarsh_test.go
@@ -0,0 +1,173 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "encoding/gob"
+ "encoding/json"
+ "io"
+ "strings"
+ "testing"
+)
+
+var floatVals = []string{
+ "0",
+ "1",
+ "0.1",
+ "2.71828",
+ "1234567890",
+ "3.14e1234",
+ "3.14e-1234",
+ "0.738957395793475734757349579759957975985497e100",
+ "0.73895739579347546656564656573475734957975995797598589749859834759476745986795497e100",
+ "inf",
+ "Inf",
+}
+
+func TestFloatGobEncoding(t *testing.T) {
+ var medium bytes.Buffer
+ enc := gob.NewEncoder(&medium)
+ dec := gob.NewDecoder(&medium)
+ for _, test := range floatVals {
+ for _, sign := range []string{"", "+", "-"} {
+ for _, prec := range []uint{0, 1, 2, 10, 53, 64, 100, 1000} {
+ for _, mode := range []RoundingMode{ToNearestEven, ToNearestAway, ToZero, AwayFromZero, ToNegativeInf, ToPositiveInf} {
+ medium.Reset() // empty buffer for each test case (in case of failures)
+ x := sign + test
+
+ var tx Float
+ _, _, err := tx.SetPrec(prec).SetMode(mode).Parse(x, 0)
+ if err != nil {
+ t.Errorf("parsing of %s (%dbits, %v) failed (invalid test case): %v", x, prec, mode, err)
+ continue
+ }
+
+ // If tx was set to prec == 0, tx.Parse(x, 0) assumes precision 64. Correct it.
+ if prec == 0 {
+ tx.SetPrec(0)
+ }
+
+ if err := enc.Encode(&tx); err != nil {
+ t.Errorf("encoding of %v (%dbits, %v) failed: %v", &tx, prec, mode, err)
+ continue
+ }
+
+ var rx Float
+ if err := dec.Decode(&rx); err != nil {
+ t.Errorf("decoding of %v (%dbits, %v) failed: %v", &tx, prec, mode, err)
+ continue
+ }
+
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("transmission of %s failed: got %s want %s", x, rx.String(), tx.String())
+ continue
+ }
+
+ if rx.Prec() != prec {
+ t.Errorf("transmission of %s's prec failed: got %d want %d", x, rx.Prec(), prec)
+ }
+
+ if rx.Mode() != mode {
+ t.Errorf("transmission of %s's mode failed: got %s want %s", x, rx.Mode(), mode)
+ }
+
+ if rx.Acc() != tx.Acc() {
+ t.Errorf("transmission of %s's accuracy failed: got %s want %s", x, rx.Acc(), tx.Acc())
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestFloatCorruptGob(t *testing.T) {
+ var buf bytes.Buffer
+ tx := NewFloat(4 / 3).SetPrec(1000).SetMode(ToPositiveInf)
+ if err := gob.NewEncoder(&buf).Encode(tx); err != nil {
+ t.Fatal(err)
+ }
+ b := buf.Bytes()
+
+ var rx Float
+ if err := gob.NewDecoder(bytes.NewReader(b)).Decode(&rx); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := gob.NewDecoder(bytes.NewReader(b[:10])).Decode(&rx); err != io.ErrUnexpectedEOF {
+ t.Errorf("got %v want EOF", err)
+ }
+
+ b[1] = 0
+ if err := gob.NewDecoder(bytes.NewReader(b)).Decode(&rx); err == nil {
+ t.Fatal("got nil want version error")
+ }
+}
+
+func TestFloatJSONEncoding(t *testing.T) {
+ for _, test := range floatVals {
+ for _, sign := range []string{"", "+", "-"} {
+ for _, prec := range []uint{0, 1, 2, 10, 53, 64, 100, 1000} {
+ if prec > 53 && testing.Short() {
+ continue
+ }
+ x := sign + test
+ var tx Float
+ _, _, err := tx.SetPrec(prec).Parse(x, 0)
+ if err != nil {
+ t.Errorf("parsing of %s (prec = %d) failed (invalid test case): %v", x, prec, err)
+ continue
+ }
+ b, err := json.Marshal(&tx)
+ if err != nil {
+ t.Errorf("marshaling of %v (prec = %d) failed: %v", &tx, prec, err)
+ continue
+ }
+ var rx Float
+ rx.SetPrec(prec)
+ if err := json.Unmarshal(b, &rx); err != nil {
+ t.Errorf("unmarshaling of %v (prec = %d) failed: %v", &tx, prec, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("JSON encoding of %v (prec = %d) failed: got %v want %v", &tx, prec, &rx, &tx)
+ }
+ }
+ }
+ }
+}
+
+func TestFloatGobDecodeShortBuffer(t *testing.T) {
+ for _, tc := range [][]byte{
+ []byte{0x1, 0x0, 0x0, 0x0},
+ []byte{0x1, 0xfa, 0x0, 0x0, 0x0, 0x0},
+ } {
+ err := NewFloat(0).GobDecode(tc)
+ if err == nil {
+ t.Error("expected GobDecode to return error for malformed input")
+ }
+ }
+}
+
+func TestFloatGobDecodeInvalid(t *testing.T) {
+ for _, tc := range []struct {
+ buf []byte
+ msg string
+ }{
+ {
+ []byte{0x1, 0x2a, 0x20, 0x20, 0x20, 0x20, 0x0, 0x20, 0x20, 0x20, 0x0, 0x20, 0x20, 0x20, 0x20, 0x0, 0x0, 0x0, 0x0, 0xc},
+ "Float.GobDecode: msb not set in last word",
+ },
+ {
+ []byte{1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+ "Float.GobDecode: nonzero finite number with empty mantissa",
+ },
+ } {
+ err := NewFloat(0).GobDecode(tc.buf)
+ if err == nil || !strings.HasPrefix(err.Error(), tc.msg) {
+ t.Errorf("expected GobDecode error prefix: %s, got: %v", tc.msg, err)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/ftoa.go b/platform/dbops/binaries/go/go/src/math/big/ftoa.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7a4345d3acf98821a6071b9c54d025ba54d3a5a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/ftoa.go
@@ -0,0 +1,529 @@
+// 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 Float-to-string conversion functions.
+// It is closely following the corresponding implementation
+// in strconv/ftoa.go, but modified and simplified for Float.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+ "strconv"
+)
+
+// Text converts the floating-point number x to a string according
+// to the given format and precision prec. The format is one of:
+//
+// 'e' -d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
+// 'E' -d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
+// 'f' -ddddd.dddd, no exponent
+// 'g' like 'e' for large exponents, like 'f' otherwise
+// 'G' like 'E' for large exponents, like 'f' otherwise
+// 'x' -0xd.dddddp±dd, hexadecimal mantissa, decimal power of two exponent
+// 'p' -0x.dddp±dd, hexadecimal mantissa, decimal power of two exponent (non-standard)
+// 'b' -ddddddp±dd, decimal mantissa, decimal power of two exponent (non-standard)
+//
+// For the power-of-two exponent formats, the mantissa is printed in normalized form:
+//
+// 'x' hexadecimal mantissa in [1, 2), or 0
+// 'p' hexadecimal mantissa in [½, 1), or 0
+// 'b' decimal integer mantissa using x.Prec() bits, or 0
+//
+// Note that the 'x' form is the one used by most other languages and libraries.
+//
+// If format is a different character, Text returns a "%" followed by the
+// unrecognized format character.
+//
+// The precision prec controls the number of digits (excluding the exponent)
+// printed by the 'e', 'E', 'f', 'g', 'G', and 'x' formats.
+// For 'e', 'E', 'f', and 'x', it is the number of digits after the decimal point.
+// For 'g' and 'G' it is the total number of digits. A negative precision selects
+// the smallest number of decimal digits necessary to identify the value x uniquely
+// using x.Prec() mantissa bits.
+// The prec value is ignored for the 'b' and 'p' formats.
+func (x *Float) Text(format byte, prec int) string {
+ cap := 10 // TODO(gri) determine a good/better value here
+ if prec > 0 {
+ cap += prec
+ }
+ return string(x.Append(make([]byte, 0, cap), format, prec))
+}
+
+// String formats x like x.Text('g', 10).
+// (String must be called explicitly, [Float.Format] does not support %s verb.)
+func (x *Float) String() string {
+ return x.Text('g', 10)
+}
+
+// Append appends to buf the string form of the floating-point number x,
+// as generated by x.Text, and returns the extended buffer.
+func (x *Float) Append(buf []byte, fmt byte, prec int) []byte {
+ // sign
+ if x.neg {
+ buf = append(buf, '-')
+ }
+
+ // Inf
+ if x.form == inf {
+ if !x.neg {
+ buf = append(buf, '+')
+ }
+ return append(buf, "Inf"...)
+ }
+
+ // pick off easy formats
+ switch fmt {
+ case 'b':
+ return x.fmtB(buf)
+ case 'p':
+ return x.fmtP(buf)
+ case 'x':
+ return x.fmtX(buf, prec)
+ }
+
+ // Algorithm:
+ // 1) convert Float to multiprecision decimal
+ // 2) round to desired precision
+ // 3) read digits out and format
+
+ // 1) convert Float to multiprecision decimal
+ var d decimal // == 0.0
+ if x.form == finite {
+ // x != 0
+ d.init(x.mant, int(x.exp)-x.mant.bitLen())
+ }
+
+ // 2) round to desired precision
+ shortest := false
+ if prec < 0 {
+ shortest = true
+ roundShortest(&d, x)
+ // Precision for shortest representation mode.
+ switch fmt {
+ case 'e', 'E':
+ prec = len(d.mant) - 1
+ case 'f':
+ prec = max(len(d.mant)-d.exp, 0)
+ case 'g', 'G':
+ prec = len(d.mant)
+ }
+ } else {
+ // round appropriately
+ switch fmt {
+ case 'e', 'E':
+ // one digit before and number of digits after decimal point
+ d.round(1 + prec)
+ case 'f':
+ // number of digits before and after decimal point
+ d.round(d.exp + prec)
+ case 'g', 'G':
+ if prec == 0 {
+ prec = 1
+ }
+ d.round(prec)
+ }
+ }
+
+ // 3) read digits out and format
+ switch fmt {
+ case 'e', 'E':
+ return fmtE(buf, fmt, prec, d)
+ case 'f':
+ return fmtF(buf, prec, d)
+ case 'g', 'G':
+ // trim trailing fractional zeros in %e format
+ eprec := prec
+ if eprec > len(d.mant) && len(d.mant) >= d.exp {
+ eprec = len(d.mant)
+ }
+ // %e is used if the exponent from the conversion
+ // is less than -4 or greater than or equal to the precision.
+ // If precision was the shortest possible, use eprec = 6 for
+ // this decision.
+ if shortest {
+ eprec = 6
+ }
+ exp := d.exp - 1
+ if exp < -4 || exp >= eprec {
+ if prec > len(d.mant) {
+ prec = len(d.mant)
+ }
+ return fmtE(buf, fmt+'e'-'g', prec-1, d)
+ }
+ if prec > d.exp {
+ prec = len(d.mant)
+ }
+ return fmtF(buf, max(prec-d.exp, 0), d)
+ }
+
+ // unknown format
+ if x.neg {
+ buf = buf[:len(buf)-1] // sign was added prematurely - remove it again
+ }
+ return append(buf, '%', fmt)
+}
+
+func roundShortest(d *decimal, x *Float) {
+ // if the mantissa is zero, the number is zero - stop now
+ if len(d.mant) == 0 {
+ return
+ }
+
+ // Approach: All numbers in the interval [x - 1/2ulp, x + 1/2ulp]
+ // (possibly exclusive) round to x for the given precision of x.
+ // Compute the lower and upper bound in decimal form and find the
+ // shortest decimal number d such that lower <= d <= upper.
+
+ // TODO(gri) strconv/ftoa.do describes a shortcut in some cases.
+ // See if we can use it (in adjusted form) here as well.
+
+ // 1) Compute normalized mantissa mant and exponent exp for x such
+ // that the lsb of mant corresponds to 1/2 ulp for the precision of
+ // x (i.e., for mant we want x.prec + 1 bits).
+ mant := nat(nil).set(x.mant)
+ exp := int(x.exp) - mant.bitLen()
+ s := mant.bitLen() - int(x.prec+1)
+ switch {
+ case s < 0:
+ mant = mant.shl(mant, uint(-s))
+ case s > 0:
+ mant = mant.shr(mant, uint(+s))
+ }
+ exp += s
+ // x = mant * 2**exp with lsb(mant) == 1/2 ulp of x.prec
+
+ // 2) Compute lower bound by subtracting 1/2 ulp.
+ var lower decimal
+ var tmp nat
+ lower.init(tmp.sub(mant, natOne), exp)
+
+ // 3) Compute upper bound by adding 1/2 ulp.
+ var upper decimal
+ upper.init(tmp.add(mant, natOne), exp)
+
+ // The upper and lower bounds are possible outputs only if
+ // the original mantissa is even, so that ToNearestEven rounding
+ // would round to the original mantissa and not the neighbors.
+ inclusive := mant[0]&2 == 0 // test bit 1 since original mantissa was shifted by 1
+
+ // Now we can figure out the minimum number of digits required.
+ // Walk along until d has distinguished itself from upper and lower.
+ for i, m := range d.mant {
+ l := lower.at(i)
+ u := upper.at(i)
+
+ // Okay to round down (truncate) if lower has a different digit
+ // or if lower is inclusive and is exactly the result of rounding
+ // down (i.e., and we have reached the final digit of lower).
+ okdown := l != m || inclusive && i+1 == len(lower.mant)
+
+ // Okay to round up if upper has a different digit and either upper
+ // is inclusive or upper is bigger than the result of rounding up.
+ okup := m != u && (inclusive || m+1 < u || i+1 < len(upper.mant))
+
+ // If it's okay to do either, then round to the nearest one.
+ // If it's okay to do only one, do it.
+ switch {
+ case okdown && okup:
+ d.round(i + 1)
+ return
+ case okdown:
+ d.roundDown(i + 1)
+ return
+ case okup:
+ d.roundUp(i + 1)
+ return
+ }
+ }
+}
+
+// %e: d.ddddde±dd
+func fmtE(buf []byte, fmt byte, prec int, d decimal) []byte {
+ // first digit
+ ch := byte('0')
+ if len(d.mant) > 0 {
+ ch = d.mant[0]
+ }
+ buf = append(buf, ch)
+
+ // .moredigits
+ if prec > 0 {
+ buf = append(buf, '.')
+ i := 1
+ m := min(len(d.mant), prec+1)
+ if i < m {
+ buf = append(buf, d.mant[i:m]...)
+ i = m
+ }
+ for ; i <= prec; i++ {
+ buf = append(buf, '0')
+ }
+ }
+
+ // e±
+ buf = append(buf, fmt)
+ var exp int64
+ if len(d.mant) > 0 {
+ exp = int64(d.exp) - 1 // -1 because first digit was printed before '.'
+ }
+ if exp < 0 {
+ ch = '-'
+ exp = -exp
+ } else {
+ ch = '+'
+ }
+ buf = append(buf, ch)
+
+ // dd...d
+ if exp < 10 {
+ buf = append(buf, '0') // at least 2 exponent digits
+ }
+ return strconv.AppendInt(buf, exp, 10)
+}
+
+// %f: ddddddd.ddddd
+func fmtF(buf []byte, prec int, d decimal) []byte {
+ // integer, padded with zeros as needed
+ if d.exp > 0 {
+ m := min(len(d.mant), d.exp)
+ buf = append(buf, d.mant[:m]...)
+ for ; m < d.exp; m++ {
+ buf = append(buf, '0')
+ }
+ } else {
+ buf = append(buf, '0')
+ }
+
+ // fraction
+ if prec > 0 {
+ buf = append(buf, '.')
+ for i := 0; i < prec; i++ {
+ buf = append(buf, d.at(d.exp+i))
+ }
+ }
+
+ return buf
+}
+
+// fmtB appends the string of x in the format mantissa "p" exponent
+// with a decimal mantissa and a binary exponent, or 0" if x is zero,
+// and returns the extended buffer.
+// The mantissa is normalized such that is uses x.Prec() bits in binary
+// representation.
+// The sign of x is ignored, and x must not be an Inf.
+// (The caller handles Inf before invoking fmtB.)
+func (x *Float) fmtB(buf []byte) []byte {
+ if x.form == zero {
+ return append(buf, '0')
+ }
+
+ if debugFloat && x.form != finite {
+ panic("non-finite float")
+ }
+ // x != 0
+
+ // adjust mantissa to use exactly x.prec bits
+ m := x.mant
+ switch w := uint32(len(x.mant)) * _W; {
+ case w < x.prec:
+ m = nat(nil).shl(m, uint(x.prec-w))
+ case w > x.prec:
+ m = nat(nil).shr(m, uint(w-x.prec))
+ }
+
+ buf = append(buf, m.utoa(10)...)
+ buf = append(buf, 'p')
+ e := int64(x.exp) - int64(x.prec)
+ if e >= 0 {
+ buf = append(buf, '+')
+ }
+ return strconv.AppendInt(buf, e, 10)
+}
+
+// fmtX appends the string of x in the format "0x1." mantissa "p" exponent
+// with a hexadecimal mantissa and a binary exponent, or "0x0p0" if x is zero,
+// and returns the extended buffer.
+// A non-zero mantissa is normalized such that 1.0 <= mantissa < 2.0.
+// The sign of x is ignored, and x must not be an Inf.
+// (The caller handles Inf before invoking fmtX.)
+func (x *Float) fmtX(buf []byte, prec int) []byte {
+ if x.form == zero {
+ buf = append(buf, "0x0"...)
+ if prec > 0 {
+ buf = append(buf, '.')
+ for i := 0; i < prec; i++ {
+ buf = append(buf, '0')
+ }
+ }
+ buf = append(buf, "p+00"...)
+ return buf
+ }
+
+ if debugFloat && x.form != finite {
+ panic("non-finite float")
+ }
+
+ // round mantissa to n bits
+ var n uint
+ if prec < 0 {
+ n = 1 + (x.MinPrec()-1+3)/4*4 // round MinPrec up to 1 mod 4
+ } else {
+ n = 1 + 4*uint(prec)
+ }
+ // n%4 == 1
+ x = new(Float).SetPrec(n).SetMode(x.mode).Set(x)
+
+ // adjust mantissa to use exactly n bits
+ m := x.mant
+ switch w := uint(len(x.mant)) * _W; {
+ case w < n:
+ m = nat(nil).shl(m, n-w)
+ case w > n:
+ m = nat(nil).shr(m, w-n)
+ }
+ exp64 := int64(x.exp) - 1 // avoid wrap-around
+
+ hm := m.utoa(16)
+ if debugFloat && hm[0] != '1' {
+ panic("incorrect mantissa: " + string(hm))
+ }
+ buf = append(buf, "0x1"...)
+ if len(hm) > 1 {
+ buf = append(buf, '.')
+ buf = append(buf, hm[1:]...)
+ }
+
+ buf = append(buf, 'p')
+ if exp64 >= 0 {
+ buf = append(buf, '+')
+ } else {
+ exp64 = -exp64
+ buf = append(buf, '-')
+ }
+ // Force at least two exponent digits, to match fmt.
+ if exp64 < 10 {
+ buf = append(buf, '0')
+ }
+ return strconv.AppendInt(buf, exp64, 10)
+}
+
+// fmtP appends the string of x in the format "0x." mantissa "p" exponent
+// with a hexadecimal mantissa and a binary exponent, or "0" if x is zero,
+// and returns the extended buffer.
+// The mantissa is normalized such that 0.5 <= 0.mantissa < 1.0.
+// The sign of x is ignored, and x must not be an Inf.
+// (The caller handles Inf before invoking fmtP.)
+func (x *Float) fmtP(buf []byte) []byte {
+ if x.form == zero {
+ return append(buf, '0')
+ }
+
+ if debugFloat && x.form != finite {
+ panic("non-finite float")
+ }
+ // x != 0
+
+ // remove trailing 0 words early
+ // (no need to convert to hex 0's and trim later)
+ m := x.mant
+ i := 0
+ for i < len(m) && m[i] == 0 {
+ i++
+ }
+ m = m[i:]
+
+ buf = append(buf, "0x."...)
+ buf = append(buf, bytes.TrimRight(m.utoa(16), "0")...)
+ buf = append(buf, 'p')
+ if x.exp >= 0 {
+ buf = append(buf, '+')
+ }
+ return strconv.AppendInt(buf, int64(x.exp), 10)
+}
+
+var _ fmt.Formatter = &floatZero // *Float must implement fmt.Formatter
+
+// Format implements [fmt.Formatter]. It accepts all the regular
+// formats for floating-point numbers ('b', 'e', 'E', 'f', 'F',
+// 'g', 'G', 'x') as well as 'p' and 'v'. See (*Float).Text for the
+// interpretation of 'p'. The 'v' format is handled like 'g'.
+// Format also supports specification of the minimum precision
+// in digits, the output field width, as well as the format flags
+// '+' and ' ' for sign control, '0' for space or zero padding,
+// and '-' for left or right justification. See the fmt package
+// for details.
+func (x *Float) Format(s fmt.State, format rune) {
+ prec, hasPrec := s.Precision()
+ if !hasPrec {
+ prec = 6 // default precision for 'e', 'f'
+ }
+
+ switch format {
+ case 'e', 'E', 'f', 'b', 'p', 'x':
+ // nothing to do
+ case 'F':
+ // (*Float).Text doesn't support 'F'; handle like 'f'
+ format = 'f'
+ case 'v':
+ // handle like 'g'
+ format = 'g'
+ fallthrough
+ case 'g', 'G':
+ if !hasPrec {
+ prec = -1 // default precision for 'g', 'G'
+ }
+ default:
+ fmt.Fprintf(s, "%%!%c(*big.Float=%s)", format, x.String())
+ return
+ }
+ var buf []byte
+ buf = x.Append(buf, byte(format), prec)
+ if len(buf) == 0 {
+ buf = []byte("?") // should never happen, but don't crash
+ }
+ // len(buf) > 0
+
+ var sign string
+ switch {
+ case buf[0] == '-':
+ sign = "-"
+ buf = buf[1:]
+ case buf[0] == '+':
+ // +Inf
+ sign = "+"
+ if s.Flag(' ') {
+ sign = " "
+ }
+ buf = buf[1:]
+ case s.Flag('+'):
+ sign = "+"
+ case s.Flag(' '):
+ sign = " "
+ }
+
+ var padding int
+ if width, hasWidth := s.Width(); hasWidth && width > len(sign)+len(buf) {
+ padding = width - len(sign) - len(buf)
+ }
+
+ switch {
+ case s.Flag('0') && !x.IsInf():
+ // 0-padding on left
+ writeMultiple(s, sign, 1)
+ writeMultiple(s, "0", padding)
+ s.Write(buf)
+ case s.Flag('-'):
+ // padding on right
+ writeMultiple(s, sign, 1)
+ s.Write(buf)
+ writeMultiple(s, " ", padding)
+ default:
+ // padding on left
+ writeMultiple(s, " ", padding)
+ writeMultiple(s, sign, 1)
+ s.Write(buf)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/gcd_test.go b/platform/dbops/binaries/go/go/src/math/big/gcd_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3cca2ecd0c821aafc46d10e53e9e853526589d9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/gcd_test.go
@@ -0,0 +1,64 @@
+// 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.
+
+// This file implements a GCD benchmark.
+// Usage: go test math/big -test.bench GCD
+
+package big
+
+import (
+ "math/rand"
+ "testing"
+)
+
+// randInt returns a pseudo-random Int in the range [1<<(size-1), (1< 1<<(size-1)
+}
+
+func runGCD(b *testing.B, aSize, bSize uint) {
+ if isRaceBuilder && (aSize > 1000 || bSize > 1000) {
+ b.Skip("skipping on race builder")
+ }
+ b.Run("WithoutXY", func(b *testing.B) {
+ runGCDExt(b, aSize, bSize, false)
+ })
+ b.Run("WithXY", func(b *testing.B) {
+ runGCDExt(b, aSize, bSize, true)
+ })
+}
+
+func runGCDExt(b *testing.B, aSize, bSize uint, calcXY bool) {
+ b.StopTimer()
+ var r = rand.New(rand.NewSource(1234))
+ aa := randInt(r, aSize)
+ bb := randInt(r, bSize)
+ var x, y *Int
+ if calcXY {
+ x = new(Int)
+ y = new(Int)
+ }
+ b.StartTimer()
+ for i := 0; i < b.N; i++ {
+ new(Int).GCD(x, y, aa, bb)
+ }
+}
+
+func BenchmarkGCD10x10(b *testing.B) { runGCD(b, 10, 10) }
+func BenchmarkGCD10x100(b *testing.B) { runGCD(b, 10, 100) }
+func BenchmarkGCD10x1000(b *testing.B) { runGCD(b, 10, 1000) }
+func BenchmarkGCD10x10000(b *testing.B) { runGCD(b, 10, 10000) }
+func BenchmarkGCD10x100000(b *testing.B) { runGCD(b, 10, 100000) }
+func BenchmarkGCD100x100(b *testing.B) { runGCD(b, 100, 100) }
+func BenchmarkGCD100x1000(b *testing.B) { runGCD(b, 100, 1000) }
+func BenchmarkGCD100x10000(b *testing.B) { runGCD(b, 100, 10000) }
+func BenchmarkGCD100x100000(b *testing.B) { runGCD(b, 100, 100000) }
+func BenchmarkGCD1000x1000(b *testing.B) { runGCD(b, 1000, 1000) }
+func BenchmarkGCD1000x10000(b *testing.B) { runGCD(b, 1000, 10000) }
+func BenchmarkGCD1000x100000(b *testing.B) { runGCD(b, 1000, 100000) }
+func BenchmarkGCD10000x10000(b *testing.B) { runGCD(b, 10000, 10000) }
+func BenchmarkGCD10000x100000(b *testing.B) { runGCD(b, 10000, 100000) }
+func BenchmarkGCD100000x100000(b *testing.B) { runGCD(b, 100000, 100000) }
diff --git a/platform/dbops/binaries/go/go/src/math/big/hilbert_test.go b/platform/dbops/binaries/go/go/src/math/big/hilbert_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1a84341b3c0b63bfa7040c5631c2af9c8670578a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/hilbert_test.go
@@ -0,0 +1,160 @@
+// 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.
+
+// A little test program and benchmark for rational arithmetics.
+// Computes a Hilbert matrix, its inverse, multiplies them
+// and verifies that the product is the identity matrix.
+
+package big
+
+import (
+ "fmt"
+ "testing"
+)
+
+type matrix struct {
+ n, m int
+ a []*Rat
+}
+
+func (a *matrix) at(i, j int) *Rat {
+ if !(0 <= i && i < a.n && 0 <= j && j < a.m) {
+ panic("index out of range")
+ }
+ return a.a[i*a.m+j]
+}
+
+func (a *matrix) set(i, j int, x *Rat) {
+ if !(0 <= i && i < a.n && 0 <= j && j < a.m) {
+ panic("index out of range")
+ }
+ a.a[i*a.m+j] = x
+}
+
+func newMatrix(n, m int) *matrix {
+ if !(0 <= n && 0 <= m) {
+ panic("illegal matrix")
+ }
+ a := new(matrix)
+ a.n = n
+ a.m = m
+ a.a = make([]*Rat, n*m)
+ return a
+}
+
+func newUnit(n int) *matrix {
+ a := newMatrix(n, n)
+ for i := 0; i < n; i++ {
+ for j := 0; j < n; j++ {
+ x := NewRat(0, 1)
+ if i == j {
+ x.SetInt64(1)
+ }
+ a.set(i, j, x)
+ }
+ }
+ return a
+}
+
+func newHilbert(n int) *matrix {
+ a := newMatrix(n, n)
+ for i := 0; i < n; i++ {
+ for j := 0; j < n; j++ {
+ a.set(i, j, NewRat(1, int64(i+j+1)))
+ }
+ }
+ return a
+}
+
+func newInverseHilbert(n int) *matrix {
+ a := newMatrix(n, n)
+ for i := 0; i < n; i++ {
+ for j := 0; j < n; j++ {
+ x1 := new(Rat).SetInt64(int64(i + j + 1))
+ x2 := new(Rat).SetInt(new(Int).Binomial(int64(n+i), int64(n-j-1)))
+ x3 := new(Rat).SetInt(new(Int).Binomial(int64(n+j), int64(n-i-1)))
+ x4 := new(Rat).SetInt(new(Int).Binomial(int64(i+j), int64(i)))
+
+ x1.Mul(x1, x2)
+ x1.Mul(x1, x3)
+ x1.Mul(x1, x4)
+ x1.Mul(x1, x4)
+
+ if (i+j)&1 != 0 {
+ x1.Neg(x1)
+ }
+
+ a.set(i, j, x1)
+ }
+ }
+ return a
+}
+
+func (a *matrix) mul(b *matrix) *matrix {
+ if a.m != b.n {
+ panic("illegal matrix multiply")
+ }
+ c := newMatrix(a.n, b.m)
+ for i := 0; i < c.n; i++ {
+ for j := 0; j < c.m; j++ {
+ x := NewRat(0, 1)
+ for k := 0; k < a.m; k++ {
+ x.Add(x, new(Rat).Mul(a.at(i, k), b.at(k, j)))
+ }
+ c.set(i, j, x)
+ }
+ }
+ return c
+}
+
+func (a *matrix) eql(b *matrix) bool {
+ if a.n != b.n || a.m != b.m {
+ return false
+ }
+ for i := 0; i < a.n; i++ {
+ for j := 0; j < a.m; j++ {
+ if a.at(i, j).Cmp(b.at(i, j)) != 0 {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func (a *matrix) String() string {
+ s := ""
+ for i := 0; i < a.n; i++ {
+ for j := 0; j < a.m; j++ {
+ s += fmt.Sprintf("\t%s", a.at(i, j))
+ }
+ s += "\n"
+ }
+ return s
+}
+
+func doHilbert(t *testing.T, n int) {
+ a := newHilbert(n)
+ b := newInverseHilbert(n)
+ I := newUnit(n)
+ ab := a.mul(b)
+ if !ab.eql(I) {
+ if t == nil {
+ panic("Hilbert failed")
+ }
+ t.Errorf("a = %s\n", a)
+ t.Errorf("b = %s\n", b)
+ t.Errorf("a*b = %s\n", ab)
+ t.Errorf("I = %s\n", I)
+ }
+}
+
+func TestHilbert(t *testing.T) {
+ doHilbert(t, 10)
+}
+
+func BenchmarkHilbert(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ doHilbert(nil, 10)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/int.go b/platform/dbops/binaries/go/go/src/math/big/int.go
new file mode 100644
index 0000000000000000000000000000000000000000..b79b4592709f9704ab314a07f0361a3f338f5eaa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/int.go
@@ -0,0 +1,1321 @@
+// 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.
+
+// This file implements signed multi-precision integers.
+
+package big
+
+import (
+ "fmt"
+ "io"
+ "math/rand"
+ "strings"
+)
+
+// An Int represents a signed multi-precision integer.
+// The zero value for an Int represents the value 0.
+//
+// Operations always take pointer arguments (*Int) rather
+// than Int values, and each unique Int value requires
+// its own unique *Int pointer. To "copy" an Int value,
+// an existing (or newly allocated) Int must be set to
+// a new value using the [Int.Set] method; shallow copies
+// of Ints are not supported and may lead to errors.
+//
+// Note that methods may leak the Int's value through timing side-channels.
+// Because of this and because of the scope and complexity of the
+// implementation, Int is not well-suited to implement cryptographic operations.
+// The standard library avoids exposing non-trivial Int methods to
+// attacker-controlled inputs and the determination of whether a bug in math/big
+// is considered a security vulnerability might depend on the impact on the
+// standard library.
+type Int struct {
+ neg bool // sign
+ abs nat // absolute value of the integer
+}
+
+var intOne = &Int{false, natOne}
+
+// Sign returns:
+//
+// -1 if x < 0
+// 0 if x == 0
+// +1 if x > 0
+func (x *Int) Sign() int {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ if len(x.abs) == 0 {
+ return 0
+ }
+ if x.neg {
+ return -1
+ }
+ return 1
+}
+
+// SetInt64 sets z to x and returns z.
+func (z *Int) SetInt64(x int64) *Int {
+ neg := false
+ if x < 0 {
+ neg = true
+ x = -x
+ }
+ z.abs = z.abs.setUint64(uint64(x))
+ z.neg = neg
+ return z
+}
+
+// SetUint64 sets z to x and returns z.
+func (z *Int) SetUint64(x uint64) *Int {
+ z.abs = z.abs.setUint64(x)
+ z.neg = false
+ return z
+}
+
+// NewInt allocates and returns a new [Int] set to x.
+func NewInt(x int64) *Int {
+ // This code is arranged to be inlineable and produce
+ // zero allocations when inlined. See issue 29951.
+ u := uint64(x)
+ if x < 0 {
+ u = -u
+ }
+ var abs []Word
+ if x == 0 {
+ } else if _W == 32 && u>>32 != 0 {
+ abs = []Word{Word(u), Word(u >> 32)}
+ } else {
+ abs = []Word{Word(u)}
+ }
+ return &Int{neg: x < 0, abs: abs}
+}
+
+// Set sets z to x and returns z.
+func (z *Int) Set(x *Int) *Int {
+ if z != x {
+ z.abs = z.abs.set(x.abs)
+ z.neg = x.neg
+ }
+ return z
+}
+
+// Bits provides raw (unchecked but fast) access to x by returning its
+// absolute value as a little-endian [Word] slice. The result and x share
+// the same underlying array.
+// Bits is intended to support implementation of missing low-level [Int]
+// functionality outside this package; it should be avoided otherwise.
+func (x *Int) Bits() []Word {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ return x.abs
+}
+
+// SetBits provides raw (unchecked but fast) access to z by setting its
+// value to abs, interpreted as a little-endian [Word] slice, and returning
+// z. The result and abs share the same underlying array.
+// SetBits is intended to support implementation of missing low-level [Int]
+// functionality outside this package; it should be avoided otherwise.
+func (z *Int) SetBits(abs []Word) *Int {
+ z.abs = nat(abs).norm()
+ z.neg = false
+ return z
+}
+
+// Abs sets z to |x| (the absolute value of x) and returns z.
+func (z *Int) Abs(x *Int) *Int {
+ z.Set(x)
+ z.neg = false
+ return z
+}
+
+// Neg sets z to -x and returns z.
+func (z *Int) Neg(x *Int) *Int {
+ z.Set(x)
+ z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign
+ return z
+}
+
+// Add sets z to the sum x+y and returns z.
+func (z *Int) Add(x, y *Int) *Int {
+ neg := x.neg
+ if x.neg == y.neg {
+ // x + y == x + y
+ // (-x) + (-y) == -(x + y)
+ z.abs = z.abs.add(x.abs, y.abs)
+ } else {
+ // x + (-y) == x - y == -(y - x)
+ // (-x) + y == y - x == -(x - y)
+ if x.abs.cmp(y.abs) >= 0 {
+ z.abs = z.abs.sub(x.abs, y.abs)
+ } else {
+ neg = !neg
+ z.abs = z.abs.sub(y.abs, x.abs)
+ }
+ }
+ z.neg = len(z.abs) > 0 && neg // 0 has no sign
+ return z
+}
+
+// Sub sets z to the difference x-y and returns z.
+func (z *Int) Sub(x, y *Int) *Int {
+ neg := x.neg
+ if x.neg != y.neg {
+ // x - (-y) == x + y
+ // (-x) - y == -(x + y)
+ z.abs = z.abs.add(x.abs, y.abs)
+ } else {
+ // x - y == x - y == -(y - x)
+ // (-x) - (-y) == y - x == -(x - y)
+ if x.abs.cmp(y.abs) >= 0 {
+ z.abs = z.abs.sub(x.abs, y.abs)
+ } else {
+ neg = !neg
+ z.abs = z.abs.sub(y.abs, x.abs)
+ }
+ }
+ z.neg = len(z.abs) > 0 && neg // 0 has no sign
+ return z
+}
+
+// Mul sets z to the product x*y and returns z.
+func (z *Int) Mul(x, y *Int) *Int {
+ // x * y == x * y
+ // x * (-y) == -(x * y)
+ // (-x) * y == -(x * y)
+ // (-x) * (-y) == x * y
+ if x == y {
+ z.abs = z.abs.sqr(x.abs)
+ z.neg = false
+ return z
+ }
+ z.abs = z.abs.mul(x.abs, y.abs)
+ z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
+ return z
+}
+
+// MulRange sets z to the product of all integers
+// in the range [a, b] inclusively and returns z.
+// If a > b (empty range), the result is 1.
+func (z *Int) MulRange(a, b int64) *Int {
+ switch {
+ case a > b:
+ return z.SetInt64(1) // empty range
+ case a <= 0 && b >= 0:
+ return z.SetInt64(0) // range includes 0
+ }
+ // a <= b && (b < 0 || a > 0)
+
+ neg := false
+ if a < 0 {
+ neg = (b-a)&1 == 0
+ a, b = -b, -a
+ }
+
+ z.abs = z.abs.mulRange(uint64(a), uint64(b))
+ z.neg = neg
+ return z
+}
+
+// Binomial sets z to the binomial coefficient C(n, k) and returns z.
+func (z *Int) Binomial(n, k int64) *Int {
+ if k > n {
+ return z.SetInt64(0)
+ }
+ // reduce the number of multiplications by reducing k
+ if k > n-k {
+ k = n - k // C(n, k) == C(n, n-k)
+ }
+ // C(n, k) == n * (n-1) * ... * (n-k+1) / k * (k-1) * ... * 1
+ // == n * (n-1) * ... * (n-k+1) / 1 * (1+1) * ... * k
+ //
+ // Using the multiplicative formula produces smaller values
+ // at each step, requiring fewer allocations and computations:
+ //
+ // z = 1
+ // for i := 0; i < k; i = i+1 {
+ // z *= n-i
+ // z /= i+1
+ // }
+ //
+ // finally to avoid computing i+1 twice per loop:
+ //
+ // z = 1
+ // i := 0
+ // for i < k {
+ // z *= n-i
+ // i++
+ // z /= i
+ // }
+ var N, K, i, t Int
+ N.SetInt64(n)
+ K.SetInt64(k)
+ z.Set(intOne)
+ for i.Cmp(&K) < 0 {
+ z.Mul(z, t.Sub(&N, &i))
+ i.Add(&i, intOne)
+ z.Quo(z, &i)
+ }
+ return z
+}
+
+// Quo sets z to the quotient x/y for y != 0 and returns z.
+// If y == 0, a division-by-zero run-time panic occurs.
+// Quo implements truncated division (like Go); see [Int.QuoRem] for more details.
+func (z *Int) Quo(x, y *Int) *Int {
+ z.abs, _ = z.abs.div(nil, x.abs, y.abs)
+ z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
+ return z
+}
+
+// Rem sets z to the remainder x%y for y != 0 and returns z.
+// If y == 0, a division-by-zero run-time panic occurs.
+// Rem implements truncated modulus (like Go); see [Int.QuoRem] for more details.
+func (z *Int) Rem(x, y *Int) *Int {
+ _, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
+ z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
+ return z
+}
+
+// QuoRem sets z to the quotient x/y and r to the remainder x%y
+// and returns the pair (z, r) for y != 0.
+// If y == 0, a division-by-zero run-time panic occurs.
+//
+// QuoRem implements T-division and modulus (like Go):
+//
+// q = x/y with the result truncated to zero
+// r = x - y*q
+//
+// (See Daan Leijen, “Division and Modulus for Computer Scientists”.)
+// See DivMod for Euclidean division and modulus (unlike Go).
+func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
+ z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
+ z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
+ return z, r
+}
+
+// Div sets z to the quotient x/y for y != 0 and returns z.
+// If y == 0, a division-by-zero run-time panic occurs.
+// Div implements Euclidean division (unlike Go); see [Int.DivMod] for more details.
+func (z *Int) Div(x, y *Int) *Int {
+ y_neg := y.neg // z may be an alias for y
+ var r Int
+ z.QuoRem(x, y, &r)
+ if r.neg {
+ if y_neg {
+ z.Add(z, intOne)
+ } else {
+ z.Sub(z, intOne)
+ }
+ }
+ return z
+}
+
+// Mod sets z to the modulus x%y for y != 0 and returns z.
+// If y == 0, a division-by-zero run-time panic occurs.
+// Mod implements Euclidean modulus (unlike Go); see [Int.DivMod] for more details.
+func (z *Int) Mod(x, y *Int) *Int {
+ y0 := y // save y
+ if z == y || alias(z.abs, y.abs) {
+ y0 = new(Int).Set(y)
+ }
+ var q Int
+ q.QuoRem(x, y, z)
+ if z.neg {
+ if y0.neg {
+ z.Sub(z, y0)
+ } else {
+ z.Add(z, y0)
+ }
+ }
+ return z
+}
+
+// DivMod sets z to the quotient x div y and m to the modulus x mod y
+// and returns the pair (z, m) for y != 0.
+// If y == 0, a division-by-zero run-time panic occurs.
+//
+// DivMod implements Euclidean division and modulus (unlike Go):
+//
+// q = x div y such that
+// m = x - y*q with 0 <= m < |y|
+//
+// (See Raymond T. Boute, “The Euclidean definition of the functions
+// div and mod”. ACM Transactions on Programming Languages and
+// Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
+// ACM press.)
+// See [Int.QuoRem] for T-division and modulus (like Go).
+func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
+ y0 := y // save y
+ if z == y || alias(z.abs, y.abs) {
+ y0 = new(Int).Set(y)
+ }
+ z.QuoRem(x, y, m)
+ if m.neg {
+ if y0.neg {
+ z.Add(z, intOne)
+ m.Sub(m, y0)
+ } else {
+ z.Sub(z, intOne)
+ m.Add(m, y0)
+ }
+ }
+ return z, m
+}
+
+// Cmp compares x and y and returns:
+//
+// -1 if x < y
+// 0 if x == y
+// +1 if x > y
+func (x *Int) Cmp(y *Int) (r int) {
+ // x cmp y == x cmp y
+ // x cmp (-y) == x
+ // (-x) cmp y == y
+ // (-x) cmp (-y) == -(x cmp y)
+ switch {
+ case x == y:
+ // nothing to do
+ case x.neg == y.neg:
+ r = x.abs.cmp(y.abs)
+ if x.neg {
+ r = -r
+ }
+ case x.neg:
+ r = -1
+ default:
+ r = 1
+ }
+ return
+}
+
+// CmpAbs compares the absolute values of x and y and returns:
+//
+// -1 if |x| < |y|
+// 0 if |x| == |y|
+// +1 if |x| > |y|
+func (x *Int) CmpAbs(y *Int) int {
+ return x.abs.cmp(y.abs)
+}
+
+// low32 returns the least significant 32 bits of x.
+func low32(x nat) uint32 {
+ if len(x) == 0 {
+ return 0
+ }
+ return uint32(x[0])
+}
+
+// low64 returns the least significant 64 bits of x.
+func low64(x nat) uint64 {
+ if len(x) == 0 {
+ return 0
+ }
+ v := uint64(x[0])
+ if _W == 32 && len(x) > 1 {
+ return uint64(x[1])<<32 | v
+ }
+ return v
+}
+
+// Int64 returns the int64 representation of x.
+// If x cannot be represented in an int64, the result is undefined.
+func (x *Int) Int64() int64 {
+ v := int64(low64(x.abs))
+ if x.neg {
+ v = -v
+ }
+ return v
+}
+
+// Uint64 returns the uint64 representation of x.
+// If x cannot be represented in a uint64, the result is undefined.
+func (x *Int) Uint64() uint64 {
+ return low64(x.abs)
+}
+
+// IsInt64 reports whether x can be represented as an int64.
+func (x *Int) IsInt64() bool {
+ if len(x.abs) <= 64/_W {
+ w := int64(low64(x.abs))
+ return w >= 0 || x.neg && w == -w
+ }
+ return false
+}
+
+// IsUint64 reports whether x can be represented as a uint64.
+func (x *Int) IsUint64() bool {
+ return !x.neg && len(x.abs) <= 64/_W
+}
+
+// Float64 returns the float64 value nearest x,
+// and an indication of any rounding that occurred.
+func (x *Int) Float64() (float64, Accuracy) {
+ n := x.abs.bitLen() // NB: still uses slow crypto impl!
+ if n == 0 {
+ return 0.0, Exact
+ }
+
+ // Fast path: no more than 53 significant bits.
+ if n <= 53 || n < 64 && n-int(x.abs.trailingZeroBits()) <= 53 {
+ f := float64(low64(x.abs))
+ if x.neg {
+ f = -f
+ }
+ return f, Exact
+ }
+
+ return new(Float).SetInt(x).Float64()
+}
+
+// SetString sets z to the value of s, interpreted in the given base,
+// and returns z and a boolean indicating success. The entire string
+// (not just a prefix) must be valid for success. If SetString fails,
+// the value of z is undefined but the returned value is nil.
+//
+// The base argument must be 0 or a value between 2 and [MaxBase].
+// For base 0, the number prefix determines the actual base: A prefix of
+// “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8,
+// and “0x” or “0X” selects base 16. Otherwise, the selected base is 10
+// and no prefix is accepted.
+//
+// For bases <= 36, lower and upper case letters are considered the same:
+// The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35.
+// For bases > 36, the upper case letters 'A' to 'Z' represent the digit
+// values 36 to 61.
+//
+// For base 0, an underscore character “_” may appear between a base
+// prefix and an adjacent digit, and between successive digits; such
+// underscores do not change the value of the number.
+// Incorrect placement of underscores is reported as an error if there
+// are no other errors. If base != 0, underscores are not recognized
+// and act like any other character that is not a valid digit.
+func (z *Int) SetString(s string, base int) (*Int, bool) {
+ return z.setFromScanner(strings.NewReader(s), base)
+}
+
+// setFromScanner implements SetString given an io.ByteScanner.
+// For documentation see comments of SetString.
+func (z *Int) setFromScanner(r io.ByteScanner, base int) (*Int, bool) {
+ if _, _, err := z.scan(r, base); err != nil {
+ return nil, false
+ }
+ // entire content must have been consumed
+ if _, err := r.ReadByte(); err != io.EOF {
+ return nil, false
+ }
+ return z, true // err == io.EOF => scan consumed all content of r
+}
+
+// SetBytes interprets buf as the bytes of a big-endian unsigned
+// integer, sets z to that value, and returns z.
+func (z *Int) SetBytes(buf []byte) *Int {
+ z.abs = z.abs.setBytes(buf)
+ z.neg = false
+ return z
+}
+
+// Bytes returns the absolute value of x as a big-endian byte slice.
+//
+// To use a fixed length slice, or a preallocated one, use [Int.FillBytes].
+func (x *Int) Bytes() []byte {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ buf := make([]byte, len(x.abs)*_S)
+ return buf[x.abs.bytes(buf):]
+}
+
+// FillBytes sets buf to the absolute value of x, storing it as a zero-extended
+// big-endian byte slice, and returns buf.
+//
+// If the absolute value of x doesn't fit in buf, FillBytes will panic.
+func (x *Int) FillBytes(buf []byte) []byte {
+ // Clear whole buffer. (This gets optimized into a memclr.)
+ for i := range buf {
+ buf[i] = 0
+ }
+ x.abs.bytes(buf)
+ return buf
+}
+
+// BitLen returns the length of the absolute value of x in bits.
+// The bit length of 0 is 0.
+func (x *Int) BitLen() int {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ return x.abs.bitLen()
+}
+
+// TrailingZeroBits returns the number of consecutive least significant zero
+// bits of |x|.
+func (x *Int) TrailingZeroBits() uint {
+ return x.abs.trailingZeroBits()
+}
+
+// Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
+// If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0,
+// and x and m are not relatively prime, z is unchanged and nil is returned.
+//
+// Modular exponentiation of inputs of a particular size is not a
+// cryptographically constant-time operation.
+func (z *Int) Exp(x, y, m *Int) *Int {
+ return z.exp(x, y, m, false)
+}
+
+func (z *Int) expSlow(x, y, m *Int) *Int {
+ return z.exp(x, y, m, true)
+}
+
+func (z *Int) exp(x, y, m *Int, slow bool) *Int {
+ // See Knuth, volume 2, section 4.6.3.
+ xWords := x.abs
+ if y.neg {
+ if m == nil || len(m.abs) == 0 {
+ return z.SetInt64(1)
+ }
+ // for y < 0: x**y mod m == (x**(-1))**|y| mod m
+ inverse := new(Int).ModInverse(x, m)
+ if inverse == nil {
+ return nil
+ }
+ xWords = inverse.abs
+ }
+ yWords := y.abs
+
+ var mWords nat
+ if m != nil {
+ if z == m || alias(z.abs, m.abs) {
+ m = new(Int).Set(m)
+ }
+ mWords = m.abs // m.abs may be nil for m == 0
+ }
+
+ z.abs = z.abs.expNN(xWords, yWords, mWords, slow)
+ z.neg = len(z.abs) > 0 && x.neg && len(yWords) > 0 && yWords[0]&1 == 1 // 0 has no sign
+ if z.neg && len(mWords) > 0 {
+ // make modulus result positive
+ z.abs = z.abs.sub(mWords, z.abs) // z == x**y mod |m| && 0 <= z < |m|
+ z.neg = false
+ }
+
+ return z
+}
+
+// GCD sets z to the greatest common divisor of a and b and returns z.
+// If x or y are not nil, GCD sets their value such that z = a*x + b*y.
+//
+// a and b may be positive, zero or negative. (Before Go 1.14 both had
+// to be > 0.) Regardless of the signs of a and b, z is always >= 0.
+//
+// If a == b == 0, GCD sets z = x = y = 0.
+//
+// If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
+//
+// If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
+func (z *Int) GCD(x, y, a, b *Int) *Int {
+ if len(a.abs) == 0 || len(b.abs) == 0 {
+ lenA, lenB, negA, negB := len(a.abs), len(b.abs), a.neg, b.neg
+ if lenA == 0 {
+ z.Set(b)
+ } else {
+ z.Set(a)
+ }
+ z.neg = false
+ if x != nil {
+ if lenA == 0 {
+ x.SetUint64(0)
+ } else {
+ x.SetUint64(1)
+ x.neg = negA
+ }
+ }
+ if y != nil {
+ if lenB == 0 {
+ y.SetUint64(0)
+ } else {
+ y.SetUint64(1)
+ y.neg = negB
+ }
+ }
+ return z
+ }
+
+ return z.lehmerGCD(x, y, a, b)
+}
+
+// lehmerSimulate attempts to simulate several Euclidean update steps
+// using the leading digits of A and B. It returns u0, u1, v0, v1
+// such that A and B can be updated as:
+//
+// A = u0*A + v0*B
+// B = u1*A + v1*B
+//
+// Requirements: A >= B and len(B.abs) >= 2
+// Since we are calculating with full words to avoid overflow,
+// we use 'even' to track the sign of the cosequences.
+// For even iterations: u0, v1 >= 0 && u1, v0 <= 0
+// For odd iterations: u0, v1 <= 0 && u1, v0 >= 0
+func lehmerSimulate(A, B *Int) (u0, u1, v0, v1 Word, even bool) {
+ // initialize the digits
+ var a1, a2, u2, v2 Word
+
+ m := len(B.abs) // m >= 2
+ n := len(A.abs) // n >= m >= 2
+
+ // extract the top Word of bits from A and B
+ h := nlz(A.abs[n-1])
+ a1 = A.abs[n-1]<>(_W-h)
+ // B may have implicit zero words in the high bits if the lengths differ
+ switch {
+ case n == m:
+ a2 = B.abs[n-1]<>(_W-h)
+ case n == m+1:
+ a2 = B.abs[n-2] >> (_W - h)
+ default:
+ a2 = 0
+ }
+
+ // Since we are calculating with full words to avoid overflow,
+ // we use 'even' to track the sign of the cosequences.
+ // For even iterations: u0, v1 >= 0 && u1, v0 <= 0
+ // For odd iterations: u0, v1 <= 0 && u1, v0 >= 0
+ // The first iteration starts with k=1 (odd).
+ even = false
+ // variables to track the cosequences
+ u0, u1, u2 = 0, 1, 0
+ v0, v1, v2 = 0, 0, 1
+
+ // Calculate the quotient and cosequences using Collins' stopping condition.
+ // Note that overflow of a Word is not possible when computing the remainder
+ // sequence and cosequences since the cosequence size is bounded by the input size.
+ // See section 4.2 of Jebelean for details.
+ for a2 >= v2 && a1-a2 >= v1+v2 {
+ q, r := a1/a2, a1%a2
+ a1, a2 = a2, r
+ u0, u1, u2 = u1, u2, u1+q*u2
+ v0, v1, v2 = v1, v2, v1+q*v2
+ even = !even
+ }
+ return
+}
+
+// lehmerUpdate updates the inputs A and B such that:
+//
+// A = u0*A + v0*B
+// B = u1*A + v1*B
+//
+// where the signs of u0, u1, v0, v1 are given by even
+// For even == true: u0, v1 >= 0 && u1, v0 <= 0
+// For even == false: u0, v1 <= 0 && u1, v0 >= 0
+// q, r, s, t are temporary variables to avoid allocations in the multiplication.
+func lehmerUpdate(A, B, q, r, s, t *Int, u0, u1, v0, v1 Word, even bool) {
+
+ t.abs = t.abs.setWord(u0)
+ s.abs = s.abs.setWord(v0)
+ t.neg = !even
+ s.neg = even
+
+ t.Mul(A, t)
+ s.Mul(B, s)
+
+ r.abs = r.abs.setWord(u1)
+ q.abs = q.abs.setWord(v1)
+ r.neg = even
+ q.neg = !even
+
+ r.Mul(A, r)
+ q.Mul(B, q)
+
+ A.Add(t, s)
+ B.Add(r, q)
+}
+
+// euclidUpdate performs a single step of the Euclidean GCD algorithm
+// if extended is true, it also updates the cosequence Ua, Ub.
+func euclidUpdate(A, B, Ua, Ub, q, r, s, t *Int, extended bool) {
+ q, r = q.QuoRem(A, B, r)
+
+ *A, *B, *r = *B, *r, *A
+
+ if extended {
+ // Ua, Ub = Ub, Ua - q*Ub
+ t.Set(Ub)
+ s.Mul(Ub, q)
+ Ub.Sub(Ua, s)
+ Ua.Set(t)
+ }
+}
+
+// lehmerGCD sets z to the greatest common divisor of a and b,
+// which both must be != 0, and returns z.
+// If x or y are not nil, their values are set such that z = a*x + b*y.
+// See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L.
+// This implementation uses the improved condition by Collins requiring only one
+// quotient and avoiding the possibility of single Word overflow.
+// See Jebelean, "Improving the multiprecision Euclidean algorithm",
+// Design and Implementation of Symbolic Computation Systems, pp 45-58.
+// The cosequences are updated according to Algorithm 10.45 from
+// Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192.
+func (z *Int) lehmerGCD(x, y, a, b *Int) *Int {
+ var A, B, Ua, Ub *Int
+
+ A = new(Int).Abs(a)
+ B = new(Int).Abs(b)
+
+ extended := x != nil || y != nil
+
+ if extended {
+ // Ua (Ub) tracks how many times input a has been accumulated into A (B).
+ Ua = new(Int).SetInt64(1)
+ Ub = new(Int)
+ }
+
+ // temp variables for multiprecision update
+ q := new(Int)
+ r := new(Int)
+ s := new(Int)
+ t := new(Int)
+
+ // ensure A >= B
+ if A.abs.cmp(B.abs) < 0 {
+ A, B = B, A
+ Ub, Ua = Ua, Ub
+ }
+
+ // loop invariant A >= B
+ for len(B.abs) > 1 {
+ // Attempt to calculate in single-precision using leading words of A and B.
+ u0, u1, v0, v1, even := lehmerSimulate(A, B)
+
+ // multiprecision Step
+ if v0 != 0 {
+ // Simulate the effect of the single-precision steps using the cosequences.
+ // A = u0*A + v0*B
+ // B = u1*A + v1*B
+ lehmerUpdate(A, B, q, r, s, t, u0, u1, v0, v1, even)
+
+ if extended {
+ // Ua = u0*Ua + v0*Ub
+ // Ub = u1*Ua + v1*Ub
+ lehmerUpdate(Ua, Ub, q, r, s, t, u0, u1, v0, v1, even)
+ }
+
+ } else {
+ // Single-digit calculations failed to simulate any quotients.
+ // Do a standard Euclidean step.
+ euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended)
+ }
+ }
+
+ if len(B.abs) > 0 {
+ // extended Euclidean algorithm base case if B is a single Word
+ if len(A.abs) > 1 {
+ // A is longer than a single Word, so one update is needed.
+ euclidUpdate(A, B, Ua, Ub, q, r, s, t, extended)
+ }
+ if len(B.abs) > 0 {
+ // A and B are both a single Word.
+ aWord, bWord := A.abs[0], B.abs[0]
+ if extended {
+ var ua, ub, va, vb Word
+ ua, ub = 1, 0
+ va, vb = 0, 1
+ even := true
+ for bWord != 0 {
+ q, r := aWord/bWord, aWord%bWord
+ aWord, bWord = bWord, r
+ ua, ub = ub, ua+q*ub
+ va, vb = vb, va+q*vb
+ even = !even
+ }
+
+ t.abs = t.abs.setWord(ua)
+ s.abs = s.abs.setWord(va)
+ t.neg = !even
+ s.neg = even
+
+ t.Mul(Ua, t)
+ s.Mul(Ub, s)
+
+ Ua.Add(t, s)
+ } else {
+ for bWord != 0 {
+ aWord, bWord = bWord, aWord%bWord
+ }
+ }
+ A.abs[0] = aWord
+ }
+ }
+ negA := a.neg
+ if y != nil {
+ // avoid aliasing b needed in the division below
+ if y == b {
+ B.Set(b)
+ } else {
+ B = b
+ }
+ // y = (z - a*x)/b
+ y.Mul(a, Ua) // y can safely alias a
+ if negA {
+ y.neg = !y.neg
+ }
+ y.Sub(A, y)
+ y.Div(y, B)
+ }
+
+ if x != nil {
+ *x = *Ua
+ if negA {
+ x.neg = !x.neg
+ }
+ }
+
+ *z = *A
+
+ return z
+}
+
+// Rand sets z to a pseudo-random number in [0, n) and returns z.
+//
+// As this uses the [math/rand] package, it must not be used for
+// security-sensitive work. Use [crypto/rand.Int] instead.
+func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
+ // z.neg is not modified before the if check, because z and n might alias.
+ if n.neg || len(n.abs) == 0 {
+ z.neg = false
+ z.abs = nil
+ return z
+ }
+ z.neg = false
+ z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
+ return z
+}
+
+// ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
+// and returns z. If g and n are not relatively prime, g has no multiplicative
+// inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value
+// is nil. If n == 0, a division-by-zero run-time panic occurs.
+func (z *Int) ModInverse(g, n *Int) *Int {
+ // GCD expects parameters a and b to be > 0.
+ if n.neg {
+ var n2 Int
+ n = n2.Neg(n)
+ }
+ if g.neg {
+ var g2 Int
+ g = g2.Mod(g, n)
+ }
+ var d, x Int
+ d.GCD(&x, nil, g, n)
+
+ // if and only if d==1, g and n are relatively prime
+ if d.Cmp(intOne) != 0 {
+ return nil
+ }
+
+ // x and y are such that g*x + n*y = 1, therefore x is the inverse element,
+ // but it may be negative, so convert to the range 0 <= z < |n|
+ if x.neg {
+ z.Add(&x, n)
+ } else {
+ z.Set(&x)
+ }
+ return z
+}
+
+func (z nat) modInverse(g, n nat) nat {
+ // TODO(rsc): ModInverse should be implemented in terms of this function.
+ return (&Int{abs: z}).ModInverse(&Int{abs: g}, &Int{abs: n}).abs
+}
+
+// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
+// The y argument must be an odd integer.
+func Jacobi(x, y *Int) int {
+ if len(y.abs) == 0 || y.abs[0]&1 == 0 {
+ panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y.String()))
+ }
+
+ // We use the formulation described in chapter 2, section 2.4,
+ // "The Yacas Book of Algorithms":
+ // http://yacas.sourceforge.net/Algo.book.pdf
+
+ var a, b, c Int
+ a.Set(x)
+ b.Set(y)
+ j := 1
+
+ if b.neg {
+ if a.neg {
+ j = -1
+ }
+ b.neg = false
+ }
+
+ for {
+ if b.Cmp(intOne) == 0 {
+ return j
+ }
+ if len(a.abs) == 0 {
+ return 0
+ }
+ a.Mod(&a, &b)
+ if len(a.abs) == 0 {
+ return 0
+ }
+ // a > 0
+
+ // handle factors of 2 in 'a'
+ s := a.abs.trailingZeroBits()
+ if s&1 != 0 {
+ bmod8 := b.abs[0] & 7
+ if bmod8 == 3 || bmod8 == 5 {
+ j = -j
+ }
+ }
+ c.Rsh(&a, s) // a = 2^s*c
+
+ // swap numerator and denominator
+ if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
+ j = -j
+ }
+ a.Set(&b)
+ b.Set(&c)
+ }
+}
+
+// modSqrt3Mod4 uses the identity
+//
+// (a^((p+1)/4))^2 mod p
+// == u^(p+1) mod p
+// == u^2 mod p
+//
+// to calculate the square root of any quadratic residue mod p quickly for 3
+// mod 4 primes.
+func (z *Int) modSqrt3Mod4Prime(x, p *Int) *Int {
+ e := new(Int).Add(p, intOne) // e = p + 1
+ e.Rsh(e, 2) // e = (p + 1) / 4
+ z.Exp(x, e, p) // z = x^e mod p
+ return z
+}
+
+// modSqrt5Mod8Prime uses Atkin's observation that 2 is not a square mod p
+//
+// alpha == (2*a)^((p-5)/8) mod p
+// beta == 2*a*alpha^2 mod p is a square root of -1
+// b == a*alpha*(beta-1) mod p is a square root of a
+//
+// to calculate the square root of any quadratic residue mod p quickly for 5
+// mod 8 primes.
+func (z *Int) modSqrt5Mod8Prime(x, p *Int) *Int {
+ // p == 5 mod 8 implies p = e*8 + 5
+ // e is the quotient and 5 the remainder on division by 8
+ e := new(Int).Rsh(p, 3) // e = (p - 5) / 8
+ tx := new(Int).Lsh(x, 1) // tx = 2*x
+ alpha := new(Int).Exp(tx, e, p)
+ beta := new(Int).Mul(alpha, alpha)
+ beta.Mod(beta, p)
+ beta.Mul(beta, tx)
+ beta.Mod(beta, p)
+ beta.Sub(beta, intOne)
+ beta.Mul(beta, x)
+ beta.Mod(beta, p)
+ beta.Mul(beta, alpha)
+ z.Mod(beta, p)
+ return z
+}
+
+// modSqrtTonelliShanks uses the Tonelli-Shanks algorithm to find the square
+// root of a quadratic residue modulo any prime.
+func (z *Int) modSqrtTonelliShanks(x, p *Int) *Int {
+ // Break p-1 into s*2^e such that s is odd.
+ var s Int
+ s.Sub(p, intOne)
+ e := s.abs.trailingZeroBits()
+ s.Rsh(&s, e)
+
+ // find some non-square n
+ var n Int
+ n.SetInt64(2)
+ for Jacobi(&n, p) != -1 {
+ n.Add(&n, intOne)
+ }
+
+ // Core of the Tonelli-Shanks algorithm. Follows the description in
+ // section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
+ // Brown:
+ // https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
+ var y, b, g, t Int
+ y.Add(&s, intOne)
+ y.Rsh(&y, 1)
+ y.Exp(x, &y, p) // y = x^((s+1)/2)
+ b.Exp(x, &s, p) // b = x^s
+ g.Exp(&n, &s, p) // g = n^s
+ r := e
+ for {
+ // find the least m such that ord_p(b) = 2^m
+ var m uint
+ t.Set(&b)
+ for t.Cmp(intOne) != 0 {
+ t.Mul(&t, &t).Mod(&t, p)
+ m++
+ }
+
+ if m == 0 {
+ return z.Set(&y)
+ }
+
+ t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
+ // t = g^(2^(r-m-1)) mod p
+ g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
+ y.Mul(&y, &t).Mod(&y, p)
+ b.Mul(&b, &g).Mod(&b, p)
+ r = m
+ }
+}
+
+// ModSqrt sets z to a square root of x mod p if such a square root exists, and
+// returns z. The modulus p must be an odd prime. If x is not a square mod p,
+// ModSqrt leaves z unchanged and returns nil. This function panics if p is
+// not an odd integer, its behavior is undefined if p is odd but not prime.
+func (z *Int) ModSqrt(x, p *Int) *Int {
+ switch Jacobi(x, p) {
+ case -1:
+ return nil // x is not a square mod p
+ case 0:
+ return z.SetInt64(0) // sqrt(0) mod p = 0
+ case 1:
+ break
+ }
+ if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
+ x = new(Int).Mod(x, p)
+ }
+
+ switch {
+ case p.abs[0]%4 == 3:
+ // Check whether p is 3 mod 4, and if so, use the faster algorithm.
+ return z.modSqrt3Mod4Prime(x, p)
+ case p.abs[0]%8 == 5:
+ // Check whether p is 5 mod 8, use Atkin's algorithm.
+ return z.modSqrt5Mod8Prime(x, p)
+ default:
+ // Otherwise, use Tonelli-Shanks.
+ return z.modSqrtTonelliShanks(x, p)
+ }
+}
+
+// Lsh sets z = x << n and returns z.
+func (z *Int) Lsh(x *Int, n uint) *Int {
+ z.abs = z.abs.shl(x.abs, n)
+ z.neg = x.neg
+ return z
+}
+
+// Rsh sets z = x >> n and returns z.
+func (z *Int) Rsh(x *Int, n uint) *Int {
+ if x.neg {
+ // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
+ t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
+ t = t.shr(t, n)
+ z.abs = t.add(t, natOne)
+ z.neg = true // z cannot be zero if x is negative
+ return z
+ }
+
+ z.abs = z.abs.shr(x.abs, n)
+ z.neg = false
+ return z
+}
+
+// Bit returns the value of the i'th bit of x. That is, it
+// returns (x>>i)&1. The bit index i must be >= 0.
+func (x *Int) Bit(i int) uint {
+ if i == 0 {
+ // optimization for common case: odd/even test of x
+ if len(x.abs) > 0 {
+ return uint(x.abs[0] & 1) // bit 0 is same for -x
+ }
+ return 0
+ }
+ if i < 0 {
+ panic("negative bit index")
+ }
+ if x.neg {
+ t := nat(nil).sub(x.abs, natOne)
+ return t.bit(uint(i)) ^ 1
+ }
+
+ return x.abs.bit(uint(i))
+}
+
+// SetBit sets z to x, with x's i'th bit set to b (0 or 1).
+// That is, if b is 1 SetBit sets z = x | (1 << i);
+// if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1,
+// SetBit will panic.
+func (z *Int) SetBit(x *Int, i int, b uint) *Int {
+ if i < 0 {
+ panic("negative bit index")
+ }
+ if x.neg {
+ t := z.abs.sub(x.abs, natOne)
+ t = t.setBit(t, uint(i), b^1)
+ z.abs = t.add(t, natOne)
+ z.neg = len(z.abs) > 0
+ return z
+ }
+ z.abs = z.abs.setBit(x.abs, uint(i), b)
+ z.neg = false
+ return z
+}
+
+// And sets z = x & y and returns z.
+func (z *Int) And(x, y *Int) *Int {
+ if x.neg == y.neg {
+ if x.neg {
+ // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
+ x1 := nat(nil).sub(x.abs, natOne)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
+ z.neg = true // z cannot be zero if x and y are negative
+ return z
+ }
+
+ // x & y == x & y
+ z.abs = z.abs.and(x.abs, y.abs)
+ z.neg = false
+ return z
+ }
+
+ // x.neg != y.neg
+ if x.neg {
+ x, y = y, x // & is symmetric
+ }
+
+ // x & (-y) == x & ^(y-1) == x &^ (y-1)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.andNot(x.abs, y1)
+ z.neg = false
+ return z
+}
+
+// AndNot sets z = x &^ y and returns z.
+func (z *Int) AndNot(x, y *Int) *Int {
+ if x.neg == y.neg {
+ if x.neg {
+ // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
+ x1 := nat(nil).sub(x.abs, natOne)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.andNot(y1, x1)
+ z.neg = false
+ return z
+ }
+
+ // x &^ y == x &^ y
+ z.abs = z.abs.andNot(x.abs, y.abs)
+ z.neg = false
+ return z
+ }
+
+ if x.neg {
+ // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
+ x1 := nat(nil).sub(x.abs, natOne)
+ z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
+ z.neg = true // z cannot be zero if x is negative and y is positive
+ return z
+ }
+
+ // x &^ (-y) == x &^ ^(y-1) == x & (y-1)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.and(x.abs, y1)
+ z.neg = false
+ return z
+}
+
+// Or sets z = x | y and returns z.
+func (z *Int) Or(x, y *Int) *Int {
+ if x.neg == y.neg {
+ if x.neg {
+ // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
+ x1 := nat(nil).sub(x.abs, natOne)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
+ z.neg = true // z cannot be zero if x and y are negative
+ return z
+ }
+
+ // x | y == x | y
+ z.abs = z.abs.or(x.abs, y.abs)
+ z.neg = false
+ return z
+ }
+
+ // x.neg != y.neg
+ if x.neg {
+ x, y = y, x // | is symmetric
+ }
+
+ // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
+ z.neg = true // z cannot be zero if one of x or y is negative
+ return z
+}
+
+// Xor sets z = x ^ y and returns z.
+func (z *Int) Xor(x, y *Int) *Int {
+ if x.neg == y.neg {
+ if x.neg {
+ // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
+ x1 := nat(nil).sub(x.abs, natOne)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.xor(x1, y1)
+ z.neg = false
+ return z
+ }
+
+ // x ^ y == x ^ y
+ z.abs = z.abs.xor(x.abs, y.abs)
+ z.neg = false
+ return z
+ }
+
+ // x.neg != y.neg
+ if x.neg {
+ x, y = y, x // ^ is symmetric
+ }
+
+ // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
+ y1 := nat(nil).sub(y.abs, natOne)
+ z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
+ z.neg = true // z cannot be zero if only one of x or y is negative
+ return z
+}
+
+// Not sets z = ^x and returns z.
+func (z *Int) Not(x *Int) *Int {
+ if x.neg {
+ // ^(-x) == ^(^(x-1)) == x-1
+ z.abs = z.abs.sub(x.abs, natOne)
+ z.neg = false
+ return z
+ }
+
+ // ^x == -x-1 == -(x+1)
+ z.abs = z.abs.add(x.abs, natOne)
+ z.neg = true // z cannot be zero if x is positive
+ return z
+}
+
+// Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.
+// It panics if x is negative.
+func (z *Int) Sqrt(x *Int) *Int {
+ if x.neg {
+ panic("square root of negative number")
+ }
+ z.neg = false
+ z.abs = z.abs.sqrt(x.abs)
+ return z
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/int_test.go b/platform/dbops/binaries/go/go/src/math/big/int_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..088bce09f9169ca8bb84e9ffcbf54642a902f384
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/int_test.go
@@ -0,0 +1,2012 @@
+// 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 big
+
+import (
+ "bytes"
+ "encoding/hex"
+ "fmt"
+ "internal/testenv"
+ "math"
+ "math/rand"
+ "strconv"
+ "strings"
+ "testing"
+ "testing/quick"
+)
+
+func isNormalized(x *Int) bool {
+ if len(x.abs) == 0 {
+ return !x.neg
+ }
+ // len(x.abs) > 0
+ return x.abs[len(x.abs)-1] != 0
+}
+
+type funZZ func(z, x, y *Int) *Int
+type argZZ struct {
+ z, x, y *Int
+}
+
+var sumZZ = []argZZ{
+ {NewInt(0), NewInt(0), NewInt(0)},
+ {NewInt(1), NewInt(1), NewInt(0)},
+ {NewInt(1111111110), NewInt(123456789), NewInt(987654321)},
+ {NewInt(-1), NewInt(-1), NewInt(0)},
+ {NewInt(864197532), NewInt(-123456789), NewInt(987654321)},
+ {NewInt(-1111111110), NewInt(-123456789), NewInt(-987654321)},
+}
+
+var prodZZ = []argZZ{
+ {NewInt(0), NewInt(0), NewInt(0)},
+ {NewInt(0), NewInt(1), NewInt(0)},
+ {NewInt(1), NewInt(1), NewInt(1)},
+ {NewInt(-991 * 991), NewInt(991), NewInt(-991)},
+ // TODO(gri) add larger products
+}
+
+func TestSignZ(t *testing.T) {
+ var zero Int
+ for _, a := range sumZZ {
+ s := a.z.Sign()
+ e := a.z.Cmp(&zero)
+ if s != e {
+ t.Errorf("got %d; want %d for z = %v", s, e, a.z)
+ }
+ }
+}
+
+func TestSetZ(t *testing.T) {
+ for _, a := range sumZZ {
+ var z Int
+ z.Set(a.z)
+ if !isNormalized(&z) {
+ t.Errorf("%v is not normalized", z)
+ }
+ if (&z).Cmp(a.z) != 0 {
+ t.Errorf("got z = %v; want %v", z, a.z)
+ }
+ }
+}
+
+func TestAbsZ(t *testing.T) {
+ var zero Int
+ for _, a := range sumZZ {
+ var z Int
+ z.Abs(a.z)
+ var e Int
+ e.Set(a.z)
+ if e.Cmp(&zero) < 0 {
+ e.Sub(&zero, &e)
+ }
+ if z.Cmp(&e) != 0 {
+ t.Errorf("got z = %v; want %v", z, e)
+ }
+ }
+}
+
+func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
+ var z Int
+ f(&z, a.x, a.y)
+ if !isNormalized(&z) {
+ t.Errorf("%s%v is not normalized", msg, z)
+ }
+ if (&z).Cmp(a.z) != 0 {
+ t.Errorf("%v %s %v\n\tgot z = %v; want %v", a.x, msg, a.y, &z, a.z)
+ }
+}
+
+func TestSumZZ(t *testing.T) {
+ AddZZ := func(z, x, y *Int) *Int { return z.Add(x, y) }
+ SubZZ := func(z, x, y *Int) *Int { return z.Sub(x, y) }
+ for _, a := range sumZZ {
+ arg := a
+ testFunZZ(t, "AddZZ", AddZZ, arg)
+
+ arg = argZZ{a.z, a.y, a.x}
+ testFunZZ(t, "AddZZ symmetric", AddZZ, arg)
+
+ arg = argZZ{a.x, a.z, a.y}
+ testFunZZ(t, "SubZZ", SubZZ, arg)
+
+ arg = argZZ{a.y, a.z, a.x}
+ testFunZZ(t, "SubZZ symmetric", SubZZ, arg)
+ }
+}
+
+func TestProdZZ(t *testing.T) {
+ MulZZ := func(z, x, y *Int) *Int { return z.Mul(x, y) }
+ for _, a := range prodZZ {
+ arg := a
+ testFunZZ(t, "MulZZ", MulZZ, arg)
+
+ arg = argZZ{a.z, a.y, a.x}
+ testFunZZ(t, "MulZZ symmetric", MulZZ, arg)
+ }
+}
+
+// mulBytes returns x*y via grade school multiplication. Both inputs
+// and the result are assumed to be in big-endian representation (to
+// match the semantics of Int.Bytes and Int.SetBytes).
+func mulBytes(x, y []byte) []byte {
+ z := make([]byte, len(x)+len(y))
+
+ // multiply
+ k0 := len(z) - 1
+ for j := len(y) - 1; j >= 0; j-- {
+ d := int(y[j])
+ if d != 0 {
+ k := k0
+ carry := 0
+ for i := len(x) - 1; i >= 0; i-- {
+ t := int(z[k]) + int(x[i])*d + carry
+ z[k], carry = byte(t), t>>8
+ k--
+ }
+ z[k] = byte(carry)
+ }
+ k0--
+ }
+
+ // normalize (remove leading 0's)
+ i := 0
+ for i < len(z) && z[i] == 0 {
+ i++
+ }
+
+ return z[i:]
+}
+
+func checkMul(a, b []byte) bool {
+ var x, y, z1 Int
+ x.SetBytes(a)
+ y.SetBytes(b)
+ z1.Mul(&x, &y)
+
+ var z2 Int
+ z2.SetBytes(mulBytes(a, b))
+
+ return z1.Cmp(&z2) == 0
+}
+
+func TestMul(t *testing.T) {
+ if err := quick.Check(checkMul, nil); err != nil {
+ t.Error(err)
+ }
+}
+
+var mulRangesZ = []struct {
+ a, b int64
+ prod string
+}{
+ // entirely positive ranges are covered by mulRangesN
+ {-1, 1, "0"},
+ {-2, -1, "2"},
+ {-3, -2, "6"},
+ {-3, -1, "-6"},
+ {1, 3, "6"},
+ {-10, -10, "-10"},
+ {0, -1, "1"}, // empty range
+ {-1, -100, "1"}, // empty range
+ {-1, 1, "0"}, // range includes 0
+ {-1e9, 0, "0"}, // range includes 0
+ {-1e9, 1e9, "0"}, // range includes 0
+ {-10, -1, "3628800"}, // 10!
+ {-20, -2, "-2432902008176640000"}, // -20!
+ {-99, -1,
+ "-933262154439441526816992388562667004907159682643816214685929" +
+ "638952175999932299156089414639761565182862536979208272237582" +
+ "511852109168640000000000000000000000", // -99!
+ },
+
+ // overflow situations
+ {math.MaxInt64 - 0, math.MaxInt64, "9223372036854775807"},
+ {math.MaxInt64 - 1, math.MaxInt64, "85070591730234615838173535747377725442"},
+ {math.MaxInt64 - 2, math.MaxInt64, "784637716923335094969050127519550606919189611815754530810"},
+ {math.MaxInt64 - 3, math.MaxInt64, "7237005577332262206126809393809643289012107973151163787181513908099760521240"},
+}
+
+func TestMulRangeZ(t *testing.T) {
+ var tmp Int
+ // test entirely positive ranges
+ for i, r := range mulRangesN {
+ // skip mulRangesN entries that overflow int64
+ if int64(r.a) < 0 || int64(r.b) < 0 {
+ continue
+ }
+ prod := tmp.MulRange(int64(r.a), int64(r.b)).String()
+ if prod != r.prod {
+ t.Errorf("#%da: got %s; want %s", i, prod, r.prod)
+ }
+ }
+ // test other ranges
+ for i, r := range mulRangesZ {
+ prod := tmp.MulRange(r.a, r.b).String()
+ if prod != r.prod {
+ t.Errorf("#%db: got %s; want %s", i, prod, r.prod)
+ }
+ }
+}
+
+func TestBinomial(t *testing.T) {
+ var z Int
+ for _, test := range []struct {
+ n, k int64
+ want string
+ }{
+ {0, 0, "1"},
+ {0, 1, "0"},
+ {1, 0, "1"},
+ {1, 1, "1"},
+ {1, 10, "0"},
+ {4, 0, "1"},
+ {4, 1, "4"},
+ {4, 2, "6"},
+ {4, 3, "4"},
+ {4, 4, "1"},
+ {10, 1, "10"},
+ {10, 9, "10"},
+ {10, 5, "252"},
+ {11, 5, "462"},
+ {11, 6, "462"},
+ {100, 10, "17310309456440"},
+ {100, 90, "17310309456440"},
+ {1000, 10, "263409560461970212832400"},
+ {1000, 990, "263409560461970212832400"},
+ } {
+ if got := z.Binomial(test.n, test.k).String(); got != test.want {
+ t.Errorf("Binomial(%d, %d) = %s; want %s", test.n, test.k, got, test.want)
+ }
+ }
+}
+
+func BenchmarkBinomial(b *testing.B) {
+ var z Int
+ for i := 0; i < b.N; i++ {
+ z.Binomial(1000, 990)
+ }
+}
+
+// Examples from the Go Language Spec, section "Arithmetic operators"
+var divisionSignsTests = []struct {
+ x, y int64
+ q, r int64 // T-division
+ d, m int64 // Euclidean division
+}{
+ {5, 3, 1, 2, 1, 2},
+ {-5, 3, -1, -2, -2, 1},
+ {5, -3, -1, 2, -1, 2},
+ {-5, -3, 1, -2, 2, 1},
+ {1, 2, 0, 1, 0, 1},
+ {8, 4, 2, 0, 2, 0},
+}
+
+func TestDivisionSigns(t *testing.T) {
+ for i, test := range divisionSignsTests {
+ x := NewInt(test.x)
+ y := NewInt(test.y)
+ q := NewInt(test.q)
+ r := NewInt(test.r)
+ d := NewInt(test.d)
+ m := NewInt(test.m)
+
+ q1 := new(Int).Quo(x, y)
+ r1 := new(Int).Rem(x, y)
+ if !isNormalized(q1) {
+ t.Errorf("#%d Quo: %v is not normalized", i, *q1)
+ }
+ if !isNormalized(r1) {
+ t.Errorf("#%d Rem: %v is not normalized", i, *r1)
+ }
+ if q1.Cmp(q) != 0 || r1.Cmp(r) != 0 {
+ t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q1, r1, q, r)
+ }
+
+ q2, r2 := new(Int).QuoRem(x, y, new(Int))
+ if !isNormalized(q2) {
+ t.Errorf("#%d Quo: %v is not normalized", i, *q2)
+ }
+ if !isNormalized(r2) {
+ t.Errorf("#%d Rem: %v is not normalized", i, *r2)
+ }
+ if q2.Cmp(q) != 0 || r2.Cmp(r) != 0 {
+ t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q2, r2, q, r)
+ }
+
+ d1 := new(Int).Div(x, y)
+ m1 := new(Int).Mod(x, y)
+ if !isNormalized(d1) {
+ t.Errorf("#%d Div: %v is not normalized", i, *d1)
+ }
+ if !isNormalized(m1) {
+ t.Errorf("#%d Mod: %v is not normalized", i, *m1)
+ }
+ if d1.Cmp(d) != 0 || m1.Cmp(m) != 0 {
+ t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d1, m1, d, m)
+ }
+
+ d2, m2 := new(Int).DivMod(x, y, new(Int))
+ if !isNormalized(d2) {
+ t.Errorf("#%d Div: %v is not normalized", i, *d2)
+ }
+ if !isNormalized(m2) {
+ t.Errorf("#%d Mod: %v is not normalized", i, *m2)
+ }
+ if d2.Cmp(d) != 0 || m2.Cmp(m) != 0 {
+ t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d2, m2, d, m)
+ }
+ }
+}
+
+func norm(x nat) nat {
+ i := len(x)
+ for i > 0 && x[i-1] == 0 {
+ i--
+ }
+ return x[:i]
+}
+
+func TestBits(t *testing.T) {
+ for _, test := range []nat{
+ nil,
+ {0},
+ {1},
+ {0, 1, 2, 3, 4},
+ {4, 3, 2, 1, 0},
+ {4, 3, 2, 1, 0, 0, 0, 0},
+ } {
+ var z Int
+ z.neg = true
+ got := z.SetBits(test)
+ want := norm(test)
+ if got.abs.cmp(want) != 0 {
+ t.Errorf("SetBits(%v) = %v; want %v", test, got.abs, want)
+ }
+
+ if got.neg {
+ t.Errorf("SetBits(%v): got negative result", test)
+ }
+
+ bits := nat(z.Bits())
+ if bits.cmp(want) != 0 {
+ t.Errorf("%v.Bits() = %v; want %v", z.abs, bits, want)
+ }
+ }
+}
+
+func checkSetBytes(b []byte) bool {
+ hex1 := hex.EncodeToString(new(Int).SetBytes(b).Bytes())
+ hex2 := hex.EncodeToString(b)
+
+ for len(hex1) < len(hex2) {
+ hex1 = "0" + hex1
+ }
+
+ for len(hex1) > len(hex2) {
+ hex2 = "0" + hex2
+ }
+
+ return hex1 == hex2
+}
+
+func TestSetBytes(t *testing.T) {
+ if err := quick.Check(checkSetBytes, nil); err != nil {
+ t.Error(err)
+ }
+}
+
+func checkBytes(b []byte) bool {
+ // trim leading zero bytes since Bytes() won't return them
+ // (was issue 12231)
+ for len(b) > 0 && b[0] == 0 {
+ b = b[1:]
+ }
+ b2 := new(Int).SetBytes(b).Bytes()
+ return bytes.Equal(b, b2)
+}
+
+func TestBytes(t *testing.T) {
+ if err := quick.Check(checkBytes, nil); err != nil {
+ t.Error(err)
+ }
+}
+
+func checkQuo(x, y []byte) bool {
+ u := new(Int).SetBytes(x)
+ v := new(Int).SetBytes(y)
+
+ if len(v.abs) == 0 {
+ return true
+ }
+
+ r := new(Int)
+ q, r := new(Int).QuoRem(u, v, r)
+
+ if r.Cmp(v) >= 0 {
+ return false
+ }
+
+ uprime := new(Int).Set(q)
+ uprime.Mul(uprime, v)
+ uprime.Add(uprime, r)
+
+ return uprime.Cmp(u) == 0
+}
+
+var quoTests = []struct {
+ x, y string
+ q, r string
+}{
+ {
+ "476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357",
+ "9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996",
+ "50911",
+ "1",
+ },
+ {
+ "11510768301994997771168",
+ "1328165573307167369775",
+ "8",
+ "885443715537658812968",
+ },
+}
+
+func TestQuo(t *testing.T) {
+ if err := quick.Check(checkQuo, nil); err != nil {
+ t.Error(err)
+ }
+
+ for i, test := range quoTests {
+ x, _ := new(Int).SetString(test.x, 10)
+ y, _ := new(Int).SetString(test.y, 10)
+ expectedQ, _ := new(Int).SetString(test.q, 10)
+ expectedR, _ := new(Int).SetString(test.r, 10)
+
+ r := new(Int)
+ q, r := new(Int).QuoRem(x, y, r)
+
+ if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
+ t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
+ }
+ }
+}
+
+func TestQuoStepD6(t *testing.T) {
+ // See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises
+ // a code path which only triggers 1 in 10^{-19} cases.
+
+ u := &Int{false, nat{0, 0, 1 + 1<<(_W-1), _M ^ (1 << (_W - 1))}}
+ v := &Int{false, nat{5, 2 + 1<<(_W-1), 1 << (_W - 1)}}
+
+ r := new(Int)
+ q, r := new(Int).QuoRem(u, v, r)
+ const expectedQ64 = "18446744073709551613"
+ const expectedR64 = "3138550867693340382088035895064302439801311770021610913807"
+ const expectedQ32 = "4294967293"
+ const expectedR32 = "39614081266355540837921718287"
+ if q.String() != expectedQ64 && q.String() != expectedQ32 ||
+ r.String() != expectedR64 && r.String() != expectedR32 {
+ t.Errorf("got (%s, %s) want (%s, %s) or (%s, %s)", q, r, expectedQ64, expectedR64, expectedQ32, expectedR32)
+ }
+}
+
+func BenchmarkQuoRem(b *testing.B) {
+ x, _ := new(Int).SetString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071", 0)
+ y, _ := new(Int).SetString("7746362281539803897849273317883545285945243323447099728551653406505888775727297253384154743724750941556720663282745352402758568446486952008757638690735720782793164586481245379056001310087907017524411556680030339452580238411650898523599802732790857831596547515523593979861803187084910989428312522918414417263055355460715745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384715398038978492733178835452859452433234470997285516534065058887757272972533841547437247509415567206632827453524027585684464869520087576386907357207827931645864812453790560013100879070175244115566800303394525802384116508985235998027327908578315965475155235939798618031870849109894283125229184144172630553554607112725169432413343763989564437170644270643461665184965150423819594083121075825", 0)
+ q := new(Int)
+ r := new(Int)
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ q.QuoRem(y, x, r)
+ }
+}
+
+var bitLenTests = []struct {
+ in string
+ out int
+}{
+ {"-1", 1},
+ {"0", 0},
+ {"1", 1},
+ {"2", 2},
+ {"4", 3},
+ {"0xabc", 12},
+ {"0x8000", 16},
+ {"0x80000000", 32},
+ {"0x800000000000", 48},
+ {"0x8000000000000000", 64},
+ {"0x80000000000000000000", 80},
+ {"-0x4000000000000000000000", 87},
+}
+
+func TestBitLen(t *testing.T) {
+ for i, test := range bitLenTests {
+ x, ok := new(Int).SetString(test.in, 0)
+ if !ok {
+ t.Errorf("#%d test input invalid: %s", i, test.in)
+ continue
+ }
+
+ if n := x.BitLen(); n != test.out {
+ t.Errorf("#%d got %d want %d", i, n, test.out)
+ }
+ }
+}
+
+var expTests = []struct {
+ x, y, m string
+ out string
+}{
+ // y <= 0
+ {"0", "0", "", "1"},
+ {"1", "0", "", "1"},
+ {"-10", "0", "", "1"},
+ {"1234", "-1", "", "1"},
+ {"1234", "-1", "0", "1"},
+ {"17", "-100", "1234", "865"},
+ {"2", "-100", "1234", ""},
+
+ // m == 1
+ {"0", "0", "1", "0"},
+ {"1", "0", "1", "0"},
+ {"-10", "0", "1", "0"},
+ {"1234", "-1", "1", "0"},
+
+ // misc
+ {"5", "1", "3", "2"},
+ {"5", "-7", "", "1"},
+ {"-5", "-7", "", "1"},
+ {"5", "0", "", "1"},
+ {"-5", "0", "", "1"},
+ {"5", "1", "", "5"},
+ {"-5", "1", "", "-5"},
+ {"-5", "1", "7", "2"},
+ {"-2", "3", "2", "0"},
+ {"5", "2", "", "25"},
+ {"1", "65537", "2", "1"},
+ {"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
+ {"0x8000000000000000", "2", "6719", "4944"},
+ {"0x8000000000000000", "3", "6719", "5447"},
+ {"0x8000000000000000", "1000", "6719", "1603"},
+ {"0x8000000000000000", "1000000", "6719", "3199"},
+ {"0x8000000000000000", "-1000000", "6719", "3663"}, // 3663 = ModInverse(3199, 6719) Issue #25865
+
+ {"0xffffffffffffffffffffffffffffffff", "0x12345678123456781234567812345678123456789", "0x01112222333344445555666677778889", "0x36168FA1DB3AAE6C8CE647E137F97A"},
+
+ {
+ "2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347",
+ "298472983472983471903246121093472394872319615612417471234712061",
+ "29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464",
+ "23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291",
+ },
+ // test case for issue 8822
+ {
+ "11001289118363089646017359372117963499250546375269047542777928006103246876688756735760905680604646624353196869572752623285140408755420374049317646428185270079555372763503115646054602867593662923894140940837479507194934267532831694565516466765025434902348314525627418515646588160955862839022051353653052947073136084780742729727874803457643848197499548297570026926927502505634297079527299004267769780768565695459945235586892627059178884998772989397505061206395455591503771677500931269477503508150175717121828518985901959919560700853226255420793148986854391552859459511723547532575574664944815966793196961286234040892865",
+ "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD",
+ "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73",
+ "21484252197776302499639938883777710321993113097987201050501182909581359357618579566746556372589385361683610524730509041328855066514963385522570894839035884713051640171474186548713546686476761306436434146475140156284389181808675016576845833340494848283681088886584219750554408060556769486628029028720727393293111678826356480455433909233520504112074401376133077150471237549474149190242010469539006449596611576612573955754349042329130631128234637924786466585703488460540228477440853493392086251021228087076124706778899179648655221663765993962724699135217212118535057766739392069738618682722216712319320435674779146070442",
+ },
+ {
+ "-0x1BCE04427D8032319A89E5C4136456671AC620883F2C4139E57F91307C485AD2D6204F4F87A58262652DB5DBBAC72B0613E51B835E7153BEC6068F5C8D696B74DBD18FEC316AEF73985CF0475663208EB46B4F17DD9DA55367B03323E5491A70997B90C059FB34809E6EE55BCFBD5F2F52233BFE62E6AA9E4E26A1D4C2439883D14F2633D55D8AA66A1ACD5595E778AC3A280517F1157989E70C1A437B849F1877B779CC3CDDEDE2DAA6594A6C66D181A00A5F777EE60596D8773998F6E988DEAE4CCA60E4DDCF9590543C89F74F603259FCAD71660D30294FBBE6490300F78A9D63FA660DC9417B8B9DDA28BEB3977B621B988E23D4D954F322C3540541BC649ABD504C50FADFD9F0987D58A2BF689313A285E773FF02899A6EF887D1D4A0D2",
+ "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD",
+ "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73",
+ "21484252197776302499639938883777710321993113097987201050501182909581359357618579566746556372589385361683610524730509041328855066514963385522570894839035884713051640171474186548713546686476761306436434146475140156284389181808675016576845833340494848283681088886584219750554408060556769486628029028720727393293111678826356480455433909233520504112074401376133077150471237549474149190242010469539006449596611576612573955754349042329130631128234637924786466585703488460540228477440853493392086251021228087076124706778899179648655221663765993962724699135217212118535057766739392069738618682722216712319320435674779146070442",
+ },
+
+ // test cases for issue 13907
+ {"0xffffffff00000001", "0xffffffff00000001", "0xffffffff00000001", "0"},
+ {"0xffffffffffffffff00000001", "0xffffffffffffffff00000001", "0xffffffffffffffff00000001", "0"},
+ {"0xffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffff00000001", "0"},
+ {"0xffffffffffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffffffffffff00000001", "0xffffffffffffffffffffffffffffffff00000001", "0"},
+
+ {
+ "2",
+ "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD",
+ "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", // odd
+ "0x6AADD3E3E424D5B713FCAA8D8945B1E055166132038C57BBD2D51C833F0C5EA2007A2324CE514F8E8C2F008A2F36F44005A4039CB55830986F734C93DAF0EB4BAB54A6A8C7081864F44346E9BC6F0A3EB9F2C0146A00C6A05187D0C101E1F2D038CDB70CB5E9E05A2D188AB6CBB46286624D4415E7D4DBFAD3BCC6009D915C406EED38F468B940F41E6BEDC0430DD78E6F19A7DA3A27498A4181E24D738B0072D8F6ADB8C9809A5B033A09785814FD9919F6EF9F83EEA519BEC593855C4C10CBEEC582D4AE0792158823B0275E6AEC35242740468FAF3D5C60FD1E376362B6322F78B7ED0CA1C5BBCD2B49734A56C0967A1D01A100932C837B91D592CE08ABFF",
+ },
+ {
+ "2",
+ "0xB08FFB20760FFED58FADA86DFEF71AD72AA0FA763219618FE022C197E54708BB1191C66470250FCE8879487507CEE41381CA4D932F81C2B3F1AB20B539D50DCD",
+ "0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF72", // even
+ "0x7858794B5897C29F4ED0B40913416AB6C48588484E6A45F2ED3E26C941D878E923575AAC434EE2750E6439A6976F9BB4D64CEDB2A53CE8D04DD48CADCDF8E46F22747C6B81C6CEA86C0D873FBF7CEF262BAAC43A522BD7F32F3CDAC52B9337C77B3DCFB3DB3EDD80476331E82F4B1DF8EFDC1220C92656DFC9197BDC1877804E28D928A2A284B8DED506CBA304435C9D0133C246C98A7D890D1DE60CBC53A024361DA83A9B8775019083D22AC6820ED7C3C68F8E801DD4EC779EE0A05C6EB682EF9840D285B838369BA7E148FA27691D524FAEAF7C6ECE2A4B99A294B9F2C241857B5B90CC8BFFCFCF18DFA7D676131D5CD3855A5A3E8EBFA0CDFADB4D198B4A",
+ },
+}
+
+func TestExp(t *testing.T) {
+ for i, test := range expTests {
+ x, ok1 := new(Int).SetString(test.x, 0)
+ y, ok2 := new(Int).SetString(test.y, 0)
+
+ var ok3, ok4 bool
+ var out, m *Int
+
+ if len(test.out) == 0 {
+ out, ok3 = nil, true
+ } else {
+ out, ok3 = new(Int).SetString(test.out, 0)
+ }
+
+ if len(test.m) == 0 {
+ m, ok4 = nil, true
+ } else {
+ m, ok4 = new(Int).SetString(test.m, 0)
+ }
+
+ if !ok1 || !ok2 || !ok3 || !ok4 {
+ t.Errorf("#%d: error in input", i)
+ continue
+ }
+
+ z1 := new(Int).Exp(x, y, m)
+ if z1 != nil && !isNormalized(z1) {
+ t.Errorf("#%d: %v is not normalized", i, *z1)
+ }
+ if !(z1 == nil && out == nil || z1.Cmp(out) == 0) {
+ t.Errorf("#%d: got %x want %x", i, z1, out)
+ }
+
+ if m == nil {
+ // The result should be the same as for m == 0;
+ // specifically, there should be no div-zero panic.
+ m = &Int{abs: nat{}} // m != nil && len(m.abs) == 0
+ z2 := new(Int).Exp(x, y, m)
+ if z2.Cmp(z1) != 0 {
+ t.Errorf("#%d: got %x want %x", i, z2, z1)
+ }
+ }
+ }
+}
+
+func BenchmarkExp(b *testing.B) {
+ x, _ := new(Int).SetString("11001289118363089646017359372117963499250546375269047542777928006103246876688756735760905680604646624353196869572752623285140408755420374049317646428185270079555372763503115646054602867593662923894140940837479507194934267532831694565516466765025434902348314525627418515646588160955862839022051353653052947073136084780742729727874803457643848197499548297570026926927502505634297079527299004267769780768565695459945235586892627059178884998772989397505061206395455591503771677500931269477503508150175717121828518985901959919560700853226255420793148986854391552859459511723547532575574664944815966793196961286234040892865", 0)
+ y, _ := new(Int).SetString("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF72", 0)
+ n, _ := new(Int).SetString("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", 0)
+ out := new(Int)
+ for i := 0; i < b.N; i++ {
+ out.Exp(x, y, n)
+ }
+}
+
+func BenchmarkExpMont(b *testing.B) {
+ x, _ := new(Int).SetString("297778224889315382157302278696111964193", 0)
+ y, _ := new(Int).SetString("2548977943381019743024248146923164919440527843026415174732254534318292492375775985739511369575861449426580651447974311336267954477239437734832604782764979371984246675241012538135715981292390886872929238062252506842498360562303324154310849745753254532852868768268023732398278338025070694508489163836616810661033068070127919590264734220833816416141878688318329193389865030063416339367925710474801991305827284114894677717927892032165200876093838921477120036402410731159852999623461591709308405270748511350289172153076023215", 0)
+ var mods = []struct {
+ name string
+ val string
+ }{
+ {"Odd", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF"},
+ {"Even1", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FE"},
+ {"Even2", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FC"},
+ {"Even3", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281F8"},
+ {"Even4", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281F0"},
+ {"Even8", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B21828100"},
+ {"Even32", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B00000000"},
+ {"Even64", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828282828200FF0000000000000000"},
+ {"Even96", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF82828283000000000000000000000000"},
+ {"Even128", "0x82828282828200FFFF28FF2B218281FF82828282828200FFFF28FF2B218281FF00000000000000000000000000000000"},
+ {"Even255", "0x82828282828200FFFF28FF2B218281FF8000000000000000000000000000000000000000000000000000000000000000"},
+ {"SmallEven1", "0x7E"},
+ {"SmallEven2", "0x7C"},
+ {"SmallEven3", "0x78"},
+ {"SmallEven4", "0x70"},
+ }
+ for _, mod := range mods {
+ n, _ := new(Int).SetString(mod.val, 0)
+ out := new(Int)
+ b.Run(mod.name, func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ out.Exp(x, y, n)
+ }
+ })
+ }
+}
+
+func BenchmarkExp2(b *testing.B) {
+ x, _ := new(Int).SetString("2", 0)
+ y, _ := new(Int).SetString("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF72", 0)
+ n, _ := new(Int).SetString("0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73", 0)
+ out := new(Int)
+ for i := 0; i < b.N; i++ {
+ out.Exp(x, y, n)
+ }
+}
+
+func checkGcd(aBytes, bBytes []byte) bool {
+ x := new(Int)
+ y := new(Int)
+ a := new(Int).SetBytes(aBytes)
+ b := new(Int).SetBytes(bBytes)
+
+ d := new(Int).GCD(x, y, a, b)
+ x.Mul(x, a)
+ y.Mul(y, b)
+ x.Add(x, y)
+
+ return x.Cmp(d) == 0
+}
+
+// euclidExtGCD is a reference implementation of Euclid's
+// extended GCD algorithm for testing against optimized algorithms.
+// Requirements: a, b > 0
+func euclidExtGCD(a, b *Int) (g, x, y *Int) {
+ A := new(Int).Set(a)
+ B := new(Int).Set(b)
+
+ // A = Ua*a + Va*b
+ // B = Ub*a + Vb*b
+ Ua := new(Int).SetInt64(1)
+ Va := new(Int)
+
+ Ub := new(Int)
+ Vb := new(Int).SetInt64(1)
+
+ q := new(Int)
+ temp := new(Int)
+
+ r := new(Int)
+ for len(B.abs) > 0 {
+ q, r = q.QuoRem(A, B, r)
+
+ A, B, r = B, r, A
+
+ // Ua, Ub = Ub, Ua-q*Ub
+ temp.Set(Ub)
+ Ub.Mul(Ub, q)
+ Ub.Sub(Ua, Ub)
+ Ua.Set(temp)
+
+ // Va, Vb = Vb, Va-q*Vb
+ temp.Set(Vb)
+ Vb.Mul(Vb, q)
+ Vb.Sub(Va, Vb)
+ Va.Set(temp)
+ }
+ return A, Ua, Va
+}
+
+func checkLehmerGcd(aBytes, bBytes []byte) bool {
+ a := new(Int).SetBytes(aBytes)
+ b := new(Int).SetBytes(bBytes)
+
+ if a.Sign() <= 0 || b.Sign() <= 0 {
+ return true // can only test positive arguments
+ }
+
+ d := new(Int).lehmerGCD(nil, nil, a, b)
+ d0, _, _ := euclidExtGCD(a, b)
+
+ return d.Cmp(d0) == 0
+}
+
+func checkLehmerExtGcd(aBytes, bBytes []byte) bool {
+ a := new(Int).SetBytes(aBytes)
+ b := new(Int).SetBytes(bBytes)
+ x := new(Int)
+ y := new(Int)
+
+ if a.Sign() <= 0 || b.Sign() <= 0 {
+ return true // can only test positive arguments
+ }
+
+ d := new(Int).lehmerGCD(x, y, a, b)
+ d0, x0, y0 := euclidExtGCD(a, b)
+
+ return d.Cmp(d0) == 0 && x.Cmp(x0) == 0 && y.Cmp(y0) == 0
+}
+
+var gcdTests = []struct {
+ d, x, y, a, b string
+}{
+ // a <= 0 || b <= 0
+ {"0", "0", "0", "0", "0"},
+ {"7", "0", "1", "0", "7"},
+ {"7", "0", "-1", "0", "-7"},
+ {"11", "1", "0", "11", "0"},
+ {"7", "-1", "-2", "-77", "35"},
+ {"935", "-3", "8", "64515", "24310"},
+ {"935", "-3", "-8", "64515", "-24310"},
+ {"935", "3", "-8", "-64515", "-24310"},
+
+ {"1", "-9", "47", "120", "23"},
+ {"7", "1", "-2", "77", "35"},
+ {"935", "-3", "8", "64515", "24310"},
+ {"935000000000000000", "-3", "8", "64515000000000000000", "24310000000000000000"},
+ {"1", "-221", "22059940471369027483332068679400581064239780177629666810348940098015901108344", "98920366548084643601728869055592650835572950932266967461790948584315647051443", "991"},
+}
+
+func testGcd(t *testing.T, d, x, y, a, b *Int) {
+ var X *Int
+ if x != nil {
+ X = new(Int)
+ }
+ var Y *Int
+ if y != nil {
+ Y = new(Int)
+ }
+
+ D := new(Int).GCD(X, Y, a, b)
+ if D.Cmp(d) != 0 {
+ t.Errorf("GCD(%s, %s, %s, %s): got d = %s, want %s", x, y, a, b, D, d)
+ }
+ if x != nil && X.Cmp(x) != 0 {
+ t.Errorf("GCD(%s, %s, %s, %s): got x = %s, want %s", x, y, a, b, X, x)
+ }
+ if y != nil && Y.Cmp(y) != 0 {
+ t.Errorf("GCD(%s, %s, %s, %s): got y = %s, want %s", x, y, a, b, Y, y)
+ }
+
+ // check results in presence of aliasing (issue #11284)
+ a2 := new(Int).Set(a)
+ b2 := new(Int).Set(b)
+ a2.GCD(X, Y, a2, b2) // result is same as 1st argument
+ if a2.Cmp(d) != 0 {
+ t.Errorf("aliased z = a GCD(%s, %s, %s, %s): got d = %s, want %s", x, y, a, b, a2, d)
+ }
+ if x != nil && X.Cmp(x) != 0 {
+ t.Errorf("aliased z = a GCD(%s, %s, %s, %s): got x = %s, want %s", x, y, a, b, X, x)
+ }
+ if y != nil && Y.Cmp(y) != 0 {
+ t.Errorf("aliased z = a GCD(%s, %s, %s, %s): got y = %s, want %s", x, y, a, b, Y, y)
+ }
+
+ a2 = new(Int).Set(a)
+ b2 = new(Int).Set(b)
+ b2.GCD(X, Y, a2, b2) // result is same as 2nd argument
+ if b2.Cmp(d) != 0 {
+ t.Errorf("aliased z = b GCD(%s, %s, %s, %s): got d = %s, want %s", x, y, a, b, b2, d)
+ }
+ if x != nil && X.Cmp(x) != 0 {
+ t.Errorf("aliased z = b GCD(%s, %s, %s, %s): got x = %s, want %s", x, y, a, b, X, x)
+ }
+ if y != nil && Y.Cmp(y) != 0 {
+ t.Errorf("aliased z = b GCD(%s, %s, %s, %s): got y = %s, want %s", x, y, a, b, Y, y)
+ }
+
+ a2 = new(Int).Set(a)
+ b2 = new(Int).Set(b)
+ D = new(Int).GCD(a2, b2, a2, b2) // x = a, y = b
+ if D.Cmp(d) != 0 {
+ t.Errorf("aliased x = a, y = b GCD(%s, %s, %s, %s): got d = %s, want %s", x, y, a, b, D, d)
+ }
+ if x != nil && a2.Cmp(x) != 0 {
+ t.Errorf("aliased x = a, y = b GCD(%s, %s, %s, %s): got x = %s, want %s", x, y, a, b, a2, x)
+ }
+ if y != nil && b2.Cmp(y) != 0 {
+ t.Errorf("aliased x = a, y = b GCD(%s, %s, %s, %s): got y = %s, want %s", x, y, a, b, b2, y)
+ }
+
+ a2 = new(Int).Set(a)
+ b2 = new(Int).Set(b)
+ D = new(Int).GCD(b2, a2, a2, b2) // x = b, y = a
+ if D.Cmp(d) != 0 {
+ t.Errorf("aliased x = b, y = a GCD(%s, %s, %s, %s): got d = %s, want %s", x, y, a, b, D, d)
+ }
+ if x != nil && b2.Cmp(x) != 0 {
+ t.Errorf("aliased x = b, y = a GCD(%s, %s, %s, %s): got x = %s, want %s", x, y, a, b, b2, x)
+ }
+ if y != nil && a2.Cmp(y) != 0 {
+ t.Errorf("aliased x = b, y = a GCD(%s, %s, %s, %s): got y = %s, want %s", x, y, a, b, a2, y)
+ }
+}
+
+func TestGcd(t *testing.T) {
+ for _, test := range gcdTests {
+ d, _ := new(Int).SetString(test.d, 0)
+ x, _ := new(Int).SetString(test.x, 0)
+ y, _ := new(Int).SetString(test.y, 0)
+ a, _ := new(Int).SetString(test.a, 0)
+ b, _ := new(Int).SetString(test.b, 0)
+
+ testGcd(t, d, nil, nil, a, b)
+ testGcd(t, d, x, nil, a, b)
+ testGcd(t, d, nil, y, a, b)
+ testGcd(t, d, x, y, a, b)
+ }
+
+ if err := quick.Check(checkGcd, nil); err != nil {
+ t.Error(err)
+ }
+
+ if err := quick.Check(checkLehmerGcd, nil); err != nil {
+ t.Error(err)
+ }
+
+ if err := quick.Check(checkLehmerExtGcd, nil); err != nil {
+ t.Error(err)
+ }
+}
+
+type intShiftTest struct {
+ in string
+ shift uint
+ out string
+}
+
+var rshTests = []intShiftTest{
+ {"0", 0, "0"},
+ {"-0", 0, "0"},
+ {"0", 1, "0"},
+ {"0", 2, "0"},
+ {"1", 0, "1"},
+ {"1", 1, "0"},
+ {"1", 2, "0"},
+ {"2", 0, "2"},
+ {"2", 1, "1"},
+ {"-1", 0, "-1"},
+ {"-1", 1, "-1"},
+ {"-1", 10, "-1"},
+ {"-100", 2, "-25"},
+ {"-100", 3, "-13"},
+ {"-100", 100, "-1"},
+ {"4294967296", 0, "4294967296"},
+ {"4294967296", 1, "2147483648"},
+ {"4294967296", 2, "1073741824"},
+ {"18446744073709551616", 0, "18446744073709551616"},
+ {"18446744073709551616", 1, "9223372036854775808"},
+ {"18446744073709551616", 2, "4611686018427387904"},
+ {"18446744073709551616", 64, "1"},
+ {"340282366920938463463374607431768211456", 64, "18446744073709551616"},
+ {"340282366920938463463374607431768211456", 128, "1"},
+}
+
+func TestRsh(t *testing.T) {
+ for i, test := range rshTests {
+ in, _ := new(Int).SetString(test.in, 10)
+ expected, _ := new(Int).SetString(test.out, 10)
+ out := new(Int).Rsh(in, test.shift)
+
+ if !isNormalized(out) {
+ t.Errorf("#%d: %v is not normalized", i, *out)
+ }
+ if out.Cmp(expected) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, expected)
+ }
+ }
+}
+
+func TestRshSelf(t *testing.T) {
+ for i, test := range rshTests {
+ z, _ := new(Int).SetString(test.in, 10)
+ expected, _ := new(Int).SetString(test.out, 10)
+ z.Rsh(z, test.shift)
+
+ if !isNormalized(z) {
+ t.Errorf("#%d: %v is not normalized", i, *z)
+ }
+ if z.Cmp(expected) != 0 {
+ t.Errorf("#%d: got %s want %s", i, z, expected)
+ }
+ }
+}
+
+var lshTests = []intShiftTest{
+ {"0", 0, "0"},
+ {"0", 1, "0"},
+ {"0", 2, "0"},
+ {"1", 0, "1"},
+ {"1", 1, "2"},
+ {"1", 2, "4"},
+ {"2", 0, "2"},
+ {"2", 1, "4"},
+ {"2", 2, "8"},
+ {"-87", 1, "-174"},
+ {"4294967296", 0, "4294967296"},
+ {"4294967296", 1, "8589934592"},
+ {"4294967296", 2, "17179869184"},
+ {"18446744073709551616", 0, "18446744073709551616"},
+ {"9223372036854775808", 1, "18446744073709551616"},
+ {"4611686018427387904", 2, "18446744073709551616"},
+ {"1", 64, "18446744073709551616"},
+ {"18446744073709551616", 64, "340282366920938463463374607431768211456"},
+ {"1", 128, "340282366920938463463374607431768211456"},
+}
+
+func TestLsh(t *testing.T) {
+ for i, test := range lshTests {
+ in, _ := new(Int).SetString(test.in, 10)
+ expected, _ := new(Int).SetString(test.out, 10)
+ out := new(Int).Lsh(in, test.shift)
+
+ if !isNormalized(out) {
+ t.Errorf("#%d: %v is not normalized", i, *out)
+ }
+ if out.Cmp(expected) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, expected)
+ }
+ }
+}
+
+func TestLshSelf(t *testing.T) {
+ for i, test := range lshTests {
+ z, _ := new(Int).SetString(test.in, 10)
+ expected, _ := new(Int).SetString(test.out, 10)
+ z.Lsh(z, test.shift)
+
+ if !isNormalized(z) {
+ t.Errorf("#%d: %v is not normalized", i, *z)
+ }
+ if z.Cmp(expected) != 0 {
+ t.Errorf("#%d: got %s want %s", i, z, expected)
+ }
+ }
+}
+
+func TestLshRsh(t *testing.T) {
+ for i, test := range rshTests {
+ in, _ := new(Int).SetString(test.in, 10)
+ out := new(Int).Lsh(in, test.shift)
+ out = out.Rsh(out, test.shift)
+
+ if !isNormalized(out) {
+ t.Errorf("#%d: %v is not normalized", i, *out)
+ }
+ if in.Cmp(out) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, in)
+ }
+ }
+ for i, test := range lshTests {
+ in, _ := new(Int).SetString(test.in, 10)
+ out := new(Int).Lsh(in, test.shift)
+ out.Rsh(out, test.shift)
+
+ if !isNormalized(out) {
+ t.Errorf("#%d: %v is not normalized", i, *out)
+ }
+ if in.Cmp(out) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, in)
+ }
+ }
+}
+
+// Entries must be sorted by value in ascending order.
+var cmpAbsTests = []string{
+ "0",
+ "1",
+ "2",
+ "10",
+ "10000000",
+ "2783678367462374683678456387645876387564783686583485",
+ "2783678367462374683678456387645876387564783686583486",
+ "32957394867987420967976567076075976570670947609750670956097509670576075067076027578341538",
+}
+
+func TestCmpAbs(t *testing.T) {
+ values := make([]*Int, len(cmpAbsTests))
+ var prev *Int
+ for i, s := range cmpAbsTests {
+ x, ok := new(Int).SetString(s, 0)
+ if !ok {
+ t.Fatalf("SetString(%s, 0) failed", s)
+ }
+ if prev != nil && prev.Cmp(x) >= 0 {
+ t.Fatal("cmpAbsTests entries not sorted in ascending order")
+ }
+ values[i] = x
+ prev = x
+ }
+
+ for i, x := range values {
+ for j, y := range values {
+ // try all combinations of signs for x, y
+ for k := 0; k < 4; k++ {
+ var a, b Int
+ a.Set(x)
+ b.Set(y)
+ if k&1 != 0 {
+ a.Neg(&a)
+ }
+ if k&2 != 0 {
+ b.Neg(&b)
+ }
+
+ got := a.CmpAbs(&b)
+ want := 0
+ switch {
+ case i > j:
+ want = 1
+ case i < j:
+ want = -1
+ }
+ if got != want {
+ t.Errorf("absCmp |%s|, |%s|: got %d; want %d", &a, &b, got, want)
+ }
+ }
+ }
+ }
+}
+
+func TestIntCmpSelf(t *testing.T) {
+ for _, s := range cmpAbsTests {
+ x, ok := new(Int).SetString(s, 0)
+ if !ok {
+ t.Fatalf("SetString(%s, 0) failed", s)
+ }
+ got := x.Cmp(x)
+ want := 0
+ if got != want {
+ t.Errorf("x = %s: x.Cmp(x): got %d; want %d", x, got, want)
+ }
+ }
+}
+
+var int64Tests = []string{
+ // int64
+ "0",
+ "1",
+ "-1",
+ "4294967295",
+ "-4294967295",
+ "4294967296",
+ "-4294967296",
+ "9223372036854775807",
+ "-9223372036854775807",
+ "-9223372036854775808",
+
+ // not int64
+ "0x8000000000000000",
+ "-0x8000000000000001",
+ "38579843757496759476987459679745",
+ "-38579843757496759476987459679745",
+}
+
+func TestInt64(t *testing.T) {
+ for _, s := range int64Tests {
+ var x Int
+ _, ok := x.SetString(s, 0)
+ if !ok {
+ t.Errorf("SetString(%s, 0) failed", s)
+ continue
+ }
+
+ want, err := strconv.ParseInt(s, 0, 64)
+ if err != nil {
+ if err.(*strconv.NumError).Err == strconv.ErrRange {
+ if x.IsInt64() {
+ t.Errorf("IsInt64(%s) succeeded unexpectedly", s)
+ }
+ } else {
+ t.Errorf("ParseInt(%s) failed", s)
+ }
+ continue
+ }
+
+ if !x.IsInt64() {
+ t.Errorf("IsInt64(%s) failed unexpectedly", s)
+ }
+
+ got := x.Int64()
+ if got != want {
+ t.Errorf("Int64(%s) = %d; want %d", s, got, want)
+ }
+ }
+}
+
+var uint64Tests = []string{
+ // uint64
+ "0",
+ "1",
+ "4294967295",
+ "4294967296",
+ "8589934591",
+ "8589934592",
+ "9223372036854775807",
+ "9223372036854775808",
+ "0x08000000000000000",
+
+ // not uint64
+ "0x10000000000000000",
+ "-0x08000000000000000",
+ "-1",
+}
+
+func TestUint64(t *testing.T) {
+ for _, s := range uint64Tests {
+ var x Int
+ _, ok := x.SetString(s, 0)
+ if !ok {
+ t.Errorf("SetString(%s, 0) failed", s)
+ continue
+ }
+
+ want, err := strconv.ParseUint(s, 0, 64)
+ if err != nil {
+ // check for sign explicitly (ErrRange doesn't cover signed input)
+ if s[0] == '-' || err.(*strconv.NumError).Err == strconv.ErrRange {
+ if x.IsUint64() {
+ t.Errorf("IsUint64(%s) succeeded unexpectedly", s)
+ }
+ } else {
+ t.Errorf("ParseUint(%s) failed", s)
+ }
+ continue
+ }
+
+ if !x.IsUint64() {
+ t.Errorf("IsUint64(%s) failed unexpectedly", s)
+ }
+
+ got := x.Uint64()
+ if got != want {
+ t.Errorf("Uint64(%s) = %d; want %d", s, got, want)
+ }
+ }
+}
+
+var bitwiseTests = []struct {
+ x, y string
+ and, or, xor, andNot string
+}{
+ {"0x00", "0x00", "0x00", "0x00", "0x00", "0x00"},
+ {"0x00", "0x01", "0x00", "0x01", "0x01", "0x00"},
+ {"0x01", "0x00", "0x00", "0x01", "0x01", "0x01"},
+ {"-0x01", "0x00", "0x00", "-0x01", "-0x01", "-0x01"},
+ {"-0xaf", "-0x50", "-0xf0", "-0x0f", "0xe1", "0x41"},
+ {"0x00", "-0x01", "0x00", "-0x01", "-0x01", "0x00"},
+ {"0x01", "0x01", "0x01", "0x01", "0x00", "0x00"},
+ {"-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"},
+ {"0x07", "0x08", "0x00", "0x0f", "0x0f", "0x07"},
+ {"0x05", "0x0f", "0x05", "0x0f", "0x0a", "0x00"},
+ {"0xff", "-0x0a", "0xf6", "-0x01", "-0xf7", "0x09"},
+ {"0x013ff6", "0x9a4e", "0x1a46", "0x01bffe", "0x01a5b8", "0x0125b0"},
+ {"-0x013ff6", "0x9a4e", "0x800a", "-0x0125b2", "-0x01a5bc", "-0x01c000"},
+ {"-0x013ff6", "-0x9a4e", "-0x01bffe", "-0x1a46", "0x01a5b8", "0x8008"},
+ {
+ "0x1000009dc6e3d9822cba04129bcbe3401",
+ "0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
+ "0x1000001186210100001000009048c2001",
+ "0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd",
+ "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc",
+ "0x8c40c2d8822caa04120b8321400",
+ },
+ {
+ "0x1000009dc6e3d9822cba04129bcbe3401",
+ "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
+ "0x8c40c2d8822caa04120b8321401",
+ "-0xb9bd7d543685789d57ca918e82229142459020483cd2014001fd",
+ "-0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fe",
+ "0x1000001186210100001000009048c2000",
+ },
+ {
+ "-0x1000009dc6e3d9822cba04129bcbe3401",
+ "-0xb9bd7d543685789d57cb918e833af352559021483cdb05cc21fd",
+ "-0xb9bd7d543685789d57cb918e8bfeff7fddb2ebe87dfbbdfe35fd",
+ "-0x1000001186210100001000009048c2001",
+ "0xb9bd7d543685789d57ca918e8ae69d6fcdb2eae87df2b97215fc",
+ "0xb9bd7d543685789d57ca918e82229142459020483cd2014001fc",
+ },
+}
+
+type bitFun func(z, x, y *Int) *Int
+
+func testBitFun(t *testing.T, msg string, f bitFun, x, y *Int, exp string) {
+ expected := new(Int)
+ expected.SetString(exp, 0)
+
+ out := f(new(Int), x, y)
+ if out.Cmp(expected) != 0 {
+ t.Errorf("%s: got %s want %s", msg, out, expected)
+ }
+}
+
+func testBitFunSelf(t *testing.T, msg string, f bitFun, x, y *Int, exp string) {
+ self := new(Int)
+ self.Set(x)
+ expected := new(Int)
+ expected.SetString(exp, 0)
+
+ self = f(self, self, y)
+ if self.Cmp(expected) != 0 {
+ t.Errorf("%s: got %s want %s", msg, self, expected)
+ }
+}
+
+func altBit(x *Int, i int) uint {
+ z := new(Int).Rsh(x, uint(i))
+ z = z.And(z, NewInt(1))
+ if z.Cmp(new(Int)) != 0 {
+ return 1
+ }
+ return 0
+}
+
+func altSetBit(z *Int, x *Int, i int, b uint) *Int {
+ one := NewInt(1)
+ m := one.Lsh(one, uint(i))
+ switch b {
+ case 1:
+ return z.Or(x, m)
+ case 0:
+ return z.AndNot(x, m)
+ }
+ panic("set bit is not 0 or 1")
+}
+
+func testBitset(t *testing.T, x *Int) {
+ n := x.BitLen()
+ z := new(Int).Set(x)
+ z1 := new(Int).Set(x)
+ for i := 0; i < n+10; i++ {
+ old := z.Bit(i)
+ old1 := altBit(z1, i)
+ if old != old1 {
+ t.Errorf("bitset: inconsistent value for Bit(%s, %d), got %v want %v", z1, i, old, old1)
+ }
+ z := new(Int).SetBit(z, i, 1)
+ z1 := altSetBit(new(Int), z1, i, 1)
+ if z.Bit(i) == 0 {
+ t.Errorf("bitset: bit %d of %s got 0 want 1", i, x)
+ }
+ if z.Cmp(z1) != 0 {
+ t.Errorf("bitset: inconsistent value after SetBit 1, got %s want %s", z, z1)
+ }
+ z.SetBit(z, i, 0)
+ altSetBit(z1, z1, i, 0)
+ if z.Bit(i) != 0 {
+ t.Errorf("bitset: bit %d of %s got 1 want 0", i, x)
+ }
+ if z.Cmp(z1) != 0 {
+ t.Errorf("bitset: inconsistent value after SetBit 0, got %s want %s", z, z1)
+ }
+ altSetBit(z1, z1, i, old)
+ z.SetBit(z, i, old)
+ if z.Cmp(z1) != 0 {
+ t.Errorf("bitset: inconsistent value after SetBit old, got %s want %s", z, z1)
+ }
+ }
+ if z.Cmp(x) != 0 {
+ t.Errorf("bitset: got %s want %s", z, x)
+ }
+}
+
+var bitsetTests = []struct {
+ x string
+ i int
+ b uint
+}{
+ {"0", 0, 0},
+ {"0", 200, 0},
+ {"1", 0, 1},
+ {"1", 1, 0},
+ {"-1", 0, 1},
+ {"-1", 200, 1},
+ {"0x2000000000000000000000000000", 108, 0},
+ {"0x2000000000000000000000000000", 109, 1},
+ {"0x2000000000000000000000000000", 110, 0},
+ {"-0x2000000000000000000000000001", 108, 1},
+ {"-0x2000000000000000000000000001", 109, 0},
+ {"-0x2000000000000000000000000001", 110, 1},
+}
+
+func TestBitSet(t *testing.T) {
+ for _, test := range bitwiseTests {
+ x := new(Int)
+ x.SetString(test.x, 0)
+ testBitset(t, x)
+ x = new(Int)
+ x.SetString(test.y, 0)
+ testBitset(t, x)
+ }
+ for i, test := range bitsetTests {
+ x := new(Int)
+ x.SetString(test.x, 0)
+ b := x.Bit(test.i)
+ if b != test.b {
+ t.Errorf("#%d got %v want %v", i, b, test.b)
+ }
+ }
+ z := NewInt(1)
+ z.SetBit(NewInt(0), 2, 1)
+ if z.Cmp(NewInt(4)) != 0 {
+ t.Errorf("destination leaked into result; got %s want 4", z)
+ }
+}
+
+var tzbTests = []struct {
+ in string
+ out uint
+}{
+ {"0", 0},
+ {"1", 0},
+ {"-1", 0},
+ {"4", 2},
+ {"-8", 3},
+ {"0x4000000000000000000", 74},
+ {"-0x8000000000000000000", 75},
+}
+
+func TestTrailingZeroBits(t *testing.T) {
+ for i, test := range tzbTests {
+ in, _ := new(Int).SetString(test.in, 0)
+ want := test.out
+ got := in.TrailingZeroBits()
+
+ if got != want {
+ t.Errorf("#%d: got %v want %v", i, got, want)
+ }
+ }
+}
+
+func BenchmarkBitset(b *testing.B) {
+ z := new(Int)
+ z.SetBit(z, 512, 1)
+ b.ResetTimer()
+ for i := b.N - 1; i >= 0; i-- {
+ z.SetBit(z, i&512, 1)
+ }
+}
+
+func BenchmarkBitsetNeg(b *testing.B) {
+ z := NewInt(-1)
+ z.SetBit(z, 512, 0)
+ b.ResetTimer()
+ for i := b.N - 1; i >= 0; i-- {
+ z.SetBit(z, i&512, 0)
+ }
+}
+
+func BenchmarkBitsetOrig(b *testing.B) {
+ z := new(Int)
+ altSetBit(z, z, 512, 1)
+ b.ResetTimer()
+ for i := b.N - 1; i >= 0; i-- {
+ altSetBit(z, z, i&512, 1)
+ }
+}
+
+func BenchmarkBitsetNegOrig(b *testing.B) {
+ z := NewInt(-1)
+ altSetBit(z, z, 512, 0)
+ b.ResetTimer()
+ for i := b.N - 1; i >= 0; i-- {
+ altSetBit(z, z, i&512, 0)
+ }
+}
+
+// tri generates the trinomial 2**(n*2) - 2**n - 1, which is always 3 mod 4 and
+// 7 mod 8, so that 2 is always a quadratic residue.
+func tri(n uint) *Int {
+ x := NewInt(1)
+ x.Lsh(x, n)
+ x2 := new(Int).Lsh(x, n)
+ x2.Sub(x2, x)
+ x2.Sub(x2, intOne)
+ return x2
+}
+
+func BenchmarkModSqrt225_Tonelli(b *testing.B) {
+ p := tri(225)
+ x := NewInt(2)
+ for i := 0; i < b.N; i++ {
+ x.SetUint64(2)
+ x.modSqrtTonelliShanks(x, p)
+ }
+}
+
+func BenchmarkModSqrt225_3Mod4(b *testing.B) {
+ p := tri(225)
+ x := new(Int).SetUint64(2)
+ for i := 0; i < b.N; i++ {
+ x.SetUint64(2)
+ x.modSqrt3Mod4Prime(x, p)
+ }
+}
+
+func BenchmarkModSqrt231_Tonelli(b *testing.B) {
+ p := tri(231)
+ p.Sub(p, intOne)
+ p.Sub(p, intOne) // tri(231) - 2 is a prime == 5 mod 8
+ x := new(Int).SetUint64(7)
+ for i := 0; i < b.N; i++ {
+ x.SetUint64(7)
+ x.modSqrtTonelliShanks(x, p)
+ }
+}
+
+func BenchmarkModSqrt231_5Mod8(b *testing.B) {
+ p := tri(231)
+ p.Sub(p, intOne)
+ p.Sub(p, intOne) // tri(231) - 2 is a prime == 5 mod 8
+ x := new(Int).SetUint64(7)
+ for i := 0; i < b.N; i++ {
+ x.SetUint64(7)
+ x.modSqrt5Mod8Prime(x, p)
+ }
+}
+
+func TestBitwise(t *testing.T) {
+ x := new(Int)
+ y := new(Int)
+ for _, test := range bitwiseTests {
+ x.SetString(test.x, 0)
+ y.SetString(test.y, 0)
+
+ testBitFun(t, "and", (*Int).And, x, y, test.and)
+ testBitFunSelf(t, "and", (*Int).And, x, y, test.and)
+ testBitFun(t, "andNot", (*Int).AndNot, x, y, test.andNot)
+ testBitFunSelf(t, "andNot", (*Int).AndNot, x, y, test.andNot)
+ testBitFun(t, "or", (*Int).Or, x, y, test.or)
+ testBitFunSelf(t, "or", (*Int).Or, x, y, test.or)
+ testBitFun(t, "xor", (*Int).Xor, x, y, test.xor)
+ testBitFunSelf(t, "xor", (*Int).Xor, x, y, test.xor)
+ }
+}
+
+var notTests = []struct {
+ in string
+ out string
+}{
+ {"0", "-1"},
+ {"1", "-2"},
+ {"7", "-8"},
+ {"0", "-1"},
+ {"-81910", "81909"},
+ {
+ "298472983472983471903246121093472394872319615612417471234712061",
+ "-298472983472983471903246121093472394872319615612417471234712062",
+ },
+}
+
+func TestNot(t *testing.T) {
+ in := new(Int)
+ out := new(Int)
+ expected := new(Int)
+ for i, test := range notTests {
+ in.SetString(test.in, 10)
+ expected.SetString(test.out, 10)
+ out = out.Not(in)
+ if out.Cmp(expected) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, expected)
+ }
+ out = out.Not(out)
+ if out.Cmp(in) != 0 {
+ t.Errorf("#%d: got %s want %s", i, out, in)
+ }
+ }
+}
+
+var modInverseTests = []struct {
+ element string
+ modulus string
+}{
+ {"1234567", "458948883992"},
+ {"239487239847", "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"},
+ {"-10", "13"}, // issue #16984
+ {"10", "-13"},
+ {"-17", "-13"},
+}
+
+func TestModInverse(t *testing.T) {
+ var element, modulus, gcd, inverse Int
+ one := NewInt(1)
+ for _, test := range modInverseTests {
+ (&element).SetString(test.element, 10)
+ (&modulus).SetString(test.modulus, 10)
+ (&inverse).ModInverse(&element, &modulus)
+ (&inverse).Mul(&inverse, &element)
+ (&inverse).Mod(&inverse, &modulus)
+ if (&inverse).Cmp(one) != 0 {
+ t.Errorf("ModInverse(%d,%d)*%d%%%d=%d, not 1", &element, &modulus, &element, &modulus, &inverse)
+ }
+ }
+ // exhaustive test for small values
+ for n := 2; n < 100; n++ {
+ (&modulus).SetInt64(int64(n))
+ for x := 1; x < n; x++ {
+ (&element).SetInt64(int64(x))
+ (&gcd).GCD(nil, nil, &element, &modulus)
+ if (&gcd).Cmp(one) != 0 {
+ continue
+ }
+ (&inverse).ModInverse(&element, &modulus)
+ (&inverse).Mul(&inverse, &element)
+ (&inverse).Mod(&inverse, &modulus)
+ if (&inverse).Cmp(one) != 0 {
+ t.Errorf("ModInverse(%d,%d)*%d%%%d=%d, not 1", &element, &modulus, &element, &modulus, &inverse)
+ }
+ }
+ }
+}
+
+func BenchmarkModInverse(b *testing.B) {
+ p := new(Int).SetInt64(1) // Mersenne prime 2**1279 -1
+ p.abs = p.abs.shl(p.abs, 1279)
+ p.Sub(p, intOne)
+ x := new(Int).Sub(p, intOne)
+ z := new(Int)
+ for i := 0; i < b.N; i++ {
+ z.ModInverse(x, p)
+ }
+}
+
+// testModSqrt is a helper for TestModSqrt,
+// which checks that ModSqrt can compute a square-root of elt^2.
+func testModSqrt(t *testing.T, elt, mod, sq, sqrt *Int) bool {
+ var sqChk, sqrtChk, sqrtsq Int
+ sq.Mul(elt, elt)
+ sq.Mod(sq, mod)
+ z := sqrt.ModSqrt(sq, mod)
+ if z != sqrt {
+ t.Errorf("ModSqrt returned wrong value %s", z)
+ }
+
+ // test ModSqrt arguments outside the range [0,mod)
+ sqChk.Add(sq, mod)
+ z = sqrtChk.ModSqrt(&sqChk, mod)
+ if z != &sqrtChk || z.Cmp(sqrt) != 0 {
+ t.Errorf("ModSqrt returned inconsistent value %s", z)
+ }
+ sqChk.Sub(sq, mod)
+ z = sqrtChk.ModSqrt(&sqChk, mod)
+ if z != &sqrtChk || z.Cmp(sqrt) != 0 {
+ t.Errorf("ModSqrt returned inconsistent value %s", z)
+ }
+
+ // test x aliasing z
+ z = sqrtChk.ModSqrt(sqrtChk.Set(sq), mod)
+ if z != &sqrtChk || z.Cmp(sqrt) != 0 {
+ t.Errorf("ModSqrt returned inconsistent value %s", z)
+ }
+
+ // make sure we actually got a square root
+ if sqrt.Cmp(elt) == 0 {
+ return true // we found the "desired" square root
+ }
+ sqrtsq.Mul(sqrt, sqrt) // make sure we found the "other" one
+ sqrtsq.Mod(&sqrtsq, mod)
+ return sq.Cmp(&sqrtsq) == 0
+}
+
+func TestModSqrt(t *testing.T) {
+ var elt, mod, modx4, sq, sqrt Int
+ r := rand.New(rand.NewSource(9))
+ for i, s := range primes[1:] { // skip 2, use only odd primes
+ mod.SetString(s, 10)
+ modx4.Lsh(&mod, 2)
+
+ // test a few random elements per prime
+ for x := 1; x < 5; x++ {
+ elt.Rand(r, &modx4)
+ elt.Sub(&elt, &mod) // test range [-mod, 3*mod)
+ if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
+ t.Errorf("#%d: failed (sqrt(e) = %s)", i, &sqrt)
+ }
+ }
+
+ if testing.Short() && i > 2 {
+ break
+ }
+ }
+
+ if testing.Short() {
+ return
+ }
+
+ // exhaustive test for small values
+ for n := 3; n < 100; n++ {
+ mod.SetInt64(int64(n))
+ if !mod.ProbablyPrime(10) {
+ continue
+ }
+ isSquare := make([]bool, n)
+
+ // test all the squares
+ for x := 1; x < n; x++ {
+ elt.SetInt64(int64(x))
+ if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
+ t.Errorf("#%d: failed (sqrt(%d,%d) = %s)", x, &elt, &mod, &sqrt)
+ }
+ isSquare[sq.Uint64()] = true
+ }
+
+ // test all non-squares
+ for x := 1; x < n; x++ {
+ sq.SetInt64(int64(x))
+ z := sqrt.ModSqrt(&sq, &mod)
+ if !isSquare[x] && z != nil {
+ t.Errorf("#%d: failed (sqrt(%d,%d) = nil)", x, &sqrt, &mod)
+ }
+ }
+ }
+}
+
+func TestJacobi(t *testing.T) {
+ testCases := []struct {
+ x, y int64
+ result int
+ }{
+ {0, 1, 1},
+ {0, -1, 1},
+ {1, 1, 1},
+ {1, -1, 1},
+ {0, 5, 0},
+ {1, 5, 1},
+ {2, 5, -1},
+ {-2, 5, -1},
+ {2, -5, -1},
+ {-2, -5, 1},
+ {3, 5, -1},
+ {5, 5, 0},
+ {-5, 5, 0},
+ {6, 5, 1},
+ {6, -5, 1},
+ {-6, 5, 1},
+ {-6, -5, -1},
+ }
+
+ var x, y Int
+
+ for i, test := range testCases {
+ x.SetInt64(test.x)
+ y.SetInt64(test.y)
+ expected := test.result
+ actual := Jacobi(&x, &y)
+ if actual != expected {
+ t.Errorf("#%d: Jacobi(%d, %d) = %d, but expected %d", i, test.x, test.y, actual, expected)
+ }
+ }
+}
+
+func TestJacobiPanic(t *testing.T) {
+ const failureMsg = "test failure"
+ defer func() {
+ msg := recover()
+ if msg == nil || msg == failureMsg {
+ panic(msg)
+ }
+ t.Log(msg)
+ }()
+ x := NewInt(1)
+ y := NewInt(2)
+ // Jacobi should panic when the second argument is even.
+ Jacobi(x, y)
+ panic(failureMsg)
+}
+
+func TestIssue2607(t *testing.T) {
+ // This code sequence used to hang.
+ n := NewInt(10)
+ n.Rand(rand.New(rand.NewSource(9)), n)
+}
+
+func TestSqrt(t *testing.T) {
+ root := 0
+ r := new(Int)
+ for i := 0; i < 10000; i++ {
+ if (root+1)*(root+1) <= i {
+ root++
+ }
+ n := NewInt(int64(i))
+ r.SetInt64(-2)
+ r.Sqrt(n)
+ if r.Cmp(NewInt(int64(root))) != 0 {
+ t.Errorf("Sqrt(%v) = %v, want %v", n, r, root)
+ }
+ }
+
+ for i := 0; i < 1000; i += 10 {
+ n, _ := new(Int).SetString("1"+strings.Repeat("0", i), 10)
+ r := new(Int).Sqrt(n)
+ root, _ := new(Int).SetString("1"+strings.Repeat("0", i/2), 10)
+ if r.Cmp(root) != 0 {
+ t.Errorf("Sqrt(1e%d) = %v, want 1e%d", i, r, i/2)
+ }
+ }
+
+ // Test aliasing.
+ r.SetInt64(100)
+ r.Sqrt(r)
+ if r.Int64() != 10 {
+ t.Errorf("Sqrt(100) = %v, want 10 (aliased output)", r.Int64())
+ }
+}
+
+// We can't test this together with the other Exp tests above because
+// it requires a different receiver setup.
+func TestIssue22830(t *testing.T) {
+ one := new(Int).SetInt64(1)
+ base, _ := new(Int).SetString("84555555300000000000", 10)
+ mod, _ := new(Int).SetString("66666670001111111111", 10)
+ want, _ := new(Int).SetString("17888885298888888889", 10)
+
+ var tests = []int64{
+ 0, 1, -1,
+ }
+
+ for _, n := range tests {
+ m := NewInt(n)
+ if got := m.Exp(base, one, mod); got.Cmp(want) != 0 {
+ t.Errorf("(%v).Exp(%s, 1, %s) = %s, want %s", n, base, mod, got, want)
+ }
+ }
+}
+
+func BenchmarkSqrt(b *testing.B) {
+ n, _ := new(Int).SetString("1"+strings.Repeat("0", 1001), 10)
+ b.ResetTimer()
+ t := new(Int)
+ for i := 0; i < b.N; i++ {
+ t.Sqrt(n)
+ }
+}
+
+func benchmarkIntSqr(b *testing.B, nwords int) {
+ x := new(Int)
+ x.abs = rndNat(nwords)
+ t := new(Int)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ t.Mul(x, x)
+ }
+}
+
+func BenchmarkIntSqr(b *testing.B) {
+ for _, n := range sqrBenchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
+ benchmarkIntSqr(b, n)
+ })
+ }
+}
+
+func benchmarkDiv(b *testing.B, aSize, bSize int) {
+ var r = rand.New(rand.NewSource(1234))
+ aa := randInt(r, uint(aSize))
+ bb := randInt(r, uint(bSize))
+ if aa.Cmp(bb) < 0 {
+ aa, bb = bb, aa
+ }
+ x := new(Int)
+ y := new(Int)
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ x.DivMod(aa, bb, y)
+ }
+}
+
+func BenchmarkDiv(b *testing.B) {
+ sizes := []int{
+ 10, 20, 50, 100, 200, 500, 1000,
+ 1e4, 1e5, 1e6, 1e7,
+ }
+ for _, i := range sizes {
+ j := 2 * i
+ b.Run(fmt.Sprintf("%d/%d", j, i), func(b *testing.B) {
+ benchmarkDiv(b, j, i)
+ })
+ }
+}
+
+func TestFillBytes(t *testing.T) {
+ checkResult := func(t *testing.T, buf []byte, want *Int) {
+ t.Helper()
+ got := new(Int).SetBytes(buf)
+ if got.CmpAbs(want) != 0 {
+ t.Errorf("got 0x%x, want 0x%x: %x", got, want, buf)
+ }
+ }
+ panics := func(f func()) (panic bool) {
+ defer func() { panic = recover() != nil }()
+ f()
+ return
+ }
+
+ for _, n := range []string{
+ "0",
+ "1000",
+ "0xffffffff",
+ "-0xffffffff",
+ "0xffffffffffffffff",
+ "0x10000000000000000",
+ "0xabababababababababababababababababababababababababa",
+ "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+ } {
+ t.Run(n, func(t *testing.T) {
+ t.Logf(n)
+ x, ok := new(Int).SetString(n, 0)
+ if !ok {
+ panic("invalid test entry")
+ }
+
+ // Perfectly sized buffer.
+ byteLen := (x.BitLen() + 7) / 8
+ buf := make([]byte, byteLen)
+ checkResult(t, x.FillBytes(buf), x)
+
+ // Way larger, checking all bytes get zeroed.
+ buf = make([]byte, 100)
+ for i := range buf {
+ buf[i] = 0xff
+ }
+ checkResult(t, x.FillBytes(buf), x)
+
+ // Too small.
+ if byteLen > 0 {
+ buf = make([]byte, byteLen-1)
+ if !panics(func() { x.FillBytes(buf) }) {
+ t.Errorf("expected panic for small buffer and value %x", x)
+ }
+ }
+ })
+ }
+}
+
+func TestNewIntMinInt64(t *testing.T) {
+ // Test for uint64 cast in NewInt.
+ want := int64(math.MinInt64)
+ if got := NewInt(want).Int64(); got != want {
+ t.Fatalf("wanted %d, got %d", want, got)
+ }
+}
+
+func TestNewIntAllocs(t *testing.T) {
+ testenv.SkipIfOptimizationOff(t)
+ for _, n := range []int64{0, 7, -7, 1 << 30, -1 << 30, 1 << 50, -1 << 50} {
+ x := NewInt(3)
+ got := testing.AllocsPerRun(100, func() {
+ // NewInt should inline, and all its allocations
+ // can happen on the stack. Passing the result of NewInt
+ // to Add should not cause any of those allocations to escape.
+ x.Add(x, NewInt(n))
+ })
+ if got != 0 {
+ t.Errorf("x.Add(x, NewInt(%d)), wanted 0 allocations, got %f", n, got)
+ }
+ }
+}
+
+func TestFloat64(t *testing.T) {
+ for _, test := range []struct {
+ istr string
+ f float64
+ acc Accuracy
+ }{
+ {"-1000000000000000000000000000000000000000000000000000000", -1000000000000000078291540404596243842305360299886116864.000000, Below},
+ {"-9223372036854775809", math.MinInt64, Above},
+ {"-9223372036854775808", -9223372036854775808, Exact}, // -2^63
+ {"-9223372036854775807", -9223372036854775807, Below},
+ {"-18014398509481985", -18014398509481984.000000, Above},
+ {"-18014398509481984", -18014398509481984.000000, Exact}, // -2^54
+ {"-18014398509481983", -18014398509481984.000000, Below},
+ {"-9007199254740993", -9007199254740992.000000, Above},
+ {"-9007199254740992", -9007199254740992.000000, Exact}, // -2^53
+ {"-9007199254740991", -9007199254740991.000000, Exact},
+ {"-4503599627370497", -4503599627370497.000000, Exact},
+ {"-4503599627370496", -4503599627370496.000000, Exact}, // -2^52
+ {"-4503599627370495", -4503599627370495.000000, Exact},
+ {"-12345", -12345, Exact},
+ {"-1", -1, Exact},
+ {"0", 0, Exact},
+ {"1", 1, Exact},
+ {"12345", 12345, Exact},
+ {"0x1010000000000000", 0x1010000000000000, Exact}, // >2^53 but exact nonetheless
+ {"9223372036854775807", 9223372036854775808, Above},
+ {"9223372036854775808", 9223372036854775808, Exact}, // +2^63
+ {"1000000000000000000000000000000000000000000000000000000", 1000000000000000078291540404596243842305360299886116864.000000, Above},
+ } {
+ i, ok := new(Int).SetString(test.istr, 0)
+ if !ok {
+ t.Errorf("SetString(%s) failed", test.istr)
+ continue
+ }
+
+ // Test against expectation.
+ f, acc := i.Float64()
+ if f != test.f || acc != test.acc {
+ t.Errorf("%s: got %f (%s); want %f (%s)", test.istr, f, acc, test.f, test.acc)
+ }
+
+ // Cross-check the fast path against the big.Float implementation.
+ f2, acc2 := new(Float).SetInt(i).Float64()
+ if f != f2 || acc != acc2 {
+ t.Errorf("%s: got %f (%s); Float.Float64 gives %f (%s)", test.istr, f, acc, f2, acc2)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/intconv.go b/platform/dbops/binaries/go/go/src/math/big/intconv.go
new file mode 100644
index 0000000000000000000000000000000000000000..51e75ffc52b6f40c73cc3e87c4c055619b128e41
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/intconv.go
@@ -0,0 +1,255 @@
+// 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 int-to-string conversion functions.
+
+package big
+
+import (
+ "errors"
+ "fmt"
+ "io"
+)
+
+// Text returns the string representation of x in the given base.
+// Base must be between 2 and 62, inclusive. The result uses the
+// lower-case letters 'a' to 'z' for digit values 10 to 35, and
+// the upper-case letters 'A' to 'Z' for digit values 36 to 61.
+// No prefix (such as "0x") is added to the string. If x is a nil
+// pointer it returns "".
+func (x *Int) Text(base int) string {
+ if x == nil {
+ return ""
+ }
+ return string(x.abs.itoa(x.neg, base))
+}
+
+// Append appends the string representation of x, as generated by
+// x.Text(base), to buf and returns the extended buffer.
+func (x *Int) Append(buf []byte, base int) []byte {
+ if x == nil {
+ return append(buf, ""...)
+ }
+ return append(buf, x.abs.itoa(x.neg, base)...)
+}
+
+// String returns the decimal representation of x as generated by
+// x.Text(10).
+func (x *Int) String() string {
+ return x.Text(10)
+}
+
+// write count copies of text to s.
+func writeMultiple(s fmt.State, text string, count int) {
+ if len(text) > 0 {
+ b := []byte(text)
+ for ; count > 0; count-- {
+ s.Write(b)
+ }
+ }
+}
+
+var _ fmt.Formatter = intOne // *Int must implement fmt.Formatter
+
+// Format implements [fmt.Formatter]. It accepts the formats
+// 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
+// 'd' (decimal), 'x' (lowercase hexadecimal), and
+// 'X' (uppercase hexadecimal).
+// Also supported are the full suite of package fmt's format
+// flags for integral types, including '+' and ' ' for sign
+// control, '#' for leading zero in octal and for hexadecimal,
+// a leading "0x" or "0X" for "%#x" and "%#X" respectively,
+// specification of minimum digits precision, output field
+// width, space or zero padding, and '-' for left or right
+// justification.
+func (x *Int) Format(s fmt.State, ch rune) {
+ // determine base
+ var base int
+ switch ch {
+ case 'b':
+ base = 2
+ case 'o', 'O':
+ base = 8
+ case 'd', 's', 'v':
+ base = 10
+ case 'x', 'X':
+ base = 16
+ default:
+ // unknown format
+ fmt.Fprintf(s, "%%!%c(big.Int=%s)", ch, x.String())
+ return
+ }
+
+ if x == nil {
+ fmt.Fprint(s, "")
+ return
+ }
+
+ // determine sign character
+ sign := ""
+ switch {
+ case x.neg:
+ sign = "-"
+ case s.Flag('+'): // supersedes ' ' when both specified
+ sign = "+"
+ case s.Flag(' '):
+ sign = " "
+ }
+
+ // determine prefix characters for indicating output base
+ prefix := ""
+ if s.Flag('#') {
+ switch ch {
+ case 'b': // binary
+ prefix = "0b"
+ case 'o': // octal
+ prefix = "0"
+ case 'x': // hexadecimal
+ prefix = "0x"
+ case 'X':
+ prefix = "0X"
+ }
+ }
+ if ch == 'O' {
+ prefix = "0o"
+ }
+
+ digits := x.abs.utoa(base)
+ if ch == 'X' {
+ // faster than bytes.ToUpper
+ for i, d := range digits {
+ if 'a' <= d && d <= 'z' {
+ digits[i] = 'A' + (d - 'a')
+ }
+ }
+ }
+
+ // number of characters for the three classes of number padding
+ var left int // space characters to left of digits for right justification ("%8d")
+ var zeros int // zero characters (actually cs[0]) as left-most digits ("%.8d")
+ var right int // space characters to right of digits for left justification ("%-8d")
+
+ // determine number padding from precision: the least number of digits to output
+ precision, precisionSet := s.Precision()
+ if precisionSet {
+ switch {
+ case len(digits) < precision:
+ zeros = precision - len(digits) // count of zero padding
+ case len(digits) == 1 && digits[0] == '0' && precision == 0:
+ return // print nothing if zero value (x == 0) and zero precision ("." or ".0")
+ }
+ }
+
+ // determine field pad from width: the least number of characters to output
+ length := len(sign) + len(prefix) + zeros + len(digits)
+ if width, widthSet := s.Width(); widthSet && length < width { // pad as specified
+ switch d := width - length; {
+ case s.Flag('-'):
+ // pad on the right with spaces; supersedes '0' when both specified
+ right = d
+ case s.Flag('0') && !precisionSet:
+ // pad with zeros unless precision also specified
+ zeros = d
+ default:
+ // pad on the left with spaces
+ left = d
+ }
+ }
+
+ // print number as [left pad][sign][prefix][zero pad][digits][right pad]
+ writeMultiple(s, " ", left)
+ writeMultiple(s, sign, 1)
+ writeMultiple(s, prefix, 1)
+ writeMultiple(s, "0", zeros)
+ s.Write(digits)
+ writeMultiple(s, " ", right)
+}
+
+// scan sets z to the integer value corresponding to the longest possible prefix
+// read from r representing a signed integer number in a given conversion base.
+// It returns z, the actual conversion base used, and an error, if any. In the
+// error case, the value of z is undefined but the returned value is nil. The
+// syntax follows the syntax of integer literals in Go.
+//
+// The base argument must be 0 or a value from 2 through MaxBase. If the base
+// is 0, the string prefix determines the actual conversion base. A prefix of
+// “0b” or “0B” selects base 2; a “0”, “0o”, or “0O” prefix selects
+// base 8, and a “0x” or “0X” prefix selects base 16. Otherwise the selected
+// base is 10.
+func (z *Int) scan(r io.ByteScanner, base int) (*Int, int, error) {
+ // determine sign
+ neg, err := scanSign(r)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ // determine mantissa
+ z.abs, base, _, err = z.abs.scan(r, base, false)
+ if err != nil {
+ return nil, base, err
+ }
+ z.neg = len(z.abs) > 0 && neg // 0 has no sign
+
+ return z, base, nil
+}
+
+func scanSign(r io.ByteScanner) (neg bool, err error) {
+ var ch byte
+ if ch, err = r.ReadByte(); err != nil {
+ return false, err
+ }
+ switch ch {
+ case '-':
+ neg = true
+ case '+':
+ // nothing to do
+ default:
+ r.UnreadByte()
+ }
+ return
+}
+
+// byteReader is a local wrapper around fmt.ScanState;
+// it implements the ByteReader interface.
+type byteReader struct {
+ fmt.ScanState
+}
+
+func (r byteReader) ReadByte() (byte, error) {
+ ch, size, err := r.ReadRune()
+ if size != 1 && err == nil {
+ err = fmt.Errorf("invalid rune %#U", ch)
+ }
+ return byte(ch), err
+}
+
+func (r byteReader) UnreadByte() error {
+ return r.UnreadRune()
+}
+
+var _ fmt.Scanner = intOne // *Int must implement fmt.Scanner
+
+// Scan is a support routine for [fmt.Scanner]; it sets z to the value of
+// the scanned number. It accepts the formats 'b' (binary), 'o' (octal),
+// 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
+func (z *Int) Scan(s fmt.ScanState, ch rune) error {
+ s.SkipSpace() // skip leading space characters
+ base := 0
+ switch ch {
+ case 'b':
+ base = 2
+ case 'o':
+ base = 8
+ case 'd':
+ base = 10
+ case 'x', 'X':
+ base = 16
+ case 's', 'v':
+ // let scan determine the base
+ default:
+ return errors.New("Int.Scan: invalid verb")
+ }
+ _, _, err := z.scan(byteReader{s}, base)
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/intconv_test.go b/platform/dbops/binaries/go/go/src/math/big/intconv_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5ba29263a6e0a9b6ab39e712c30800fb14b38011
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/intconv_test.go
@@ -0,0 +1,431 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+)
+
+var stringTests = []struct {
+ in string
+ out string
+ base int
+ val int64
+ ok bool
+}{
+ // invalid inputs
+ {in: ""},
+ {in: "a"},
+ {in: "z"},
+ {in: "+"},
+ {in: "-"},
+ {in: "0b"},
+ {in: "0o"},
+ {in: "0x"},
+ {in: "0y"},
+ {in: "2", base: 2},
+ {in: "0b2", base: 0},
+ {in: "08"},
+ {in: "8", base: 8},
+ {in: "0xg", base: 0},
+ {in: "g", base: 16},
+
+ // invalid inputs with separators
+ // (smoke tests only - a comprehensive set of tests is in natconv_test.go)
+ {in: "_"},
+ {in: "0_"},
+ {in: "_0"},
+ {in: "-1__0"},
+ {in: "0x10_"},
+ {in: "1_000", base: 10}, // separators are not permitted for bases != 0
+ {in: "d_e_a_d", base: 16},
+
+ // valid inputs
+ {"0", "0", 0, 0, true},
+ {"0", "0", 10, 0, true},
+ {"0", "0", 16, 0, true},
+ {"+0", "0", 0, 0, true},
+ {"-0", "0", 0, 0, true},
+ {"10", "10", 0, 10, true},
+ {"10", "10", 10, 10, true},
+ {"10", "10", 16, 16, true},
+ {"-10", "-10", 16, -16, true},
+ {"+10", "10", 16, 16, true},
+ {"0b10", "2", 0, 2, true},
+ {"0o10", "8", 0, 8, true},
+ {"0x10", "16", 0, 16, true},
+ {in: "0x10", base: 16},
+ {"-0x10", "-16", 0, -16, true},
+ {"+0x10", "16", 0, 16, true},
+ {"00", "0", 0, 0, true},
+ {"0", "0", 8, 0, true},
+ {"07", "7", 0, 7, true},
+ {"7", "7", 8, 7, true},
+ {"023", "19", 0, 19, true},
+ {"23", "23", 8, 19, true},
+ {"cafebabe", "cafebabe", 16, 0xcafebabe, true},
+ {"0b0", "0", 0, 0, true},
+ {"-111", "-111", 2, -7, true},
+ {"-0b111", "-7", 0, -7, true},
+ {"0b1001010111", "599", 0, 0x257, true},
+ {"1001010111", "1001010111", 2, 0x257, true},
+ {"A", "a", 36, 10, true},
+ {"A", "A", 37, 36, true},
+ {"ABCXYZ", "abcxyz", 36, 623741435, true},
+ {"ABCXYZ", "ABCXYZ", 62, 33536793425, true},
+
+ // valid input with separators
+ // (smoke tests only - a comprehensive set of tests is in natconv_test.go)
+ {"1_000", "1000", 0, 1000, true},
+ {"0b_1010", "10", 0, 10, true},
+ {"+0o_660", "432", 0, 0660, true},
+ {"-0xF00D_1E", "-15731998", 0, -0xf00d1e, true},
+}
+
+func TestIntText(t *testing.T) {
+ z := new(Int)
+ for _, test := range stringTests {
+ if !test.ok {
+ continue
+ }
+
+ _, ok := z.SetString(test.in, test.base)
+ if !ok {
+ t.Errorf("%v: failed to parse", test)
+ continue
+ }
+
+ base := test.base
+ if base == 0 {
+ base = 10
+ }
+
+ if got := z.Text(base); got != test.out {
+ t.Errorf("%v: got %s; want %s", test, got, test.out)
+ }
+ }
+}
+
+func TestAppendText(t *testing.T) {
+ z := new(Int)
+ var buf []byte
+ for _, test := range stringTests {
+ if !test.ok {
+ continue
+ }
+
+ _, ok := z.SetString(test.in, test.base)
+ if !ok {
+ t.Errorf("%v: failed to parse", test)
+ continue
+ }
+
+ base := test.base
+ if base == 0 {
+ base = 10
+ }
+
+ i := len(buf)
+ buf = z.Append(buf, base)
+ if got := string(buf[i:]); got != test.out {
+ t.Errorf("%v: got %s; want %s", test, got, test.out)
+ }
+ }
+}
+
+func format(base int) string {
+ switch base {
+ case 2:
+ return "%b"
+ case 8:
+ return "%o"
+ case 16:
+ return "%x"
+ }
+ return "%d"
+}
+
+func TestGetString(t *testing.T) {
+ z := new(Int)
+ for i, test := range stringTests {
+ if !test.ok {
+ continue
+ }
+ z.SetInt64(test.val)
+
+ if test.base == 10 {
+ if got := z.String(); got != test.out {
+ t.Errorf("#%da got %s; want %s", i, got, test.out)
+ }
+ }
+
+ f := format(test.base)
+ got := fmt.Sprintf(f, z)
+ if f == "%d" {
+ if got != fmt.Sprintf("%d", test.val) {
+ t.Errorf("#%db got %s; want %d", i, got, test.val)
+ }
+ } else {
+ if got != test.out {
+ t.Errorf("#%dc got %s; want %s", i, got, test.out)
+ }
+ }
+ }
+}
+
+func TestSetString(t *testing.T) {
+ tmp := new(Int)
+ for i, test := range stringTests {
+ // initialize to a non-zero value so that issues with parsing
+ // 0 are detected
+ tmp.SetInt64(1234567890)
+ n1, ok1 := new(Int).SetString(test.in, test.base)
+ n2, ok2 := tmp.SetString(test.in, test.base)
+ expected := NewInt(test.val)
+ if ok1 != test.ok || ok2 != test.ok {
+ t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
+ continue
+ }
+ if !ok1 {
+ if n1 != nil {
+ t.Errorf("#%d (input '%s') n1 != nil", i, test.in)
+ }
+ continue
+ }
+ if !ok2 {
+ if n2 != nil {
+ t.Errorf("#%d (input '%s') n2 != nil", i, test.in)
+ }
+ continue
+ }
+
+ if ok1 && !isNormalized(n1) {
+ t.Errorf("#%d (input '%s'): %v is not normalized", i, test.in, *n1)
+ }
+ if ok2 && !isNormalized(n2) {
+ t.Errorf("#%d (input '%s'): %v is not normalized", i, test.in, *n2)
+ }
+
+ if n1.Cmp(expected) != 0 {
+ t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
+ }
+ if n2.Cmp(expected) != 0 {
+ t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
+ }
+ }
+}
+
+var formatTests = []struct {
+ input string
+ format string
+ output string
+}{
+ {"", "%x", ""},
+ {"", "%#x", ""},
+ {"", "%#y", "%!y(big.Int=)"},
+
+ {"10", "%b", "1010"},
+ {"10", "%o", "12"},
+ {"10", "%d", "10"},
+ {"10", "%v", "10"},
+ {"10", "%x", "a"},
+ {"10", "%X", "A"},
+ {"-10", "%X", "-A"},
+ {"10", "%y", "%!y(big.Int=10)"},
+ {"-10", "%y", "%!y(big.Int=-10)"},
+
+ {"10", "%#b", "0b1010"},
+ {"10", "%#o", "012"},
+ {"10", "%O", "0o12"},
+ {"-10", "%#b", "-0b1010"},
+ {"-10", "%#o", "-012"},
+ {"-10", "%O", "-0o12"},
+ {"10", "%#d", "10"},
+ {"10", "%#v", "10"},
+ {"10", "%#x", "0xa"},
+ {"10", "%#X", "0XA"},
+ {"-10", "%#X", "-0XA"},
+ {"10", "%#y", "%!y(big.Int=10)"},
+ {"-10", "%#y", "%!y(big.Int=-10)"},
+
+ {"1234", "%d", "1234"},
+ {"1234", "%3d", "1234"},
+ {"1234", "%4d", "1234"},
+ {"-1234", "%d", "-1234"},
+ {"1234", "% 5d", " 1234"},
+ {"1234", "%+5d", "+1234"},
+ {"1234", "%-5d", "1234 "},
+ {"1234", "%x", "4d2"},
+ {"1234", "%X", "4D2"},
+ {"-1234", "%3x", "-4d2"},
+ {"-1234", "%4x", "-4d2"},
+ {"-1234", "%5x", " -4d2"},
+ {"-1234", "%-5x", "-4d2 "},
+ {"1234", "%03d", "1234"},
+ {"1234", "%04d", "1234"},
+ {"1234", "%05d", "01234"},
+ {"1234", "%06d", "001234"},
+ {"-1234", "%06d", "-01234"},
+ {"1234", "%+06d", "+01234"},
+ {"1234", "% 06d", " 01234"},
+ {"1234", "%-6d", "1234 "},
+ {"1234", "%-06d", "1234 "},
+ {"-1234", "%-06d", "-1234 "},
+
+ {"1234", "%.3d", "1234"},
+ {"1234", "%.4d", "1234"},
+ {"1234", "%.5d", "01234"},
+ {"1234", "%.6d", "001234"},
+ {"-1234", "%.3d", "-1234"},
+ {"-1234", "%.4d", "-1234"},
+ {"-1234", "%.5d", "-01234"},
+ {"-1234", "%.6d", "-001234"},
+
+ {"1234", "%8.3d", " 1234"},
+ {"1234", "%8.4d", " 1234"},
+ {"1234", "%8.5d", " 01234"},
+ {"1234", "%8.6d", " 001234"},
+ {"-1234", "%8.3d", " -1234"},
+ {"-1234", "%8.4d", " -1234"},
+ {"-1234", "%8.5d", " -01234"},
+ {"-1234", "%8.6d", " -001234"},
+
+ {"1234", "%+8.3d", " +1234"},
+ {"1234", "%+8.4d", " +1234"},
+ {"1234", "%+8.5d", " +01234"},
+ {"1234", "%+8.6d", " +001234"},
+ {"-1234", "%+8.3d", " -1234"},
+ {"-1234", "%+8.4d", " -1234"},
+ {"-1234", "%+8.5d", " -01234"},
+ {"-1234", "%+8.6d", " -001234"},
+
+ {"1234", "% 8.3d", " 1234"},
+ {"1234", "% 8.4d", " 1234"},
+ {"1234", "% 8.5d", " 01234"},
+ {"1234", "% 8.6d", " 001234"},
+ {"-1234", "% 8.3d", " -1234"},
+ {"-1234", "% 8.4d", " -1234"},
+ {"-1234", "% 8.5d", " -01234"},
+ {"-1234", "% 8.6d", " -001234"},
+
+ {"1234", "%.3x", "4d2"},
+ {"1234", "%.4x", "04d2"},
+ {"1234", "%.5x", "004d2"},
+ {"1234", "%.6x", "0004d2"},
+ {"-1234", "%.3x", "-4d2"},
+ {"-1234", "%.4x", "-04d2"},
+ {"-1234", "%.5x", "-004d2"},
+ {"-1234", "%.6x", "-0004d2"},
+
+ {"1234", "%8.3x", " 4d2"},
+ {"1234", "%8.4x", " 04d2"},
+ {"1234", "%8.5x", " 004d2"},
+ {"1234", "%8.6x", " 0004d2"},
+ {"-1234", "%8.3x", " -4d2"},
+ {"-1234", "%8.4x", " -04d2"},
+ {"-1234", "%8.5x", " -004d2"},
+ {"-1234", "%8.6x", " -0004d2"},
+
+ {"1234", "%+8.3x", " +4d2"},
+ {"1234", "%+8.4x", " +04d2"},
+ {"1234", "%+8.5x", " +004d2"},
+ {"1234", "%+8.6x", " +0004d2"},
+ {"-1234", "%+8.3x", " -4d2"},
+ {"-1234", "%+8.4x", " -04d2"},
+ {"-1234", "%+8.5x", " -004d2"},
+ {"-1234", "%+8.6x", " -0004d2"},
+
+ {"1234", "% 8.3x", " 4d2"},
+ {"1234", "% 8.4x", " 04d2"},
+ {"1234", "% 8.5x", " 004d2"},
+ {"1234", "% 8.6x", " 0004d2"},
+ {"1234", "% 8.7x", " 00004d2"},
+ {"1234", "% 8.8x", " 000004d2"},
+ {"-1234", "% 8.3x", " -4d2"},
+ {"-1234", "% 8.4x", " -04d2"},
+ {"-1234", "% 8.5x", " -004d2"},
+ {"-1234", "% 8.6x", " -0004d2"},
+ {"-1234", "% 8.7x", "-00004d2"},
+ {"-1234", "% 8.8x", "-000004d2"},
+
+ {"1234", "%-8.3d", "1234 "},
+ {"1234", "%-8.4d", "1234 "},
+ {"1234", "%-8.5d", "01234 "},
+ {"1234", "%-8.6d", "001234 "},
+ {"1234", "%-8.7d", "0001234 "},
+ {"1234", "%-8.8d", "00001234"},
+ {"-1234", "%-8.3d", "-1234 "},
+ {"-1234", "%-8.4d", "-1234 "},
+ {"-1234", "%-8.5d", "-01234 "},
+ {"-1234", "%-8.6d", "-001234 "},
+ {"-1234", "%-8.7d", "-0001234"},
+ {"-1234", "%-8.8d", "-00001234"},
+
+ {"16777215", "%b", "111111111111111111111111"}, // 2**24 - 1
+
+ {"0", "%.d", ""},
+ {"0", "%.0d", ""},
+ {"0", "%3.d", ""},
+}
+
+func TestFormat(t *testing.T) {
+ for i, test := range formatTests {
+ var x *Int
+ if test.input != "" {
+ var ok bool
+ x, ok = new(Int).SetString(test.input, 0)
+ if !ok {
+ t.Errorf("#%d failed reading input %s", i, test.input)
+ }
+ }
+ output := fmt.Sprintf(test.format, x)
+ if output != test.output {
+ t.Errorf("#%d got %q; want %q, {%q, %q, %q}", i, output, test.output, test.input, test.format, test.output)
+ }
+ }
+}
+
+var scanTests = []struct {
+ input string
+ format string
+ output string
+ remaining int
+}{
+ {"1010", "%b", "10", 0},
+ {"0b1010", "%v", "10", 0},
+ {"12", "%o", "10", 0},
+ {"012", "%v", "10", 0},
+ {"10", "%d", "10", 0},
+ {"10", "%v", "10", 0},
+ {"a", "%x", "10", 0},
+ {"0xa", "%v", "10", 0},
+ {"A", "%X", "10", 0},
+ {"-A", "%X", "-10", 0},
+ {"+0b1011001", "%v", "89", 0},
+ {"0xA", "%v", "10", 0},
+ {"0 ", "%v", "0", 1},
+ {"2+3", "%v", "2", 2},
+ {"0XABC 12", "%v", "2748", 3},
+}
+
+func TestScan(t *testing.T) {
+ var buf bytes.Buffer
+ for i, test := range scanTests {
+ x := new(Int)
+ buf.Reset()
+ buf.WriteString(test.input)
+ if _, err := fmt.Fscanf(&buf, test.format, x); err != nil {
+ t.Errorf("#%d error: %s", i, err)
+ }
+ if x.String() != test.output {
+ t.Errorf("#%d got %s; want %s", i, x.String(), test.output)
+ }
+ if buf.Len() != test.remaining {
+ t.Errorf("#%d got %d bytes remaining; want %d", i, buf.Len(), test.remaining)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/intmarsh.go b/platform/dbops/binaries/go/go/src/math/big/intmarsh.go
new file mode 100644
index 0000000000000000000000000000000000000000..56eeefb884d8c26f77509b2f8898c3f45f574365
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/intmarsh.go
@@ -0,0 +1,83 @@
+// 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 encoding/decoding of Ints.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+)
+
+// Gob codec version. Permits backward-compatible changes to the encoding.
+const intGobVersion byte = 1
+
+// GobEncode implements the [encoding/gob.GobEncoder] interface.
+func (x *Int) GobEncode() ([]byte, error) {
+ if x == nil {
+ return nil, nil
+ }
+ buf := make([]byte, 1+len(x.abs)*_S) // extra byte for version and sign bit
+ i := x.abs.bytes(buf) - 1 // i >= 0
+ b := intGobVersion << 1 // make space for sign bit
+ if x.neg {
+ b |= 1
+ }
+ buf[i] = b
+ return buf[i:], nil
+}
+
+// GobDecode implements the [encoding/gob.GobDecoder] interface.
+func (z *Int) GobDecode(buf []byte) error {
+ if len(buf) == 0 {
+ // Other side sent a nil or default value.
+ *z = Int{}
+ return nil
+ }
+ b := buf[0]
+ if b>>1 != intGobVersion {
+ return fmt.Errorf("Int.GobDecode: encoding version %d not supported", b>>1)
+ }
+ z.neg = b&1 != 0
+ z.abs = z.abs.setBytes(buf[1:])
+ return nil
+}
+
+// MarshalText implements the [encoding.TextMarshaler] interface.
+func (x *Int) MarshalText() (text []byte, err error) {
+ if x == nil {
+ return []byte(""), nil
+ }
+ return x.abs.itoa(x.neg, 10), nil
+}
+
+// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
+func (z *Int) UnmarshalText(text []byte) error {
+ if _, ok := z.setFromScanner(bytes.NewReader(text), 0); !ok {
+ return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Int", text)
+ }
+ return nil
+}
+
+// The JSON marshalers are only here for API backward compatibility
+// (programs that explicitly look for these two methods). JSON works
+// fine with the TextMarshaler only.
+
+// MarshalJSON implements the [encoding/json.Marshaler] interface.
+func (x *Int) MarshalJSON() ([]byte, error) {
+ if x == nil {
+ return []byte("null"), nil
+ }
+ return x.abs.itoa(x.neg, 10), nil
+}
+
+// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface.
+func (z *Int) UnmarshalJSON(text []byte) error {
+ // Ignore null, like in the main JSON package.
+ if string(text) == "null" {
+ return nil
+ }
+ return z.UnmarshalText(text)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/intmarsh_test.go b/platform/dbops/binaries/go/go/src/math/big/intmarsh_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e7d29f9ddc71994f81195707b63acc34be2cd32
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/intmarsh_test.go
@@ -0,0 +1,134 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "encoding/gob"
+ "encoding/json"
+ "encoding/xml"
+ "testing"
+)
+
+var encodingTests = []string{
+ "0",
+ "1",
+ "2",
+ "10",
+ "1000",
+ "1234567890",
+ "298472983472983471903246121093472394872319615612417471234712061",
+}
+
+func TestIntGobEncoding(t *testing.T) {
+ var medium bytes.Buffer
+ enc := gob.NewEncoder(&medium)
+ dec := gob.NewDecoder(&medium)
+ for _, test := range encodingTests {
+ for _, sign := range []string{"", "+", "-"} {
+ x := sign + test
+ medium.Reset() // empty buffer for each test case (in case of failures)
+ var tx Int
+ tx.SetString(x, 10)
+ if err := enc.Encode(&tx); err != nil {
+ t.Errorf("encoding of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Int
+ if err := dec.Decode(&rx); err != nil {
+ t.Errorf("decoding of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("transmission of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+ }
+}
+
+// Sending a nil Int pointer (inside a slice) on a round trip through gob should yield a zero.
+// TODO: top-level nils.
+func TestGobEncodingNilIntInSlice(t *testing.T) {
+ buf := new(bytes.Buffer)
+ enc := gob.NewEncoder(buf)
+ dec := gob.NewDecoder(buf)
+
+ var in = make([]*Int, 1)
+ err := enc.Encode(&in)
+ if err != nil {
+ t.Errorf("gob encode failed: %q", err)
+ }
+ var out []*Int
+ err = dec.Decode(&out)
+ if err != nil {
+ t.Fatalf("gob decode failed: %q", err)
+ }
+ if len(out) != 1 {
+ t.Fatalf("wrong len; want 1 got %d", len(out))
+ }
+ var zero Int
+ if out[0].Cmp(&zero) != 0 {
+ t.Fatalf("transmission of (*Int)(nil) failed: got %s want 0", out)
+ }
+}
+
+func TestIntJSONEncoding(t *testing.T) {
+ for _, test := range encodingTests {
+ for _, sign := range []string{"", "+", "-"} {
+ x := sign + test
+ var tx Int
+ tx.SetString(x, 10)
+ b, err := json.Marshal(&tx)
+ if err != nil {
+ t.Errorf("marshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Int
+ if err := json.Unmarshal(b, &rx); err != nil {
+ t.Errorf("unmarshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("JSON encoding of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+ }
+}
+
+func TestIntJSONEncodingNil(t *testing.T) {
+ var x *Int
+ b, err := x.MarshalJSON()
+ if err != nil {
+ t.Fatalf("marshaling of nil failed: %s", err)
+ }
+ got := string(b)
+ want := "null"
+ if got != want {
+ t.Fatalf("marshaling of nil failed: got %s want %s", got, want)
+ }
+}
+
+func TestIntXMLEncoding(t *testing.T) {
+ for _, test := range encodingTests {
+ for _, sign := range []string{"", "+", "-"} {
+ x := sign + test
+ var tx Int
+ tx.SetString(x, 0)
+ b, err := xml.Marshal(&tx)
+ if err != nil {
+ t.Errorf("marshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Int
+ if err := xml.Unmarshal(b, &rx); err != nil {
+ t.Errorf("unmarshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("XML encoding of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/link_test.go b/platform/dbops/binaries/go/go/src/math/big/link_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6e33aa5e5e571bad8ba11f8928e86b1056ca64df
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/link_test.go
@@ -0,0 +1,63 @@
+// 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 big
+
+import (
+ "bytes"
+ "internal/testenv"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+// Tests that the linker is able to remove references to Float, Rat,
+// and Int if unused (notably, not used by init).
+func TestLinkerGC(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping in short mode")
+ }
+ t.Parallel()
+ tmp := t.TempDir()
+ goBin := testenv.GoToolPath(t)
+ goFile := filepath.Join(tmp, "x.go")
+ file := []byte(`package main
+import _ "math/big"
+func main() {}
+`)
+ if err := os.WriteFile(goFile, file, 0644); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(goBin, "build", "-o", "x.exe", "x.go")
+ cmd.Dir = tmp
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("compile: %v, %s", err, out)
+ }
+
+ cmd = exec.Command(goBin, "tool", "nm", "x.exe")
+ cmd.Dir = tmp
+ nm, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("nm: %v, %s", err, nm)
+ }
+ const want = "runtime.main"
+ if !bytes.Contains(nm, []byte(want)) {
+ // Test the test.
+ t.Errorf("expected symbol %q not found", want)
+ }
+ bad := []string{
+ "math/big.(*Float)",
+ "math/big.(*Rat)",
+ "math/big.(*Int)",
+ }
+ for _, sym := range bad {
+ if bytes.Contains(nm, []byte(sym)) {
+ t.Errorf("unexpected symbol %q found", sym)
+ }
+ }
+ if t.Failed() {
+ t.Logf("Got: %s", nm)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/nat.go b/platform/dbops/binaries/go/go/src/math/big/nat.go
new file mode 100644
index 0000000000000000000000000000000000000000..ecb7d363d4fb368915eb64a857e53253e304e266
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/nat.go
@@ -0,0 +1,1422 @@
+// 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.
+
+// This file implements unsigned multi-precision integers (natural
+// numbers). They are the building blocks for the implementation
+// of signed integers, rationals, and floating-point numbers.
+//
+// Caution: This implementation relies on the function "alias"
+// which assumes that (nat) slice capacities are never
+// changed (no 3-operand slice expressions). If that
+// changes, alias needs to be updated for correctness.
+
+package big
+
+import (
+ "encoding/binary"
+ "math/bits"
+ "math/rand"
+ "sync"
+)
+
+// An unsigned integer x of the form
+//
+// x = x[n-1]*_B^(n-1) + x[n-2]*_B^(n-2) + ... + x[1]*_B + x[0]
+//
+// with 0 <= x[i] < _B and 0 <= i < n is stored in a slice of length n,
+// with the digits x[i] as the slice elements.
+//
+// A number is normalized if the slice contains no leading 0 digits.
+// During arithmetic operations, denormalized values may occur but are
+// always normalized before returning the final result. The normalized
+// representation of 0 is the empty or nil slice (length = 0).
+type nat []Word
+
+var (
+ natOne = nat{1}
+ natTwo = nat{2}
+ natFive = nat{5}
+ natTen = nat{10}
+)
+
+func (z nat) String() string {
+ return "0x" + string(z.itoa(false, 16))
+}
+
+func (z nat) clear() {
+ for i := range z {
+ z[i] = 0
+ }
+}
+
+func (z nat) norm() nat {
+ i := len(z)
+ for i > 0 && z[i-1] == 0 {
+ i--
+ }
+ return z[0:i]
+}
+
+func (z nat) make(n int) nat {
+ if n <= cap(z) {
+ return z[:n] // reuse z
+ }
+ if n == 1 {
+ // Most nats start small and stay that way; don't over-allocate.
+ return make(nat, 1)
+ }
+ // Choosing a good value for e has significant performance impact
+ // because it increases the chance that a value can be reused.
+ const e = 4 // extra capacity
+ return make(nat, n, n+e)
+}
+
+func (z nat) setWord(x Word) nat {
+ if x == 0 {
+ return z[:0]
+ }
+ z = z.make(1)
+ z[0] = x
+ return z
+}
+
+func (z nat) setUint64(x uint64) nat {
+ // single-word value
+ if w := Word(x); uint64(w) == x {
+ return z.setWord(w)
+ }
+ // 2-word value
+ z = z.make(2)
+ z[1] = Word(x >> 32)
+ z[0] = Word(x)
+ return z
+}
+
+func (z nat) set(x nat) nat {
+ z = z.make(len(x))
+ copy(z, x)
+ return z
+}
+
+func (z nat) add(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+
+ switch {
+ case m < n:
+ return z.add(y, x)
+ case m == 0:
+ // n == 0 because m >= n; result is 0
+ return z[:0]
+ case n == 0:
+ // result is x
+ return z.set(x)
+ }
+ // m > 0
+
+ z = z.make(m + 1)
+ c := addVV(z[0:n], x, y)
+ if m > n {
+ c = addVW(z[n:m], x[n:], c)
+ }
+ z[m] = c
+
+ return z.norm()
+}
+
+func (z nat) sub(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+
+ switch {
+ case m < n:
+ panic("underflow")
+ case m == 0:
+ // n == 0 because m >= n; result is 0
+ return z[:0]
+ case n == 0:
+ // result is x
+ return z.set(x)
+ }
+ // m > 0
+
+ z = z.make(m)
+ c := subVV(z[0:n], x, y)
+ if m > n {
+ c = subVW(z[n:], x[n:], c)
+ }
+ if c != 0 {
+ panic("underflow")
+ }
+
+ return z.norm()
+}
+
+func (x nat) cmp(y nat) (r int) {
+ m := len(x)
+ n := len(y)
+ if m != n || m == 0 {
+ switch {
+ case m < n:
+ r = -1
+ case m > n:
+ r = 1
+ }
+ return
+ }
+
+ i := m - 1
+ for i > 0 && x[i] == y[i] {
+ i--
+ }
+
+ switch {
+ case x[i] < y[i]:
+ r = -1
+ case x[i] > y[i]:
+ r = 1
+ }
+ return
+}
+
+func (z nat) mulAddWW(x nat, y, r Word) nat {
+ m := len(x)
+ if m == 0 || y == 0 {
+ return z.setWord(r) // result is r
+ }
+ // m > 0
+
+ z = z.make(m + 1)
+ z[m] = mulAddVWW(z[0:m], x, y, r)
+
+ return z.norm()
+}
+
+// basicMul multiplies x and y and leaves the result in z.
+// The (non-normalized) result is placed in z[0 : len(x) + len(y)].
+func basicMul(z, x, y nat) {
+ z[0 : len(x)+len(y)].clear() // initialize z
+ for i, d := range y {
+ if d != 0 {
+ z[len(x)+i] = addMulVVW(z[i:i+len(x)], x, d)
+ }
+ }
+}
+
+// montgomery computes z mod m = x*y*2**(-n*_W) mod m,
+// assuming k = -1/m mod 2**_W.
+// z is used for storing the result which is returned;
+// z must not alias x, y or m.
+// See Gueron, "Efficient Software Implementations of Modular Exponentiation".
+// https://eprint.iacr.org/2011/239.pdf
+// In the terminology of that paper, this is an "Almost Montgomery Multiplication":
+// x and y are required to satisfy 0 <= z < 2**(n*_W) and then the result
+// z is guaranteed to satisfy 0 <= z < 2**(n*_W), but it may not be < m.
+func (z nat) montgomery(x, y, m nat, k Word, n int) nat {
+ // This code assumes x, y, m are all the same length, n.
+ // (required by addMulVVW and the for loop).
+ // It also assumes that x, y are already reduced mod m,
+ // or else the result will not be properly reduced.
+ if len(x) != n || len(y) != n || len(m) != n {
+ panic("math/big: mismatched montgomery number lengths")
+ }
+ z = z.make(n * 2)
+ z.clear()
+ var c Word
+ for i := 0; i < n; i++ {
+ d := y[i]
+ c2 := addMulVVW(z[i:n+i], x, d)
+ t := z[i] * k
+ c3 := addMulVVW(z[i:n+i], m, t)
+ cx := c + c2
+ cy := cx + c3
+ z[n+i] = cy
+ if cx < c2 || cy < c3 {
+ c = 1
+ } else {
+ c = 0
+ }
+ }
+ if c != 0 {
+ subVV(z[:n], z[n:], m)
+ } else {
+ copy(z[:n], z[n:])
+ }
+ return z[:n]
+}
+
+// Fast version of z[0:n+n>>1].add(z[0:n+n>>1], x[0:n]) w/o bounds checks.
+// Factored out for readability - do not use outside karatsuba.
+func karatsubaAdd(z, x nat, n int) {
+ if c := addVV(z[0:n], z, x); c != 0 {
+ addVW(z[n:n+n>>1], z[n:], c)
+ }
+}
+
+// Like karatsubaAdd, but does subtract.
+func karatsubaSub(z, x nat, n int) {
+ if c := subVV(z[0:n], z, x); c != 0 {
+ subVW(z[n:n+n>>1], z[n:], c)
+ }
+}
+
+// Operands that are shorter than karatsubaThreshold are multiplied using
+// "grade school" multiplication; for longer operands the Karatsuba algorithm
+// is used.
+var karatsubaThreshold = 40 // computed by calibrate_test.go
+
+// karatsuba multiplies x and y and leaves the result in z.
+// Both x and y must have the same length n and n must be a
+// power of 2. The result vector z must have len(z) >= 6*n.
+// The (non-normalized) result is placed in z[0 : 2*n].
+func karatsuba(z, x, y nat) {
+ n := len(y)
+
+ // Switch to basic multiplication if numbers are odd or small.
+ // (n is always even if karatsubaThreshold is even, but be
+ // conservative)
+ if n&1 != 0 || n < karatsubaThreshold || n < 2 {
+ basicMul(z, x, y)
+ return
+ }
+ // n&1 == 0 && n >= karatsubaThreshold && n >= 2
+
+ // Karatsuba multiplication is based on the observation that
+ // for two numbers x and y with:
+ //
+ // x = x1*b + x0
+ // y = y1*b + y0
+ //
+ // the product x*y can be obtained with 3 products z2, z1, z0
+ // instead of 4:
+ //
+ // x*y = x1*y1*b*b + (x1*y0 + x0*y1)*b + x0*y0
+ // = z2*b*b + z1*b + z0
+ //
+ // with:
+ //
+ // xd = x1 - x0
+ // yd = y0 - y1
+ //
+ // z1 = xd*yd + z2 + z0
+ // = (x1-x0)*(y0 - y1) + z2 + z0
+ // = x1*y0 - x1*y1 - x0*y0 + x0*y1 + z2 + z0
+ // = x1*y0 - z2 - z0 + x0*y1 + z2 + z0
+ // = x1*y0 + x0*y1
+
+ // split x, y into "digits"
+ n2 := n >> 1 // n2 >= 1
+ x1, x0 := x[n2:], x[0:n2] // x = x1*b + y0
+ y1, y0 := y[n2:], y[0:n2] // y = y1*b + y0
+
+ // z is used for the result and temporary storage:
+ //
+ // 6*n 5*n 4*n 3*n 2*n 1*n 0*n
+ // z = [z2 copy|z0 copy| xd*yd | yd:xd | x1*y1 | x0*y0 ]
+ //
+ // For each recursive call of karatsuba, an unused slice of
+ // z is passed in that has (at least) half the length of the
+ // caller's z.
+
+ // compute z0 and z2 with the result "in place" in z
+ karatsuba(z, x0, y0) // z0 = x0*y0
+ karatsuba(z[n:], x1, y1) // z2 = x1*y1
+
+ // compute xd (or the negative value if underflow occurs)
+ s := 1 // sign of product xd*yd
+ xd := z[2*n : 2*n+n2]
+ if subVV(xd, x1, x0) != 0 { // x1-x0
+ s = -s
+ subVV(xd, x0, x1) // x0-x1
+ }
+
+ // compute yd (or the negative value if underflow occurs)
+ yd := z[2*n+n2 : 3*n]
+ if subVV(yd, y0, y1) != 0 { // y0-y1
+ s = -s
+ subVV(yd, y1, y0) // y1-y0
+ }
+
+ // p = (x1-x0)*(y0-y1) == x1*y0 - x1*y1 - x0*y0 + x0*y1 for s > 0
+ // p = (x0-x1)*(y0-y1) == x0*y0 - x0*y1 - x1*y0 + x1*y1 for s < 0
+ p := z[n*3:]
+ karatsuba(p, xd, yd)
+
+ // save original z2:z0
+ // (ok to use upper half of z since we're done recurring)
+ r := z[n*4:]
+ copy(r, z[:n*2])
+
+ // add up all partial products
+ //
+ // 2*n n 0
+ // z = [ z2 | z0 ]
+ // + [ z0 ]
+ // + [ z2 ]
+ // + [ p ]
+ //
+ karatsubaAdd(z[n2:], r, n)
+ karatsubaAdd(z[n2:], r[n:], n)
+ if s > 0 {
+ karatsubaAdd(z[n2:], p, n)
+ } else {
+ karatsubaSub(z[n2:], p, n)
+ }
+}
+
+// alias reports whether x and y share the same base array.
+//
+// Note: alias assumes that the capacity of underlying arrays
+// is never changed for nat values; i.e. that there are
+// no 3-operand slice expressions in this code (or worse,
+// reflect-based operations to the same effect).
+func alias(x, y nat) bool {
+ return cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]
+}
+
+// addAt implements z += x<<(_W*i); z must be long enough.
+// (we don't use nat.add because we need z to stay the same
+// slice, and we don't need to normalize z after each addition)
+func addAt(z, x nat, i int) {
+ if n := len(x); n > 0 {
+ if c := addVV(z[i:i+n], z[i:], x); c != 0 {
+ j := i + n
+ if j < len(z) {
+ addVW(z[j:], z[j:], c)
+ }
+ }
+ }
+}
+
+// karatsubaLen computes an approximation to the maximum k <= n such that
+// k = p<= 0. Thus, the
+// result is the largest number that can be divided repeatedly by 2 before
+// becoming about the value of threshold.
+func karatsubaLen(n, threshold int) int {
+ i := uint(0)
+ for n > threshold {
+ n >>= 1
+ i++
+ }
+ return n << i
+}
+
+func (z nat) mul(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+
+ switch {
+ case m < n:
+ return z.mul(y, x)
+ case m == 0 || n == 0:
+ return z[:0]
+ case n == 1:
+ return z.mulAddWW(x, y[0], 0)
+ }
+ // m >= n > 1
+
+ // determine if z can be reused
+ if alias(z, x) || alias(z, y) {
+ z = nil // z is an alias for x or y - cannot reuse
+ }
+
+ // use basic multiplication if the numbers are small
+ if n < karatsubaThreshold {
+ z = z.make(m + n)
+ basicMul(z, x, y)
+ return z.norm()
+ }
+ // m >= n && n >= karatsubaThreshold && n >= 2
+
+ // determine Karatsuba length k such that
+ //
+ // x = xh*b + x0 (0 <= x0 < b)
+ // y = yh*b + y0 (0 <= y0 < b)
+ // b = 1<<(_W*k) ("base" of digits xi, yi)
+ //
+ k := karatsubaLen(n, karatsubaThreshold)
+ // k <= n
+
+ // multiply x0 and y0 via Karatsuba
+ x0 := x[0:k] // x0 is not normalized
+ y0 := y[0:k] // y0 is not normalized
+ z = z.make(max(6*k, m+n)) // enough space for karatsuba of x0*y0 and full result of x*y
+ karatsuba(z, x0, y0)
+ z = z[0 : m+n] // z has final length but may be incomplete
+ z[2*k:].clear() // upper portion of z is garbage (and 2*k <= m+n since k <= n <= m)
+
+ // If xh != 0 or yh != 0, add the missing terms to z. For
+ //
+ // xh = xi*b^i + ... + x2*b^2 + x1*b (0 <= xi < b)
+ // yh = y1*b (0 <= y1 < b)
+ //
+ // the missing terms are
+ //
+ // x0*y1*b and xi*y0*b^i, xi*y1*b^(i+1) for i > 0
+ //
+ // since all the yi for i > 1 are 0 by choice of k: If any of them
+ // were > 0, then yh >= b^2 and thus y >= b^2. Then k' = k*2 would
+ // be a larger valid threshold contradicting the assumption about k.
+ //
+ if k < n || m != n {
+ tp := getNat(3 * k)
+ t := *tp
+
+ // add x0*y1*b
+ x0 := x0.norm()
+ y1 := y[k:] // y1 is normalized because y is
+ t = t.mul(x0, y1) // update t so we don't lose t's underlying array
+ addAt(z, t, k)
+
+ // add xi*y0< k {
+ xi = xi[:k]
+ }
+ xi = xi.norm()
+ t = t.mul(xi, y0)
+ addAt(z, t, i)
+ t = t.mul(xi, y1)
+ addAt(z, t, i+k)
+ }
+
+ putNat(tp)
+ }
+
+ return z.norm()
+}
+
+// basicSqr sets z = x*x and is asymptotically faster than basicMul
+// by about a factor of 2, but slower for small arguments due to overhead.
+// Requirements: len(x) > 0, len(z) == 2*len(x)
+// The (non-normalized) result is placed in z.
+func basicSqr(z, x nat) {
+ n := len(x)
+ tp := getNat(2 * n)
+ t := *tp // temporary variable to hold the products
+ t.clear()
+ z[1], z[0] = mulWW(x[0], x[0]) // the initial square
+ for i := 1; i < n; i++ {
+ d := x[i]
+ // z collects the squares x[i] * x[i]
+ z[2*i+1], z[2*i] = mulWW(d, d)
+ // t collects the products x[i] * x[j] where j < i
+ t[2*i] = addMulVVW(t[i:2*i], x[0:i], d)
+ }
+ t[2*n-1] = shlVU(t[1:2*n-1], t[1:2*n-1], 1) // double the j < i products
+ addVV(z, z, t) // combine the result
+ putNat(tp)
+}
+
+// karatsubaSqr squares x and leaves the result in z.
+// len(x) must be a power of 2 and len(z) >= 6*len(x).
+// The (non-normalized) result is placed in z[0 : 2*len(x)].
+//
+// The algorithm and the layout of z are the same as for karatsuba.
+func karatsubaSqr(z, x nat) {
+ n := len(x)
+
+ if n&1 != 0 || n < karatsubaSqrThreshold || n < 2 {
+ basicSqr(z[:2*n], x)
+ return
+ }
+
+ n2 := n >> 1
+ x1, x0 := x[n2:], x[0:n2]
+
+ karatsubaSqr(z, x0)
+ karatsubaSqr(z[n:], x1)
+
+ // s = sign(xd*yd) == -1 for xd != 0; s == 1 for xd == 0
+ xd := z[2*n : 2*n+n2]
+ if subVV(xd, x1, x0) != 0 {
+ subVV(xd, x0, x1)
+ }
+
+ p := z[n*3:]
+ karatsubaSqr(p, xd)
+
+ r := z[n*4:]
+ copy(r, z[:n*2])
+
+ karatsubaAdd(z[n2:], r, n)
+ karatsubaAdd(z[n2:], r[n:], n)
+ karatsubaSub(z[n2:], p, n) // s == -1 for p != 0; s == 1 for p == 0
+}
+
+// Operands that are shorter than basicSqrThreshold are squared using
+// "grade school" multiplication; for operands longer than karatsubaSqrThreshold
+// we use the Karatsuba algorithm optimized for x == y.
+var basicSqrThreshold = 20 // computed by calibrate_test.go
+var karatsubaSqrThreshold = 260 // computed by calibrate_test.go
+
+// z = x*x
+func (z nat) sqr(x nat) nat {
+ n := len(x)
+ switch {
+ case n == 0:
+ return z[:0]
+ case n == 1:
+ d := x[0]
+ z = z.make(2)
+ z[1], z[0] = mulWW(d, d)
+ return z.norm()
+ }
+
+ if alias(z, x) {
+ z = nil // z is an alias for x - cannot reuse
+ }
+
+ if n < basicSqrThreshold {
+ z = z.make(2 * n)
+ basicMul(z, x, x)
+ return z.norm()
+ }
+ if n < karatsubaSqrThreshold {
+ z = z.make(2 * n)
+ basicSqr(z, x)
+ return z.norm()
+ }
+
+ // Use Karatsuba multiplication optimized for x == y.
+ // The algorithm and layout of z are the same as for mul.
+
+ // z = (x1*b + x0)^2 = x1^2*b^2 + 2*x1*x0*b + x0^2
+
+ k := karatsubaLen(n, karatsubaSqrThreshold)
+
+ x0 := x[0:k]
+ z = z.make(max(6*k, 2*n))
+ karatsubaSqr(z, x0) // z = x0^2
+ z = z[0 : 2*n]
+ z[2*k:].clear()
+
+ if k < n {
+ tp := getNat(2 * k)
+ t := *tp
+ x0 := x0.norm()
+ x1 := x[k:]
+ t = t.mul(x0, x1)
+ addAt(z, t, k)
+ addAt(z, t, k) // z = 2*x1*x0*b + x0^2
+ t = t.sqr(x1)
+ addAt(z, t, 2*k) // z = x1^2*b^2 + 2*x1*x0*b + x0^2
+ putNat(tp)
+ }
+
+ return z.norm()
+}
+
+// mulRange computes the product of all the unsigned integers in the
+// range [a, b] inclusively. If a > b (empty range), the result is 1.
+func (z nat) mulRange(a, b uint64) nat {
+ switch {
+ case a == 0:
+ // cut long ranges short (optimization)
+ return z.setUint64(0)
+ case a > b:
+ return z.setUint64(1)
+ case a == b:
+ return z.setUint64(a)
+ case a+1 == b:
+ return z.mul(nat(nil).setUint64(a), nat(nil).setUint64(b))
+ }
+ m := a + (b-a)/2 // avoid overflow
+ return z.mul(nat(nil).mulRange(a, m), nat(nil).mulRange(m+1, b))
+}
+
+// getNat returns a *nat of len n. The contents may not be zero.
+// The pool holds *nat to avoid allocation when converting to interface{}.
+func getNat(n int) *nat {
+ var z *nat
+ if v := natPool.Get(); v != nil {
+ z = v.(*nat)
+ }
+ if z == nil {
+ z = new(nat)
+ }
+ *z = z.make(n)
+ if n > 0 {
+ (*z)[0] = 0xfedcb // break code expecting zero
+ }
+ return z
+}
+
+func putNat(x *nat) {
+ natPool.Put(x)
+}
+
+var natPool sync.Pool
+
+// bitLen returns the length of x in bits.
+// Unlike most methods, it works even if x is not normalized.
+func (x nat) bitLen() int {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ if i := len(x) - 1; i >= 0 {
+ // bits.Len uses a lookup table for the low-order bits on some
+ // architectures. Neutralize any input-dependent behavior by setting all
+ // bits after the first one bit.
+ top := uint(x[i])
+ top |= top >> 1
+ top |= top >> 2
+ top |= top >> 4
+ top |= top >> 8
+ top |= top >> 16
+ top |= top >> 16 >> 16 // ">> 32" doesn't compile on 32-bit architectures
+ return i*_W + bits.Len(top)
+ }
+ return 0
+}
+
+// trailingZeroBits returns the number of consecutive least significant zero
+// bits of x.
+func (x nat) trailingZeroBits() uint {
+ if len(x) == 0 {
+ return 0
+ }
+ var i uint
+ for x[i] == 0 {
+ i++
+ }
+ // x[i] != 0
+ return i*_W + uint(bits.TrailingZeros(uint(x[i])))
+}
+
+// isPow2 returns i, true when x == 2**i and 0, false otherwise.
+func (x nat) isPow2() (uint, bool) {
+ var i uint
+ for x[i] == 0 {
+ i++
+ }
+ if i == uint(len(x))-1 && x[i]&(x[i]-1) == 0 {
+ return i*_W + uint(bits.TrailingZeros(uint(x[i]))), true
+ }
+ return 0, false
+}
+
+func same(x, y nat) bool {
+ return len(x) == len(y) && len(x) > 0 && &x[0] == &y[0]
+}
+
+// z = x << s
+func (z nat) shl(x nat, s uint) nat {
+ if s == 0 {
+ if same(z, x) {
+ return z
+ }
+ if !alias(z, x) {
+ return z.set(x)
+ }
+ }
+
+ m := len(x)
+ if m == 0 {
+ return z[:0]
+ }
+ // m > 0
+
+ n := m + int(s/_W)
+ z = z.make(n + 1)
+ z[n] = shlVU(z[n-m:n], x, s%_W)
+ z[0 : n-m].clear()
+
+ return z.norm()
+}
+
+// z = x >> s
+func (z nat) shr(x nat, s uint) nat {
+ if s == 0 {
+ if same(z, x) {
+ return z
+ }
+ if !alias(z, x) {
+ return z.set(x)
+ }
+ }
+
+ m := len(x)
+ n := m - int(s/_W)
+ if n <= 0 {
+ return z[:0]
+ }
+ // n > 0
+
+ z = z.make(n)
+ shrVU(z, x[m-n:], s%_W)
+
+ return z.norm()
+}
+
+func (z nat) setBit(x nat, i uint, b uint) nat {
+ j := int(i / _W)
+ m := Word(1) << (i % _W)
+ n := len(x)
+ switch b {
+ case 0:
+ z = z.make(n)
+ copy(z, x)
+ if j >= n {
+ // no need to grow
+ return z
+ }
+ z[j] &^= m
+ return z.norm()
+ case 1:
+ if j >= n {
+ z = z.make(j + 1)
+ z[n:].clear()
+ } else {
+ z = z.make(n)
+ }
+ copy(z, x)
+ z[j] |= m
+ // no need to normalize
+ return z
+ }
+ panic("set bit is not 0 or 1")
+}
+
+// bit returns the value of the i'th bit, with lsb == bit 0.
+func (x nat) bit(i uint) uint {
+ j := i / _W
+ if j >= uint(len(x)) {
+ return 0
+ }
+ // 0 <= j < len(x)
+ return uint(x[j] >> (i % _W) & 1)
+}
+
+// sticky returns 1 if there's a 1 bit within the
+// i least significant bits, otherwise it returns 0.
+func (x nat) sticky(i uint) uint {
+ j := i / _W
+ if j >= uint(len(x)) {
+ if len(x) == 0 {
+ return 0
+ }
+ return 1
+ }
+ // 0 <= j < len(x)
+ for _, x := range x[:j] {
+ if x != 0 {
+ return 1
+ }
+ }
+ if x[j]<<(_W-i%_W) != 0 {
+ return 1
+ }
+ return 0
+}
+
+func (z nat) and(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+ if m > n {
+ m = n
+ }
+ // m <= n
+
+ z = z.make(m)
+ for i := 0; i < m; i++ {
+ z[i] = x[i] & y[i]
+ }
+
+ return z.norm()
+}
+
+// trunc returns z = x mod 2ⁿ.
+func (z nat) trunc(x nat, n uint) nat {
+ w := (n + _W - 1) / _W
+ if uint(len(x)) < w {
+ return z.set(x)
+ }
+ z = z.make(int(w))
+ copy(z, x)
+ if n%_W != 0 {
+ z[len(z)-1] &= 1<<(n%_W) - 1
+ }
+ return z.norm()
+}
+
+func (z nat) andNot(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+ if n > m {
+ n = m
+ }
+ // m >= n
+
+ z = z.make(m)
+ for i := 0; i < n; i++ {
+ z[i] = x[i] &^ y[i]
+ }
+ copy(z[n:m], x[n:m])
+
+ return z.norm()
+}
+
+func (z nat) or(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+ s := x
+ if m < n {
+ n, m = m, n
+ s = y
+ }
+ // m >= n
+
+ z = z.make(m)
+ for i := 0; i < n; i++ {
+ z[i] = x[i] | y[i]
+ }
+ copy(z[n:m], s[n:m])
+
+ return z.norm()
+}
+
+func (z nat) xor(x, y nat) nat {
+ m := len(x)
+ n := len(y)
+ s := x
+ if m < n {
+ n, m = m, n
+ s = y
+ }
+ // m >= n
+
+ z = z.make(m)
+ for i := 0; i < n; i++ {
+ z[i] = x[i] ^ y[i]
+ }
+ copy(z[n:m], s[n:m])
+
+ return z.norm()
+}
+
+// random creates a random integer in [0..limit), using the space in z if
+// possible. n is the bit length of limit.
+func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
+ if alias(z, limit) {
+ z = nil // z is an alias for limit - cannot reuse
+ }
+ z = z.make(len(limit))
+
+ bitLengthOfMSW := uint(n % _W)
+ if bitLengthOfMSW == 0 {
+ bitLengthOfMSW = _W
+ }
+ mask := Word((1 << bitLengthOfMSW) - 1)
+
+ for {
+ switch _W {
+ case 32:
+ for i := range z {
+ z[i] = Word(rand.Uint32())
+ }
+ case 64:
+ for i := range z {
+ z[i] = Word(rand.Uint32()) | Word(rand.Uint32())<<32
+ }
+ default:
+ panic("unknown word size")
+ }
+ z[len(limit)-1] &= mask
+ if z.cmp(limit) < 0 {
+ break
+ }
+ }
+
+ return z.norm()
+}
+
+// If m != 0 (i.e., len(m) != 0), expNN sets z to x**y mod m;
+// otherwise it sets z to x**y. The result is the value of z.
+func (z nat) expNN(x, y, m nat, slow bool) nat {
+ if alias(z, x) || alias(z, y) {
+ // We cannot allow in-place modification of x or y.
+ z = nil
+ }
+
+ // x**y mod 1 == 0
+ if len(m) == 1 && m[0] == 1 {
+ return z.setWord(0)
+ }
+ // m == 0 || m > 1
+
+ // x**0 == 1
+ if len(y) == 0 {
+ return z.setWord(1)
+ }
+ // y > 0
+
+ // 0**y = 0
+ if len(x) == 0 {
+ return z.setWord(0)
+ }
+ // x > 0
+
+ // 1**y = 1
+ if len(x) == 1 && x[0] == 1 {
+ return z.setWord(1)
+ }
+ // x > 1
+
+ // x**1 == x
+ if len(y) == 1 && y[0] == 1 {
+ if len(m) != 0 {
+ return z.rem(x, m)
+ }
+ return z.set(x)
+ }
+ // y > 1
+
+ if len(m) != 0 {
+ // We likely end up being as long as the modulus.
+ z = z.make(len(m))
+
+ // If the exponent is large, we use the Montgomery method for odd values,
+ // and a 4-bit, windowed exponentiation for powers of two,
+ // and a CRT-decomposed Montgomery method for the remaining values
+ // (even values times non-trivial odd values, which decompose into one
+ // instance of each of the first two cases).
+ if len(y) > 1 && !slow {
+ if m[0]&1 == 1 {
+ return z.expNNMontgomery(x, y, m)
+ }
+ if logM, ok := m.isPow2(); ok {
+ return z.expNNWindowed(x, y, logM)
+ }
+ return z.expNNMontgomeryEven(x, y, m)
+ }
+ }
+
+ z = z.set(x)
+ v := y[len(y)-1] // v > 0 because y is normalized and y > 0
+ shift := nlz(v) + 1
+ v <<= shift
+ var q nat
+
+ const mask = 1 << (_W - 1)
+
+ // We walk through the bits of the exponent one by one. Each time we
+ // see a bit, we square, thus doubling the power. If the bit is a one,
+ // we also multiply by x, thus adding one to the power.
+
+ w := _W - int(shift)
+ // zz and r are used to avoid allocating in mul and div as
+ // otherwise the arguments would alias.
+ var zz, r nat
+ for j := 0; j < w; j++ {
+ zz = zz.sqr(z)
+ zz, z = z, zz
+
+ if v&mask != 0 {
+ zz = zz.mul(z, x)
+ zz, z = z, zz
+ }
+
+ if len(m) != 0 {
+ zz, r = zz.div(r, z, m)
+ zz, r, q, z = q, z, zz, r
+ }
+
+ v <<= 1
+ }
+
+ for i := len(y) - 2; i >= 0; i-- {
+ v = y[i]
+
+ for j := 0; j < _W; j++ {
+ zz = zz.sqr(z)
+ zz, z = z, zz
+
+ if v&mask != 0 {
+ zz = zz.mul(z, x)
+ zz, z = z, zz
+ }
+
+ if len(m) != 0 {
+ zz, r = zz.div(r, z, m)
+ zz, r, q, z = q, z, zz, r
+ }
+
+ v <<= 1
+ }
+ }
+
+ return z.norm()
+}
+
+// expNNMontgomeryEven calculates x**y mod m where m = m1 × m2 for m1 = 2ⁿ and m2 odd.
+// It uses two recursive calls to expNN for x**y mod m1 and x**y mod m2
+// and then uses the Chinese Remainder Theorem to combine the results.
+// The recursive call using m1 will use expNNWindowed,
+// while the recursive call using m2 will use expNNMontgomery.
+// For more details, see Ç. K. Koç, “Montgomery Reduction with Even Modulus”,
+// IEE Proceedings: Computers and Digital Techniques, 141(5) 314-316, September 1994.
+// http://www.people.vcu.edu/~jwang3/CMSC691/j34monex.pdf
+func (z nat) expNNMontgomeryEven(x, y, m nat) nat {
+ // Split m = m₁ × m₂ where m₁ = 2ⁿ
+ n := m.trailingZeroBits()
+ m1 := nat(nil).shl(natOne, n)
+ m2 := nat(nil).shr(m, n)
+
+ // We want z = x**y mod m.
+ // z₁ = x**y mod m1 = (x**y mod m) mod m1 = z mod m1
+ // z₂ = x**y mod m2 = (x**y mod m) mod m2 = z mod m2
+ // (We are using the math/big convention for names here,
+ // where the computation is z = x**y mod m, so its parts are z1 and z2.
+ // The paper is computing x = a**e mod n; it refers to these as x2 and z1.)
+ z1 := nat(nil).expNN(x, y, m1, false)
+ z2 := nat(nil).expNN(x, y, m2, false)
+
+ // Reconstruct z from z₁, z₂ using CRT, using algorithm from paper,
+ // which uses only a single modInverse (and an easy one at that).
+ // p = (z₁ - z₂) × m₂⁻¹ (mod m₁)
+ // z = z₂ + p × m₂
+ // The final addition is in range because:
+ // z = z₂ + p × m₂
+ // ≤ z₂ + (m₁-1) × m₂
+ // < m₂ + (m₁-1) × m₂
+ // = m₁ × m₂
+ // = m.
+ z = z.set(z2)
+
+ // Compute (z₁ - z₂) mod m1 [m1 == 2**n] into z1.
+ z1 = z1.subMod2N(z1, z2, n)
+
+ // Reuse z2 for p = (z₁ - z₂) [in z1] * m2⁻¹ (mod m₁ [= 2ⁿ]).
+ m2inv := nat(nil).modInverse(m2, m1)
+ z2 = z2.mul(z1, m2inv)
+ z2 = z2.trunc(z2, n)
+
+ // Reuse z1 for p * m2.
+ z = z.add(z, z1.mul(z2, m2))
+
+ return z
+}
+
+// expNNWindowed calculates x**y mod m using a fixed, 4-bit window,
+// where m = 2**logM.
+func (z nat) expNNWindowed(x, y nat, logM uint) nat {
+ if len(y) <= 1 {
+ panic("big: misuse of expNNWindowed")
+ }
+ if x[0]&1 == 0 {
+ // len(y) > 1, so y > logM.
+ // x is even, so x**y is a multiple of 2**y which is a multiple of 2**logM.
+ return z.setWord(0)
+ }
+ if logM == 1 {
+ return z.setWord(1)
+ }
+
+ // zz is used to avoid allocating in mul as otherwise
+ // the arguments would alias.
+ w := int((logM + _W - 1) / _W)
+ zzp := getNat(w)
+ zz := *zzp
+
+ const n = 4
+ // powers[i] contains x^i.
+ var powers [1 << n]*nat
+ for i := range powers {
+ powers[i] = getNat(w)
+ }
+ *powers[0] = powers[0].set(natOne)
+ *powers[1] = powers[1].trunc(x, logM)
+ for i := 2; i < 1< mtop {
+ i = mtop
+ }
+ advance := false
+ z = z.setWord(1)
+ for ; i >= 0; i-- {
+ yi := y[i]
+ if i == mtop {
+ yi &= mmask
+ }
+ for j := 0; j < _W; j += n {
+ if advance {
+ // Account for use of 4 bits in previous iteration.
+ // Unrolled loop for significant performance
+ // gain. Use go test -bench=".*" in crypto/rsa
+ // to check performance before making changes.
+ zz = zz.sqr(z)
+ zz, z = z, zz
+ z = z.trunc(z, logM)
+
+ zz = zz.sqr(z)
+ zz, z = z, zz
+ z = z.trunc(z, logM)
+
+ zz = zz.sqr(z)
+ zz, z = z, zz
+ z = z.trunc(z, logM)
+
+ zz = zz.sqr(z)
+ zz, z = z, zz
+ z = z.trunc(z, logM)
+ }
+
+ zz = zz.mul(z, *powers[yi>>(_W-n)])
+ zz, z = z, zz
+ z = z.trunc(z, logM)
+
+ yi <<= n
+ advance = true
+ }
+ }
+
+ *zzp = zz
+ putNat(zzp)
+ for i := range powers {
+ putNat(powers[i])
+ }
+
+ return z.norm()
+}
+
+// expNNMontgomery calculates x**y mod m using a fixed, 4-bit window.
+// Uses Montgomery representation.
+func (z nat) expNNMontgomery(x, y, m nat) nat {
+ numWords := len(m)
+
+ // We want the lengths of x and m to be equal.
+ // It is OK if x >= m as long as len(x) == len(m).
+ if len(x) > numWords {
+ _, x = nat(nil).div(nil, x, m)
+ // Note: now len(x) <= numWords, not guaranteed ==.
+ }
+ if len(x) < numWords {
+ rr := make(nat, numWords)
+ copy(rr, x)
+ x = rr
+ }
+
+ // Ideally the precomputations would be performed outside, and reused
+ // k0 = -m**-1 mod 2**_W. Algorithm from: Dumas, J.G. "On Newton–Raphson
+ // Iteration for Multiplicative Inverses Modulo Prime Powers".
+ k0 := 2 - m[0]
+ t := m[0] - 1
+ for i := 1; i < _W; i <<= 1 {
+ t *= t
+ k0 *= (t + 1)
+ }
+ k0 = -k0
+
+ // RR = 2**(2*_W*len(m)) mod m
+ RR := nat(nil).setWord(1)
+ zz := nat(nil).shl(RR, uint(2*numWords*_W))
+ _, RR = nat(nil).div(RR, zz, m)
+ if len(RR) < numWords {
+ zz = zz.make(numWords)
+ copy(zz, RR)
+ RR = zz
+ }
+ // one = 1, with equal length to that of m
+ one := make(nat, numWords)
+ one[0] = 1
+
+ const n = 4
+ // powers[i] contains x^i
+ var powers [1 << n]nat
+ powers[0] = powers[0].montgomery(one, RR, m, k0, numWords)
+ powers[1] = powers[1].montgomery(x, RR, m, k0, numWords)
+ for i := 2; i < 1<= 0; i-- {
+ yi := y[i]
+ for j := 0; j < _W; j += n {
+ if i != len(y)-1 || j != 0 {
+ zz = zz.montgomery(z, z, m, k0, numWords)
+ z = z.montgomery(zz, zz, m, k0, numWords)
+ zz = zz.montgomery(z, z, m, k0, numWords)
+ z = z.montgomery(zz, zz, m, k0, numWords)
+ }
+ zz = zz.montgomery(z, powers[yi>>(_W-n)], m, k0, numWords)
+ z, zz = zz, z
+ yi <<= n
+ }
+ }
+ // convert to regular number
+ zz = zz.montgomery(z, one, m, k0, numWords)
+
+ // One last reduction, just in case.
+ // See golang.org/issue/13907.
+ if zz.cmp(m) >= 0 {
+ // Common case is m has high bit set; in that case,
+ // since zz is the same length as m, there can be just
+ // one multiple of m to remove. Just subtract.
+ // We think that the subtract should be sufficient in general,
+ // so do that unconditionally, but double-check,
+ // in case our beliefs are wrong.
+ // The div is not expected to be reached.
+ zz = zz.sub(zz, m)
+ if zz.cmp(m) >= 0 {
+ _, zz = nat(nil).div(nil, zz, m)
+ }
+ }
+
+ return zz.norm()
+}
+
+// bytes writes the value of z into buf using big-endian encoding.
+// The value of z is encoded in the slice buf[i:]. If the value of z
+// cannot be represented in buf, bytes panics. The number i of unused
+// bytes at the beginning of buf is returned as result.
+func (z nat) bytes(buf []byte) (i int) {
+ // This function is used in cryptographic operations. It must not leak
+ // anything but the Int's sign and bit size through side-channels. Any
+ // changes must be reviewed by a security expert.
+ i = len(buf)
+ for _, d := range z {
+ for j := 0; j < _S; j++ {
+ i--
+ if i >= 0 {
+ buf[i] = byte(d)
+ } else if byte(d) != 0 {
+ panic("math/big: buffer too small to fit value")
+ }
+ d >>= 8
+ }
+ }
+
+ if i < 0 {
+ i = 0
+ }
+ for i < len(buf) && buf[i] == 0 {
+ i++
+ }
+
+ return
+}
+
+// bigEndianWord returns the contents of buf interpreted as a big-endian encoded Word value.
+func bigEndianWord(buf []byte) Word {
+ if _W == 64 {
+ return Word(binary.BigEndian.Uint64(buf))
+ }
+ return Word(binary.BigEndian.Uint32(buf))
+}
+
+// setBytes interprets buf as the bytes of a big-endian unsigned
+// integer, sets z to that value, and returns z.
+func (z nat) setBytes(buf []byte) nat {
+ z = z.make((len(buf) + _S - 1) / _S)
+
+ i := len(buf)
+ for k := 0; i >= _S; k++ {
+ z[k] = bigEndianWord(buf[i-_S : i])
+ i -= _S
+ }
+ if i > 0 {
+ var d Word
+ for s := uint(0); i > 0; s += 8 {
+ d |= Word(buf[i-1]) << s
+ i--
+ }
+ z[len(z)-1] = d
+ }
+
+ return z.norm()
+}
+
+// sqrt sets z = ⌊√x⌋
+func (z nat) sqrt(x nat) nat {
+ if x.cmp(natOne) <= 0 {
+ return z.set(x)
+ }
+ if alias(z, x) {
+ z = nil
+ }
+
+ // Start with value known to be too large and repeat "z = ⌊(z + ⌊x/z⌋)/2⌋" until it stops getting smaller.
+ // See Brent and Zimmermann, Modern Computer Arithmetic, Algorithm 1.13 (SqrtInt).
+ // https://members.loria.fr/PZimmermann/mca/pub226.html
+ // If x is one less than a perfect square, the sequence oscillates between the correct z and z+1;
+ // otherwise it converges to the correct z and stays there.
+ var z1, z2 nat
+ z1 = z
+ z1 = z1.setUint64(1)
+ z1 = z1.shl(z1, uint(x.bitLen()+1)/2) // must be ≥ √x
+ for n := 0; ; n++ {
+ z2, _ = z2.div(nil, x, z1)
+ z2 = z2.add(z2, z1)
+ z2 = z2.shr(z2, 1)
+ if z2.cmp(z1) >= 0 {
+ // z1 is answer.
+ // Figure out whether z1 or z2 is currently aliased to z by looking at loop count.
+ if n&1 == 0 {
+ return z1
+ }
+ return z.set(z1)
+ }
+ z1, z2 = z2, z1
+ }
+}
+
+// subMod2N returns z = (x - y) mod 2ⁿ.
+func (z nat) subMod2N(x, y nat, n uint) nat {
+ if uint(x.bitLen()) > n {
+ if alias(z, x) {
+ // ok to overwrite x in place
+ x = x.trunc(x, n)
+ } else {
+ x = nat(nil).trunc(x, n)
+ }
+ }
+ if uint(y.bitLen()) > n {
+ if alias(z, y) {
+ // ok to overwrite y in place
+ y = y.trunc(y, n)
+ } else {
+ y = nat(nil).trunc(y, n)
+ }
+ }
+ if x.cmp(y) >= 0 {
+ return z.sub(x, y)
+ }
+ // x - y < 0; x - y mod 2ⁿ = x - y + 2ⁿ = 2ⁿ - (y - x) = 1 + 2ⁿ-1 - (y - x) = 1 + ^(y - x).
+ z = z.sub(y, x)
+ for uint(len(z))*_W < n {
+ z = append(z, 0)
+ }
+ for i := range z {
+ z[i] = ^z[i]
+ }
+ z = z.trunc(z, n)
+ return z.add(z, natOne)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/nat_test.go b/platform/dbops/binaries/go/go/src/math/big/nat_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4722548fa965faafc0fdd0549888a90b9d7a7528
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/nat_test.go
@@ -0,0 +1,891 @@
+// 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 big
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+var cmpTests = []struct {
+ x, y nat
+ r int
+}{
+ {nil, nil, 0},
+ {nil, nat(nil), 0},
+ {nat(nil), nil, 0},
+ {nat(nil), nat(nil), 0},
+ {nat{0}, nat{0}, 0},
+ {nat{0}, nat{1}, -1},
+ {nat{1}, nat{0}, 1},
+ {nat{1}, nat{1}, 0},
+ {nat{0, _M}, nat{1}, 1},
+ {nat{1}, nat{0, _M}, -1},
+ {nat{1, _M}, nat{0, _M}, 1},
+ {nat{0, _M}, nat{1, _M}, -1},
+ {nat{16, 571956, 8794, 68}, nat{837, 9146, 1, 754489}, -1},
+ {nat{34986, 41, 105, 1957}, nat{56, 7458, 104, 1957}, 1},
+}
+
+func TestCmp(t *testing.T) {
+ for i, a := range cmpTests {
+ r := a.x.cmp(a.y)
+ if r != a.r {
+ t.Errorf("#%d got r = %v; want %v", i, r, a.r)
+ }
+ }
+}
+
+type funNN func(z, x, y nat) nat
+type argNN struct {
+ z, x, y nat
+}
+
+var sumNN = []argNN{
+ {},
+ {nat{1}, nil, nat{1}},
+ {nat{1111111110}, nat{123456789}, nat{987654321}},
+ {nat{0, 0, 0, 1}, nil, nat{0, 0, 0, 1}},
+ {nat{0, 0, 0, 1111111110}, nat{0, 0, 0, 123456789}, nat{0, 0, 0, 987654321}},
+ {nat{0, 0, 0, 1}, nat{0, 0, _M}, nat{0, 0, 1}},
+}
+
+var prodNN = []argNN{
+ {},
+ {nil, nil, nil},
+ {nil, nat{991}, nil},
+ {nat{991}, nat{991}, nat{1}},
+ {nat{991 * 991}, nat{991}, nat{991}},
+ {nat{0, 0, 991 * 991}, nat{0, 991}, nat{0, 991}},
+ {nat{1 * 991, 2 * 991, 3 * 991, 4 * 991}, nat{1, 2, 3, 4}, nat{991}},
+ {nat{4, 11, 20, 30, 20, 11, 4}, nat{1, 2, 3, 4}, nat{4, 3, 2, 1}},
+ // 3^100 * 3^28 = 3^128
+ {
+ natFromString("11790184577738583171520872861412518665678211592275841109096961"),
+ natFromString("515377520732011331036461129765621272702107522001"),
+ natFromString("22876792454961"),
+ },
+ // z = 111....1 (70000 digits)
+ // x = 10^(99*700) + ... + 10^1400 + 10^700 + 1
+ // y = 111....1 (700 digits, larger than Karatsuba threshold on 32-bit and 64-bit)
+ {
+ natFromString(strings.Repeat("1", 70000)),
+ natFromString("1" + strings.Repeat(strings.Repeat("0", 699)+"1", 99)),
+ natFromString(strings.Repeat("1", 700)),
+ },
+ // z = 111....1 (20000 digits)
+ // x = 10^10000 + 1
+ // y = 111....1 (10000 digits)
+ {
+ natFromString(strings.Repeat("1", 20000)),
+ natFromString("1" + strings.Repeat("0", 9999) + "1"),
+ natFromString(strings.Repeat("1", 10000)),
+ },
+}
+
+func natFromString(s string) nat {
+ x, _, _, err := nat(nil).scan(strings.NewReader(s), 0, false)
+ if err != nil {
+ panic(err)
+ }
+ return x
+}
+
+func TestSet(t *testing.T) {
+ for _, a := range sumNN {
+ z := nat(nil).set(a.z)
+ if z.cmp(a.z) != 0 {
+ t.Errorf("got z = %v; want %v", z, a.z)
+ }
+ }
+}
+
+func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
+ z := f(nil, a.x, a.y)
+ if z.cmp(a.z) != 0 {
+ t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, z, a.z)
+ }
+}
+
+func TestFunNN(t *testing.T) {
+ for _, a := range sumNN {
+ arg := a
+ testFunNN(t, "add", nat.add, arg)
+
+ arg = argNN{a.z, a.y, a.x}
+ testFunNN(t, "add symmetric", nat.add, arg)
+
+ arg = argNN{a.x, a.z, a.y}
+ testFunNN(t, "sub", nat.sub, arg)
+
+ arg = argNN{a.y, a.z, a.x}
+ testFunNN(t, "sub symmetric", nat.sub, arg)
+ }
+
+ for _, a := range prodNN {
+ arg := a
+ testFunNN(t, "mul", nat.mul, arg)
+
+ arg = argNN{a.z, a.y, a.x}
+ testFunNN(t, "mul symmetric", nat.mul, arg)
+ }
+}
+
+var mulRangesN = []struct {
+ a, b uint64
+ prod string
+}{
+ {0, 0, "0"},
+ {1, 1, "1"},
+ {1, 2, "2"},
+ {1, 3, "6"},
+ {10, 10, "10"},
+ {0, 100, "0"},
+ {0, 1e9, "0"},
+ {1, 0, "1"}, // empty range
+ {100, 1, "1"}, // empty range
+ {1, 10, "3628800"}, // 10!
+ {1, 20, "2432902008176640000"}, // 20!
+ {1, 100,
+ "933262154439441526816992388562667004907159682643816214685929" +
+ "638952175999932299156089414639761565182862536979208272237582" +
+ "51185210916864000000000000000000000000", // 100!
+ },
+ {math.MaxUint64 - 0, math.MaxUint64, "18446744073709551615"},
+ {math.MaxUint64 - 1, math.MaxUint64, "340282366920938463408034375210639556610"},
+ {math.MaxUint64 - 2, math.MaxUint64, "6277101735386680761794095221682035635525021984684230311930"},
+ {math.MaxUint64 - 3, math.MaxUint64, "115792089237316195360799967654821100226821973275796746098729803619699194331160"},
+}
+
+func TestMulRangeN(t *testing.T) {
+ for i, r := range mulRangesN {
+ prod := string(nat(nil).mulRange(r.a, r.b).utoa(10))
+ if prod != r.prod {
+ t.Errorf("#%d: got %s; want %s", i, prod, r.prod)
+ }
+ }
+}
+
+// allocBytes returns the number of bytes allocated by invoking f.
+func allocBytes(f func()) uint64 {
+ var stats runtime.MemStats
+ runtime.ReadMemStats(&stats)
+ t := stats.TotalAlloc
+ f()
+ runtime.ReadMemStats(&stats)
+ return stats.TotalAlloc - t
+}
+
+// TestMulUnbalanced tests that multiplying numbers of different lengths
+// does not cause deep recursion and in turn allocate too much memory.
+// Test case for issue 3807.
+func TestMulUnbalanced(t *testing.T) {
+ defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
+ x := rndNat(50000)
+ y := rndNat(40)
+ allocSize := allocBytes(func() {
+ nat(nil).mul(x, y)
+ })
+ inputSize := uint64(len(x)+len(y)) * _S
+ if ratio := allocSize / uint64(inputSize); ratio > 10 {
+ t.Errorf("multiplication uses too much memory (%d > %d times the size of inputs)", allocSize, ratio)
+ }
+}
+
+// rndNat returns a random nat value >= 0 of (usually) n words in length.
+// In extremely unlikely cases it may be smaller than n words if the top-
+// most words are 0.
+func rndNat(n int) nat {
+ return nat(rndV(n)).norm()
+}
+
+// rndNat1 is like rndNat but the result is guaranteed to be > 0.
+func rndNat1(n int) nat {
+ x := nat(rndV(n)).norm()
+ if len(x) == 0 {
+ x.setWord(1)
+ }
+ return x
+}
+
+func BenchmarkMul(b *testing.B) {
+ mulx := rndNat(1e4)
+ muly := rndNat(1e4)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ var z nat
+ z.mul(mulx, muly)
+ }
+}
+
+func benchmarkNatMul(b *testing.B, nwords int) {
+ x := rndNat(nwords)
+ y := rndNat(nwords)
+ var z nat
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ z.mul(x, y)
+ }
+}
+
+var mulBenchSizes = []int{10, 100, 1000, 10000, 100000}
+
+func BenchmarkNatMul(b *testing.B) {
+ for _, n := range mulBenchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
+ benchmarkNatMul(b, n)
+ })
+ }
+}
+
+func TestNLZ(t *testing.T) {
+ var x Word = _B >> 1
+ for i := 0; i <= _W; i++ {
+ if int(nlz(x)) != i {
+ t.Errorf("failed at %x: got %d want %d", x, nlz(x), i)
+ }
+ x >>= 1
+ }
+}
+
+type shiftTest struct {
+ in nat
+ shift uint
+ out nat
+}
+
+var leftShiftTests = []shiftTest{
+ {nil, 0, nil},
+ {nil, 1, nil},
+ {natOne, 0, natOne},
+ {natOne, 1, natTwo},
+ {nat{1 << (_W - 1)}, 1, nat{0}},
+ {nat{1 << (_W - 1), 0}, 1, nat{0, 1}},
+}
+
+func TestShiftLeft(t *testing.T) {
+ for i, test := range leftShiftTests {
+ var z nat
+ z = z.shl(test.in, test.shift)
+ for j, d := range test.out {
+ if j >= len(z) || z[j] != d {
+ t.Errorf("#%d: got: %v want: %v", i, z, test.out)
+ break
+ }
+ }
+ }
+}
+
+var rightShiftTests = []shiftTest{
+ {nil, 0, nil},
+ {nil, 1, nil},
+ {natOne, 0, natOne},
+ {natOne, 1, nil},
+ {natTwo, 1, natOne},
+ {nat{0, 1}, 1, nat{1 << (_W - 1)}},
+ {nat{2, 1, 1}, 1, nat{1<<(_W-1) + 1, 1 << (_W - 1)}},
+}
+
+func TestShiftRight(t *testing.T) {
+ for i, test := range rightShiftTests {
+ var z nat
+ z = z.shr(test.in, test.shift)
+ for j, d := range test.out {
+ if j >= len(z) || z[j] != d {
+ t.Errorf("#%d: got: %v want: %v", i, z, test.out)
+ break
+ }
+ }
+ }
+}
+
+func BenchmarkZeroShifts(b *testing.B) {
+ x := rndNat(800)
+
+ b.Run("Shl", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ var z nat
+ z.shl(x, 0)
+ }
+ })
+ b.Run("ShlSame", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ x.shl(x, 0)
+ }
+ })
+
+ b.Run("Shr", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ var z nat
+ z.shr(x, 0)
+ }
+ })
+ b.Run("ShrSame", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ x.shr(x, 0)
+ }
+ })
+}
+
+type modWTest struct {
+ in string
+ dividend string
+ out string
+}
+
+var modWTests32 = []modWTest{
+ {"23492635982634928349238759823742", "252341", "220170"},
+}
+
+var modWTests64 = []modWTest{
+ {"6527895462947293856291561095690465243862946", "524326975699234", "375066989628668"},
+}
+
+func runModWTests(t *testing.T, tests []modWTest) {
+ for i, test := range tests {
+ in, _ := new(Int).SetString(test.in, 10)
+ d, _ := new(Int).SetString(test.dividend, 10)
+ out, _ := new(Int).SetString(test.out, 10)
+
+ r := in.abs.modW(d.abs[0])
+ if r != out.abs[0] {
+ t.Errorf("#%d failed: got %d want %s", i, r, out)
+ }
+ }
+}
+
+func TestModW(t *testing.T) {
+ if _W >= 32 {
+ runModWTests(t, modWTests32)
+ }
+ if _W >= 64 {
+ runModWTests(t, modWTests64)
+ }
+}
+
+var montgomeryTests = []struct {
+ x, y, m string
+ k0 uint64
+ out32, out64 string
+}{
+ {
+ "0xffffffffffffffffffffffffffffffffffffffffffffffffe",
+ "0xffffffffffffffffffffffffffffffffffffffffffffffffe",
+ "0xfffffffffffffffffffffffffffffffffffffffffffffffff",
+ 1,
+ "0x1000000000000000000000000000000000000000000",
+ "0x10000000000000000000000000000000000",
+ },
+ {
+ "0x000000000ffffff5",
+ "0x000000000ffffff0",
+ "0x0000000010000001",
+ 0xff0000000fffffff,
+ "0x000000000bfffff4",
+ "0x0000000003400001",
+ },
+ {
+ "0x0000000080000000",
+ "0x00000000ffffffff",
+ "0x1000000000000001",
+ 0xfffffffffffffff,
+ "0x0800000008000001",
+ "0x0800000008000001",
+ },
+ {
+ "0x0000000080000000",
+ "0x0000000080000000",
+ "0xffffffff00000001",
+ 0xfffffffeffffffff,
+ "0xbfffffff40000001",
+ "0xbfffffff40000001",
+ },
+ {
+ "0x0000000080000000",
+ "0x0000000080000000",
+ "0x00ffffff00000001",
+ 0xfffffeffffffff,
+ "0xbfffff40000001",
+ "0xbfffff40000001",
+ },
+ {
+ "0x0000000080000000",
+ "0x0000000080000000",
+ "0x0000ffff00000001",
+ 0xfffeffffffff,
+ "0xbfff40000001",
+ "0xbfff40000001",
+ },
+ {
+ "0x3321ffffffffffffffffffffffffffff00000000000022222623333333332bbbb888c0",
+ "0x3321ffffffffffffffffffffffffffff00000000000022222623333333332bbbb888c0",
+ "0x33377fffffffffffffffffffffffffffffffffffffffffffff0000000000022222eee1",
+ 0xdecc8f1249812adf,
+ "0x04eb0e11d72329dc0915f86784820fc403275bf2f6620a20e0dd344c5cd0875e50deb5",
+ "0x0d7144739a7d8e11d72329dc0915f86784820fc403275bf2f61ed96f35dd34dbb3d6a0",
+ },
+ {
+ "0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffff00000000000022222223333333333444444444",
+ "0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffff999999999999999aaabbbbbbbbcccccccccccc",
+ "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff33377fffffffffffffffffffffffffffffffffffffffffffff0000000000022222eee1",
+ 0xdecc8f1249812adf,
+ "0x5c0d52f451aec609b15da8e5e5626c4eaa88723bdeac9d25ca9b961269400410ca208a16af9c2fb07d7a11c7772cba02c22f9711078d51a3797eb18e691295293284d988e349fa6deba46b25a4ecd9f715",
+ "0x92fcad4b5c0d52f451aec609b15da8e5e5626c4eaa88723bdeac9d25ca9b961269400410ca208a16af9c2fb07d799c32fe2f3cc5422f9711078d51a3797eb18e691295293284d8f5e69caf6decddfe1df6",
+ },
+}
+
+func TestMontgomery(t *testing.T) {
+ one := NewInt(1)
+ _B := new(Int).Lsh(one, _W)
+ for i, test := range montgomeryTests {
+ x := natFromString(test.x)
+ y := natFromString(test.y)
+ m := natFromString(test.m)
+ for len(x) < len(m) {
+ x = append(x, 0)
+ }
+ for len(y) < len(m) {
+ y = append(y, 0)
+ }
+
+ if x.cmp(m) > 0 {
+ _, r := nat(nil).div(nil, x, m)
+ t.Errorf("#%d: x > m (0x%s > 0x%s; use 0x%s)", i, x.utoa(16), m.utoa(16), r.utoa(16))
+ }
+ if y.cmp(m) > 0 {
+ _, r := nat(nil).div(nil, x, m)
+ t.Errorf("#%d: y > m (0x%s > 0x%s; use 0x%s)", i, y.utoa(16), m.utoa(16), r.utoa(16))
+ }
+
+ var out nat
+ if _W == 32 {
+ out = natFromString(test.out32)
+ } else {
+ out = natFromString(test.out64)
+ }
+
+ // t.Logf("#%d: len=%d\n", i, len(m))
+
+ // check output in table
+ xi := &Int{abs: x}
+ yi := &Int{abs: y}
+ mi := &Int{abs: m}
+ p := new(Int).Mod(new(Int).Mul(xi, new(Int).Mul(yi, new(Int).ModInverse(new(Int).Lsh(one, uint(len(m))*_W), mi))), mi)
+ if out.cmp(p.abs.norm()) != 0 {
+ t.Errorf("#%d: out in table=0x%s, computed=0x%s", i, out.utoa(16), p.abs.norm().utoa(16))
+ }
+
+ // check k0 in table
+ k := new(Int).Mod(&Int{abs: m}, _B)
+ k = new(Int).Sub(_B, k)
+ k = new(Int).Mod(k, _B)
+ k0 := Word(new(Int).ModInverse(k, _B).Uint64())
+ if k0 != Word(test.k0) {
+ t.Errorf("#%d: k0 in table=%#x, computed=%#x\n", i, test.k0, k0)
+ }
+
+ // check montgomery with correct k0 produces correct output
+ z := nat(nil).montgomery(x, y, m, k0, len(m))
+ z = z.norm()
+ if z.cmp(out) != 0 {
+ t.Errorf("#%d: got 0x%s want 0x%s", i, z.utoa(16), out.utoa(16))
+ }
+ }
+}
+
+var expNNTests = []struct {
+ x, y, m string
+ out string
+}{
+ {"0", "0", "0", "1"},
+ {"0", "0", "1", "0"},
+ {"1", "1", "1", "0"},
+ {"2", "1", "1", "0"},
+ {"2", "2", "1", "0"},
+ {"10", "100000000000", "1", "0"},
+ {"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
+ {"0x8000000000000000", "2", "6719", "4944"},
+ {"0x8000000000000000", "3", "6719", "5447"},
+ {"0x8000000000000000", "1000", "6719", "1603"},
+ {"0x8000000000000000", "1000000", "6719", "3199"},
+ {
+ "2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347",
+ "298472983472983471903246121093472394872319615612417471234712061",
+ "29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464",
+ "23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291",
+ },
+ {
+ "11521922904531591643048817447554701904414021819823889996244743037378330903763518501116638828335352811871131385129455853417360623007349090150042001944696604737499160174391019030572483602867266711107136838523916077674888297896995042968746762200926853379",
+ "426343618817810911523",
+ "444747819283133684179",
+ "42",
+ },
+ {"375", "249", "388", "175"},
+ {"375", "18446744073709551801", "388", "175"},
+ {"0", "0x40000000000000", "0x200", "0"},
+ {"0xeffffff900002f00", "0x40000000000000", "0x200", "0"},
+ {"5", "1435700818", "72", "49"},
+ {"0xffff", "0x300030003000300030003000300030003000302a3000300030003000300030003000300030003000300030003000300030003030623066307f3030783062303430383064303630343036", "0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "0xa3f94c08b0b90e87af637cacc9383f7ea032352b8961fc036a52b659b6c9b33491b335ffd74c927f64ddd62cfca0001"},
+}
+
+func TestExpNN(t *testing.T) {
+ for i, test := range expNNTests {
+ x := natFromString(test.x)
+ y := natFromString(test.y)
+ out := natFromString(test.out)
+
+ var m nat
+ if len(test.m) > 0 {
+ m = natFromString(test.m)
+ }
+
+ z := nat(nil).expNN(x, y, m, false)
+ if z.cmp(out) != 0 {
+ t.Errorf("#%d got %s want %s", i, z.utoa(10), out.utoa(10))
+ }
+ }
+}
+
+func FuzzExpMont(f *testing.F) {
+ f.Fuzz(func(t *testing.T, x1, x2, x3, y1, y2, y3, m1, m2, m3 uint) {
+ if m1 == 0 && m2 == 0 && m3 == 0 {
+ return
+ }
+ x := new(Int).SetBits([]Word{Word(x1), Word(x2), Word(x3)})
+ y := new(Int).SetBits([]Word{Word(y1), Word(y2), Word(y3)})
+ m := new(Int).SetBits([]Word{Word(m1), Word(m2), Word(m3)})
+ out := new(Int).Exp(x, y, m)
+ want := new(Int).expSlow(x, y, m)
+ if out.Cmp(want) != 0 {
+ t.Errorf("x = %#x\ny=%#x\nz=%#x\nout=%#x\nwant=%#x\ndc: 16o 16i %X %X %X |p", x, y, m, out, want, x, y, m)
+ }
+ })
+}
+
+func BenchmarkExp3Power(b *testing.B) {
+ const x = 3
+ for _, y := range []Word{
+ 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000,
+ } {
+ b.Run(fmt.Sprintf("%#x", y), func(b *testing.B) {
+ var z nat
+ for i := 0; i < b.N; i++ {
+ z.expWW(x, y)
+ }
+ })
+ }
+}
+
+func fibo(n int) nat {
+ switch n {
+ case 0:
+ return nil
+ case 1:
+ return nat{1}
+ }
+ f0 := fibo(0)
+ f1 := fibo(1)
+ var f2 nat
+ for i := 1; i < n; i++ {
+ f2 = f2.add(f0, f1)
+ f0, f1, f2 = f1, f2, f0
+ }
+ return f1
+}
+
+var fiboNums = []string{
+ "0",
+ "55",
+ "6765",
+ "832040",
+ "102334155",
+ "12586269025",
+ "1548008755920",
+ "190392490709135",
+ "23416728348467685",
+ "2880067194370816120",
+ "354224848179261915075",
+}
+
+func TestFibo(t *testing.T) {
+ for i, want := range fiboNums {
+ n := i * 10
+ got := string(fibo(n).utoa(10))
+ if got != want {
+ t.Errorf("fibo(%d) failed: got %s want %s", n, got, want)
+ }
+ }
+}
+
+func BenchmarkFibo(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ fibo(1e0)
+ fibo(1e1)
+ fibo(1e2)
+ fibo(1e3)
+ fibo(1e4)
+ fibo(1e5)
+ }
+}
+
+var bitTests = []struct {
+ x string
+ i uint
+ want uint
+}{
+ {"0", 0, 0},
+ {"0", 1, 0},
+ {"0", 1000, 0},
+
+ {"0x1", 0, 1},
+ {"0x10", 0, 0},
+ {"0x10", 3, 0},
+ {"0x10", 4, 1},
+ {"0x10", 5, 0},
+
+ {"0x8000000000000000", 62, 0},
+ {"0x8000000000000000", 63, 1},
+ {"0x8000000000000000", 64, 0},
+
+ {"0x3" + strings.Repeat("0", 32), 127, 0},
+ {"0x3" + strings.Repeat("0", 32), 128, 1},
+ {"0x3" + strings.Repeat("0", 32), 129, 1},
+ {"0x3" + strings.Repeat("0", 32), 130, 0},
+}
+
+func TestBit(t *testing.T) {
+ for i, test := range bitTests {
+ x := natFromString(test.x)
+ if got := x.bit(test.i); got != test.want {
+ t.Errorf("#%d: %s.bit(%d) = %v; want %v", i, test.x, test.i, got, test.want)
+ }
+ }
+}
+
+var stickyTests = []struct {
+ x string
+ i uint
+ want uint
+}{
+ {"0", 0, 0},
+ {"0", 1, 0},
+ {"0", 1000, 0},
+
+ {"0x1", 0, 0},
+ {"0x1", 1, 1},
+
+ {"0x1350", 0, 0},
+ {"0x1350", 4, 0},
+ {"0x1350", 5, 1},
+
+ {"0x8000000000000000", 63, 0},
+ {"0x8000000000000000", 64, 1},
+
+ {"0x1" + strings.Repeat("0", 100), 400, 0},
+ {"0x1" + strings.Repeat("0", 100), 401, 1},
+}
+
+func TestSticky(t *testing.T) {
+ for i, test := range stickyTests {
+ x := natFromString(test.x)
+ if got := x.sticky(test.i); got != test.want {
+ t.Errorf("#%d: %s.sticky(%d) = %v; want %v", i, test.x, test.i, got, test.want)
+ }
+ if test.want == 1 {
+ // all subsequent i's should also return 1
+ for d := uint(1); d <= 3; d++ {
+ if got := x.sticky(test.i + d); got != 1 {
+ t.Errorf("#%d: %s.sticky(%d) = %v; want %v", i, test.x, test.i+d, got, 1)
+ }
+ }
+ }
+ }
+}
+
+func testSqr(t *testing.T, x nat) {
+ got := make(nat, 2*len(x))
+ want := make(nat, 2*len(x))
+ got = got.sqr(x)
+ want = want.mul(x, x)
+ if got.cmp(want) != 0 {
+ t.Errorf("basicSqr(%v), got %v, want %v", x, got, want)
+ }
+}
+
+func TestSqr(t *testing.T) {
+ for _, a := range prodNN {
+ if a.x != nil {
+ testSqr(t, a.x)
+ }
+ if a.y != nil {
+ testSqr(t, a.y)
+ }
+ if a.z != nil {
+ testSqr(t, a.z)
+ }
+ }
+}
+
+func benchmarkNatSqr(b *testing.B, nwords int) {
+ x := rndNat(nwords)
+ var z nat
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ z.sqr(x)
+ }
+}
+
+var sqrBenchSizes = []int{
+ 1, 2, 3, 5, 8, 10, 20, 30, 50, 80,
+ 100, 200, 300, 500, 800,
+ 1000, 10000, 100000,
+}
+
+func BenchmarkNatSqr(b *testing.B) {
+ for _, n := range sqrBenchSizes {
+ if isRaceBuilder && n > 1e3 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
+ benchmarkNatSqr(b, n)
+ })
+ }
+}
+
+var subMod2NTests = []struct {
+ x string
+ y string
+ n uint
+ z string
+}{
+ {"1", "2", 0, "0"},
+ {"1", "0", 1, "1"},
+ {"0", "1", 1, "1"},
+ {"3", "5", 3, "6"},
+ {"5", "3", 3, "2"},
+ // 2^65, 2^66-1, 2^65 - (2^66-1) + 2^67
+ {"36893488147419103232", "73786976294838206463", 67, "110680464442257309697"},
+ // 2^66-1, 2^65, 2^65-1
+ {"73786976294838206463", "36893488147419103232", 67, "36893488147419103231"},
+}
+
+func TestNatSubMod2N(t *testing.T) {
+ for _, mode := range []string{"noalias", "aliasX", "aliasY"} {
+ t.Run(mode, func(t *testing.T) {
+ for _, tt := range subMod2NTests {
+ x0 := natFromString(tt.x)
+ y0 := natFromString(tt.y)
+ want := natFromString(tt.z)
+ x := nat(nil).set(x0)
+ y := nat(nil).set(y0)
+ var z nat
+ switch mode {
+ case "aliasX":
+ z = x
+ case "aliasY":
+ z = y
+ }
+ z = z.subMod2N(x, y, tt.n)
+ if z.cmp(want) != 0 {
+ t.Fatalf("subMod2N(%d, %d, %d) = %d, want %d", x0, y0, tt.n, z, want)
+ }
+ if mode != "aliasX" && x.cmp(x0) != 0 {
+ t.Fatalf("subMod2N(%d, %d, %d) modified x", x0, y0, tt.n)
+ }
+ if mode != "aliasY" && y.cmp(y0) != 0 {
+ t.Fatalf("subMod2N(%d, %d, %d) modified y", x0, y0, tt.n)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkNatSetBytes(b *testing.B) {
+ const maxLength = 128
+ lengths := []int{
+ // No remainder:
+ 8, 24, maxLength,
+ // With remainder:
+ 7, 23, maxLength - 1,
+ }
+ n := make(nat, maxLength/_W) // ensure n doesn't need to grow during the test
+ buf := make([]byte, maxLength)
+ for _, l := range lengths {
+ b.Run(fmt.Sprint(l), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ n.setBytes(buf[:l])
+ }
+ })
+ }
+}
+
+func TestNatDiv(t *testing.T) {
+ sizes := []int{
+ 1, 2, 5, 8, 15, 25, 40, 65, 100,
+ 200, 500, 800, 1500, 2500, 4000, 6500, 10000,
+ }
+ for _, i := range sizes {
+ for _, j := range sizes {
+ a := rndNat1(i)
+ b := rndNat1(j)
+ // the test requires b >= 2
+ if len(b) == 1 && b[0] == 1 {
+ b[0] = 2
+ }
+ // choose a remainder c < b
+ c := rndNat1(len(b))
+ if len(c) == len(b) && c[len(c)-1] >= b[len(b)-1] {
+ c[len(c)-1] = 0
+ c = c.norm()
+ }
+ // compute x = a*b+c
+ x := nat(nil).mul(a, b)
+ x = x.add(x, c)
+
+ var q, r nat
+ q, r = q.div(r, x, b)
+ if q.cmp(a) != 0 {
+ t.Fatalf("wrong quotient: got %s; want %s for %s/%s", q.utoa(10), a.utoa(10), x.utoa(10), b.utoa(10))
+ }
+ if r.cmp(c) != 0 {
+ t.Fatalf("wrong remainder: got %s; want %s for %s/%s", r.utoa(10), c.utoa(10), x.utoa(10), b.utoa(10))
+ }
+ }
+ }
+}
+
+// TestIssue37499 triggers the edge case of divBasic where
+// the inaccurate estimate of the first word's quotient
+// happens at the very beginning of the loop.
+func TestIssue37499(t *testing.T) {
+ // Choose u and v such that v is slightly larger than u >> N.
+ // This tricks divBasic into choosing 1 as the first word
+ // of the quotient. This works in both 32-bit and 64-bit settings.
+ u := natFromString("0x2b6c385a05be027f5c22005b63c42a1165b79ff510e1706b39f8489c1d28e57bb5ba4ef9fd9387a3e344402c0a453381")
+ v := natFromString("0x2b6c385a05be027f5c22005b63c42a1165b79ff510e1706c")
+
+ q := nat(nil).make(8)
+ q.divBasic(u, v)
+ q = q.norm()
+ if s := string(q.utoa(16)); s != "fffffffffffffffffffffffffffffffffffffffffffffffb" {
+ t.Fatalf("incorrect quotient: %s", s)
+ }
+}
+
+// TestIssue42552 triggers an edge case of recursive division
+// where the first division loop is never entered, and correcting
+// the remainder takes exactly two iterations in the final loop.
+func TestIssue42552(t *testing.T) {
+ u := natFromString("0xc23b166884c3869092a520eceedeced2b00847bd256c9cf3b2c5e2227c15bd5e6ee7ef8a2f49236ad0eedf2c8a3b453cf6e0706f64285c526b372c4b1321245519d430540804a50b7ca8b6f1b34a2ec05cdbc24de7599af112d3e3c8db347e8799fe70f16e43c6566ba3aeb169463a3ecc486172deb2d9b80a3699c776e44fef20036bd946f1b4d054dd88a2c1aeb986199b0b2b7e58c42288824b74934d112fe1fc06e06b4d99fe1c5e725946b23210521e209cd507cce90b5f39a523f27e861f9e232aee50c3f585208b4573dcc0b897b6177f2ba20254fd5c50a033e849dee1b3a93bd2dc44ba8ca836cab2c2ae50e50b126284524fa0187af28628ff0face68d87709200329db1392852c8b8963fbe3d05fb1efe19f0ed5ca9fadc2f96f82187c24bb2512b2e85a66333a7e176605695211e1c8e0b9b9e82813e50654964945b1e1e66a90840396c7d10e23e47f364d2d3f660fa54598e18d1ca2ea4fe4f35a40a11f69f201c80b48eaee3e2e9b0eda63decf92bec08a70f731587d4ed0f218d5929285c8b2ccbc497e20db42de73885191fa453350335990184d8df805072f958d5354debda38f5421effaaafd6cb9b721ace74be0892d77679f62a4a126697cd35797f6858193da4ba1770c06aea2e5c59ec04b8ea26749e61b72ecdde403f3bc7e5e546cd799578cc939fa676dfd5e648576d4a06cbadb028adc2c0b461f145b2321f42e5e0f3b4fb898ecd461df07a6f5154067787bf74b5cc5c03704a1ce47494961931f0263b0aac32505102595957531a2de69dd71aac51f8a49902f81f21283dbe8e21e01e5d82517868826f86acf338d935aa6b4d5a25c8d540389b277dd9d64569d68baf0f71bd03dba45b92a7fc052601d1bd011a2fc6790a23f97c6fa5caeea040ab86841f268d39ce4f7caf01069df78bba098e04366492f0c2ac24f1bf16828752765fa523c9a4d42b71109d123e6be8c7b1ab3ccf8ea03404075fe1a9596f1bba1d267f9a7879ceece514818316c9c0583469d2367831fc42b517ea028a28df7c18d783d16ea2436cee2b15d52db68b5dfdee6b4d26f0905f9b030c911a04d078923a4136afea96eed6874462a482917353264cc9bee298f167ac65a6db4e4eda88044b39cc0b33183843eaa946564a00c3a0ab661f2c915e70bf0bb65bfbb6fa2eea20aed16bf2c1a1d00ec55fb4ff2f76b8e462ea70c19efa579c9ee78194b86708fdae66a9ce6e2cf3d366037798cfb50277ba6d2fd4866361022fd788ab7735b40b8b61d55e32243e06719e53992e9ac16c9c4b6e6933635c3c47c8f7e73e17dd54d0dd8aeba5d76de46894e7b3f9d3ec25ad78ee82297ba69905ea0fa094b8667faa2b8885e2187b3da80268aa1164761d7b0d6de206b676777348152b8ae1d4afed753bc63c739a5ca8ce7afb2b241a226bd9e502baba391b5b13f5054f070b65a9cf3a67063bfaa803ba390732cd03888f664023f888741d04d564e0b5674b0a183ace81452001b3fbb4214c77d42ca75376742c471e58f67307726d56a1032bd236610cbcbcd03d0d7a452900136897dc55bb3ce959d10d4e6a10fb635006bd8c41cd9ded2d3dfdd8f2e229590324a7370cb2124210b2330f4c56155caa09a2564932ceded8d92c79664dcdeb87faad7d3da006cc2ea267ee3df41e9677789cc5a8cc3b83add6491561b3047919e0648b1b2e97d7ad6f6c2aa80cab8e9ae10e1f75b1fdd0246151af709d259a6a0ed0b26bd711024965ecad7c41387de45443defce53f66612948694a6032279131c257119ed876a8e805dfb49576ef5c563574115ee87050d92d191bc761ef51d966918e2ef925639400069e3959d8fe19f36136e947ff430bf74e71da0aa5923b00000000")
+ v := natFromString("0x838332321d443a3d30373d47301d47073847473a383d3030f25b3d3d3e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002e00000000000000000041603038331c3d32f5303441e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e01c0a5459bfc7b9be9fcbb9d2383840464319434707303030f43a32f53034411c0a5459413820878787878787878787878787878787878787878787878787878787878787878787870630303a3a30334036605b923a6101f83638413943413960204337602043323801526040523241846038414143015238604060328452413841413638523c0240384141364036605b923a6101f83638413943413960204334602043323801526040523241846038414143015238604060328452413841413638523c02403841413638433030f25a8b83838383838383838383838383838383837d838383ffffffffffffffff838383838383838383000000000000000000030000007d26e27c7c8b83838383838383838383838383838383837d838383ffffffffffffffff83838383838383838383838383838383838383838383435960f535073030f3343200000000000000011881301938343030fa398383300000002300000000000000000000f11af4600c845252904141364138383c60406032414443095238010241414303364443434132305b595a15434160b042385341ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff47476043410536613603593a6005411c437405fcfcfcfcfcfcfc0000000000005a3b075815054359000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
+ q := nat(nil).make(16)
+ q.div(q, u, v)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/natconv.go b/platform/dbops/binaries/go/go/src/math/big/natconv.go
new file mode 100644
index 0000000000000000000000000000000000000000..ce94f2cf72e9a1b3fb385c01ac4dd10694f3fb8c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/natconv.go
@@ -0,0 +1,511 @@
+// 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 nat-to-string conversion functions.
+
+package big
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "math/bits"
+ "sync"
+)
+
+const digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+// Note: MaxBase = len(digits), but it must remain an untyped rune constant
+// for API compatibility.
+
+// MaxBase is the largest number base accepted for string conversions.
+const MaxBase = 10 + ('z' - 'a' + 1) + ('Z' - 'A' + 1)
+const maxBaseSmall = 10 + ('z' - 'a' + 1)
+
+// maxPow returns (b**n, n) such that b**n is the largest power b**n <= _M.
+// For instance maxPow(10) == (1e19, 19) for 19 decimal digits in a 64bit Word.
+// In other words, at most n digits in base b fit into a Word.
+// TODO(gri) replace this with a table, generated at build time.
+func maxPow(b Word) (p Word, n int) {
+ p, n = b, 1 // assuming b <= _M
+ for max := _M / b; p <= max; {
+ // p == b**n && p <= max
+ p *= b
+ n++
+ }
+ // p == b**n && p <= _M
+ return
+}
+
+// pow returns x**n for n > 0, and 1 otherwise.
+func pow(x Word, n int) (p Word) {
+ // n == sum of bi * 2**i, for 0 <= i < imax, and bi is 0 or 1
+ // thus x**n == product of x**(2**i) for all i where bi == 1
+ // (Russian Peasant Method for exponentiation)
+ p = 1
+ for n > 0 {
+ if n&1 != 0 {
+ p *= x
+ }
+ x *= x
+ n >>= 1
+ }
+ return
+}
+
+// scan errors
+var (
+ errNoDigits = errors.New("number has no digits")
+ errInvalSep = errors.New("'_' must separate successive digits")
+)
+
+// scan scans the number corresponding to the longest possible prefix
+// from r representing an unsigned number in a given conversion base.
+// scan returns the corresponding natural number res, the actual base b,
+// a digit count, and a read or syntax error err, if any.
+//
+// For base 0, an underscore character “_” may appear between a base
+// prefix and an adjacent digit, and between successive digits; such
+// underscores do not change the value of the number, or the returned
+// digit count. Incorrect placement of underscores is reported as an
+// error if there are no other errors. If base != 0, underscores are
+// not recognized and thus terminate scanning like any other character
+// that is not a valid radix point or digit.
+//
+// number = mantissa | prefix pmantissa .
+// prefix = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
+// mantissa = digits "." [ digits ] | digits | "." digits .
+// pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
+// digits = digit { [ "_" ] digit } .
+// digit = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
+//
+// Unless fracOk is set, the base argument must be 0 or a value between
+// 2 and MaxBase. If fracOk is set, the base argument must be one of
+// 0, 2, 8, 10, or 16. Providing an invalid base argument leads to a run-
+// time panic.
+//
+// For base 0, the number prefix determines the actual base: A prefix of
+// “0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and
+// “0x” or “0X” selects base 16. If fracOk is false, a “0” prefix
+// (immediately followed by digits) selects base 8 as well. Otherwise,
+// the selected base is 10 and no prefix is accepted.
+//
+// If fracOk is set, a period followed by a fractional part is permitted.
+// The result value is computed as if there were no period present; and
+// the count value is used to determine the fractional part.
+//
+// For bases <= 36, lower and upper case letters are considered the same:
+// The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35.
+// For bases > 36, the upper case letters 'A' to 'Z' represent the digit
+// values 36 to 61.
+//
+// A result digit count > 0 corresponds to the number of (non-prefix) digits
+// parsed. A digit count <= 0 indicates the presence of a period (if fracOk
+// is set, only), and -count is the number of fractional digits found.
+// In this case, the actual value of the scanned number is res * b**count.
+func (z nat) scan(r io.ByteScanner, base int, fracOk bool) (res nat, b, count int, err error) {
+ // reject invalid bases
+ baseOk := base == 0 ||
+ !fracOk && 2 <= base && base <= MaxBase ||
+ fracOk && (base == 2 || base == 8 || base == 10 || base == 16)
+ if !baseOk {
+ panic(fmt.Sprintf("invalid number base %d", base))
+ }
+
+ // prev encodes the previously seen char: it is one
+ // of '_', '0' (a digit), or '.' (anything else). A
+ // valid separator '_' may only occur after a digit
+ // and if base == 0.
+ prev := '.'
+ invalSep := false
+
+ // one char look-ahead
+ ch, err := r.ReadByte()
+
+ // determine actual base
+ b, prefix := base, 0
+ if base == 0 {
+ // actual base is 10 unless there's a base prefix
+ b = 10
+ if err == nil && ch == '0' {
+ prev = '0'
+ count = 1
+ ch, err = r.ReadByte()
+ if err == nil {
+ // possibly one of 0b, 0B, 0o, 0O, 0x, 0X
+ switch ch {
+ case 'b', 'B':
+ b, prefix = 2, 'b'
+ case 'o', 'O':
+ b, prefix = 8, 'o'
+ case 'x', 'X':
+ b, prefix = 16, 'x'
+ default:
+ if !fracOk {
+ b, prefix = 8, '0'
+ }
+ }
+ if prefix != 0 {
+ count = 0 // prefix is not counted
+ if prefix != '0' {
+ ch, err = r.ReadByte()
+ }
+ }
+ }
+ }
+ }
+
+ // convert string
+ // Algorithm: Collect digits in groups of at most n digits in di
+ // and then use mulAddWW for every such group to add them to the
+ // result.
+ z = z[:0]
+ b1 := Word(b)
+ bn, n := maxPow(b1) // at most n digits in base b1 fit into Word
+ di := Word(0) // 0 <= di < b1**i < bn
+ i := 0 // 0 <= i < n
+ dp := -1 // position of decimal point
+ for err == nil {
+ if ch == '.' && fracOk {
+ fracOk = false
+ if prev == '_' {
+ invalSep = true
+ }
+ prev = '.'
+ dp = count
+ } else if ch == '_' && base == 0 {
+ if prev != '0' {
+ invalSep = true
+ }
+ prev = '_'
+ } else {
+ // convert rune into digit value d1
+ var d1 Word
+ switch {
+ case '0' <= ch && ch <= '9':
+ d1 = Word(ch - '0')
+ case 'a' <= ch && ch <= 'z':
+ d1 = Word(ch - 'a' + 10)
+ case 'A' <= ch && ch <= 'Z':
+ if b <= maxBaseSmall {
+ d1 = Word(ch - 'A' + 10)
+ } else {
+ d1 = Word(ch - 'A' + maxBaseSmall)
+ }
+ default:
+ d1 = MaxBase + 1
+ }
+ if d1 >= b1 {
+ r.UnreadByte() // ch does not belong to number anymore
+ break
+ }
+ prev = '0'
+ count++
+
+ // collect d1 in di
+ di = di*b1 + d1
+ i++
+
+ // if di is "full", add it to the result
+ if i == n {
+ z = z.mulAddWW(z, bn, di)
+ di = 0
+ i = 0
+ }
+ }
+
+ ch, err = r.ReadByte()
+ }
+
+ if err == io.EOF {
+ err = nil
+ }
+
+ // other errors take precedence over invalid separators
+ if err == nil && (invalSep || prev == '_') {
+ err = errInvalSep
+ }
+
+ if count == 0 {
+ // no digits found
+ if prefix == '0' {
+ // there was only the octal prefix 0 (possibly followed by separators and digits > 7);
+ // interpret as decimal 0
+ return z[:0], 10, 1, err
+ }
+ err = errNoDigits // fall through; result will be 0
+ }
+
+ // add remaining digits to result
+ if i > 0 {
+ z = z.mulAddWW(z, pow(b1, i), di)
+ }
+ res = z.norm()
+
+ // adjust count for fraction, if any
+ if dp >= 0 {
+ // 0 <= dp <= count
+ count = dp - count
+ }
+
+ return
+}
+
+// utoa converts x to an ASCII representation in the given base;
+// base must be between 2 and MaxBase, inclusive.
+func (x nat) utoa(base int) []byte {
+ return x.itoa(false, base)
+}
+
+// itoa is like utoa but it prepends a '-' if neg && x != 0.
+func (x nat) itoa(neg bool, base int) []byte {
+ if base < 2 || base > MaxBase {
+ panic("invalid base")
+ }
+
+ // x == 0
+ if len(x) == 0 {
+ return []byte("0")
+ }
+ // len(x) > 0
+
+ // allocate buffer for conversion
+ i := int(float64(x.bitLen())/math.Log2(float64(base))) + 1 // off by 1 at most
+ if neg {
+ i++
+ }
+ s := make([]byte, i)
+
+ // convert power of two and non power of two bases separately
+ if b := Word(base); b == b&-b {
+ // shift is base b digit size in bits
+ shift := uint(bits.TrailingZeros(uint(b))) // shift > 0 because b >= 2
+ mask := Word(1<= shift {
+ i--
+ s[i] = digits[w&mask]
+ w >>= shift
+ nbits -= shift
+ }
+
+ // convert any partial leading digit and advance to next word
+ if nbits == 0 {
+ // no partial digit remaining, just advance
+ w = x[k]
+ nbits = _W
+ } else {
+ // partial digit in current word w (== x[k-1]) and next word x[k]
+ w |= x[k] << nbits
+ i--
+ s[i] = digits[w&mask]
+
+ // advance
+ w = x[k] >> (shift - nbits)
+ nbits = _W - (shift - nbits)
+ }
+ }
+
+ // convert digits of most-significant word w (omit leading zeros)
+ for w != 0 {
+ i--
+ s[i] = digits[w&mask]
+ w >>= shift
+ }
+
+ } else {
+ bb, ndigits := maxPow(b)
+
+ // construct table of successive squares of bb*leafSize to use in subdivisions
+ // result (table != nil) <=> (len(x) > leafSize > 0)
+ table := divisors(len(x), b, ndigits, bb)
+
+ // preserve x, create local copy for use by convertWords
+ q := nat(nil).set(x)
+
+ // convert q to string s in base b
+ q.convertWords(s, b, ndigits, bb, table)
+
+ // strip leading zeros
+ // (x != 0; thus s must contain at least one non-zero digit
+ // and the loop will terminate)
+ i = 0
+ for s[i] == '0' {
+ i++
+ }
+ }
+
+ if neg {
+ i--
+ s[i] = '-'
+ }
+
+ return s[i:]
+}
+
+// Convert words of q to base b digits in s. If q is large, it is recursively "split in half"
+// by nat/nat division using tabulated divisors. Otherwise, it is converted iteratively using
+// repeated nat/Word division.
+//
+// The iterative method processes n Words by n divW() calls, each of which visits every Word in the
+// incrementally shortened q for a total of n + (n-1) + (n-2) ... + 2 + 1, or n(n+1)/2 divW()'s.
+// Recursive conversion divides q by its approximate square root, yielding two parts, each half
+// the size of q. Using the iterative method on both halves means 2 * (n/2)(n/2 + 1)/2 divW()'s
+// plus the expensive long div(). Asymptotically, the ratio is favorable at 1/2 the divW()'s, and
+// is made better by splitting the subblocks recursively. Best is to split blocks until one more
+// split would take longer (because of the nat/nat div()) than the twice as many divW()'s of the
+// iterative approach. This threshold is represented by leafSize. Benchmarking of leafSize in the
+// range 2..64 shows that values of 8 and 16 work well, with a 4x speedup at medium lengths and
+// ~30x for 20000 digits. Use nat_test.go's BenchmarkLeafSize tests to optimize leafSize for
+// specific hardware.
+func (q nat) convertWords(s []byte, b Word, ndigits int, bb Word, table []divisor) {
+ // split larger blocks recursively
+ if table != nil {
+ // len(q) > leafSize > 0
+ var r nat
+ index := len(table) - 1
+ for len(q) > leafSize {
+ // find divisor close to sqrt(q) if possible, but in any case < q
+ maxLength := q.bitLen() // ~= log2 q, or at of least largest possible q of this bit length
+ minLength := maxLength >> 1 // ~= log2 sqrt(q)
+ for index > 0 && table[index-1].nbits > minLength {
+ index-- // desired
+ }
+ if table[index].nbits >= maxLength && table[index].bbb.cmp(q) >= 0 {
+ index--
+ if index < 0 {
+ panic("internal inconsistency")
+ }
+ }
+
+ // split q into the two digit number (q'*bbb + r) to form independent subblocks
+ q, r = q.div(r, q, table[index].bbb)
+
+ // convert subblocks and collect results in s[:h] and s[h:]
+ h := len(s) - table[index].ndigits
+ r.convertWords(s[h:], b, ndigits, bb, table[0:index])
+ s = s[:h] // == q.convertWords(s, b, ndigits, bb, table[0:index+1])
+ }
+ }
+
+ // having split any large blocks now process the remaining (small) block iteratively
+ i := len(s)
+ var r Word
+ if b == 10 {
+ // hard-coding for 10 here speeds this up by 1.25x (allows for / and % by constants)
+ for len(q) > 0 {
+ // extract least significant, base bb "digit"
+ q, r = q.divW(q, bb)
+ for j := 0; j < ndigits && i > 0; j++ {
+ i--
+ // avoid % computation since r%10 == r - int(r/10)*10;
+ // this appears to be faster for BenchmarkString10000Base10
+ // and smaller strings (but a bit slower for larger ones)
+ t := r / 10
+ s[i] = '0' + byte(r-t*10)
+ r = t
+ }
+ }
+ } else {
+ for len(q) > 0 {
+ // extract least significant, base bb "digit"
+ q, r = q.divW(q, bb)
+ for j := 0; j < ndigits && i > 0; j++ {
+ i--
+ s[i] = digits[r%b]
+ r /= b
+ }
+ }
+ }
+
+ // prepend high-order zeros
+ for i > 0 { // while need more leading zeros
+ i--
+ s[i] = '0'
+ }
+}
+
+// Split blocks greater than leafSize Words (or set to 0 to disable recursive conversion)
+// Benchmark and configure leafSize using: go test -bench="Leaf"
+//
+// 8 and 16 effective on 3.0 GHz Xeon "Clovertown" CPU (128 byte cache lines)
+// 8 and 16 effective on 2.66 GHz Core 2 Duo "Penryn" CPU
+var leafSize int = 8 // number of Word-size binary values treat as a monolithic block
+
+type divisor struct {
+ bbb nat // divisor
+ nbits int // bit length of divisor (discounting leading zeros) ~= log2(bbb)
+ ndigits int // digit length of divisor in terms of output base digits
+}
+
+var cacheBase10 struct {
+ sync.Mutex
+ table [64]divisor // cached divisors for base 10
+}
+
+// expWW computes x**y
+func (z nat) expWW(x, y Word) nat {
+ return z.expNN(nat(nil).setWord(x), nat(nil).setWord(y), nil, false)
+}
+
+// construct table of powers of bb*leafSize to use in subdivisions.
+func divisors(m int, b Word, ndigits int, bb Word) []divisor {
+ // only compute table when recursive conversion is enabled and x is large
+ if leafSize == 0 || m <= leafSize {
+ return nil
+ }
+
+ // determine k where (bb**leafSize)**(2**k) >= sqrt(x)
+ k := 1
+ for words := leafSize; words < m>>1 && k < len(cacheBase10.table); words <<= 1 {
+ k++
+ }
+
+ // reuse and extend existing table of divisors or create new table as appropriate
+ var table []divisor // for b == 10, table overlaps with cacheBase10.table
+ if b == 10 {
+ cacheBase10.Lock()
+ table = cacheBase10.table[0:k] // reuse old table for this conversion
+ } else {
+ table = make([]divisor, k) // create new table for this conversion
+ }
+
+ // extend table
+ if table[k-1].ndigits == 0 {
+ // add new entries as needed
+ var larger nat
+ for i := 0; i < k; i++ {
+ if table[i].ndigits == 0 {
+ if i == 0 {
+ table[0].bbb = nat(nil).expWW(bb, Word(leafSize))
+ table[0].ndigits = ndigits * leafSize
+ } else {
+ table[i].bbb = nat(nil).sqr(table[i-1].bbb)
+ table[i].ndigits = 2 * table[i-1].ndigits
+ }
+
+ // optimization: exploit aggregated extra bits in macro blocks
+ larger = nat(nil).set(table[i].bbb)
+ for mulAddVWW(larger, larger, b, 0) == 0 {
+ table[i].bbb = table[i].bbb.set(larger)
+ table[i].ndigits++
+ }
+
+ table[i].nbits = table[i].bbb.bitLen()
+ }
+ }
+ }
+
+ if b == 10 {
+ cacheBase10.Unlock()
+ }
+
+ return table
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/natconv_test.go b/platform/dbops/binaries/go/go/src/math/big/natconv_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d39027210851529a124f9dcc1b827124243693b8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/natconv_test.go
@@ -0,0 +1,463 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "math/bits"
+ "strings"
+ "testing"
+)
+
+func TestMaxBase(t *testing.T) {
+ if MaxBase != len(digits) {
+ t.Fatalf("%d != %d", MaxBase, len(digits))
+ }
+}
+
+// log2 computes the integer binary logarithm of x.
+// The result is the integer n for which 2^n <= x < 2^(n+1).
+// If x == 0, the result is -1.
+func log2(x Word) int {
+ return bits.Len(uint(x)) - 1
+}
+
+func itoa(x nat, base int) []byte {
+ // special cases
+ switch {
+ case base < 2:
+ panic("illegal base")
+ case len(x) == 0:
+ return []byte("0")
+ }
+
+ // allocate buffer for conversion
+ i := x.bitLen()/log2(Word(base)) + 1 // +1: round up
+ s := make([]byte, i)
+
+ // don't destroy x
+ q := nat(nil).set(x)
+
+ // convert
+ for len(q) > 0 {
+ i--
+ var r Word
+ q, r = q.divW(q, Word(base))
+ s[i] = digits[r]
+ }
+
+ return s[i:]
+}
+
+var strTests = []struct {
+ x nat // nat value to be converted
+ b int // conversion base
+ s string // expected result
+}{
+ {nil, 2, "0"},
+ {nat{1}, 2, "1"},
+ {nat{0xc5}, 2, "11000101"},
+ {nat{03271}, 8, "3271"},
+ {nat{10}, 10, "10"},
+ {nat{1234567890}, 10, "1234567890"},
+ {nat{0xdeadbeef}, 16, "deadbeef"},
+ {nat{0x229be7}, 17, "1a2b3c"},
+ {nat{0x309663e6}, 32, "o9cov6"},
+ {nat{0x309663e6}, 62, "TakXI"},
+}
+
+func TestString(t *testing.T) {
+ // test invalid base explicitly
+ var panicStr string
+ func() {
+ defer func() {
+ panicStr = recover().(string)
+ }()
+ natOne.utoa(1)
+ }()
+ if panicStr != "invalid base" {
+ t.Errorf("expected panic for invalid base")
+ }
+
+ for _, a := range strTests {
+ s := string(a.x.utoa(a.b))
+ if s != a.s {
+ t.Errorf("string%+v\n\tgot s = %s; want %s", a, s, a.s)
+ }
+
+ x, b, _, err := nat(nil).scan(strings.NewReader(a.s), a.b, false)
+ if x.cmp(a.x) != 0 {
+ t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
+ }
+ if b != a.b {
+ t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.b)
+ }
+ if err != nil {
+ t.Errorf("scan%+v\n\tgot error = %s", a, err)
+ }
+ }
+}
+
+var natScanTests = []struct {
+ s string // string to be scanned
+ base int // input base
+ frac bool // fraction ok
+ x nat // expected nat
+ b int // expected base
+ count int // expected digit count
+ err error // expected error
+ next rune // next character (or 0, if at EOF)
+}{
+ // invalid: no digits
+ {"", 0, false, nil, 10, 0, errNoDigits, 0},
+ {"_", 0, false, nil, 10, 0, errNoDigits, 0},
+ {"?", 0, false, nil, 10, 0, errNoDigits, '?'},
+ {"?", 10, false, nil, 10, 0, errNoDigits, '?'},
+ {"", 10, false, nil, 10, 0, errNoDigits, 0},
+ {"", 36, false, nil, 36, 0, errNoDigits, 0},
+ {"", 62, false, nil, 62, 0, errNoDigits, 0},
+ {"0b", 0, false, nil, 2, 0, errNoDigits, 0},
+ {"0o", 0, false, nil, 8, 0, errNoDigits, 0},
+ {"0x", 0, false, nil, 16, 0, errNoDigits, 0},
+ {"0x_", 0, false, nil, 16, 0, errNoDigits, 0},
+ {"0b2", 0, false, nil, 2, 0, errNoDigits, '2'},
+ {"0B2", 0, false, nil, 2, 0, errNoDigits, '2'},
+ {"0o8", 0, false, nil, 8, 0, errNoDigits, '8'},
+ {"0O8", 0, false, nil, 8, 0, errNoDigits, '8'},
+ {"0xg", 0, false, nil, 16, 0, errNoDigits, 'g'},
+ {"0Xg", 0, false, nil, 16, 0, errNoDigits, 'g'},
+ {"345", 2, false, nil, 2, 0, errNoDigits, '3'},
+
+ // invalid: incorrect use of decimal point
+ {"._", 0, true, nil, 10, 0, errNoDigits, 0},
+ {".0", 0, false, nil, 10, 0, errNoDigits, '.'},
+ {".0", 10, false, nil, 10, 0, errNoDigits, '.'},
+ {".", 0, true, nil, 10, 0, errNoDigits, 0},
+ {"0x.", 0, true, nil, 16, 0, errNoDigits, 0},
+ {"0x.g", 0, true, nil, 16, 0, errNoDigits, 'g'},
+ {"0x.0", 0, false, nil, 16, 0, errNoDigits, '.'},
+
+ // invalid: incorrect use of separators
+ {"_0", 0, false, nil, 10, 1, errInvalSep, 0},
+ {"0_", 0, false, nil, 10, 1, errInvalSep, 0},
+ {"0__0", 0, false, nil, 8, 1, errInvalSep, 0},
+ {"0x___0", 0, false, nil, 16, 1, errInvalSep, 0},
+ {"0_x", 0, false, nil, 10, 1, errInvalSep, 'x'},
+ {"0_8", 0, false, nil, 10, 1, errInvalSep, '8'},
+ {"123_.", 0, true, nat{123}, 10, 0, errInvalSep, 0},
+ {"._123", 0, true, nat{123}, 10, -3, errInvalSep, 0},
+ {"0b__1000", 0, false, nat{0x8}, 2, 4, errInvalSep, 0},
+ {"0o60___0", 0, false, nat{0600}, 8, 3, errInvalSep, 0},
+ {"0466_", 0, false, nat{0466}, 8, 3, errInvalSep, 0},
+ {"01234567_8", 0, false, nat{01234567}, 8, 7, errInvalSep, '8'},
+ {"1_.", 0, true, nat{1}, 10, 0, errInvalSep, 0},
+ {"0._1", 0, true, nat{1}, 10, -1, errInvalSep, 0},
+ {"2.7_", 0, true, nat{27}, 10, -1, errInvalSep, 0},
+ {"0x1.0_", 0, true, nat{0x10}, 16, -1, errInvalSep, 0},
+
+ // valid: separators are not accepted for base != 0
+ {"0_", 10, false, nil, 10, 1, nil, '_'},
+ {"1__0", 10, false, nat{1}, 10, 1, nil, '_'},
+ {"0__8", 10, false, nil, 10, 1, nil, '_'},
+ {"xy_z_", 36, false, nat{33*36 + 34}, 36, 2, nil, '_'},
+
+ // valid, no decimal point
+ {"0", 0, false, nil, 10, 1, nil, 0},
+ {"0", 36, false, nil, 36, 1, nil, 0},
+ {"0", 62, false, nil, 62, 1, nil, 0},
+ {"1", 0, false, nat{1}, 10, 1, nil, 0},
+ {"1", 10, false, nat{1}, 10, 1, nil, 0},
+ {"0 ", 0, false, nil, 10, 1, nil, ' '},
+ {"00 ", 0, false, nil, 8, 1, nil, ' '}, // octal 0
+ {"0b1", 0, false, nat{1}, 2, 1, nil, 0},
+ {"0B11000101", 0, false, nat{0xc5}, 2, 8, nil, 0},
+ {"0B110001012", 0, false, nat{0xc5}, 2, 8, nil, '2'},
+ {"07", 0, false, nat{7}, 8, 1, nil, 0},
+ {"08", 0, false, nil, 10, 1, nil, '8'},
+ {"08", 10, false, nat{8}, 10, 2, nil, 0},
+ {"018", 0, false, nat{1}, 8, 1, nil, '8'},
+ {"0o7", 0, false, nat{7}, 8, 1, nil, 0},
+ {"0o18", 0, false, nat{1}, 8, 1, nil, '8'},
+ {"0O17", 0, false, nat{017}, 8, 2, nil, 0},
+ {"03271", 0, false, nat{03271}, 8, 4, nil, 0},
+ {"10ab", 0, false, nat{10}, 10, 2, nil, 'a'},
+ {"1234567890", 0, false, nat{1234567890}, 10, 10, nil, 0},
+ {"A", 36, false, nat{10}, 36, 1, nil, 0},
+ {"A", 37, false, nat{36}, 37, 1, nil, 0},
+ {"xyz", 36, false, nat{(33*36+34)*36 + 35}, 36, 3, nil, 0},
+ {"XYZ?", 36, false, nat{(33*36+34)*36 + 35}, 36, 3, nil, '?'},
+ {"XYZ?", 62, false, nat{(59*62+60)*62 + 61}, 62, 3, nil, '?'},
+ {"0x", 16, false, nil, 16, 1, nil, 'x'},
+ {"0xdeadbeef", 0, false, nat{0xdeadbeef}, 16, 8, nil, 0},
+ {"0XDEADBEEF", 0, false, nat{0xdeadbeef}, 16, 8, nil, 0},
+
+ // valid, with decimal point
+ {"0.", 0, false, nil, 10, 1, nil, '.'},
+ {"0.", 10, true, nil, 10, 0, nil, 0},
+ {"0.1.2", 10, true, nat{1}, 10, -1, nil, '.'},
+ {".000", 10, true, nil, 10, -3, nil, 0},
+ {"12.3", 10, true, nat{123}, 10, -1, nil, 0},
+ {"012.345", 10, true, nat{12345}, 10, -3, nil, 0},
+ {"0.1", 0, true, nat{1}, 10, -1, nil, 0},
+ {"0.1", 2, true, nat{1}, 2, -1, nil, 0},
+ {"0.12", 2, true, nat{1}, 2, -1, nil, '2'},
+ {"0b0.1", 0, true, nat{1}, 2, -1, nil, 0},
+ {"0B0.12", 0, true, nat{1}, 2, -1, nil, '2'},
+ {"0o0.7", 0, true, nat{7}, 8, -1, nil, 0},
+ {"0O0.78", 0, true, nat{7}, 8, -1, nil, '8'},
+ {"0xdead.beef", 0, true, nat{0xdeadbeef}, 16, -4, nil, 0},
+
+ // valid, with separators
+ {"1_000", 0, false, nat{1000}, 10, 4, nil, 0},
+ {"0_466", 0, false, nat{0466}, 8, 3, nil, 0},
+ {"0o_600", 0, false, nat{0600}, 8, 3, nil, 0},
+ {"0x_f0_0d", 0, false, nat{0xf00d}, 16, 4, nil, 0},
+ {"0b1000_0001", 0, false, nat{0x81}, 2, 8, nil, 0},
+ {"1_000.000_1", 0, true, nat{10000001}, 10, -4, nil, 0},
+ {"0x_f00d.1e", 0, true, nat{0xf00d1e}, 16, -2, nil, 0},
+ {"0x_f00d.1E2", 0, true, nat{0xf00d1e2}, 16, -3, nil, 0},
+ {"0x_f00d.1eg", 0, true, nat{0xf00d1e}, 16, -2, nil, 'g'},
+}
+
+func TestScanBase(t *testing.T) {
+ for _, a := range natScanTests {
+ r := strings.NewReader(a.s)
+ x, b, count, err := nat(nil).scan(r, a.base, a.frac)
+ if err != a.err {
+ t.Errorf("scan%+v\n\tgot error = %v; want %v", a, err, a.err)
+ }
+ if x.cmp(a.x) != 0 {
+ t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
+ }
+ if b != a.b {
+ t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
+ }
+ if count != a.count {
+ t.Errorf("scan%+v\n\tgot count = %d; want %d", a, count, a.count)
+ }
+ next, _, err := r.ReadRune()
+ if err == io.EOF {
+ next = 0
+ err = nil
+ }
+ if err == nil && next != a.next {
+ t.Errorf("scan%+v\n\tgot next = %q; want %q", a, next, a.next)
+ }
+ }
+}
+
+var pi = "3" +
+ "14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" +
+ "32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" +
+ "28475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920" +
+ "96282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179" +
+ "31051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798" +
+ "60943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901" +
+ "22495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837" +
+ "29780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083" +
+ "81420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909" +
+ "21642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151" +
+ "55748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035" +
+ "63707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104" +
+ "75216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992" +
+ "45863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818" +
+ "34797753566369807426542527862551818417574672890977772793800081647060016145249192173217214772350141441973568548" +
+ "16136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179" +
+ "04946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886" +
+ "26945604241965285022210661186306744278622039194945047123713786960956364371917287467764657573962413890865832645" +
+ "99581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745" +
+ "53050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382" +
+ "68683868942774155991855925245953959431049972524680845987273644695848653836736222626099124608051243884390451244" +
+ "13654976278079771569143599770012961608944169486855584840635342207222582848864815845602850601684273945226746767" +
+ "88952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288" +
+ "79710893145669136867228748940560101503308617928680920874760917824938589009714909675985261365549781893129784821" +
+ "68299894872265880485756401427047755513237964145152374623436454285844479526586782105114135473573952311342716610" +
+ "21359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435" +
+ "06430218453191048481005370614680674919278191197939952061419663428754440643745123718192179998391015919561814675" +
+ "14269123974894090718649423196156794520809514655022523160388193014209376213785595663893778708303906979207734672" +
+ "21825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539" +
+ "05796268561005508106658796998163574736384052571459102897064140110971206280439039759515677157700420337869936007" +
+ "23055876317635942187312514712053292819182618612586732157919841484882916447060957527069572209175671167229109816" +
+ "90915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398" +
+ "31501970165151168517143765761835155650884909989859982387345528331635507647918535893226185489632132933089857064" +
+ "20467525907091548141654985946163718027098199430992448895757128289059232332609729971208443357326548938239119325" +
+ "97463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100" +
+ "44929321516084244485963766983895228684783123552658213144957685726243344189303968642624341077322697802807318915" +
+ "44110104468232527162010526522721116603966655730925471105578537634668206531098965269186205647693125705863566201" +
+ "85581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318" +
+ "58676975145661406800700237877659134401712749470420562230538994561314071127000407854733269939081454664645880797" +
+ "27082668306343285878569830523580893306575740679545716377525420211495576158140025012622859413021647155097925923" +
+ "09907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111" +
+ "79042978285647503203198691514028708085990480109412147221317947647772622414254854540332157185306142288137585043" +
+ "06332175182979866223717215916077166925474873898665494945011465406284336639379003976926567214638530673609657120" +
+ "91807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862" +
+ "94726547364252308177036751590673502350728354056704038674351362222477158915049530984448933309634087807693259939" +
+ "78054193414473774418426312986080998886874132604721569516239658645730216315981931951673538129741677294786724229" +
+ "24654366800980676928238280689964004824354037014163149658979409243237896907069779422362508221688957383798623001" +
+ "59377647165122893578601588161755782973523344604281512627203734314653197777416031990665541876397929334419521541" +
+ "34189948544473456738316249934191318148092777710386387734317720754565453220777092120190516609628049092636019759" +
+ "88281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267" +
+ "94561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337"
+
+// Test case for BenchmarkScanPi.
+func TestScanPi(t *testing.T) {
+ var x nat
+ z, _, _, err := x.scan(strings.NewReader(pi), 10, false)
+ if err != nil {
+ t.Errorf("scanning pi: %s", err)
+ }
+ if s := string(z.utoa(10)); s != pi {
+ t.Errorf("scanning pi: got %s", s)
+ }
+}
+
+func TestScanPiParallel(t *testing.T) {
+ const n = 2
+ c := make(chan int)
+ for i := 0; i < n; i++ {
+ go func() {
+ TestScanPi(t)
+ c <- 0
+ }()
+ }
+ for i := 0; i < n; i++ {
+ <-c
+ }
+}
+
+func BenchmarkScanPi(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ var x nat
+ x.scan(strings.NewReader(pi), 10, false)
+ }
+}
+
+func BenchmarkStringPiParallel(b *testing.B) {
+ var x nat
+ x, _, _, _ = x.scan(strings.NewReader(pi), 0, false)
+ if string(x.utoa(10)) != pi {
+ panic("benchmark incorrect: conversion failed")
+ }
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ x.utoa(10)
+ }
+ })
+}
+
+func BenchmarkScan(b *testing.B) {
+ const x = 10
+ for _, base := range []int{2, 8, 10, 16} {
+ for _, y := range []Word{10, 100, 1000, 10000, 100000} {
+ if isRaceBuilder && y > 1000 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d/Base%d", y, base), func(b *testing.B) {
+ b.StopTimer()
+ var z nat
+ z = z.expWW(x, y)
+
+ s := z.utoa(base)
+ if t := itoa(z, base); !bytes.Equal(s, t) {
+ b.Fatalf("scanning: got %s; want %s", s, t)
+ }
+ b.StartTimer()
+
+ for i := 0; i < b.N; i++ {
+ z.scan(bytes.NewReader(s), base, false)
+ }
+ })
+ }
+ }
+}
+
+func BenchmarkString(b *testing.B) {
+ const x = 10
+ for _, base := range []int{2, 8, 10, 16} {
+ for _, y := range []Word{10, 100, 1000, 10000, 100000} {
+ if isRaceBuilder && y > 1000 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d/Base%d", y, base), func(b *testing.B) {
+ b.StopTimer()
+ var z nat
+ z = z.expWW(x, y)
+ z.utoa(base) // warm divisor cache
+ b.StartTimer()
+
+ for i := 0; i < b.N; i++ {
+ _ = z.utoa(base)
+ }
+ })
+ }
+ }
+}
+
+func BenchmarkLeafSize(b *testing.B) {
+ for n := 0; n <= 16; n++ {
+ b.Run(fmt.Sprint(n), func(b *testing.B) { LeafSizeHelper(b, 10, n) })
+ }
+ // Try some large lengths
+ for _, n := range []int{32, 64} {
+ b.Run(fmt.Sprint(n), func(b *testing.B) { LeafSizeHelper(b, 10, n) })
+ }
+}
+
+func LeafSizeHelper(b *testing.B, base, size int) {
+ b.StopTimer()
+ originalLeafSize := leafSize
+ resetTable(cacheBase10.table[:])
+ leafSize = size
+ b.StartTimer()
+
+ for d := 1; d <= 10000; d *= 10 {
+ b.StopTimer()
+ var z nat
+ z = z.expWW(Word(base), Word(d)) // build target number
+ _ = z.utoa(base) // warm divisor cache
+ b.StartTimer()
+
+ for i := 0; i < b.N; i++ {
+ _ = z.utoa(base)
+ }
+ }
+
+ b.StopTimer()
+ resetTable(cacheBase10.table[:])
+ leafSize = originalLeafSize
+ b.StartTimer()
+}
+
+func resetTable(table []divisor) {
+ if table != nil && table[0].bbb != nil {
+ for i := 0; i < len(table); i++ {
+ table[i].bbb = nil
+ table[i].nbits = 0
+ table[i].ndigits = 0
+ }
+ }
+}
+
+func TestStringPowers(t *testing.T) {
+ var p Word
+ for b := 2; b <= 16; b++ {
+ for p = 0; p <= 512; p++ {
+ if testing.Short() && p > 10 {
+ break
+ }
+ x := nat(nil).expWW(Word(b), p)
+ xs := x.utoa(b)
+ xs2 := itoa(x, b)
+ if !bytes.Equal(xs, xs2) {
+ t.Errorf("failed at %d ** %d in base %d: %s != %s", b, p, b, xs, xs2)
+ }
+ }
+ if b >= 3 && testing.Short() {
+ break
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/natdiv.go b/platform/dbops/binaries/go/go/src/math/big/natdiv.go
new file mode 100644
index 0000000000000000000000000000000000000000..14233a2ddb57e2406d2b762255cead3ee0b73d46
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/natdiv.go
@@ -0,0 +1,897 @@
+// 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.
+
+/*
+
+Multi-precision division. Here be dragons.
+
+Given u and v, where u is n+m digits, and v is n digits (with no leading zeros),
+the goal is to return quo, rem such that u = quo*v + rem, where 0 ≤ rem < v.
+That is, quo = ⌊u/v⌋ where ⌊x⌋ denotes the floor (truncation to integer) of x,
+and rem = u - quo·v.
+
+
+Long Division
+
+Division in a computer proceeds the same as long division in elementary school,
+but computers are not as good as schoolchildren at following vague directions,
+so we have to be much more precise about the actual steps and what can happen.
+
+We work from most to least significant digit of the quotient, doing:
+
+ • Guess a digit q, the number of v to subtract from the current
+ section of u to zero out the topmost digit.
+ • Check the guess by multiplying q·v and comparing it against
+ the current section of u, adjusting the guess as needed.
+ • Subtract q·v from the current section of u.
+ • Add q to the corresponding section of the result quo.
+
+When all digits have been processed, the final remainder is left in u
+and returned as rem.
+
+For example, here is a sketch of dividing 5 digits by 3 digits (n=3, m=2).
+
+ q₂ q₁ q₀
+ _________________
+ v₂ v₁ v₀ ) u₄ u₃ u₂ u₁ u₀
+ ↓ ↓ ↓ | |
+ [u₄ u₃ u₂]| |
+ - [ q₂·v ]| |
+ ----------- ↓ |
+ [ rem | u₁]|
+ - [ q₁·v ]|
+ ----------- ↓
+ [ rem | u₀]
+ - [ q₀·v ]
+ ------------
+ [ rem ]
+
+Instead of creating new storage for the remainders and copying digits from u
+as indicated by the arrows, we use u's storage directly as both the source
+and destination of the subtractions, so that the remainders overwrite
+successive overlapping sections of u as the division proceeds, using a slice
+of u to identify the current section. This avoids all the copying as well as
+shifting of remainders.
+
+Division of u with n+m digits by v with n digits (in base B) can in general
+produce at most m+1 digits, because:
+
+ • u < B^(n+m) [B^(n+m) has n+m+1 digits]
+ • v ≥ B^(n-1) [B^(n-1) is the smallest n-digit number]
+ • u/v < B^(n+m) / B^(n-1) [divide bounds for u, v]
+ • u/v < B^(m+1) [simplify]
+
+The first step is special: it takes the top n digits of u and divides them by
+the n digits of v, producing the first quotient digit and an n-digit remainder.
+In the example, q₂ = ⌊u₄u₃u₂ / v⌋.
+
+The first step divides n digits by n digits to ensure that it produces only a
+single digit.
+
+Each subsequent step appends the next digit from u to the remainder and divides
+those n+1 digits by the n digits of v, producing another quotient digit and a
+new n-digit remainder.
+
+Subsequent steps divide n+1 digits by n digits, an operation that in general
+might produce two digits. However, as used in the algorithm, that division is
+guaranteed to produce only a single digit. The dividend is of the form
+rem·B + d, where rem is a remainder from the previous step and d is a single
+digit, so:
+
+ • rem ≤ v - 1 [rem is a remainder from dividing by v]
+ • rem·B ≤ v·B - B [multiply by B]
+ • d ≤ B - 1 [d is a single digit]
+ • rem·B + d ≤ v·B - 1 [add]
+ • rem·B + d < v·B [change ≤ to <]
+ • (rem·B + d)/v < B [divide by v]
+
+
+Guess and Check
+
+At each step we need to divide n+1 digits by n digits, but this is for the
+implementation of division by n digits, so we can't just invoke a division
+routine: we _are_ the division routine. Instead, we guess at the answer and
+then check it using multiplication. If the guess is wrong, we correct it.
+
+How can this guessing possibly be efficient? It turns out that the following
+statement (let's call it the Good Guess Guarantee) is true.
+
+If
+
+ • q = ⌊u/v⌋ where u is n+1 digits and v is n digits,
+ • q < B, and
+ • the topmost digit of v = vₙ₋₁ ≥ B/2,
+
+then q̂ = ⌊uₙuₙ₋₁ / vₙ₋₁⌋ satisfies q ≤ q̂ ≤ q+2. (Proof below.)
+
+That is, if we know the answer has only a single digit and we guess an answer
+by ignoring the bottom n-1 digits of u and v, using a 2-by-1-digit division,
+then that guess is at least as large as the correct answer. It is also not
+too much larger: it is off by at most two from the correct answer.
+
+Note that in the first step of the overall division, which is an n-by-n-digit
+division, the 2-by-1 guess uses an implicit uₙ = 0.
+
+Note that using a 2-by-1-digit division here does not mean calling ourselves
+recursively. Instead, we use an efficient direct hardware implementation of
+that operation.
+
+Note that because q is u/v rounded down, q·v must not exceed u: u ≥ q·v.
+If a guess q̂ is too big, it will not satisfy this test. Viewed a different way,
+the remainder r̂ for a given q̂ is u - q̂·v, which must be positive. If it is
+negative, then the guess q̂ is too big.
+
+This gives us a way to compute q. First compute q̂ with 2-by-1-digit division.
+Then, while u < q̂·v, decrement q̂; this loop executes at most twice, because
+q̂ ≤ q+2.
+
+
+Scaling Inputs
+
+The Good Guess Guarantee requires that the top digit of v (vₙ₋₁) be at least B/2.
+For example in base 10, ⌊172/19⌋ = 9, but ⌊18/1⌋ = 18: the guess is wildly off
+because the first digit 1 is smaller than B/2 = 5.
+
+We can ensure that v has a large top digit by multiplying both u and v by the
+right amount. Continuing the example, if we multiply both 172 and 19 by 3, we
+now have ⌊516/57⌋, the leading digit of v is now ≥ 5, and sure enough
+⌊51/5⌋ = 10 is much closer to the correct answer 9. It would be easier here
+to multiply by 4, because that can be done with a shift. Specifically, we can
+always count the number of leading zeros i in the first digit of v and then
+shift both u and v left by i bits.
+
+Having scaled u and v, the value ⌊u/v⌋ is unchanged, but the remainder will
+be scaled: 172 mod 19 is 1, but 516 mod 57 is 3. We have to divide the remainder
+by the scaling factor (shifting right i bits) when we finish.
+
+Note that these shifts happen before and after the entire division algorithm,
+not at each step in the per-digit iteration.
+
+Note the effect of scaling inputs on the size of the possible quotient.
+In the scaled u/v, u can gain a digit from scaling; v never does, because we
+pick the scaling factor to make v's top digit larger but without overflowing.
+If u and v have n+m and n digits after scaling, then:
+
+ • u < B^(n+m) [B^(n+m) has n+m+1 digits]
+ • v ≥ B^n / 2 [vₙ₋₁ ≥ B/2, so vₙ₋₁·B^(n-1) ≥ B^n/2]
+ • u/v < B^(n+m) / (B^n / 2) [divide bounds for u, v]
+ • u/v < 2 B^m [simplify]
+
+The quotient can still have m+1 significant digits, but if so the top digit
+must be a 1. This provides a different way to handle the first digit of the
+result: compare the top n digits of u against v and fill in either a 0 or a 1.
+
+
+Refining Guesses
+
+Before we check whether u < q̂·v, we can adjust our guess to change it from
+q̂ = ⌊uₙuₙ₋₁ / vₙ₋₁⌋ into the refined guess ⌊uₙuₙ₋₁uₙ₋₂ / vₙ₋₁vₙ₋₂⌋.
+Although not mentioned above, the Good Guess Guarantee also promises that this
+3-by-2-digit division guess is more precise and at most one away from the real
+answer q. The improvement from the 2-by-1 to the 3-by-2 guess can also be done
+without n-digit math.
+
+If we have a guess q̂ = ⌊uₙuₙ₋₁ / vₙ₋₁⌋ and we want to see if it also equal to
+⌊uₙuₙ₋₁uₙ₋₂ / vₙ₋₁vₙ₋₂⌋, we can use the same check we would for the full division:
+if uₙuₙ₋₁uₙ₋₂ < q̂·vₙ₋₁vₙ₋₂, then the guess is too large and should be reduced.
+
+Checking uₙuₙ₋₁uₙ₋₂ < q̂·vₙ₋₁vₙ₋₂ is the same as uₙuₙ₋₁uₙ₋₂ - q̂·vₙ₋₁vₙ₋₂ < 0,
+and
+
+ uₙuₙ₋₁uₙ₋₂ - q̂·vₙ₋₁vₙ₋₂ = (uₙuₙ₋₁·B + uₙ₋₂) - q̂·(vₙ₋₁·B + vₙ₋₂)
+ [splitting off the bottom digit]
+ = (uₙuₙ₋₁ - q̂·vₙ₋₁)·B + uₙ₋₂ - q̂·vₙ₋₂
+ [regrouping]
+
+The expression (uₙuₙ₋₁ - q̂·vₙ₋₁) is the remainder of uₙuₙ₋₁ / vₙ₋₁.
+If the initial guess returns both q̂ and its remainder r̂, then checking
+whether uₙuₙ₋₁uₙ₋₂ < q̂·vₙ₋₁vₙ₋₂ is the same as checking r̂·B + uₙ₋₂ < q̂·vₙ₋₂.
+
+If we find that r̂·B + uₙ₋₂ < q̂·vₙ₋₂, then we can adjust the guess by
+decrementing q̂ and adding vₙ₋₁ to r̂. We repeat until r̂·B + uₙ₋₂ ≥ q̂·vₙ₋₂.
+(As before, this fixup is only needed at most twice.)
+
+Now that q̂ = ⌊uₙuₙ₋₁uₙ₋₂ / vₙ₋₁vₙ₋₂⌋, as mentioned above it is at most one
+away from the correct q, and we've avoided doing any n-digit math.
+(If we need the new remainder, it can be computed as r̂·B + uₙ₋₂ - q̂·vₙ₋₂.)
+
+The final check u < q̂·v and the possible fixup must be done at full precision.
+For random inputs, a fixup at this step is exceedingly rare: the 3-by-2 guess
+is not often wrong at all. But still we must do the check. Note that since the
+3-by-2 guess is off by at most 1, it can be convenient to perform the final
+u < q̂·v as part of the computation of the remainder r = u - q̂·v. If the
+subtraction underflows, decremeting q̂ and adding one v back to r is enough to
+arrive at the final q, r.
+
+That's the entirety of long division: scale the inputs, and then loop over
+each output position, guessing, checking, and correcting the next output digit.
+
+For a 2n-digit number divided by an n-digit number (the worst size-n case for
+division complexity), this algorithm uses n+1 iterations, each of which must do
+at least the 1-by-n-digit multiplication q̂·v. That's O(n) iterations of
+O(n) time each, so O(n²) time overall.
+
+
+Recursive Division
+
+For very large inputs, it is possible to improve on the O(n²) algorithm.
+Let's call a group of n/2 real digits a (very) “wide digit”. We can run the
+standard long division algorithm explained above over the wide digits instead of
+the actual digits. This will result in many fewer steps, but the math involved in
+each step is more work.
+
+Where basic long division uses a 2-by-1-digit division to guess the initial q̂,
+the new algorithm must use a 2-by-1-wide-digit division, which is of course
+really an n-by-n/2-digit division. That's OK: if we implement n-digit division
+in terms of n/2-digit division, the recursion will terminate when the divisor
+becomes small enough to handle with standard long division or even with the
+2-by-1 hardware instruction.
+
+For example, here is a sketch of dividing 10 digits by 4, proceeding with
+wide digits corresponding to two regular digits. The first step, still special,
+must leave off a (regular) digit, dividing 5 by 4 and producing a 4-digit
+remainder less than v. The middle steps divide 6 digits by 4, guaranteed to
+produce two output digits each (one wide digit) with 4-digit remainders.
+The final step must use what it has: the 4-digit remainder plus one more,
+5 digits to divide by 4.
+
+ q₆ q₅ q₄ q₃ q₂ q₁ q₀
+ _______________________________
+ v₃ v₂ v₁ v₀ ) u₉ u₈ u₇ u₆ u₅ u₄ u₃ u₂ u₁ u₀
+ ↓ ↓ ↓ ↓ ↓ | | | | |
+ [u₉ u₈ u₇ u₆ u₅]| | | | |
+ - [ q₆q₅·v ]| | | | |
+ ----------------- ↓ ↓ | | |
+ [ rem |u₄ u₃]| | |
+ - [ q₄q₃·v ]| | |
+ -------------------- ↓ ↓ |
+ [ rem |u₂ u₁]|
+ - [ q₂q₁·v ]|
+ -------------------- ↓
+ [ rem |u₀]
+ - [ q₀·v ]
+ ------------------
+ [ rem ]
+
+An alternative would be to look ahead to how well n/2 divides into n+m and
+adjust the first step to use fewer digits as needed, making the first step
+more special to make the last step not special at all. For example, using the
+same input, we could choose to use only 4 digits in the first step, leaving
+a full wide digit for the last step:
+
+ q₆ q₅ q₄ q₃ q₂ q₁ q₀
+ _______________________________
+ v₃ v₂ v₁ v₀ ) u₉ u₈ u₇ u₆ u₅ u₄ u₃ u₂ u₁ u₀
+ ↓ ↓ ↓ ↓ | | | | | |
+ [u₉ u₈ u₇ u₆]| | | | | |
+ - [ q₆·v ]| | | | | |
+ -------------- ↓ ↓ | | | |
+ [ rem |u₅ u₄]| | | |
+ - [ q₅q₄·v ]| | | |
+ -------------------- ↓ ↓ | |
+ [ rem |u₃ u₂]| |
+ - [ q₃q₂·v ]| |
+ -------------------- ↓ ↓
+ [ rem |u₁ u₀]
+ - [ q₁q₀·v ]
+ ---------------------
+ [ rem ]
+
+Today, the code in divRecursiveStep works like the first example. Perhaps in
+the future we will make it work like the alternative, to avoid a special case
+in the final iteration.
+
+Either way, each step is a 3-by-2-wide-digit division approximated first by
+a 2-by-1-wide-digit division, just as we did for regular digits in long division.
+Because the actual answer we want is a 3-by-2-wide-digit division, instead of
+multiplying q̂·v directly during the fixup, we can use the quick refinement
+from long division (an n/2-by-n/2 multiply) to correct q to its actual value
+and also compute the remainder (as mentioned above), and then stop after that,
+never doing a full n-by-n multiply.
+
+Instead of using an n-by-n/2-digit division to produce n/2 digits, we can add
+(not discard) one more real digit, doing an (n+1)-by-(n/2+1)-digit division that
+produces n/2+1 digits. That single extra digit tightens the Good Guess Guarantee
+to q ≤ q̂ ≤ q+1 and lets us drop long division's special treatment of the first
+digit. These benefits are discussed more after the Good Guess Guarantee proof
+below.
+
+
+How Fast is Recursive Division?
+
+For a 2n-by-n-digit division, this algorithm runs a 4-by-2 long division over
+wide digits, producing two wide digits plus a possible leading regular digit 1,
+which can be handled without a recursive call. That is, the algorithm uses two
+full iterations, each using an n-by-n/2-digit division and an n/2-by-n/2-digit
+multiplication, along with a few n-digit additions and subtractions. The standard
+n-by-n-digit multiplication algorithm requires O(n²) time, making the overall
+algorithm require time T(n) where
+
+ T(n) = 2T(n/2) + O(n) + O(n²)
+
+which, by the Bentley-Haken-Saxe theorem, ends up reducing to T(n) = O(n²).
+This is not an improvement over regular long division.
+
+When the number of digits n becomes large enough, Karatsuba's algorithm for
+multiplication can be used instead, which takes O(n^log₂3) = O(n^1.6) time.
+(Karatsuba multiplication is implemented in func karatsuba in nat.go.)
+That makes the overall recursive division algorithm take O(n^1.6) time as well,
+which is an improvement, but again only for large enough numbers.
+
+It is not critical to make sure that every recursion does only two recursive
+calls. While in general the number of recursive calls can change the time
+analysis, in this case doing three calls does not change the analysis:
+
+ T(n) = 3T(n/2) + O(n) + O(n^log₂3)
+
+ends up being T(n) = O(n^log₂3). Because the Karatsuba multiplication taking
+time O(n^log₂3) is itself doing 3 half-sized recursions, doing three for the
+division does not hurt the asymptotic performance. Of course, it is likely
+still faster in practice to do two.
+
+
+Proof of the Good Guess Guarantee
+
+Given numbers x, y, let us break them into the quotients and remainders when
+divided by some scaling factor S, with the added constraints that the quotient
+x/y and the high part of y are both less than some limit T, and that the high
+part of y is at least half as big as T.
+
+ x₁ = ⌊x/S⌋ y₁ = ⌊y/S⌋
+ x₀ = x mod S y₀ = y mod S
+
+ x = x₁·S + x₀ 0 ≤ x₀ < S x/y < T
+ y = y₁·S + y₀ 0 ≤ y₀ < S T/2 ≤ y₁ < T
+
+And consider the two truncated quotients:
+
+ q = ⌊x/y⌋
+ q̂ = ⌊x₁/y₁⌋
+
+We will prove that q ≤ q̂ ≤ q+2.
+
+The guarantee makes no real demands on the scaling factor S: it is simply the
+magnitude of the digits cut from both x and y to produce x₁ and y₁.
+The guarantee makes only limited demands on T: it must be large enough to hold
+the quotient x/y, and y₁ must have roughly the same size.
+
+To apply to the earlier discussion of 2-by-1 guesses in long division,
+we would choose:
+
+ S = Bⁿ⁻¹
+ T = B
+ x = u
+ x₁ = uₙuₙ₋₁
+ x₀ = uₙ₋₂...u₀
+ y = v
+ y₁ = vₙ₋₁
+ y₀ = vₙ₋₂...u₀
+
+These simpler variables avoid repeating those longer expressions in the proof.
+
+Note also that, by definition, truncating division ⌊x/y⌋ satisfies
+
+ x/y - 1 < ⌊x/y⌋ ≤ x/y.
+
+This fact will be used a few times in the proofs.
+
+Proof that q ≤ q̂:
+
+ q̂·y₁ = ⌊x₁/y₁⌋·y₁ [by definition, q̂ = ⌊x₁/y₁⌋]
+ > (x₁/y₁ - 1)·y₁ [x₁/y₁ - 1 < ⌊x₁/y₁⌋]
+ = x₁ - y₁ [distribute y₁]
+
+ So q̂·y₁ > x₁ - y₁.
+ Since q̂·y₁ is an integer, q̂·y₁ ≥ x₁ - y₁ + 1.
+
+ q̂ - q = q̂ - ⌊x/y⌋ [by definition, q = ⌊x/y⌋]
+ ≥ q̂ - x/y [⌊x/y⌋ < x/y]
+ = (1/y)·(q̂·y - x) [factor out 1/y]
+ ≥ (1/y)·(q̂·y₁·S - x) [y = y₁·S + y₀ ≥ y₁·S]
+ ≥ (1/y)·((x₁ - y₁ + 1)·S - x) [above: q̂·y₁ ≥ x₁ - y₁ + 1]
+ = (1/y)·(x₁·S - y₁·S + S - x) [distribute S]
+ = (1/y)·(S - x₀ - y₁·S) [-x = -x₁·S - x₀]
+ > -y₁·S / y [x₀ < S, so S - x₀ < 0; drop it]
+ ≥ -1 [y₁·S ≤ y]
+
+ So q̂ - q > -1.
+ Since q̂ - q is an integer, q̂ - q ≥ 0, or equivalently q ≤ q̂.
+
+Proof that q̂ ≤ q+2:
+
+ x₁/y₁ - x/y = x₁·S/y₁·S - x/y [multiply left term by S/S]
+ ≤ x/y₁·S - x/y [x₁S ≤ x]
+ = (x/y)·(y/y₁·S - 1) [factor out x/y]
+ = (x/y)·((y - y₁·S)/y₁·S) [move -1 into y/y₁·S fraction]
+ = (x/y)·(y₀/y₁·S) [y - y₁·S = y₀]
+ = (x/y)·(1/y₁)·(y₀/S) [factor out 1/y₁]
+ < (x/y)·(1/y₁) [y₀ < S, so y₀/S < 1]
+ ≤ (x/y)·(2/T) [y₁ ≥ T/2, so 1/y₁ ≤ 2/T]
+ < T·(2/T) [x/y < T]
+ = 2 [T·(2/T) = 2]
+
+ So x₁/y₁ - x/y < 2.
+
+ q̂ - q = ⌊x₁/y₁⌋ - q [by definition, q̂ = ⌊x₁/y₁⌋]
+ = ⌊x₁/y₁⌋ - ⌊x/y⌋ [by definition, q = ⌊x/y⌋]
+ ≤ x₁/y₁ - ⌊x/y⌋ [⌊x₁/y₁⌋ ≤ x₁/y₁]
+ < x₁/y₁ - (x/y - 1) [⌊x/y⌋ > x/y - 1]
+ = (x₁/y₁ - x/y) + 1 [regrouping]
+ < 2 + 1 [above: x₁/y₁ - x/y < 2]
+ = 3
+
+ So q̂ - q < 3.
+ Since q̂ - q is an integer, q̂ - q ≤ 2.
+
+Note that when x/y < T/2, the bounds tighten to x₁/y₁ - x/y < 1 and therefore
+q̂ - q ≤ 1.
+
+Note also that in the general case 2n-by-n division where we don't know that
+x/y < T, we do know that x/y < 2T, yielding the bound q̂ - q ≤ 4. So we could
+remove the special case first step of long division as long as we allow the
+first fixup loop to run up to four times. (Using a simple comparison to decide
+whether the first digit is 0 or 1 is still more efficient, though.)
+
+Finally, note that when dividing three leading base-B digits by two (scaled),
+we have T = B² and x/y < B = T/B, a much tighter bound than x/y < T.
+This in turn yields the much tighter bound x₁/y₁ - x/y < 2/B. This means that
+⌊x₁/y₁⌋ and ⌊x/y⌋ can only differ when x/y is less than 2/B greater than an
+integer. For random x and y, the chance of this is 2/B, or, for large B,
+approximately zero. This means that after we produce the 3-by-2 guess in the
+long division algorithm, the fixup loop essentially never runs.
+
+In the recursive algorithm, the extra digit in (2·⌊n/2⌋+1)-by-(⌊n/2⌋+1)-digit
+division has exactly the same effect: the probability of needing a fixup is the
+same 2/B. Even better, we can allow the general case x/y < 2T and the fixup
+probability only grows to 4/B, still essentially zero.
+
+
+References
+
+There are no great references for implementing long division; thus this comment.
+Here are some notes about what to expect from the obvious references.
+
+Knuth Volume 2 (Seminumerical Algorithms) section 4.3.1 is the usual canonical
+reference for long division, but that entire series is highly compressed, never
+repeating a necessary fact and leaving important insights to the exercises.
+For example, no rationale whatsoever is given for the calculation that extends
+q̂ from a 2-by-1 to a 3-by-2 guess, nor why it reduces the error bound.
+The proof that the calculation even has the desired effect is left to exercises.
+The solutions to those exercises provided at the back of the book are entirely
+calculations, still with no explanation as to what is going on or how you would
+arrive at the idea of doing those exact calculations. Nowhere is it mentioned
+that this test extends the 2-by-1 guess into a 3-by-2 guess. The proof of the
+Good Guess Guarantee is only for the 2-by-1 guess and argues by contradiction,
+making it difficult to understand how modifications like adding another digit
+or adjusting the quotient range affects the overall bound.
+
+All that said, Knuth remains the canonical reference. It is dense but packed
+full of information and references, and the proofs are simpler than many other
+presentations. The proofs above are reworkings of Knuth's to remove the
+arguments by contradiction and add explanations or steps that Knuth omitted.
+But beware of errors in older printings. Take the published errata with you.
+
+Brinch Hansen's “Multiple-length Division Revisited: a Tour of the Minefield”
+starts with a blunt critique of Knuth's presentation (among others) and then
+presents a more detailed and easier to follow treatment of long division,
+including an implementation in Pascal. But the algorithm and implementation
+work entirely in terms of 3-by-2 division, which is much less useful on modern
+hardware than an algorithm using 2-by-1 division. The proofs are a bit too
+focused on digit counting and seem needlessly complex, especially compared to
+the ones given above.
+
+Burnikel and Ziegler's “Fast Recursive Division” introduced the key insight of
+implementing division by an n-digit divisor using recursive calls to division
+by an n/2-digit divisor, relying on Karatsuba multiplication to yield a
+sub-quadratic run time. However, the presentation decisions are made almost
+entirely for the purpose of simplifying the run-time analysis, rather than
+simplifying the presentation. Instead of a single algorithm that loops over
+quotient digits, the paper presents two mutually-recursive algorithms, for
+2n-by-n and 3n-by-2n. The paper also does not present any general (n+m)-by-n
+algorithm.
+
+The proofs in the paper are remarkably complex, especially considering that
+the algorithm is at its core just long division on wide digits, so that the
+usual long division proofs apply essentially unaltered.
+*/
+
+package big
+
+import "math/bits"
+
+// rem returns r such that r = u%v.
+// It uses z as the storage for r.
+func (z nat) rem(u, v nat) (r nat) {
+ if alias(z, u) {
+ z = nil
+ }
+ qp := getNat(0)
+ q, r := qp.div(z, u, v)
+ *qp = q
+ putNat(qp)
+ return r
+}
+
+// div returns q, r such that q = ⌊u/v⌋ and r = u%v = u - q·v.
+// It uses z and z2 as the storage for q and r.
+func (z nat) div(z2, u, v nat) (q, r nat) {
+ if len(v) == 0 {
+ panic("division by zero")
+ }
+
+ if u.cmp(v) < 0 {
+ q = z[:0]
+ r = z2.set(u)
+ return
+ }
+
+ if len(v) == 1 {
+ // Short division: long optimized for a single-word divisor.
+ // In that case, the 2-by-1 guess is all we need at each step.
+ var r2 Word
+ q, r2 = z.divW(u, v[0])
+ r = z2.setWord(r2)
+ return
+ }
+
+ q, r = z.divLarge(z2, u, v)
+ return
+}
+
+// divW returns q, r such that q = ⌊x/y⌋ and r = x%y = x - q·y.
+// It uses z as the storage for q.
+// Note that y is a single digit (Word), not a big number.
+func (z nat) divW(x nat, y Word) (q nat, r Word) {
+ m := len(x)
+ switch {
+ case y == 0:
+ panic("division by zero")
+ case y == 1:
+ q = z.set(x) // result is x
+ return
+ case m == 0:
+ q = z[:0] // result is 0
+ return
+ }
+ // m > 0
+ z = z.make(m)
+ r = divWVW(z, 0, x, y)
+ q = z.norm()
+ return
+}
+
+// modW returns x % d.
+func (x nat) modW(d Word) (r Word) {
+ // TODO(agl): we don't actually need to store the q value.
+ var q nat
+ q = q.make(len(x))
+ return divWVW(q, 0, x, d)
+}
+
+// divWVW overwrites z with ⌊x/y⌋, returning the remainder r.
+// The caller must ensure that len(z) = len(x).
+func divWVW(z []Word, xn Word, x []Word, y Word) (r Word) {
+ r = xn
+ if len(x) == 1 {
+ qq, rr := bits.Div(uint(r), uint(x[0]), uint(y))
+ z[0] = Word(qq)
+ return Word(rr)
+ }
+ rec := reciprocalWord(y)
+ for i := len(z) - 1; i >= 0; i-- {
+ z[i], r = divWW(r, x[i], y, rec)
+ }
+ return r
+}
+
+// div returns q, r such that q = ⌊uIn/vIn⌋ and r = uIn%vIn = uIn - q·vIn.
+// It uses z and u as the storage for q and r.
+// The caller must ensure that len(vIn) ≥ 2 (use divW otherwise)
+// and that len(uIn) ≥ len(vIn) (the answer is 0, uIn otherwise).
+func (z nat) divLarge(u, uIn, vIn nat) (q, r nat) {
+ n := len(vIn)
+ m := len(uIn) - n
+
+ // Scale the inputs so vIn's top bit is 1 (see “Scaling Inputs” above).
+ // vIn is treated as a read-only input (it may be in use by another
+ // goroutine), so we must make a copy.
+ // uIn is copied to u.
+ shift := nlz(vIn[n-1])
+ vp := getNat(n)
+ v := *vp
+ shlVU(v, vIn, shift)
+ u = u.make(len(uIn) + 1)
+ u[len(uIn)] = shlVU(u[0:len(uIn)], uIn, shift)
+
+ // The caller should not pass aliased z and u, since those are
+ // the two different outputs, but correct just in case.
+ if alias(z, u) {
+ z = nil
+ }
+ q = z.make(m + 1)
+
+ // Use basic or recursive long division depending on size.
+ if n < divRecursiveThreshold {
+ q.divBasic(u, v)
+ } else {
+ q.divRecursive(u, v)
+ }
+ putNat(vp)
+
+ q = q.norm()
+
+ // Undo scaling of remainder.
+ shrVU(u, u, shift)
+ r = u.norm()
+
+ return q, r
+}
+
+// divBasic implements long division as described above.
+// It overwrites q with ⌊u/v⌋ and overwrites u with the remainder r.
+// q must be large enough to hold ⌊u/v⌋.
+func (q nat) divBasic(u, v nat) {
+ n := len(v)
+ m := len(u) - n
+
+ qhatvp := getNat(n + 1)
+ qhatv := *qhatvp
+
+ // Set up for divWW below, precomputing reciprocal argument.
+ vn1 := v[n-1]
+ rec := reciprocalWord(vn1)
+
+ // Compute each digit of quotient.
+ for j := m; j >= 0; j-- {
+ // Compute the 2-by-1 guess q̂.
+ // The first iteration must invent a leading 0 for u.
+ qhat := Word(_M)
+ var ujn Word
+ if j+n < len(u) {
+ ujn = u[j+n]
+ }
+
+ // ujn ≤ vn1, or else q̂ would be more than one digit.
+ // For ujn == vn1, we set q̂ to the max digit M above.
+ // Otherwise, we compute the 2-by-1 guess.
+ if ujn != vn1 {
+ var rhat Word
+ qhat, rhat = divWW(ujn, u[j+n-1], vn1, rec)
+
+ // Refine q̂ to a 3-by-2 guess. See “Refining Guesses” above.
+ vn2 := v[n-2]
+ x1, x2 := mulWW(qhat, vn2)
+ ujn2 := u[j+n-2]
+ for greaterThan(x1, x2, rhat, ujn2) { // x1x2 > r̂ u[j+n-2]
+ qhat--
+ prevRhat := rhat
+ rhat += vn1
+ // If r̂ overflows, then
+ // r̂ u[j+n-2]v[n-1] is now definitely > x1 x2.
+ if rhat < prevRhat {
+ break
+ }
+ // TODO(rsc): No need for a full mulWW.
+ // x2 += vn2; if x2 overflows, x1++
+ x1, x2 = mulWW(qhat, vn2)
+ }
+ }
+
+ // Compute q̂·v.
+ qhatv[n] = mulAddVWW(qhatv[0:n], v, qhat, 0)
+ qhl := len(qhatv)
+ if j+qhl > len(u) && qhatv[n] == 0 {
+ qhl--
+ }
+
+ // Subtract q̂·v from the current section of u.
+ // If it underflows, q̂·v > u, which we fix up
+ // by decrementing q̂ and adding v back.
+ c := subVV(u[j:j+qhl], u[j:], qhatv)
+ if c != 0 {
+ c := addVV(u[j:j+n], u[j:], v)
+ // If n == qhl, the carry from subVV and the carry from addVV
+ // cancel out and don't affect u[j+n].
+ if n < qhl {
+ u[j+n] += c
+ }
+ qhat--
+ }
+
+ // Save quotient digit.
+ // Caller may know the top digit is zero and not leave room for it.
+ if j == m && m == len(q) && qhat == 0 {
+ continue
+ }
+ q[j] = qhat
+ }
+
+ putNat(qhatvp)
+}
+
+// greaterThan reports whether the two digit numbers x1 x2 > y1 y2.
+// TODO(rsc): In contradiction to most of this file, x1 is the high
+// digit and x2 is the low digit. This should be fixed.
+func greaterThan(x1, x2, y1, y2 Word) bool {
+ return x1 > y1 || x1 == y1 && x2 > y2
+}
+
+// divRecursiveThreshold is the number of divisor digits
+// at which point divRecursive is faster than divBasic.
+const divRecursiveThreshold = 100
+
+// divRecursive implements recursive division as described above.
+// It overwrites z with ⌊u/v⌋ and overwrites u with the remainder r.
+// z must be large enough to hold ⌊u/v⌋.
+// This function is just for allocating and freeing temporaries
+// around divRecursiveStep, the real implementation.
+func (z nat) divRecursive(u, v nat) {
+ // Recursion depth is (much) less than 2 log₂(len(v)).
+ // Allocate a slice of temporaries to be reused across recursion,
+ // plus one extra temporary not live across the recursion.
+ recDepth := 2 * bits.Len(uint(len(v)))
+ tmp := getNat(3 * len(v))
+ temps := make([]*nat, recDepth)
+
+ z.clear()
+ z.divRecursiveStep(u, v, 0, tmp, temps)
+
+ // Free temporaries.
+ for _, n := range temps {
+ if n != nil {
+ putNat(n)
+ }
+ }
+ putNat(tmp)
+}
+
+// divRecursiveStep is the actual implementation of recursive division.
+// It adds ⌊u/v⌋ to z and overwrites u with the remainder r.
+// z must be large enough to hold ⌊u/v⌋.
+// It uses temps[depth] (allocating if needed) as a temporary live across
+// the recursive call. It also uses tmp, but not live across the recursion.
+func (z nat) divRecursiveStep(u, v nat, depth int, tmp *nat, temps []*nat) {
+ // u is a subsection of the original and may have leading zeros.
+ // TODO(rsc): The v = v.norm() is useless and should be removed.
+ // We know (and require) that v's top digit is ≥ B/2.
+ u = u.norm()
+ v = v.norm()
+ if len(u) == 0 {
+ z.clear()
+ return
+ }
+
+ // Fall back to basic division if the problem is now small enough.
+ n := len(v)
+ if n < divRecursiveThreshold {
+ z.divBasic(u, v)
+ return
+ }
+
+ // Nothing to do if u is shorter than v (implies u < v).
+ m := len(u) - n
+ if m < 0 {
+ return
+ }
+
+ // We consider B digits in a row as a single wide digit.
+ // (See “Recursive Division” above.)
+ //
+ // TODO(rsc): rename B to Wide, to avoid confusion with _B,
+ // which is something entirely different.
+ // TODO(rsc): Look into whether using ⌈n/2⌉ is better than ⌊n/2⌋.
+ B := n / 2
+
+ // Allocate a nat for qhat below.
+ if temps[depth] == nil {
+ temps[depth] = getNat(n) // TODO(rsc): Can be just B+1.
+ } else {
+ *temps[depth] = temps[depth].make(B + 1)
+ }
+
+ // Compute each wide digit of the quotient.
+ //
+ // TODO(rsc): Change the loop to be
+ // for j := (m+B-1)/B*B; j > 0; j -= B {
+ // which will make the final step a regular step, letting us
+ // delete what amounts to an extra copy of the loop body below.
+ j := m
+ for j > B {
+ // Divide u[j-B:j+n] (3 wide digits) by v (2 wide digits).
+ // First make the 2-by-1-wide-digit guess using a recursive call.
+ // Then extend the guess to the full 3-by-2 (see “Refining Guesses”).
+ //
+ // For the 2-by-1-wide-digit guess, instead of doing 2B-by-B-digit,
+ // we use a (2B+1)-by-(B+1) digit, which handles the possibility that
+ // the result has an extra leading 1 digit as well as guaranteeing
+ // that the computed q̂ will be off by at most 1 instead of 2.
+
+ // s is the number of digits to drop from the 3B- and 2B-digit chunks.
+ // We drop B-1 to be left with 2B+1 and B+1.
+ s := (B - 1)
+
+ // uu is the up-to-3B-digit section of u we are working on.
+ uu := u[j-B:]
+
+ // Compute the 2-by-1 guess q̂, leaving r̂ in uu[s:B+n].
+ qhat := *temps[depth]
+ qhat.clear()
+ qhat.divRecursiveStep(uu[s:B+n], v[s:], depth+1, tmp, temps)
+ qhat = qhat.norm()
+
+ // Extend to a 3-by-2 quotient and remainder.
+ // Because divRecursiveStep overwrote the top part of uu with
+ // the remainder r̂, the full uu already contains the equivalent
+ // of r̂·B + uₙ₋₂ from the “Refining Guesses” discussion.
+ // Subtracting q̂·vₙ₋₂ from it will compute the full-length remainder.
+ // If that subtraction underflows, q̂·v > u, which we fix up
+ // by decrementing q̂ and adding v back, same as in long division.
+
+ // TODO(rsc): Instead of subtract and fix-up, this code is computing
+ // q̂·vₙ₋₂ and decrementing q̂ until that product is ≤ u.
+ // But we can do the subtraction directly, as in the comment above
+ // and in long division, because we know that q̂ is wrong by at most one.
+ qhatv := tmp.make(3 * n)
+ qhatv.clear()
+ qhatv = qhatv.mul(qhat, v[:s])
+ for i := 0; i < 2; i++ {
+ e := qhatv.cmp(uu.norm())
+ if e <= 0 {
+ break
+ }
+ subVW(qhat, qhat, 1)
+ c := subVV(qhatv[:s], qhatv[:s], v[:s])
+ if len(qhatv) > s {
+ subVW(qhatv[s:], qhatv[s:], c)
+ }
+ addAt(uu[s:], v[s:], 0)
+ }
+ if qhatv.cmp(uu.norm()) > 0 {
+ panic("impossible")
+ }
+ c := subVV(uu[:len(qhatv)], uu[:len(qhatv)], qhatv)
+ if c > 0 {
+ subVW(uu[len(qhatv):], uu[len(qhatv):], c)
+ }
+ addAt(z, qhat, j-B)
+ j -= B
+ }
+
+ // TODO(rsc): Rewrite loop as described above and delete all this code.
+
+ // Now u < (v< 0 {
+ subVW(qhat, qhat, 1)
+ c := subVV(qhatv[:s], qhatv[:s], v[:s])
+ if len(qhatv) > s {
+ subVW(qhatv[s:], qhatv[s:], c)
+ }
+ addAt(u[s:], v[s:], 0)
+ }
+ }
+ if qhatv.cmp(u.norm()) > 0 {
+ panic("impossible")
+ }
+ c := subVV(u[0:len(qhatv)], u[0:len(qhatv)], qhatv)
+ if c > 0 {
+ c = subVW(u[len(qhatv):], u[len(qhatv):], c)
+ }
+ if c > 0 {
+ panic("impossible")
+ }
+
+ // Done!
+ addAt(z, qhat.norm(), 0)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/prime.go b/platform/dbops/binaries/go/go/src/math/big/prime.go
new file mode 100644
index 0000000000000000000000000000000000000000..26688bbd64e9f2221d2a64a696ed05d037d4b5e1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/prime.go
@@ -0,0 +1,320 @@
+// 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 big
+
+import "math/rand"
+
+// ProbablyPrime reports whether x is probably prime,
+// applying the Miller-Rabin test with n pseudorandomly chosen bases
+// as well as a Baillie-PSW test.
+//
+// If x is prime, ProbablyPrime returns true.
+// If x is chosen randomly and not prime, ProbablyPrime probably returns false.
+// The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.
+//
+// ProbablyPrime is 100% accurate for inputs less than 2⁶⁴.
+// See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149,
+// and FIPS 186-4 Appendix F for further discussion of the error probabilities.
+//
+// ProbablyPrime is not suitable for judging primes that an adversary may
+// have crafted to fool the test.
+//
+// As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test.
+// Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked.
+func (x *Int) ProbablyPrime(n int) bool {
+ // Note regarding the doc comment above:
+ // It would be more precise to say that the Baillie-PSW test uses the
+ // extra strong Lucas test as its Lucas test, but since no one knows
+ // how to tell any of the Lucas tests apart inside a Baillie-PSW test
+ // (they all work equally well empirically), that detail need not be
+ // documented or implicitly guaranteed.
+ // The comment does avoid saying "the" Baillie-PSW test
+ // because of this general ambiguity.
+
+ if n < 0 {
+ panic("negative n for ProbablyPrime")
+ }
+ if x.neg || len(x.abs) == 0 {
+ return false
+ }
+
+ // primeBitMask records the primes < 64.
+ const primeBitMask uint64 = 1<<2 | 1<<3 | 1<<5 | 1<<7 |
+ 1<<11 | 1<<13 | 1<<17 | 1<<19 | 1<<23 | 1<<29 | 1<<31 |
+ 1<<37 | 1<<41 | 1<<43 | 1<<47 | 1<<53 | 1<<59 | 1<<61
+
+ w := x.abs[0]
+ if len(x.abs) == 1 && w < 64 {
+ return primeBitMask&(1< 10000 {
+ // This is widely believed to be impossible.
+ // If we get a report, we'll want the exact number n.
+ panic("math/big: internal error: cannot find (D/n) = -1 for " + intN.String())
+ }
+ d[0] = p*p - 4
+ j := Jacobi(intD, intN)
+ if j == -1 {
+ break
+ }
+ if j == 0 {
+ // d = p²-4 = (p-2)(p+2).
+ // If (d/n) == 0 then d shares a prime factor with n.
+ // Since the loop proceeds in increasing p and starts with p-2==1,
+ // the shared prime factor must be p+2.
+ // If p+2 == n, then n is prime; otherwise p+2 is a proper factor of n.
+ return len(n) == 1 && n[0] == p+2
+ }
+ if p == 40 {
+ // We'll never find (d/n) = -1 if n is a square.
+ // If n is a non-square we expect to find a d in just a few attempts on average.
+ // After 40 attempts, take a moment to check if n is indeed a square.
+ t1 = t1.sqrt(n)
+ t1 = t1.sqr(t1)
+ if t1.cmp(n) == 0 {
+ return false
+ }
+ }
+ }
+
+ // Grantham definition of "extra strong Lucas pseudoprime", after Thm 2.3 on p. 876
+ // (D, P, Q above have become Δ, b, 1):
+ //
+ // Let U_n = U_n(b, 1), V_n = V_n(b, 1), and Δ = b²-4.
+ // An extra strong Lucas pseudoprime to base b is a composite n = 2^r s + Jacobi(Δ, n),
+ // where s is odd and gcd(n, 2*Δ) = 1, such that either (i) U_s ≡ 0 mod n and V_s ≡ ±2 mod n,
+ // or (ii) V_{2^t s} ≡ 0 mod n for some 0 ≤ t < r-1.
+ //
+ // We know gcd(n, Δ) = 1 or else we'd have found Jacobi(d, n) == 0 above.
+ // We know gcd(n, 2) = 1 because n is odd.
+ //
+ // Arrange s = (n - Jacobi(Δ, n)) / 2^r = (n+1) / 2^r.
+ s := nat(nil).add(n, natOne)
+ r := int(s.trailingZeroBits())
+ s = s.shr(s, uint(r))
+ nm2 := nat(nil).sub(n, natTwo) // n-2
+
+ // We apply the "almost extra strong" test, which checks the above conditions
+ // except for U_s ≡ 0 mod n, which allows us to avoid computing any U_k values.
+ // Jacobsen points out that maybe we should just do the full extra strong test:
+ // "It is also possible to recover U_n using Crandall and Pomerance equation 3.13:
+ // U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test
+ // at the cost of a single modular inversion. This computation is easy and fast in GMP,
+ // so we can get the full extra-strong test at essentially the same performance as the
+ // almost extra strong test."
+
+ // Compute Lucas sequence V_s(b, 1), where:
+ //
+ // V(0) = 2
+ // V(1) = P
+ // V(k) = P V(k-1) - Q V(k-2).
+ //
+ // (Remember that due to method C above, P = b, Q = 1.)
+ //
+ // In general V(k) = α^k + β^k, where α and β are roots of x² - Px + Q.
+ // Crandall and Pomerance (p.147) observe that for 0 ≤ j ≤ k,
+ //
+ // V(j+k) = V(j)V(k) - V(k-j).
+ //
+ // So in particular, to quickly double the subscript:
+ //
+ // V(2k) = V(k)² - 2
+ // V(2k+1) = V(k) V(k+1) - P
+ //
+ // We can therefore start with k=0 and build up to k=s in log₂(s) steps.
+ natP := nat(nil).setWord(p)
+ vk := nat(nil).setWord(2)
+ vk1 := nat(nil).setWord(p)
+ t2 := nat(nil) // temp
+ for i := int(s.bitLen()); i >= 0; i-- {
+ if s.bit(uint(i)) != 0 {
+ // k' = 2k+1
+ // V(k') = V(2k+1) = V(k) V(k+1) - P.
+ t1 = t1.mul(vk, vk1)
+ t1 = t1.add(t1, n)
+ t1 = t1.sub(t1, natP)
+ t2, vk = t2.div(vk, t1, n)
+ // V(k'+1) = V(2k+2) = V(k+1)² - 2.
+ t1 = t1.sqr(vk1)
+ t1 = t1.add(t1, nm2)
+ t2, vk1 = t2.div(vk1, t1, n)
+ } else {
+ // k' = 2k
+ // V(k'+1) = V(2k+1) = V(k) V(k+1) - P.
+ t1 = t1.mul(vk, vk1)
+ t1 = t1.add(t1, n)
+ t1 = t1.sub(t1, natP)
+ t2, vk1 = t2.div(vk1, t1, n)
+ // V(k') = V(2k) = V(k)² - 2
+ t1 = t1.sqr(vk)
+ t1 = t1.add(t1, nm2)
+ t2, vk = t2.div(vk, t1, n)
+ }
+ }
+
+ // Now k=s, so vk = V(s). Check V(s) ≡ ±2 (mod n).
+ if vk.cmp(natTwo) == 0 || vk.cmp(nm2) == 0 {
+ // Check U(s) ≡ 0.
+ // As suggested by Jacobsen, apply Crandall and Pomerance equation 3.13:
+ //
+ // U(k) = D⁻¹ (2 V(k+1) - P V(k))
+ //
+ // Since we are checking for U(k) == 0 it suffices to check 2 V(k+1) == P V(k) mod n,
+ // or P V(k) - 2 V(k+1) == 0 mod n.
+ t1 := t1.mul(vk, natP)
+ t2 := t2.shl(vk1, 1)
+ if t1.cmp(t2) < 0 {
+ t1, t2 = t2, t1
+ }
+ t1 = t1.sub(t1, t2)
+ t3 := vk1 // steal vk1, no longer needed below
+ vk1 = nil
+ _ = vk1
+ t2, t3 = t2.div(t3, t1, n)
+ if len(t3) == 0 {
+ return true
+ }
+ }
+
+ // Check V(2^t s) ≡ 0 mod n for some 0 ≤ t < r-1.
+ for t := 0; t < r-1; t++ {
+ if len(vk) == 0 { // vk == 0
+ return true
+ }
+ // Optimization: V(k) = 2 is a fixed point for V(k') = V(k)² - 2,
+ // so if V(k) = 2, we can stop: we will never find a future V(k) == 0.
+ if len(vk) == 1 && vk[0] == 2 { // vk == 2
+ return false
+ }
+ // k' = 2k
+ // V(k') = V(2k) = V(k)² - 2
+ t1 = t1.sqr(vk)
+ t1 = t1.sub(t1, natTwo)
+ t2, vk = t2.div(vk, t1, n)
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/prime_test.go b/platform/dbops/binaries/go/go/src/math/big/prime_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8596e33a13b86480df855ec7626a7891edb8b76b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/prime_test.go
@@ -0,0 +1,222 @@
+// 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 big
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+ "unicode"
+)
+
+var primes = []string{
+ "2",
+ "3",
+ "5",
+ "7",
+ "11",
+
+ "13756265695458089029",
+ "13496181268022124907",
+ "10953742525620032441",
+ "17908251027575790097",
+
+ // https://golang.org/issue/638
+ "18699199384836356663",
+
+ "98920366548084643601728869055592650835572950932266967461790948584315647051443",
+ "94560208308847015747498523884063394671606671904944666360068158221458669711639",
+
+ // https://primes.utm.edu/lists/small/small3.html
+ "449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163",
+ "230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593",
+ "5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993",
+ "203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123",
+
+ // ECC primes: https://tools.ietf.org/html/draft-ladd-safecurves-02
+ "3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9
+ "57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19
+ "9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105
+ "42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17
+ "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1
+}
+
+var composites = []string{
+ "0",
+ "1",
+ "21284175091214687912771199898307297748211672914763848041968395774954376176754",
+ "6084766654921918907427900243509372380954290099172559290432744450051395395951",
+ "84594350493221918389213352992032324280367711247940675652888030554255915464401",
+ "82793403787388584738507275144194252681",
+
+ // Arnault, "Rabin-Miller Primality Test: Composite Numbers Which Pass It",
+ // Mathematics of Computation, 64(209) (January 1995), pp. 335-361.
+ "1195068768795265792518361315725116351898245581", // strong pseudoprime to prime bases 2 through 29
+ // strong pseudoprime to all prime bases up to 200
+ `
+ 80383745745363949125707961434194210813883768828755814583748891752229
+ 74273765333652186502336163960045457915042023603208766569966760987284
+ 0439654082329287387918508691668573282677617710293896977394701670823
+ 0428687109997439976544144845341155872450633409279022275296229414984
+ 2306881685404326457534018329786111298960644845216191652872597534901`,
+
+ // Extra-strong Lucas pseudoprimes. https://oeis.org/A217719
+ "989",
+ "3239",
+ "5777",
+ "10877",
+ "27971",
+ "29681",
+ "30739",
+ "31631",
+ "39059",
+ "72389",
+ "73919",
+ "75077",
+ "100127",
+ "113573",
+ "125249",
+ "137549",
+ "137801",
+ "153931",
+ "155819",
+ "161027",
+ "162133",
+ "189419",
+ "218321",
+ "231703",
+ "249331",
+ "370229",
+ "429479",
+ "430127",
+ "459191",
+ "473891",
+ "480689",
+ "600059",
+ "621781",
+ "632249",
+ "635627",
+
+ "3673744903",
+ "3281593591",
+ "2385076987",
+ "2738053141",
+ "2009621503",
+ "1502682721",
+ "255866131",
+ "117987841",
+ "587861",
+
+ "6368689",
+ "8725753",
+ "80579735209",
+ "105919633",
+}
+
+func cutSpace(r rune) rune {
+ if unicode.IsSpace(r) {
+ return -1
+ }
+ return r
+}
+
+func TestProbablyPrime(t *testing.T) {
+ nreps := 20
+ if testing.Short() {
+ nreps = 1
+ }
+ for i, s := range primes {
+ p, _ := new(Int).SetString(s, 10)
+ if !p.ProbablyPrime(nreps) || nreps != 1 && !p.ProbablyPrime(1) || !p.ProbablyPrime(0) {
+ t.Errorf("#%d prime found to be non-prime (%s)", i, s)
+ }
+ }
+
+ for i, s := range composites {
+ s = strings.Map(cutSpace, s)
+ c, _ := new(Int).SetString(s, 10)
+ if c.ProbablyPrime(nreps) || nreps != 1 && c.ProbablyPrime(1) || c.ProbablyPrime(0) {
+ t.Errorf("#%d composite found to be prime (%s)", i, s)
+ }
+ }
+
+ // check that ProbablyPrime panics if n <= 0
+ c := NewInt(11) // a prime
+ for _, n := range []int{-1, 0, 1} {
+ func() {
+ defer func() {
+ if n < 0 && recover() == nil {
+ t.Fatalf("expected panic from ProbablyPrime(%d)", n)
+ }
+ }()
+ if !c.ProbablyPrime(n) {
+ t.Fatalf("%v should be a prime", c)
+ }
+ }()
+ }
+}
+
+func BenchmarkProbablyPrime(b *testing.B) {
+ p, _ := new(Int).SetString("203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123", 10)
+ for _, n := range []int{0, 1, 5, 10, 20} {
+ b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ p.ProbablyPrime(n)
+ }
+ })
+ }
+
+ b.Run("Lucas", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ p.abs.probablyPrimeLucas()
+ }
+ })
+ b.Run("MillerRabinBase2", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ p.abs.probablyPrimeMillerRabin(1, true)
+ }
+ })
+}
+
+func TestMillerRabinPseudoprimes(t *testing.T) {
+ testPseudoprimes(t, "probablyPrimeMillerRabin",
+ func(n nat) bool { return n.probablyPrimeMillerRabin(1, true) && !n.probablyPrimeLucas() },
+ // https://oeis.org/A001262
+ []int{2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581, 85489, 88357, 90751})
+}
+
+func TestLucasPseudoprimes(t *testing.T) {
+ testPseudoprimes(t, "probablyPrimeLucas",
+ func(n nat) bool { return n.probablyPrimeLucas() && !n.probablyPrimeMillerRabin(1, true) },
+ // https://oeis.org/A217719
+ []int{989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077})
+}
+
+func testPseudoprimes(t *testing.T, name string, cond func(nat) bool, want []int) {
+ n := nat{1}
+ for i := 3; i < 100000; i += 2 {
+ if testing.Short() {
+ if len(want) == 0 {
+ break
+ }
+ if i < want[0]-2 {
+ i = want[0] - 2
+ }
+ }
+ n[0] = Word(i)
+ pseudo := cond(n)
+ if pseudo && (len(want) == 0 || i != want[0]) {
+ t.Errorf("%s(%v, base=2) = true, want false", name, i)
+ } else if !pseudo && len(want) >= 1 && i == want[0] {
+ t.Errorf("%s(%v, base=2) = false, want true", name, i)
+ }
+ if len(want) > 0 && i == want[0] {
+ want = want[1:]
+ }
+ }
+ if len(want) > 0 {
+ t.Fatalf("forgot to test %v", want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/rat.go b/platform/dbops/binaries/go/go/src/math/big/rat.go
new file mode 100644
index 0000000000000000000000000000000000000000..cb32b783a1b032f44fdedf06cfa5a005827fcc3f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/rat.go
@@ -0,0 +1,542 @@
+// 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.
+
+// This file implements multi-precision rational numbers.
+
+package big
+
+import (
+ "fmt"
+ "math"
+)
+
+// A Rat represents a quotient a/b of arbitrary precision.
+// The zero value for a Rat represents the value 0.
+//
+// Operations always take pointer arguments (*Rat) rather
+// than Rat values, and each unique Rat value requires
+// its own unique *Rat pointer. To "copy" a Rat value,
+// an existing (or newly allocated) Rat must be set to
+// a new value using the [Rat.Set] method; shallow copies
+// of Rats are not supported and may lead to errors.
+type Rat struct {
+ // To make zero values for Rat work w/o initialization,
+ // a zero value of b (len(b) == 0) acts like b == 1. At
+ // the earliest opportunity (when an assignment to the Rat
+ // is made), such uninitialized denominators are set to 1.
+ // a.neg determines the sign of the Rat, b.neg is ignored.
+ a, b Int
+}
+
+// NewRat creates a new [Rat] with numerator a and denominator b.
+func NewRat(a, b int64) *Rat {
+ return new(Rat).SetFrac64(a, b)
+}
+
+// SetFloat64 sets z to exactly f and returns z.
+// If f is not finite, SetFloat returns nil.
+func (z *Rat) SetFloat64(f float64) *Rat {
+ const expMask = 1<<11 - 1
+ bits := math.Float64bits(f)
+ mantissa := bits & (1<<52 - 1)
+ exp := int((bits >> 52) & expMask)
+ switch exp {
+ case expMask: // non-finite
+ return nil
+ case 0: // denormal
+ exp -= 1022
+ default: // normal
+ mantissa |= 1 << 52
+ exp -= 1023
+ }
+
+ shift := 52 - exp
+
+ // Optimization (?): partially pre-normalise.
+ for mantissa&1 == 0 && shift > 0 {
+ mantissa >>= 1
+ shift--
+ }
+
+ z.a.SetUint64(mantissa)
+ z.a.neg = f < 0
+ z.b.Set(intOne)
+ if shift > 0 {
+ z.b.Lsh(&z.b, uint(shift))
+ } else {
+ z.a.Lsh(&z.a, uint(-shift))
+ }
+ return z.norm()
+}
+
+// quotToFloat32 returns the non-negative float32 value
+// nearest to the quotient a/b, using round-to-even in
+// halfway cases. It does not mutate its arguments.
+// Preconditions: b is non-zero; a and b have no common factors.
+func quotToFloat32(a, b nat) (f float32, exact bool) {
+ const (
+ // float size in bits
+ Fsize = 32
+
+ // mantissa
+ Msize = 23
+ Msize1 = Msize + 1 // incl. implicit 1
+ Msize2 = Msize1 + 1
+
+ // exponent
+ Esize = Fsize - Msize1
+ Ebias = 1<<(Esize-1) - 1
+ Emin = 1 - Ebias
+ Emax = Ebias
+ )
+
+ // TODO(adonovan): specialize common degenerate cases: 1.0, integers.
+ alen := a.bitLen()
+ if alen == 0 {
+ return 0, true
+ }
+ blen := b.bitLen()
+ if blen == 0 {
+ panic("division by zero")
+ }
+
+ // 1. Left-shift A or B such that quotient A/B is in [1<= B).
+ // This is 2 or 3 more than the float32 mantissa field width of Msize:
+ // - the optional extra bit is shifted away in step 3 below.
+ // - the high-order 1 is omitted in "normal" representation;
+ // - the low-order 1 will be used during rounding then discarded.
+ exp := alen - blen
+ var a2, b2 nat
+ a2 = a2.set(a)
+ b2 = b2.set(b)
+ if shift := Msize2 - exp; shift > 0 {
+ a2 = a2.shl(a2, uint(shift))
+ } else if shift < 0 {
+ b2 = b2.shl(b2, uint(-shift))
+ }
+
+ // 2. Compute quotient and remainder (q, r). NB: due to the
+ // extra shift, the low-order bit of q is logically the
+ // high-order bit of r.
+ var q nat
+ q, r := q.div(a2, a2, b2) // (recycle a2)
+ mantissa := low32(q)
+ haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
+
+ // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
+ // (in effect---we accomplish this incrementally).
+ if mantissa>>Msize2 == 1 {
+ if mantissa&1 == 1 {
+ haveRem = true
+ }
+ mantissa >>= 1
+ exp++
+ }
+ if mantissa>>Msize1 != 1 {
+ panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
+ }
+
+ // 4. Rounding.
+ if Emin-Msize <= exp && exp <= Emin {
+ // Denormal case; lose 'shift' bits of precision.
+ shift := uint(Emin - (exp - 1)) // [1..Esize1)
+ lostbits := mantissa & (1<>= shift
+ exp = 2 - Ebias // == exp + shift
+ }
+ // Round q using round-half-to-even.
+ exact = !haveRem
+ if mantissa&1 != 0 {
+ exact = false
+ if haveRem || mantissa&2 != 0 {
+ if mantissa++; mantissa >= 1< 100...0, so shift is safe
+ mantissa >>= 1
+ exp++
+ }
+ }
+ }
+ mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1<= B).
+ // This is 2 or 3 more than the float64 mantissa field width of Msize:
+ // - the optional extra bit is shifted away in step 3 below.
+ // - the high-order 1 is omitted in "normal" representation;
+ // - the low-order 1 will be used during rounding then discarded.
+ exp := alen - blen
+ var a2, b2 nat
+ a2 = a2.set(a)
+ b2 = b2.set(b)
+ if shift := Msize2 - exp; shift > 0 {
+ a2 = a2.shl(a2, uint(shift))
+ } else if shift < 0 {
+ b2 = b2.shl(b2, uint(-shift))
+ }
+
+ // 2. Compute quotient and remainder (q, r). NB: due to the
+ // extra shift, the low-order bit of q is logically the
+ // high-order bit of r.
+ var q nat
+ q, r := q.div(a2, a2, b2) // (recycle a2)
+ mantissa := low64(q)
+ haveRem := len(r) > 0 // mantissa&1 && !haveRem => remainder is exactly half
+
+ // 3. If quotient didn't fit in Msize2 bits, redo division by b2<<1
+ // (in effect---we accomplish this incrementally).
+ if mantissa>>Msize2 == 1 {
+ if mantissa&1 == 1 {
+ haveRem = true
+ }
+ mantissa >>= 1
+ exp++
+ }
+ if mantissa>>Msize1 != 1 {
+ panic(fmt.Sprintf("expected exactly %d bits of result", Msize2))
+ }
+
+ // 4. Rounding.
+ if Emin-Msize <= exp && exp <= Emin {
+ // Denormal case; lose 'shift' bits of precision.
+ shift := uint(Emin - (exp - 1)) // [1..Esize1)
+ lostbits := mantissa & (1<>= shift
+ exp = 2 - Ebias // == exp + shift
+ }
+ // Round q using round-half-to-even.
+ exact = !haveRem
+ if mantissa&1 != 0 {
+ exact = false
+ if haveRem || mantissa&2 != 0 {
+ if mantissa++; mantissa >= 1< 100...0, so shift is safe
+ mantissa >>= 1
+ exp++
+ }
+ }
+ }
+ mantissa >>= 1 // discard rounding bit. Mantissa now scaled by 1< 0 && !z.a.neg // 0 has no sign
+ return z
+}
+
+// Inv sets z to 1/x and returns z.
+// If x == 0, Inv panics.
+func (z *Rat) Inv(x *Rat) *Rat {
+ if len(x.a.abs) == 0 {
+ panic("division by zero")
+ }
+ z.Set(x)
+ z.a.abs, z.b.abs = z.b.abs, z.a.abs
+ return z
+}
+
+// Sign returns:
+//
+// -1 if x < 0
+// 0 if x == 0
+// +1 if x > 0
+func (x *Rat) Sign() int {
+ return x.a.Sign()
+}
+
+// IsInt reports whether the denominator of x is 1.
+func (x *Rat) IsInt() bool {
+ return len(x.b.abs) == 0 || x.b.abs.cmp(natOne) == 0
+}
+
+// Num returns the numerator of x; it may be <= 0.
+// The result is a reference to x's numerator; it
+// may change if a new value is assigned to x, and vice versa.
+// The sign of the numerator corresponds to the sign of x.
+func (x *Rat) Num() *Int {
+ return &x.a
+}
+
+// Denom returns the denominator of x; it is always > 0.
+// The result is a reference to x's denominator, unless
+// x is an uninitialized (zero value) [Rat], in which case
+// the result is a new [Int] of value 1. (To initialize x,
+// any operation that sets x will do, including x.Set(x).)
+// If the result is a reference to x's denominator it
+// may change if a new value is assigned to x, and vice versa.
+func (x *Rat) Denom() *Int {
+ // Note that x.b.neg is guaranteed false.
+ if len(x.b.abs) == 0 {
+ // Note: If this proves problematic, we could
+ // panic instead and require the Rat to
+ // be explicitly initialized.
+ return &Int{abs: nat{1}}
+ }
+ return &x.b
+}
+
+func (z *Rat) norm() *Rat {
+ switch {
+ case len(z.a.abs) == 0:
+ // z == 0; normalize sign and denominator
+ z.a.neg = false
+ fallthrough
+ case len(z.b.abs) == 0:
+ // z is integer; normalize denominator
+ z.b.abs = z.b.abs.setWord(1)
+ default:
+ // z is fraction; normalize numerator and denominator
+ neg := z.a.neg
+ z.a.neg = false
+ z.b.neg = false
+ if f := NewInt(0).lehmerGCD(nil, nil, &z.a, &z.b); f.Cmp(intOne) != 0 {
+ z.a.abs, _ = z.a.abs.div(nil, z.a.abs, f.abs)
+ z.b.abs, _ = z.b.abs.div(nil, z.b.abs, f.abs)
+ }
+ z.a.neg = neg
+ }
+ return z
+}
+
+// mulDenom sets z to the denominator product x*y (by taking into
+// account that 0 values for x or y must be interpreted as 1) and
+// returns z.
+func mulDenom(z, x, y nat) nat {
+ switch {
+ case len(x) == 0 && len(y) == 0:
+ return z.setWord(1)
+ case len(x) == 0:
+ return z.set(y)
+ case len(y) == 0:
+ return z.set(x)
+ }
+ return z.mul(x, y)
+}
+
+// scaleDenom sets z to the product x*f.
+// If f == 0 (zero value of denominator), z is set to (a copy of) x.
+func (z *Int) scaleDenom(x *Int, f nat) {
+ if len(f) == 0 {
+ z.Set(x)
+ return
+ }
+ z.abs = z.abs.mul(x.abs, f)
+ z.neg = x.neg
+}
+
+// Cmp compares x and y and returns:
+//
+// -1 if x < y
+// 0 if x == y
+// +1 if x > y
+func (x *Rat) Cmp(y *Rat) int {
+ var a, b Int
+ a.scaleDenom(&x.a, y.b.abs)
+ b.scaleDenom(&y.a, x.b.abs)
+ return a.Cmp(&b)
+}
+
+// Add sets z to the sum x+y and returns z.
+func (z *Rat) Add(x, y *Rat) *Rat {
+ var a1, a2 Int
+ a1.scaleDenom(&x.a, y.b.abs)
+ a2.scaleDenom(&y.a, x.b.abs)
+ z.a.Add(&a1, &a2)
+ z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
+ return z.norm()
+}
+
+// Sub sets z to the difference x-y and returns z.
+func (z *Rat) Sub(x, y *Rat) *Rat {
+ var a1, a2 Int
+ a1.scaleDenom(&x.a, y.b.abs)
+ a2.scaleDenom(&y.a, x.b.abs)
+ z.a.Sub(&a1, &a2)
+ z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
+ return z.norm()
+}
+
+// Mul sets z to the product x*y and returns z.
+func (z *Rat) Mul(x, y *Rat) *Rat {
+ if x == y {
+ // a squared Rat is positive and can't be reduced (no need to call norm())
+ z.a.neg = false
+ z.a.abs = z.a.abs.sqr(x.a.abs)
+ if len(x.b.abs) == 0 {
+ z.b.abs = z.b.abs.setWord(1)
+ } else {
+ z.b.abs = z.b.abs.sqr(x.b.abs)
+ }
+ return z
+ }
+ z.a.Mul(&x.a, &y.a)
+ z.b.abs = mulDenom(z.b.abs, x.b.abs, y.b.abs)
+ return z.norm()
+}
+
+// Quo sets z to the quotient x/y and returns z.
+// If y == 0, Quo panics.
+func (z *Rat) Quo(x, y *Rat) *Rat {
+ if len(y.a.abs) == 0 {
+ panic("division by zero")
+ }
+ var a, b Int
+ a.scaleDenom(&x.a, y.b.abs)
+ b.scaleDenom(&y.a, x.b.abs)
+ z.a.abs = a.abs
+ z.b.abs = b.abs
+ z.a.neg = a.neg != b.neg
+ return z.norm()
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/rat_test.go b/platform/dbops/binaries/go/go/src/math/big/rat_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d98c89b3578a7aee1e88e62411c6b192e61cce57
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/rat_test.go
@@ -0,0 +1,746 @@
+// 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 big
+
+import (
+ "math"
+ "testing"
+)
+
+func TestZeroRat(t *testing.T) {
+ var x, y, z Rat
+ y.SetFrac64(0, 42)
+
+ if x.Cmp(&y) != 0 {
+ t.Errorf("x and y should be both equal and zero")
+ }
+
+ if s := x.String(); s != "0/1" {
+ t.Errorf("got x = %s, want 0/1", s)
+ }
+
+ if s := x.RatString(); s != "0" {
+ t.Errorf("got x = %s, want 0", s)
+ }
+
+ z.Add(&x, &y)
+ if s := z.RatString(); s != "0" {
+ t.Errorf("got x+y = %s, want 0", s)
+ }
+
+ z.Sub(&x, &y)
+ if s := z.RatString(); s != "0" {
+ t.Errorf("got x-y = %s, want 0", s)
+ }
+
+ z.Mul(&x, &y)
+ if s := z.RatString(); s != "0" {
+ t.Errorf("got x*y = %s, want 0", s)
+ }
+
+ // check for division by zero
+ defer func() {
+ if s := recover(); s == nil || s.(string) != "division by zero" {
+ panic(s)
+ }
+ }()
+ z.Quo(&x, &y)
+}
+
+func TestRatSign(t *testing.T) {
+ zero := NewRat(0, 1)
+ for _, a := range setStringTests {
+ x, ok := new(Rat).SetString(a.in)
+ if !ok {
+ continue
+ }
+ s := x.Sign()
+ e := x.Cmp(zero)
+ if s != e {
+ t.Errorf("got %d; want %d for z = %v", s, e, &x)
+ }
+ }
+}
+
+var ratCmpTests = []struct {
+ rat1, rat2 string
+ out int
+}{
+ {"0", "0/1", 0},
+ {"1/1", "1", 0},
+ {"-1", "-2/2", 0},
+ {"1", "0", 1},
+ {"0/1", "1/1", -1},
+ {"-5/1434770811533343057144", "-5/1434770811533343057145", -1},
+ {"49832350382626108453/8964749413", "49832350382626108454/8964749413", -1},
+ {"-37414950961700930/7204075375675961", "37414950961700930/7204075375675961", -1},
+ {"37414950961700930/7204075375675961", "74829901923401860/14408150751351922", 0},
+}
+
+func TestRatCmp(t *testing.T) {
+ for i, test := range ratCmpTests {
+ x, _ := new(Rat).SetString(test.rat1)
+ y, _ := new(Rat).SetString(test.rat2)
+
+ out := x.Cmp(y)
+ if out != test.out {
+ t.Errorf("#%d got out = %v; want %v", i, out, test.out)
+ }
+ }
+}
+
+func TestIsInt(t *testing.T) {
+ one := NewInt(1)
+ for _, a := range setStringTests {
+ x, ok := new(Rat).SetString(a.in)
+ if !ok {
+ continue
+ }
+ i := x.IsInt()
+ e := x.Denom().Cmp(one) == 0
+ if i != e {
+ t.Errorf("got IsInt(%v) == %v; want %v", x, i, e)
+ }
+ }
+}
+
+func TestRatAbs(t *testing.T) {
+ zero := new(Rat)
+ for _, a := range setStringTests {
+ x, ok := new(Rat).SetString(a.in)
+ if !ok {
+ continue
+ }
+ e := new(Rat).Set(x)
+ if e.Cmp(zero) < 0 {
+ e.Sub(zero, e)
+ }
+ z := new(Rat).Abs(x)
+ if z.Cmp(e) != 0 {
+ t.Errorf("got Abs(%v) = %v; want %v", x, z, e)
+ }
+ }
+}
+
+func TestRatNeg(t *testing.T) {
+ zero := new(Rat)
+ for _, a := range setStringTests {
+ x, ok := new(Rat).SetString(a.in)
+ if !ok {
+ continue
+ }
+ e := new(Rat).Sub(zero, x)
+ z := new(Rat).Neg(x)
+ if z.Cmp(e) != 0 {
+ t.Errorf("got Neg(%v) = %v; want %v", x, z, e)
+ }
+ }
+}
+
+func TestRatInv(t *testing.T) {
+ zero := new(Rat)
+ for _, a := range setStringTests {
+ x, ok := new(Rat).SetString(a.in)
+ if !ok {
+ continue
+ }
+ if x.Cmp(zero) == 0 {
+ continue // avoid division by zero
+ }
+ e := new(Rat).SetFrac(x.Denom(), x.Num())
+ z := new(Rat).Inv(x)
+ if z.Cmp(e) != 0 {
+ t.Errorf("got Inv(%v) = %v; want %v", x, z, e)
+ }
+ }
+}
+
+type ratBinFun func(z, x, y *Rat) *Rat
+type ratBinArg struct {
+ x, y, z string
+}
+
+func testRatBin(t *testing.T, i int, name string, f ratBinFun, a ratBinArg) {
+ x, _ := new(Rat).SetString(a.x)
+ y, _ := new(Rat).SetString(a.y)
+ z, _ := new(Rat).SetString(a.z)
+ out := f(new(Rat), x, y)
+
+ if out.Cmp(z) != 0 {
+ t.Errorf("%s #%d got %s want %s", name, i, out, z)
+ }
+}
+
+var ratBinTests = []struct {
+ x, y string
+ sum, prod string
+}{
+ {"0", "0", "0", "0"},
+ {"0", "1", "1", "0"},
+ {"-1", "0", "-1", "0"},
+ {"-1", "1", "0", "-1"},
+ {"1", "1", "2", "1"},
+ {"1/2", "1/2", "1", "1/4"},
+ {"1/4", "1/3", "7/12", "1/12"},
+ {"2/5", "-14/3", "-64/15", "-28/15"},
+ {"4707/49292519774798173060", "-3367/70976135186689855734", "84058377121001851123459/1749296273614329067191168098769082663020", "-1760941/388732505247628681598037355282018369560"},
+ {"-61204110018146728334/3", "-31052192278051565633/2", "-215564796870448153567/6", "950260896245257153059642991192710872711/3"},
+ {"-854857841473707320655/4237645934602118692642972629634714039", "-18/31750379913563777419", "-27/133467566250814981", "15387441146526731771790/134546868362786310073779084329032722548987800600710485341"},
+ {"618575745270541348005638912139/19198433543745179392300736", "-19948846211000086/637313996471", "27674141753240653/30123979153216", "-6169936206128396568797607742807090270137721977/6117715203873571641674006593837351328"},
+ {"-3/26206484091896184128", "5/2848423294177090248", "15310893822118706237/9330894968229805033368778458685147968", "-5/24882386581946146755650075889827061248"},
+ {"26946729/330400702820", "41563965/225583428284", "1238218672302860271/4658307703098666660055", "224002580204097/14906584649915733312176"},
+ {"-8259900599013409474/7", "-84829337473700364773/56707961321161574960", "-468402123685491748914621885145127724451/396955729248131024720", "350340947706464153265156004876107029701/198477864624065512360"},
+ {"575775209696864/1320203974639986246357", "29/712593081308", "410331716733912717985762465/940768218243776489278275419794956", "808/45524274987585732633"},
+ {"1786597389946320496771/2066653520653241", "6269770/1992362624741777", "3559549865190272133656109052308126637/4117523232840525481453983149257", "8967230/3296219033"},
+ {"-36459180403360509753/32150500941194292113930", "9381566963714/9633539", "301622077145533298008420642898530153/309723104686531919656937098270", "-3784609207827/3426986245"},
+}
+
+func TestRatBin(t *testing.T) {
+ for i, test := range ratBinTests {
+ arg := ratBinArg{test.x, test.y, test.sum}
+ testRatBin(t, i, "Add", (*Rat).Add, arg)
+
+ arg = ratBinArg{test.y, test.x, test.sum}
+ testRatBin(t, i, "Add symmetric", (*Rat).Add, arg)
+
+ arg = ratBinArg{test.sum, test.x, test.y}
+ testRatBin(t, i, "Sub", (*Rat).Sub, arg)
+
+ arg = ratBinArg{test.sum, test.y, test.x}
+ testRatBin(t, i, "Sub symmetric", (*Rat).Sub, arg)
+
+ arg = ratBinArg{test.x, test.y, test.prod}
+ testRatBin(t, i, "Mul", (*Rat).Mul, arg)
+
+ arg = ratBinArg{test.y, test.x, test.prod}
+ testRatBin(t, i, "Mul symmetric", (*Rat).Mul, arg)
+
+ if test.x != "0" {
+ arg = ratBinArg{test.prod, test.x, test.y}
+ testRatBin(t, i, "Quo", (*Rat).Quo, arg)
+ }
+
+ if test.y != "0" {
+ arg = ratBinArg{test.prod, test.y, test.x}
+ testRatBin(t, i, "Quo symmetric", (*Rat).Quo, arg)
+ }
+ }
+}
+
+func TestIssue820(t *testing.T) {
+ x := NewRat(3, 1)
+ y := NewRat(2, 1)
+ z := y.Quo(x, y)
+ q := NewRat(3, 2)
+ if z.Cmp(q) != 0 {
+ t.Errorf("got %s want %s", z, q)
+ }
+
+ y = NewRat(3, 1)
+ x = NewRat(2, 1)
+ z = y.Quo(x, y)
+ q = NewRat(2, 3)
+ if z.Cmp(q) != 0 {
+ t.Errorf("got %s want %s", z, q)
+ }
+
+ x = NewRat(3, 1)
+ z = x.Quo(x, x)
+ q = NewRat(3, 3)
+ if z.Cmp(q) != 0 {
+ t.Errorf("got %s want %s", z, q)
+ }
+}
+
+var setFrac64Tests = []struct {
+ a, b int64
+ out string
+}{
+ {0, 1, "0"},
+ {0, -1, "0"},
+ {1, 1, "1"},
+ {-1, 1, "-1"},
+ {1, -1, "-1"},
+ {-1, -1, "1"},
+ {-9223372036854775808, -9223372036854775808, "1"},
+}
+
+func TestRatSetFrac64Rat(t *testing.T) {
+ for i, test := range setFrac64Tests {
+ x := new(Rat).SetFrac64(test.a, test.b)
+ if x.RatString() != test.out {
+ t.Errorf("#%d got %s want %s", i, x.RatString(), test.out)
+ }
+ }
+}
+
+func TestIssue2379(t *testing.T) {
+ // 1) no aliasing
+ q := NewRat(3, 2)
+ x := new(Rat)
+ x.SetFrac(NewInt(3), NewInt(2))
+ if x.Cmp(q) != 0 {
+ t.Errorf("1) got %s want %s", x, q)
+ }
+
+ // 2) aliasing of numerator
+ x = NewRat(2, 3)
+ x.SetFrac(NewInt(3), x.Num())
+ if x.Cmp(q) != 0 {
+ t.Errorf("2) got %s want %s", x, q)
+ }
+
+ // 3) aliasing of denominator
+ x = NewRat(2, 3)
+ x.SetFrac(x.Denom(), NewInt(2))
+ if x.Cmp(q) != 0 {
+ t.Errorf("3) got %s want %s", x, q)
+ }
+
+ // 4) aliasing of numerator and denominator
+ x = NewRat(2, 3)
+ x.SetFrac(x.Denom(), x.Num())
+ if x.Cmp(q) != 0 {
+ t.Errorf("4) got %s want %s", x, q)
+ }
+
+ // 5) numerator and denominator are the same
+ q = NewRat(1, 1)
+ x = new(Rat)
+ n := NewInt(7)
+ x.SetFrac(n, n)
+ if x.Cmp(q) != 0 {
+ t.Errorf("5) got %s want %s", x, q)
+ }
+}
+
+func TestIssue3521(t *testing.T) {
+ a := new(Int)
+ b := new(Int)
+ a.SetString("64375784358435883458348587", 0)
+ b.SetString("4789759874531", 0)
+
+ // 0) a raw zero value has 1 as denominator
+ zero := new(Rat)
+ one := NewInt(1)
+ if zero.Denom().Cmp(one) != 0 {
+ t.Errorf("0) got %s want %s", zero.Denom(), one)
+ }
+
+ // 1a) the denominator of an (uninitialized) zero value is not shared with the value
+ s := &zero.b
+ d := zero.Denom()
+ if d == s {
+ t.Errorf("1a) got %s (%p) == %s (%p) want different *Int values", d, d, s, s)
+ }
+
+ // 1b) the denominator of an (uninitialized) value is a new 1 each time
+ d1 := zero.Denom()
+ d2 := zero.Denom()
+ if d1 == d2 {
+ t.Errorf("1b) got %s (%p) == %s (%p) want different *Int values", d1, d1, d2, d2)
+ }
+
+ // 1c) the denominator of an initialized zero value is shared with the value
+ x := new(Rat)
+ x.Set(x) // initialize x (any operation that sets x explicitly will do)
+ s = &x.b
+ d = x.Denom()
+ if d != s {
+ t.Errorf("1c) got %s (%p) != %s (%p) want identical *Int values", d, d, s, s)
+ }
+
+ // 1d) a zero value remains zero independent of denominator
+ x.Denom().Set(new(Int).Neg(b))
+ if x.Cmp(zero) != 0 {
+ t.Errorf("1d) got %s want %s", x, zero)
+ }
+
+ // 1e) a zero value may have a denominator != 0 and != 1
+ x.Num().Set(a)
+ qab := new(Rat).SetFrac(a, b)
+ if x.Cmp(qab) != 0 {
+ t.Errorf("1e) got %s want %s", x, qab)
+ }
+
+ // 2a) an integral value becomes a fraction depending on denominator
+ x.SetFrac64(10, 2)
+ x.Denom().SetInt64(3)
+ q53 := NewRat(5, 3)
+ if x.Cmp(q53) != 0 {
+ t.Errorf("2a) got %s want %s", x, q53)
+ }
+
+ // 2b) an integral value becomes a fraction depending on denominator
+ x = NewRat(10, 2)
+ x.Denom().SetInt64(3)
+ if x.Cmp(q53) != 0 {
+ t.Errorf("2b) got %s want %s", x, q53)
+ }
+
+ // 3) changing the numerator/denominator of a Rat changes the Rat
+ x.SetFrac(a, b)
+ a = x.Num()
+ b = x.Denom()
+ a.SetInt64(5)
+ b.SetInt64(3)
+ if x.Cmp(q53) != 0 {
+ t.Errorf("3) got %s want %s", x, q53)
+ }
+}
+
+func TestFloat32Distribution(t *testing.T) {
+ // Generate a distribution of (sign, mantissa, exp) values
+ // broader than the float32 range, and check Rat.Float32()
+ // always picks the closest float32 approximation.
+ var add = []int64{
+ 0,
+ 1,
+ 3,
+ 5,
+ 7,
+ 9,
+ 11,
+ }
+ var winc, einc = uint64(5), 15 // quick test (~60ms on x86-64)
+ if *long {
+ winc, einc = uint64(1), 1 // soak test (~1.5s on x86-64)
+ }
+
+ for _, sign := range "+-" {
+ for _, a := range add {
+ for wid := uint64(0); wid < 30; wid += winc {
+ b := 1< 0 {
+ num.Lsh(num, uint(exp))
+ } else {
+ den.Lsh(den, uint(-exp))
+ }
+ r := new(Rat).SetFrac(num, den)
+ f, _ := r.Float32()
+
+ if !checkIsBestApprox32(t, f, r) {
+ // Append context information.
+ t.Errorf("(input was mantissa %#x, exp %d; f = %g (%b); f ~ %g; r = %v)",
+ b, exp, f, f, math.Ldexp(float64(b), exp), r)
+ }
+
+ checkNonLossyRoundtrip32(t, f)
+ }
+ }
+ }
+ }
+}
+
+func TestFloat64Distribution(t *testing.T) {
+ // Generate a distribution of (sign, mantissa, exp) values
+ // broader than the float64 range, and check Rat.Float64()
+ // always picks the closest float64 approximation.
+ var add = []int64{
+ 0,
+ 1,
+ 3,
+ 5,
+ 7,
+ 9,
+ 11,
+ }
+ var winc, einc = uint64(10), 500 // quick test (~12ms on x86-64)
+ if *long {
+ winc, einc = uint64(1), 1 // soak test (~75s on x86-64)
+ }
+
+ for _, sign := range "+-" {
+ for _, a := range add {
+ for wid := uint64(0); wid < 60; wid += winc {
+ b := 1< 0 {
+ num.Lsh(num, uint(exp))
+ } else {
+ den.Lsh(den, uint(-exp))
+ }
+ r := new(Rat).SetFrac(num, den)
+ f, _ := r.Float64()
+
+ if !checkIsBestApprox64(t, f, r) {
+ // Append context information.
+ t.Errorf("(input was mantissa %#x, exp %d; f = %g (%b); f ~ %g; r = %v)",
+ b, exp, f, f, math.Ldexp(float64(b), exp), r)
+ }
+
+ checkNonLossyRoundtrip64(t, f)
+ }
+ }
+ }
+ }
+}
+
+// TestSetFloat64NonFinite checks that SetFloat64 of a non-finite value
+// returns nil.
+func TestSetFloat64NonFinite(t *testing.T) {
+ for _, f := range []float64{math.NaN(), math.Inf(+1), math.Inf(-1)} {
+ var r Rat
+ if r2 := r.SetFloat64(f); r2 != nil {
+ t.Errorf("SetFloat64(%g) was %v, want nil", f, r2)
+ }
+ }
+}
+
+// checkNonLossyRoundtrip32 checks that a float->Rat->float roundtrip is
+// non-lossy for finite f.
+func checkNonLossyRoundtrip32(t *testing.T, f float32) {
+ if !isFinite(float64(f)) {
+ return
+ }
+ r := new(Rat).SetFloat64(float64(f))
+ if r == nil {
+ t.Errorf("Rat.SetFloat64(float64(%g) (%b)) == nil", f, f)
+ return
+ }
+ f2, exact := r.Float32()
+ if f != f2 || !exact {
+ t.Errorf("Rat.SetFloat64(float64(%g)).Float32() = %g (%b), %v, want %g (%b), %v; delta = %b",
+ f, f2, f2, exact, f, f, true, f2-f)
+ }
+}
+
+// checkNonLossyRoundtrip64 checks that a float->Rat->float roundtrip is
+// non-lossy for finite f.
+func checkNonLossyRoundtrip64(t *testing.T, f float64) {
+ if !isFinite(f) {
+ return
+ }
+ r := new(Rat).SetFloat64(f)
+ if r == nil {
+ t.Errorf("Rat.SetFloat64(%g (%b)) == nil", f, f)
+ return
+ }
+ f2, exact := r.Float64()
+ if f != f2 || !exact {
+ t.Errorf("Rat.SetFloat64(%g).Float64() = %g (%b), %v, want %g (%b), %v; delta = %b",
+ f, f2, f2, exact, f, f, true, f2-f)
+ }
+}
+
+// delta returns the absolute difference between r and f.
+func delta(r *Rat, f float64) *Rat {
+ d := new(Rat).Sub(r, new(Rat).SetFloat64(f))
+ return d.Abs(d)
+}
+
+// checkIsBestApprox32 checks that f is the best possible float32
+// approximation of r.
+// Returns true on success.
+func checkIsBestApprox32(t *testing.T, f float32, r *Rat) bool {
+ if math.Abs(float64(f)) >= math.MaxFloat32 {
+ // Cannot check +Inf, -Inf, nor the float next to them (MaxFloat32).
+ // But we have tests for these special cases.
+ return true
+ }
+
+ // r must be strictly between f0 and f1, the floats bracketing f.
+ f0 := math.Nextafter32(f, float32(math.Inf(-1)))
+ f1 := math.Nextafter32(f, float32(math.Inf(+1)))
+
+ // For f to be correct, r must be closer to f than to f0 or f1.
+ df := delta(r, float64(f))
+ df0 := delta(r, float64(f0))
+ df1 := delta(r, float64(f1))
+ if df.Cmp(df0) > 0 {
+ t.Errorf("Rat(%v).Float32() = %g (%b), but previous float32 %g (%b) is closer", r, f, f, f0, f0)
+ return false
+ }
+ if df.Cmp(df1) > 0 {
+ t.Errorf("Rat(%v).Float32() = %g (%b), but next float32 %g (%b) is closer", r, f, f, f1, f1)
+ return false
+ }
+ if df.Cmp(df0) == 0 && !isEven32(f) {
+ t.Errorf("Rat(%v).Float32() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f0, f0)
+ return false
+ }
+ if df.Cmp(df1) == 0 && !isEven32(f) {
+ t.Errorf("Rat(%v).Float32() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f1, f1)
+ return false
+ }
+ return true
+}
+
+// checkIsBestApprox64 checks that f is the best possible float64
+// approximation of r.
+// Returns true on success.
+func checkIsBestApprox64(t *testing.T, f float64, r *Rat) bool {
+ if math.Abs(f) >= math.MaxFloat64 {
+ // Cannot check +Inf, -Inf, nor the float next to them (MaxFloat64).
+ // But we have tests for these special cases.
+ return true
+ }
+
+ // r must be strictly between f0 and f1, the floats bracketing f.
+ f0 := math.Nextafter(f, math.Inf(-1))
+ f1 := math.Nextafter(f, math.Inf(+1))
+
+ // For f to be correct, r must be closer to f than to f0 or f1.
+ df := delta(r, f)
+ df0 := delta(r, f0)
+ df1 := delta(r, f1)
+ if df.Cmp(df0) > 0 {
+ t.Errorf("Rat(%v).Float64() = %g (%b), but previous float64 %g (%b) is closer", r, f, f, f0, f0)
+ return false
+ }
+ if df.Cmp(df1) > 0 {
+ t.Errorf("Rat(%v).Float64() = %g (%b), but next float64 %g (%b) is closer", r, f, f, f1, f1)
+ return false
+ }
+ if df.Cmp(df0) == 0 && !isEven64(f) {
+ t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f0, f0)
+ return false
+ }
+ if df.Cmp(df1) == 0 && !isEven64(f) {
+ t.Errorf("Rat(%v).Float64() = %g (%b); halfway should have rounded to %g (%b) instead", r, f, f, f1, f1)
+ return false
+ }
+ return true
+}
+
+func isEven32(f float32) bool { return math.Float32bits(f)&1 == 0 }
+func isEven64(f float64) bool { return math.Float64bits(f)&1 == 0 }
+
+func TestIsFinite(t *testing.T) {
+ finites := []float64{
+ 1.0 / 3,
+ 4891559871276714924261e+222,
+ math.MaxFloat64,
+ math.SmallestNonzeroFloat64,
+ -math.MaxFloat64,
+ -math.SmallestNonzeroFloat64,
+ }
+ for _, f := range finites {
+ if !isFinite(f) {
+ t.Errorf("!IsFinite(%g (%b))", f, f)
+ }
+ }
+ nonfinites := []float64{
+ math.NaN(),
+ math.Inf(-1),
+ math.Inf(+1),
+ }
+ for _, f := range nonfinites {
+ if isFinite(f) {
+ t.Errorf("IsFinite(%g, (%b))", f, f)
+ }
+ }
+}
+
+func TestRatSetInt64(t *testing.T) {
+ var testCases = []int64{
+ 0,
+ 1,
+ -1,
+ 12345,
+ -98765,
+ math.MaxInt64,
+ math.MinInt64,
+ }
+ var r = new(Rat)
+ for i, want := range testCases {
+ r.SetInt64(want)
+ if !r.IsInt() {
+ t.Errorf("#%d: Rat.SetInt64(%d) is not an integer", i, want)
+ }
+ num := r.Num()
+ if !num.IsInt64() {
+ t.Errorf("#%d: Rat.SetInt64(%d) numerator is not an int64", i, want)
+ }
+ got := num.Int64()
+ if got != want {
+ t.Errorf("#%d: Rat.SetInt64(%d) = %d, but expected %d", i, want, got, want)
+ }
+ }
+}
+
+func TestRatSetUint64(t *testing.T) {
+ var testCases = []uint64{
+ 0,
+ 1,
+ 12345,
+ ^uint64(0),
+ }
+ var r = new(Rat)
+ for i, want := range testCases {
+ r.SetUint64(want)
+ if !r.IsInt() {
+ t.Errorf("#%d: Rat.SetUint64(%d) is not an integer", i, want)
+ }
+ num := r.Num()
+ if !num.IsUint64() {
+ t.Errorf("#%d: Rat.SetUint64(%d) numerator is not a uint64", i, want)
+ }
+ got := num.Uint64()
+ if got != want {
+ t.Errorf("#%d: Rat.SetUint64(%d) = %d, but expected %d", i, want, got, want)
+ }
+ }
+}
+
+func BenchmarkRatCmp(b *testing.B) {
+ x, y := NewRat(4, 1), NewRat(7, 2)
+ for i := 0; i < b.N; i++ {
+ x.Cmp(y)
+ }
+}
+
+// TestIssue34919 verifies that a Rat's denominator is not modified
+// when simply accessing the Rat value.
+func TestIssue34919(t *testing.T) {
+ for _, acc := range []struct {
+ name string
+ f func(*Rat)
+ }{
+ {"Float32", func(x *Rat) { x.Float32() }},
+ {"Float64", func(x *Rat) { x.Float64() }},
+ {"Inv", func(x *Rat) { new(Rat).Inv(x) }},
+ {"Sign", func(x *Rat) { x.Sign() }},
+ {"IsInt", func(x *Rat) { x.IsInt() }},
+ {"Num", func(x *Rat) { x.Num() }},
+ // {"Denom", func(x *Rat) { x.Denom() }}, TODO(gri) should we change the API? See issue #33792.
+ } {
+ // A denominator of length 0 is interpreted as 1. Make sure that
+ // "materialization" of the denominator doesn't lead to setting
+ // the underlying array element 0 to 1.
+ r := &Rat{Int{abs: nat{991}}, Int{abs: make(nat, 0, 1)}}
+ acc.f(r)
+ if d := r.b.abs[:1][0]; d != 0 {
+ t.Errorf("%s modified denominator: got %d, want 0", acc.name, d)
+ }
+ }
+}
+
+func TestDenomRace(t *testing.T) {
+ x := NewRat(1, 2)
+ const N = 3
+ c := make(chan bool, N)
+ for i := 0; i < N; i++ {
+ go func() {
+ // Denom (also used by Float.SetRat) used to mutate x unnecessarily,
+ // provoking race reports when run in the race detector.
+ x.Denom()
+ new(Float).SetRat(x)
+ c <- true
+ }()
+ }
+ for i := 0; i < N; i++ {
+ <-c
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/ratconv.go b/platform/dbops/binaries/go/go/src/math/big/ratconv.go
new file mode 100644
index 0000000000000000000000000000000000000000..dd99aecdc04af0982deb588205e9b0a5cb509f55
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/ratconv.go
@@ -0,0 +1,459 @@
+// 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 rat-to-string conversion functions.
+
+package big
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+)
+
+func ratTok(ch rune) bool {
+ return strings.ContainsRune("+-/0123456789.eE", ch)
+}
+
+var ratZero Rat
+var _ fmt.Scanner = &ratZero // *Rat must implement fmt.Scanner
+
+// Scan is a support routine for fmt.Scanner. It accepts the formats
+// 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
+func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
+ tok, err := s.Token(true, ratTok)
+ if err != nil {
+ return err
+ }
+ if !strings.ContainsRune("efgEFGv", ch) {
+ return errors.New("Rat.Scan: invalid verb")
+ }
+ if _, ok := z.SetString(string(tok)); !ok {
+ return errors.New("Rat.Scan: invalid syntax")
+ }
+ return nil
+}
+
+// SetString sets z to the value of s and returns z and a boolean indicating
+// success. s can be given as a (possibly signed) fraction "a/b", or as a
+// floating-point number optionally followed by an exponent.
+// If a fraction is provided, both the dividend and the divisor may be a
+// decimal integer or independently use a prefix of “0b”, “0” or “0o”,
+// or “0x” (or their upper-case variants) to denote a binary, octal, or
+// hexadecimal integer, respectively. The divisor may not be signed.
+// If a floating-point number is provided, it may be in decimal form or
+// use any of the same prefixes as above but for “0” to denote a non-decimal
+// mantissa. A leading “0” is considered a decimal leading 0; it does not
+// indicate octal representation in this case.
+// An optional base-10 “e” or base-2 “p” (or their upper-case variants)
+// exponent may be provided as well, except for hexadecimal floats which
+// only accept an (optional) “p” exponent (because an “e” or “E” cannot
+// be distinguished from a mantissa digit). If the exponent's absolute value
+// is too large, the operation may fail.
+// The entire string, not just a prefix, must be valid for success. If the
+// operation failed, the value of z is undefined but the returned value is nil.
+func (z *Rat) SetString(s string) (*Rat, bool) {
+ if len(s) == 0 {
+ return nil, false
+ }
+ // len(s) > 0
+
+ // parse fraction a/b, if any
+ if sep := strings.Index(s, "/"); sep >= 0 {
+ if _, ok := z.a.SetString(s[:sep], 0); !ok {
+ return nil, false
+ }
+ r := strings.NewReader(s[sep+1:])
+ var err error
+ if z.b.abs, _, _, err = z.b.abs.scan(r, 0, false); err != nil {
+ return nil, false
+ }
+ // entire string must have been consumed
+ if _, err = r.ReadByte(); err != io.EOF {
+ return nil, false
+ }
+ if len(z.b.abs) == 0 {
+ return nil, false
+ }
+ return z.norm(), true
+ }
+
+ // parse floating-point number
+ r := strings.NewReader(s)
+
+ // sign
+ neg, err := scanSign(r)
+ if err != nil {
+ return nil, false
+ }
+
+ // mantissa
+ var base int
+ var fcount int // fractional digit count; valid if <= 0
+ z.a.abs, base, fcount, err = z.a.abs.scan(r, 0, true)
+ if err != nil {
+ return nil, false
+ }
+
+ // exponent
+ var exp int64
+ var ebase int
+ exp, ebase, err = scanExponent(r, true, true)
+ if err != nil {
+ return nil, false
+ }
+
+ // there should be no unread characters left
+ if _, err = r.ReadByte(); err != io.EOF {
+ return nil, false
+ }
+
+ // special-case 0 (see also issue #16176)
+ if len(z.a.abs) == 0 {
+ return z.norm(), true
+ }
+ // len(z.a.abs) > 0
+
+ // The mantissa may have a radix point (fcount <= 0) and there
+ // may be a nonzero exponent exp. The radix point amounts to a
+ // division by base**(-fcount), which equals a multiplication by
+ // base**fcount. An exponent means multiplication by ebase**exp.
+ // Multiplications are commutative, so we can apply them in any
+ // order. We only have powers of 2 and 10, and we split powers
+ // of 10 into the product of the same powers of 2 and 5. This
+ // may reduce the size of shift/multiplication factors or
+ // divisors required to create the final fraction, depending
+ // on the actual floating-point value.
+
+ // determine binary or decimal exponent contribution of radix point
+ var exp2, exp5 int64
+ if fcount < 0 {
+ // The mantissa has a radix point ddd.dddd; and
+ // -fcount is the number of digits to the right
+ // of '.'. Adjust relevant exponent accordingly.
+ d := int64(fcount)
+ switch base {
+ case 10:
+ exp5 = d
+ fallthrough // 10**e == 5**e * 2**e
+ case 2:
+ exp2 = d
+ case 8:
+ exp2 = d * 3 // octal digits are 3 bits each
+ case 16:
+ exp2 = d * 4 // hexadecimal digits are 4 bits each
+ default:
+ panic("unexpected mantissa base")
+ }
+ // fcount consumed - not needed anymore
+ }
+
+ // take actual exponent into account
+ switch ebase {
+ case 10:
+ exp5 += exp
+ fallthrough // see fallthrough above
+ case 2:
+ exp2 += exp
+ default:
+ panic("unexpected exponent base")
+ }
+ // exp consumed - not needed anymore
+
+ // apply exp5 contributions
+ // (start with exp5 so the numbers to multiply are smaller)
+ if exp5 != 0 {
+ n := exp5
+ if n < 0 {
+ n = -n
+ if n < 0 {
+ // This can occur if -n overflows. -(-1 << 63) would become
+ // -1 << 63, which is still negative.
+ return nil, false
+ }
+ }
+ if n > 1e6 {
+ return nil, false // avoid excessively large exponents
+ }
+ pow5 := z.b.abs.expNN(natFive, nat(nil).setWord(Word(n)), nil, false) // use underlying array of z.b.abs
+ if exp5 > 0 {
+ z.a.abs = z.a.abs.mul(z.a.abs, pow5)
+ z.b.abs = z.b.abs.setWord(1)
+ } else {
+ z.b.abs = pow5
+ }
+ } else {
+ z.b.abs = z.b.abs.setWord(1)
+ }
+
+ // apply exp2 contributions
+ if exp2 < -1e7 || exp2 > 1e7 {
+ return nil, false // avoid excessively large exponents
+ }
+ if exp2 > 0 {
+ z.a.abs = z.a.abs.shl(z.a.abs, uint(exp2))
+ } else if exp2 < 0 {
+ z.b.abs = z.b.abs.shl(z.b.abs, uint(-exp2))
+ }
+
+ z.a.neg = neg && len(z.a.abs) > 0 // 0 has no sign
+
+ return z.norm(), true
+}
+
+// scanExponent scans the longest possible prefix of r representing a base 10
+// (“e”, “E”) or a base 2 (“p”, “P”) exponent, if any. It returns the
+// exponent, the exponent base (10 or 2), or a read or syntax error, if any.
+//
+// If sepOk is set, an underscore character “_” may appear between successive
+// exponent digits; such underscores do not change the value of the exponent.
+// Incorrect placement of underscores is reported as an error if there are no
+// other errors. If sepOk is not set, underscores are not recognized and thus
+// terminate scanning like any other character that is not a valid digit.
+//
+// exponent = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
+// sign = "+" | "-" .
+// digits = digit { [ '_' ] digit } .
+// digit = "0" ... "9" .
+//
+// A base 2 exponent is only permitted if base2ok is set.
+func scanExponent(r io.ByteScanner, base2ok, sepOk bool) (exp int64, base int, err error) {
+ // one char look-ahead
+ ch, err := r.ReadByte()
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ }
+ return 0, 10, err
+ }
+
+ // exponent char
+ switch ch {
+ case 'e', 'E':
+ base = 10
+ case 'p', 'P':
+ if base2ok {
+ base = 2
+ break // ok
+ }
+ fallthrough // binary exponent not permitted
+ default:
+ r.UnreadByte() // ch does not belong to exponent anymore
+ return 0, 10, nil
+ }
+
+ // sign
+ var digits []byte
+ ch, err = r.ReadByte()
+ if err == nil && (ch == '+' || ch == '-') {
+ if ch == '-' {
+ digits = append(digits, '-')
+ }
+ ch, err = r.ReadByte()
+ }
+
+ // prev encodes the previously seen char: it is one
+ // of '_', '0' (a digit), or '.' (anything else). A
+ // valid separator '_' may only occur after a digit.
+ prev := '.'
+ invalSep := false
+
+ // exponent value
+ hasDigits := false
+ for err == nil {
+ if '0' <= ch && ch <= '9' {
+ digits = append(digits, ch)
+ prev = '0'
+ hasDigits = true
+ } else if ch == '_' && sepOk {
+ if prev != '0' {
+ invalSep = true
+ }
+ prev = '_'
+ } else {
+ r.UnreadByte() // ch does not belong to number anymore
+ break
+ }
+ ch, err = r.ReadByte()
+ }
+
+ if err == io.EOF {
+ err = nil
+ }
+ if err == nil && !hasDigits {
+ err = errNoDigits
+ }
+ if err == nil {
+ exp, err = strconv.ParseInt(string(digits), 10, 64)
+ }
+ // other errors take precedence over invalid separators
+ if err == nil && (invalSep || prev == '_') {
+ err = errInvalSep
+ }
+
+ return
+}
+
+// String returns a string representation of x in the form "a/b" (even if b == 1).
+func (x *Rat) String() string {
+ return string(x.marshal())
+}
+
+// marshal implements String returning a slice of bytes
+func (x *Rat) marshal() []byte {
+ var buf []byte
+ buf = x.a.Append(buf, 10)
+ buf = append(buf, '/')
+ if len(x.b.abs) != 0 {
+ buf = x.b.Append(buf, 10)
+ } else {
+ buf = append(buf, '1')
+ }
+ return buf
+}
+
+// RatString returns a string representation of x in the form "a/b" if b != 1,
+// and in the form "a" if b == 1.
+func (x *Rat) RatString() string {
+ if x.IsInt() {
+ return x.a.String()
+ }
+ return x.String()
+}
+
+// FloatString returns a string representation of x in decimal form with prec
+// digits of precision after the radix point. The last digit is rounded to
+// nearest, with halves rounded away from zero.
+func (x *Rat) FloatString(prec int) string {
+ var buf []byte
+
+ if x.IsInt() {
+ buf = x.a.Append(buf, 10)
+ if prec > 0 {
+ buf = append(buf, '.')
+ for i := prec; i > 0; i-- {
+ buf = append(buf, '0')
+ }
+ }
+ return string(buf)
+ }
+ // x.b.abs != 0
+
+ q, r := nat(nil).div(nat(nil), x.a.abs, x.b.abs)
+
+ p := natOne
+ if prec > 0 {
+ p = nat(nil).expNN(natTen, nat(nil).setUint64(uint64(prec)), nil, false)
+ }
+
+ r = r.mul(r, p)
+ r, r2 := r.div(nat(nil), r, x.b.abs)
+
+ // see if we need to round up
+ r2 = r2.add(r2, r2)
+ if x.b.abs.cmp(r2) <= 0 {
+ r = r.add(r, natOne)
+ if r.cmp(p) >= 0 {
+ q = nat(nil).add(q, natOne)
+ r = nat(nil).sub(r, p)
+ }
+ }
+
+ if x.a.neg {
+ buf = append(buf, '-')
+ }
+ buf = append(buf, q.utoa(10)...) // itoa ignores sign if q == 0
+
+ if prec > 0 {
+ buf = append(buf, '.')
+ rs := r.utoa(10)
+ for i := prec - len(rs); i > 0; i-- {
+ buf = append(buf, '0')
+ }
+ buf = append(buf, rs...)
+ }
+
+ return string(buf)
+}
+
+// Note: FloatPrec (below) is in this file rather than rat.go because
+// its results are relevant for decimal representation/printing.
+
+// FloatPrec returns the number n of non-repeating digits immediately
+// following the decimal point of the decimal representation of x.
+// The boolean result indicates whether a decimal representation of x
+// with that many fractional digits is exact or rounded.
+//
+// Examples:
+//
+// x n exact decimal representation n fractional digits
+// 0 0 true 0
+// 1 0 true 1
+// 1/2 1 true 0.5
+// 1/3 0 false 0 (0.333... rounded)
+// 1/4 2 true 0.25
+// 1/6 1 false 0.2 (0.166... rounded)
+func (x *Rat) FloatPrec() (n int, exact bool) {
+ // Determine q and largest p2, p5 such that d = q·2^p2·5^p5.
+ // The results n, exact are:
+ //
+ // n = max(p2, p5)
+ // exact = q == 1
+ //
+ // For details see:
+ // https://en.wikipedia.org/wiki/Repeating_decimal#Reciprocals_of_integers_not_coprime_to_10
+ d := x.Denom().abs // d >= 1
+
+ // Determine p2 by counting factors of 2.
+ // p2 corresponds to the trailing zero bits in d.
+ // Do this first to reduce q as much as possible.
+ var q nat
+ p2 := d.trailingZeroBits()
+ q = q.shr(d, p2)
+
+ // Determine p5 by counting factors of 5.
+ // Build a table starting with an initial power of 5,
+ // and use repeated squaring until the factor doesn't
+ // divide q anymore. Then use the table to determine
+ // the power of 5 in q.
+ const fp = 13 // f == 5^fp
+ var tab []nat // tab[i] == (5^fp)^(2^i) == 5^(fp·2^i)
+ f := nat{1220703125} // == 5^fp (must fit into a uint32 Word)
+ var t, r nat // temporaries
+ for {
+ if _, r = t.div(r, q, f); len(r) != 0 {
+ break // f doesn't divide q evenly
+ }
+ tab = append(tab, f)
+ f = nat(nil).sqr(f) // nat(nil) to ensure a new f for each table entry
+ }
+
+ // Factor q using the table entries, if any.
+ // We start with the largest factor f = tab[len(tab)-1]
+ // that evenly divides q. It does so at most once because
+ // otherwise f·f would also divide q. That can't be true
+ // because f·f is the next higher table entry, contradicting
+ // how f was chosen in the first place.
+ // The same reasoning applies to the subsequent factors.
+ var p5 uint
+ for i := len(tab) - 1; i >= 0; i-- {
+ if t, r = t.div(r, q, tab[i]); len(r) == 0 {
+ p5 += fp * (1 << i) // tab[i] == 5^(fp·2^i)
+ q = q.set(t)
+ }
+ }
+
+ // If fp != 1, we may still have multiples of 5 left.
+ for {
+ if t, r = t.div(r, q, natFive); len(r) != 0 {
+ break
+ }
+ p5++
+ q = q.set(t)
+ }
+
+ return int(max(p2, p5)), q.cmp(natOne) == 0
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/ratconv_test.go b/platform/dbops/binaries/go/go/src/math/big/ratconv_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..93e89ad1c8ebc01cf04472a675f1f70124e6297f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/ratconv_test.go
@@ -0,0 +1,765 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+var exponentTests = []struct {
+ s string // string to be scanned
+ base2ok bool // true if 'p'/'P' exponents are accepted
+ sepOk bool // true if '_' separators are accepted
+ x int64 // expected exponent
+ b int // expected exponent base
+ err error // expected error
+ next rune // next character (or 0, if at EOF)
+}{
+ // valid, without separators
+ {"", false, false, 0, 10, nil, 0},
+ {"1", false, false, 0, 10, nil, '1'},
+ {"e0", false, false, 0, 10, nil, 0},
+ {"E1", false, false, 1, 10, nil, 0},
+ {"e+10", false, false, 10, 10, nil, 0},
+ {"e-10", false, false, -10, 10, nil, 0},
+ {"e123456789a", false, false, 123456789, 10, nil, 'a'},
+ {"p", false, false, 0, 10, nil, 'p'},
+ {"P+100", false, false, 0, 10, nil, 'P'},
+ {"p0", true, false, 0, 2, nil, 0},
+ {"P-123", true, false, -123, 2, nil, 0},
+ {"p+0a", true, false, 0, 2, nil, 'a'},
+ {"p+123__", true, false, 123, 2, nil, '_'}, // '_' is not part of the number anymore
+
+ // valid, with separators
+ {"e+1_0", false, true, 10, 10, nil, 0},
+ {"e-1_0", false, true, -10, 10, nil, 0},
+ {"e123_456_789a", false, true, 123456789, 10, nil, 'a'},
+ {"P+1_00", false, true, 0, 10, nil, 'P'},
+ {"p-1_2_3", true, true, -123, 2, nil, 0},
+
+ // invalid: no digits
+ {"e", false, false, 0, 10, errNoDigits, 0},
+ {"ef", false, false, 0, 10, errNoDigits, 'f'},
+ {"e+", false, false, 0, 10, errNoDigits, 0},
+ {"E-x", false, false, 0, 10, errNoDigits, 'x'},
+ {"p", true, false, 0, 2, errNoDigits, 0},
+ {"P-", true, false, 0, 2, errNoDigits, 0},
+ {"p+e", true, false, 0, 2, errNoDigits, 'e'},
+ {"e+_x", false, true, 0, 10, errNoDigits, 'x'},
+
+ // invalid: incorrect use of separator
+ {"e0_", false, true, 0, 10, errInvalSep, 0},
+ {"e_0", false, true, 0, 10, errInvalSep, 0},
+ {"e-1_2__3", false, true, -123, 10, errInvalSep, 0},
+}
+
+func TestScanExponent(t *testing.T) {
+ for _, a := range exponentTests {
+ r := strings.NewReader(a.s)
+ x, b, err := scanExponent(r, a.base2ok, a.sepOk)
+ if err != a.err {
+ t.Errorf("scanExponent%+v\n\tgot error = %v; want %v", a, err, a.err)
+ }
+ if x != a.x {
+ t.Errorf("scanExponent%+v\n\tgot z = %v; want %v", a, x, a.x)
+ }
+ if b != a.b {
+ t.Errorf("scanExponent%+v\n\tgot b = %d; want %d", a, b, a.b)
+ }
+ next, _, err := r.ReadRune()
+ if err == io.EOF {
+ next = 0
+ err = nil
+ }
+ if err == nil && next != a.next {
+ t.Errorf("scanExponent%+v\n\tgot next = %q; want %q", a, next, a.next)
+ }
+ }
+}
+
+type StringTest struct {
+ in, out string
+ ok bool
+}
+
+var setStringTests = []StringTest{
+ // invalid
+ {in: "1e"},
+ {in: "1.e"},
+ {in: "1e+14e-5"},
+ {in: "1e4.5"},
+ {in: "r"},
+ {in: "a/b"},
+ {in: "a.b"},
+ {in: "1/0"},
+ {in: "4/3/2"}, // issue 17001
+ {in: "4/3/"},
+ {in: "4/3."},
+ {in: "4/"},
+ {in: "13e-9223372036854775808"}, // CVE-2022-23772
+
+ // valid
+ {"0", "0", true},
+ {"-0", "0", true},
+ {"1", "1", true},
+ {"-1", "-1", true},
+ {"1.", "1", true},
+ {"1e0", "1", true},
+ {"1.e1", "10", true},
+ {"-0.1", "-1/10", true},
+ {"-.1", "-1/10", true},
+ {"2/4", "1/2", true},
+ {".25", "1/4", true},
+ {"-1/5", "-1/5", true},
+ {"8129567.7690E14", "812956776900000000000", true},
+ {"78189e+4", "781890000", true},
+ {"553019.8935e+8", "55301989350000", true},
+ {"98765432109876543210987654321e-10", "98765432109876543210987654321/10000000000", true},
+ {"9877861857500000E-7", "3951144743/4", true},
+ {"2169378.417e-3", "2169378417/1000000", true},
+ {"884243222337379604041632732738665534", "884243222337379604041632732738665534", true},
+ {"53/70893980658822810696", "53/70893980658822810696", true},
+ {"106/141787961317645621392", "53/70893980658822810696", true},
+ {"204211327800791583.81095", "4084226556015831676219/20000", true},
+ {"0e9999999999", "0", true}, // issue #16176
+}
+
+// These are not supported by fmt.Fscanf.
+var setStringTests2 = []StringTest{
+ // invalid
+ {in: "4/3x"},
+ {in: "0/-1"},
+ {in: "-1/-1"},
+
+ // invalid with separators
+ // (smoke tests only - a comprehensive set of tests is in natconv_test.go)
+ {in: "10_/1"},
+ {in: "_10/1"},
+ {in: "1/1__0"},
+
+ // valid
+ {"0b1000/3", "8/3", true},
+ {"0B1000/0x8", "1", true},
+ {"-010/1", "-8", true}, // 0-prefix indicates octal in this case
+ {"-010.0", "-10", true},
+ {"-0o10/1", "-8", true},
+ {"0x10/1", "16", true},
+ {"0x10/0x20", "1/2", true},
+
+ {"0010", "10", true}, // 0-prefix is ignored in this case (not a fraction)
+ {"0x10.0", "16", true},
+ {"0x1.8", "3/2", true},
+ {"0X1.8p4", "24", true},
+ {"0x1.1E2", "2289/2048", true}, // E is part of hex mantissa, not exponent
+ {"0b1.1E2", "150", true},
+ {"0B1.1P3", "12", true},
+ {"0o10e-2", "2/25", true},
+ {"0O10p-3", "1", true},
+
+ // valid with separators
+ // (smoke tests only - a comprehensive set of tests is in natconv_test.go)
+ {"0b_1000/3", "8/3", true},
+ {"0B_10_00/0x8", "1", true},
+ {"0xdead/0B1101_1110_1010_1101", "1", true},
+ {"0B1101_1110_1010_1101/0XD_E_A_D", "1", true},
+ {"1_000.0", "1000", true},
+
+ {"0x_10.0", "16", true},
+ {"0x1_0.0", "16", true},
+ {"0x1.8_0", "3/2", true},
+ {"0X1.8p0_4", "24", true},
+ {"0b1.1_0E2", "150", true},
+ {"0o1_0e-2", "2/25", true},
+ {"0O_10p-3", "1", true},
+}
+
+func TestRatSetString(t *testing.T) {
+ var tests []StringTest
+ tests = append(tests, setStringTests...)
+ tests = append(tests, setStringTests2...)
+
+ for i, test := range tests {
+ x, ok := new(Rat).SetString(test.in)
+
+ if ok {
+ if !test.ok {
+ t.Errorf("#%d SetString(%q) expected failure", i, test.in)
+ } else if x.RatString() != test.out {
+ t.Errorf("#%d SetString(%q) got %s want %s", i, test.in, x.RatString(), test.out)
+ }
+ } else {
+ if test.ok {
+ t.Errorf("#%d SetString(%q) expected success", i, test.in)
+ } else if x != nil {
+ t.Errorf("#%d SetString(%q) got %p want nil", i, test.in, x)
+ }
+ }
+ }
+}
+
+func TestRatSetStringZero(t *testing.T) {
+ got, _ := new(Rat).SetString("0")
+ want := new(Rat).SetInt64(0)
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("got %#+v, want %#+v", got, want)
+ }
+}
+
+func TestRatScan(t *testing.T) {
+ var buf bytes.Buffer
+ for i, test := range setStringTests {
+ x := new(Rat)
+ buf.Reset()
+ buf.WriteString(test.in)
+
+ _, err := fmt.Fscanf(&buf, "%v", x)
+ if err == nil != test.ok {
+ if test.ok {
+ t.Errorf("#%d (%s) error: %s", i, test.in, err)
+ } else {
+ t.Errorf("#%d (%s) expected error", i, test.in)
+ }
+ continue
+ }
+ if err == nil && x.RatString() != test.out {
+ t.Errorf("#%d got %s want %s", i, x.RatString(), test.out)
+ }
+ }
+}
+
+var floatStringTests = []struct {
+ in string
+ prec int
+ out string
+}{
+ {"0", 0, "0"},
+ {"0", 4, "0.0000"},
+ {"1", 0, "1"},
+ {"1", 2, "1.00"},
+ {"-1", 0, "-1"},
+ {"0.05", 1, "0.1"},
+ {"-0.05", 1, "-0.1"},
+ {".25", 2, "0.25"},
+ {".25", 1, "0.3"},
+ {".25", 3, "0.250"},
+ {"-1/3", 3, "-0.333"},
+ {"-2/3", 4, "-0.6667"},
+ {"0.96", 1, "1.0"},
+ {"0.999", 2, "1.00"},
+ {"0.9", 0, "1"},
+ {".25", -1, "0"},
+ {".55", -1, "1"},
+}
+
+func TestFloatString(t *testing.T) {
+ for i, test := range floatStringTests {
+ x, _ := new(Rat).SetString(test.in)
+
+ if x.FloatString(test.prec) != test.out {
+ t.Errorf("#%d got %s want %s", i, x.FloatString(test.prec), test.out)
+ }
+ }
+}
+
+// Test inputs to Rat.SetString. The prefix "long:" causes the test
+// to be skipped except in -long mode. (The threshold is about 500us.)
+var float64inputs = []string{
+ // Constants plundered from strconv/testfp.txt.
+
+ // Table 1: Stress Inputs for Conversion to 53-bit Binary, < 1/2 ULP
+ "5e+125",
+ "69e+267",
+ "999e-026",
+ "7861e-034",
+ "75569e-254",
+ "928609e-261",
+ "9210917e+080",
+ "84863171e+114",
+ "653777767e+273",
+ "5232604057e-298",
+ "27235667517e-109",
+ "653532977297e-123",
+ "3142213164987e-294",
+ "46202199371337e-072",
+ "231010996856685e-073",
+ "9324754620109615e+212",
+ "78459735791271921e+049",
+ "272104041512242479e+200",
+ "6802601037806061975e+198",
+ "20505426358836677347e-221",
+ "836168422905420598437e-234",
+ "4891559871276714924261e+222",
+
+ // Table 2: Stress Inputs for Conversion to 53-bit Binary, > 1/2 ULP
+ "9e-265",
+ "85e-037",
+ "623e+100",
+ "3571e+263",
+ "81661e+153",
+ "920657e-023",
+ "4603285e-024",
+ "87575437e-309",
+ "245540327e+122",
+ "6138508175e+120",
+ "83356057653e+193",
+ "619534293513e+124",
+ "2335141086879e+218",
+ "36167929443327e-159",
+ "609610927149051e-255",
+ "3743626360493413e-165",
+ "94080055902682397e-242",
+ "899810892172646163e+283",
+ "7120190517612959703e+120",
+ "25188282901709339043e-252",
+ "308984926168550152811e-052",
+ "6372891218502368041059e+064",
+
+ // Table 14: Stress Inputs for Conversion to 24-bit Binary, <1/2 ULP
+ "5e-20",
+ "67e+14",
+ "985e+15",
+ "7693e-42",
+ "55895e-16",
+ "996622e-44",
+ "7038531e-32",
+ "60419369e-46",
+ "702990899e-20",
+ "6930161142e-48",
+ "25933168707e+13",
+ "596428896559e+20",
+
+ // Table 15: Stress Inputs for Conversion to 24-bit Binary, >1/2 ULP
+ "3e-23",
+ "57e+18",
+ "789e-35",
+ "2539e-18",
+ "76173e+28",
+ "887745e-11",
+ "5382571e-37",
+ "82381273e-35",
+ "750486563e-38",
+ "3752432815e-39",
+ "75224575729e-45",
+ "459926601011e+15",
+
+ // Constants plundered from strconv/atof_test.go.
+
+ "0",
+ "1",
+ "+1",
+ "1e23",
+ "1E23",
+ "100000000000000000000000",
+ "1e-100",
+ "123456700",
+ "99999999999999974834176",
+ "100000000000000000000001",
+ "100000000000000008388608",
+ "100000000000000016777215",
+ "100000000000000016777216",
+ "-1",
+ "-0.1",
+ "-0", // NB: exception made for this input
+ "1e-20",
+ "625e-3",
+
+ // largest float64
+ "1.7976931348623157e308",
+ "-1.7976931348623157e308",
+ // next float64 - too large
+ "1.7976931348623159e308",
+ "-1.7976931348623159e308",
+ // the border is ...158079
+ // borderline - okay
+ "1.7976931348623158e308",
+ "-1.7976931348623158e308",
+ // borderline - too large
+ "1.797693134862315808e308",
+ "-1.797693134862315808e308",
+
+ // a little too large
+ "1e308",
+ "2e308",
+ "1e309",
+
+ // way too large
+ "1e310",
+ "-1e310",
+ "1e400",
+ "-1e400",
+ "long:1e400000",
+ "long:-1e400000",
+
+ // denormalized
+ "1e-305",
+ "1e-306",
+ "1e-307",
+ "1e-308",
+ "1e-309",
+ "1e-310",
+ "1e-322",
+ // smallest denormal
+ "5e-324",
+ "4e-324",
+ "3e-324",
+ // too small
+ "2e-324",
+ // way too small
+ "1e-350",
+ "long:1e-400000",
+ // way too small, negative
+ "-1e-350",
+ "long:-1e-400000",
+
+ // try to overflow exponent
+ // [Disabled: too slow and memory-hungry with rationals.]
+ // "1e-4294967296",
+ // "1e+4294967296",
+ // "1e-18446744073709551616",
+ // "1e+18446744073709551616",
+
+ // https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
+ "2.2250738585072012e-308",
+ // https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/
+ "2.2250738585072011e-308",
+
+ // A very large number (initially wrongly parsed by the fast algorithm).
+ "4.630813248087435e+307",
+
+ // A different kind of very large number.
+ "22.222222222222222",
+ "long:2." + strings.Repeat("2", 4000) + "e+1",
+
+ // Exactly halfway between 1 and math.Nextafter(1, 2).
+ // Round to even (down).
+ "1.00000000000000011102230246251565404236316680908203125",
+ // Slightly lower; still round down.
+ "1.00000000000000011102230246251565404236316680908203124",
+ // Slightly higher; round up.
+ "1.00000000000000011102230246251565404236316680908203126",
+ // Slightly higher, but you have to read all the way to the end.
+ "long:1.00000000000000011102230246251565404236316680908203125" + strings.Repeat("0", 10000) + "1",
+
+ // Smallest denormal, 2^(-1022-52)
+ "4.940656458412465441765687928682213723651e-324",
+ // Half of smallest denormal, 2^(-1022-53)
+ "2.470328229206232720882843964341106861825e-324",
+ // A little more than the exact half of smallest denormal
+ // 2^-1075 + 2^-1100. (Rounds to 1p-1074.)
+ "2.470328302827751011111470718709768633275e-324",
+ // The exact halfway between smallest normal and largest denormal:
+ // 2^-1022 - 2^-1075. (Rounds to 2^-1022.)
+ "2.225073858507201136057409796709131975935e-308",
+
+ "1152921504606846975", // 1<<60 - 1
+ "-1152921504606846975", // -(1<<60 - 1)
+ "1152921504606846977", // 1<<60 + 1
+ "-1152921504606846977", // -(1<<60 + 1)
+
+ "1/3",
+}
+
+// isFinite reports whether f represents a finite rational value.
+// It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
+func isFinite(f float64) bool {
+ return math.Abs(f) <= math.MaxFloat64
+}
+
+func TestFloat32SpecialCases(t *testing.T) {
+ for _, input := range float64inputs {
+ if strings.HasPrefix(input, "long:") {
+ if !*long {
+ continue
+ }
+ input = input[len("long:"):]
+ }
+
+ r, ok := new(Rat).SetString(input)
+ if !ok {
+ t.Errorf("Rat.SetString(%q) failed", input)
+ continue
+ }
+ f, exact := r.Float32()
+
+ // 1. Check string -> Rat -> float32 conversions are
+ // consistent with strconv.ParseFloat.
+ // Skip this check if the input uses "a/b" rational syntax.
+ if !strings.Contains(input, "/") {
+ e64, _ := strconv.ParseFloat(input, 32)
+ e := float32(e64)
+
+ // Careful: negative Rats too small for
+ // float64 become -0, but Rat obviously cannot
+ // preserve the sign from SetString("-0").
+ switch {
+ case math.Float32bits(e) == math.Float32bits(f):
+ // Ok: bitwise equal.
+ case f == 0 && r.Num().BitLen() == 0:
+ // Ok: Rat(0) is equivalent to both +/- float64(0).
+ default:
+ t.Errorf("strconv.ParseFloat(%q) = %g (%b), want %g (%b); delta = %g", input, e, e, f, f, f-e)
+ }
+ }
+
+ if !isFinite(float64(f)) {
+ continue
+ }
+
+ // 2. Check f is best approximation to r.
+ if !checkIsBestApprox32(t, f, r) {
+ // Append context information.
+ t.Errorf("(input was %q)", input)
+ }
+
+ // 3. Check f->R->f roundtrip is non-lossy.
+ checkNonLossyRoundtrip32(t, f)
+
+ // 4. Check exactness using slow algorithm.
+ if wasExact := new(Rat).SetFloat64(float64(f)).Cmp(r) == 0; wasExact != exact {
+ t.Errorf("Rat.SetString(%q).Float32().exact = %t, want %t", input, exact, wasExact)
+ }
+ }
+}
+
+func TestFloat64SpecialCases(t *testing.T) {
+ for _, input := range float64inputs {
+ if strings.HasPrefix(input, "long:") {
+ if !*long {
+ continue
+ }
+ input = input[len("long:"):]
+ }
+
+ r, ok := new(Rat).SetString(input)
+ if !ok {
+ t.Errorf("Rat.SetString(%q) failed", input)
+ continue
+ }
+ f, exact := r.Float64()
+
+ // 1. Check string -> Rat -> float64 conversions are
+ // consistent with strconv.ParseFloat.
+ // Skip this check if the input uses "a/b" rational syntax.
+ if !strings.Contains(input, "/") {
+ e, _ := strconv.ParseFloat(input, 64)
+
+ // Careful: negative Rats too small for
+ // float64 become -0, but Rat obviously cannot
+ // preserve the sign from SetString("-0").
+ switch {
+ case math.Float64bits(e) == math.Float64bits(f):
+ // Ok: bitwise equal.
+ case f == 0 && r.Num().BitLen() == 0:
+ // Ok: Rat(0) is equivalent to both +/- float64(0).
+ default:
+ t.Errorf("strconv.ParseFloat(%q) = %g (%b), want %g (%b); delta = %g", input, e, e, f, f, f-e)
+ }
+ }
+
+ if !isFinite(f) {
+ continue
+ }
+
+ // 2. Check f is best approximation to r.
+ if !checkIsBestApprox64(t, f, r) {
+ // Append context information.
+ t.Errorf("(input was %q)", input)
+ }
+
+ // 3. Check f->R->f roundtrip is non-lossy.
+ checkNonLossyRoundtrip64(t, f)
+
+ // 4. Check exactness using slow algorithm.
+ if wasExact := new(Rat).SetFloat64(f).Cmp(r) == 0; wasExact != exact {
+ t.Errorf("Rat.SetString(%q).Float64().exact = %t, want %t", input, exact, wasExact)
+ }
+ }
+}
+
+func TestIssue31184(t *testing.T) {
+ var x Rat
+ for _, want := range []string{
+ "-213.090",
+ "8.192",
+ "16.000",
+ } {
+ x.SetString(want)
+ got := x.FloatString(3)
+ if got != want {
+ t.Errorf("got %s, want %s", got, want)
+ }
+ }
+}
+
+func TestIssue45910(t *testing.T) {
+ var x Rat
+ for _, test := range []struct {
+ input string
+ want bool
+ }{
+ {"1e-1000001", false},
+ {"1e-1000000", true},
+ {"1e+1000000", true},
+ {"1e+1000001", false},
+
+ {"0p1000000000000", true},
+ {"1p-10000001", false},
+ {"1p-10000000", true},
+ {"1p+10000000", true},
+ {"1p+10000001", false},
+ {"1.770p02041010010011001001", false}, // test case from issue
+ } {
+ _, got := x.SetString(test.input)
+ if got != test.want {
+ t.Errorf("SetString(%s) got ok = %v; want %v", test.input, got, test.want)
+ }
+ }
+}
+func TestFloatPrec(t *testing.T) {
+ var tests = []struct {
+ f string
+ prec int
+ ok bool
+ fdec string
+ }{
+ // examples from the issue #50489
+ {"10/100", 1, true, "0.1"},
+ {"3/100", 2, true, "0.03"},
+ {"10", 0, true, "10"},
+
+ // more examples
+ {"zero", 0, true, "0"}, // test uninitialized zero value for Rat
+ {"0", 0, true, "0"}, // 0
+ {"1", 0, true, "1"}, // 1
+ {"1/2", 1, true, "0.5"}, // 0.5
+ {"1/3", 0, false, "0"}, // 0.(3)
+ {"1/4", 2, true, "0.25"}, // 0.25
+ {"1/5", 1, true, "0.2"}, // 0.2
+ {"1/6", 1, false, "0.2"}, // 0.1(6)
+ {"1/7", 0, false, "0"}, // 0.(142857)
+ {"1/8", 3, true, "0.125"}, // 0.125
+ {"1/9", 0, false, "0"}, // 0.(1)
+ {"1/10", 1, true, "0.1"}, // 0.1
+ {"1/11", 0, false, "0"}, // 0.(09)
+ {"1/12", 2, false, "0.08"}, // 0.08(3)
+ {"1/13", 0, false, "0"}, // 0.(076923)
+ {"1/14", 1, false, "0.1"}, // 0.0(714285)
+ {"1/15", 1, false, "0.1"}, // 0.0(6)
+ {"1/16", 4, true, "0.0625"}, // 0.0625
+
+ {"10/2", 0, true, "5"}, // 5
+ {"10/3", 0, false, "3"}, // 3.(3)
+ {"10/6", 0, false, "2"}, // 1.(6)
+ {"1/10000000", 7, true, "0.0000001"}, // 0.0000001
+ {"1/3125", 5, true, "0.00032"}, // "0.00032"
+ {"1/1024", 10, true, "0.0009765625"}, // 0.0009765625
+ {"1/304000", 7, false, "0.0000033"}, // 0.0000032(894736842105263157)
+ {"1/48828125", 11, true, "0.00000002048"}, // 0.00000002048
+ }
+
+ for _, test := range tests {
+ var f Rat
+
+ // check uninitialized zero value
+ if test.f != "zero" {
+ _, ok := f.SetString(test.f)
+ if !ok {
+ t.Fatalf("invalid test case: f = %s", test.f)
+ }
+ }
+
+ // results for f and -f must be the same
+ fdec := test.fdec
+ for i := 0; i < 2; i++ {
+ prec, ok := f.FloatPrec()
+ if prec != test.prec || ok != test.ok {
+ t.Errorf("%s: FloatPrec(%s): got prec, ok = %d, %v; want %d, %v", test.f, &f, prec, ok, test.prec, test.ok)
+ }
+ s := f.FloatString(test.prec)
+ if s != fdec {
+ t.Errorf("%s: FloatString(%s, %d): got %s; want %s", test.f, &f, prec, s, fdec)
+ }
+ // proceed with -f but don't add a "-" before a "0"
+ if f.Sign() > 0 {
+ f.Neg(&f)
+ fdec = "-" + fdec
+ }
+ }
+ }
+}
+
+func BenchmarkFloatPrecExact(b *testing.B) {
+ for _, n := range []int{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
+ // d := 5^n
+ d := NewInt(5)
+ p := NewInt(int64(n))
+ d.Exp(d, p, nil)
+
+ // r := 1/d
+ var r Rat
+ r.SetFrac(NewInt(1), d)
+
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ prec, ok := r.FloatPrec()
+ if prec != n || !ok {
+ b.Fatalf("got exact, ok = %d, %v; want %d, %v", prec, ok, uint64(n), true)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkFloatPrecMixed(b *testing.B) {
+ for _, n := range []int{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
+ // d := (3·5·7·11)^n
+ d := NewInt(3 * 5 * 7 * 11)
+ p := NewInt(int64(n))
+ d.Exp(d, p, nil)
+
+ // r := 1/d
+ var r Rat
+ r.SetFrac(NewInt(1), d)
+
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ prec, ok := r.FloatPrec()
+ if prec != n || ok {
+ b.Fatalf("got exact, ok = %d, %v; want %d, %v", prec, ok, uint64(n), false)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkFloatPrecInexact(b *testing.B) {
+ for _, n := range []int{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
+ // d := 5^n + 1
+ d := NewInt(5)
+ p := NewInt(int64(n))
+ d.Exp(d, p, nil)
+ d.Add(d, NewInt(1))
+
+ // r := 1/d
+ var r Rat
+ r.SetFrac(NewInt(1), d)
+
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, ok := r.FloatPrec()
+ if ok {
+ b.Fatalf("got unexpected ok")
+ }
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/ratmarsh.go b/platform/dbops/binaries/go/go/src/math/big/ratmarsh.go
new file mode 100644
index 0000000000000000000000000000000000000000..033fb4459df8a74bcd93fbaa3ed7d586444973ad
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/ratmarsh.go
@@ -0,0 +1,86 @@
+// 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 encoding/decoding of Rats.
+
+package big
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "math"
+)
+
+// Gob codec version. Permits backward-compatible changes to the encoding.
+const ratGobVersion byte = 1
+
+// GobEncode implements the [encoding/gob.GobEncoder] interface.
+func (x *Rat) GobEncode() ([]byte, error) {
+ if x == nil {
+ return nil, nil
+ }
+ buf := make([]byte, 1+4+(len(x.a.abs)+len(x.b.abs))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
+ i := x.b.abs.bytes(buf)
+ j := x.a.abs.bytes(buf[:i])
+ n := i - j
+ if int(uint32(n)) != n {
+ // this should never happen
+ return nil, errors.New("Rat.GobEncode: numerator too large")
+ }
+ binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
+ j -= 1 + 4
+ b := ratGobVersion << 1 // make space for sign bit
+ if x.a.neg {
+ b |= 1
+ }
+ buf[j] = b
+ return buf[j:], nil
+}
+
+// GobDecode implements the [encoding/gob.GobDecoder] interface.
+func (z *Rat) GobDecode(buf []byte) error {
+ if len(buf) == 0 {
+ // Other side sent a nil or default value.
+ *z = Rat{}
+ return nil
+ }
+ if len(buf) < 5 {
+ return errors.New("Rat.GobDecode: buffer too small")
+ }
+ b := buf[0]
+ if b>>1 != ratGobVersion {
+ return fmt.Errorf("Rat.GobDecode: encoding version %d not supported", b>>1)
+ }
+ const j = 1 + 4
+ ln := binary.BigEndian.Uint32(buf[j-4 : j])
+ if uint64(ln) > math.MaxInt-j {
+ return errors.New("Rat.GobDecode: invalid length")
+ }
+ i := j + int(ln)
+ if len(buf) < i {
+ return errors.New("Rat.GobDecode: buffer too small")
+ }
+ z.a.neg = b&1 != 0
+ z.a.abs = z.a.abs.setBytes(buf[j:i])
+ z.b.abs = z.b.abs.setBytes(buf[i:])
+ return nil
+}
+
+// MarshalText implements the [encoding.TextMarshaler] interface.
+func (x *Rat) MarshalText() (text []byte, err error) {
+ if x.IsInt() {
+ return x.a.MarshalText()
+ }
+ return x.marshal(), nil
+}
+
+// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
+func (z *Rat) UnmarshalText(text []byte) error {
+ // TODO(gri): get rid of the []byte/string conversion
+ if _, ok := z.SetString(string(text)); !ok {
+ return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", text)
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/ratmarsh_test.go b/platform/dbops/binaries/go/go/src/math/big/ratmarsh_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..15c933efa6d43bb14926abf82dfb83285b042601
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/ratmarsh_test.go
@@ -0,0 +1,138 @@
+// 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.
+
+package big
+
+import (
+ "bytes"
+ "encoding/gob"
+ "encoding/json"
+ "encoding/xml"
+ "testing"
+)
+
+func TestRatGobEncoding(t *testing.T) {
+ var medium bytes.Buffer
+ enc := gob.NewEncoder(&medium)
+ dec := gob.NewDecoder(&medium)
+ for _, test := range encodingTests {
+ medium.Reset() // empty buffer for each test case (in case of failures)
+ var tx Rat
+ tx.SetString(test + ".14159265")
+ if err := enc.Encode(&tx); err != nil {
+ t.Errorf("encoding of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Rat
+ if err := dec.Decode(&rx); err != nil {
+ t.Errorf("decoding of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("transmission of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+}
+
+// Sending a nil Rat pointer (inside a slice) on a round trip through gob should yield a zero.
+// TODO: top-level nils.
+func TestGobEncodingNilRatInSlice(t *testing.T) {
+ buf := new(bytes.Buffer)
+ enc := gob.NewEncoder(buf)
+ dec := gob.NewDecoder(buf)
+
+ var in = make([]*Rat, 1)
+ err := enc.Encode(&in)
+ if err != nil {
+ t.Errorf("gob encode failed: %q", err)
+ }
+ var out []*Rat
+ err = dec.Decode(&out)
+ if err != nil {
+ t.Fatalf("gob decode failed: %q", err)
+ }
+ if len(out) != 1 {
+ t.Fatalf("wrong len; want 1 got %d", len(out))
+ }
+ var zero Rat
+ if out[0].Cmp(&zero) != 0 {
+ t.Fatalf("transmission of (*Int)(nil) failed: got %s want 0", out)
+ }
+}
+
+var ratNums = []string{
+ "-141592653589793238462643383279502884197169399375105820974944592307816406286",
+ "-1415926535897932384626433832795028841971",
+ "-141592653589793",
+ "-1",
+ "0",
+ "1",
+ "141592653589793",
+ "1415926535897932384626433832795028841971",
+ "141592653589793238462643383279502884197169399375105820974944592307816406286",
+}
+
+var ratDenoms = []string{
+ "1",
+ "718281828459045",
+ "7182818284590452353602874713526624977572",
+ "718281828459045235360287471352662497757247093699959574966967627724076630353",
+}
+
+func TestRatJSONEncoding(t *testing.T) {
+ for _, num := range ratNums {
+ for _, denom := range ratDenoms {
+ var tx Rat
+ tx.SetString(num + "/" + denom)
+ b, err := json.Marshal(&tx)
+ if err != nil {
+ t.Errorf("marshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Rat
+ if err := json.Unmarshal(b, &rx); err != nil {
+ t.Errorf("unmarshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("JSON encoding of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+ }
+}
+
+func TestRatXMLEncoding(t *testing.T) {
+ for _, num := range ratNums {
+ for _, denom := range ratDenoms {
+ var tx Rat
+ tx.SetString(num + "/" + denom)
+ b, err := xml.Marshal(&tx)
+ if err != nil {
+ t.Errorf("marshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ var rx Rat
+ if err := xml.Unmarshal(b, &rx); err != nil {
+ t.Errorf("unmarshaling of %s failed: %s", &tx, err)
+ continue
+ }
+ if rx.Cmp(&tx) != 0 {
+ t.Errorf("XML encoding of %s failed: got %s want %s", &tx, &rx, &tx)
+ }
+ }
+ }
+}
+
+func TestRatGobDecodeShortBuffer(t *testing.T) {
+ for _, tc := range [][]byte{
+ []byte{0x2},
+ []byte{0x2, 0x0, 0x0, 0x0, 0xff},
+ []byte{0x2, 0xff, 0xff, 0xff, 0xff},
+ } {
+ err := NewRat(1, 2).GobDecode(tc)
+ if err == nil {
+ t.Error("expected GobDecode to return error for malformed input")
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/roundingmode_string.go b/platform/dbops/binaries/go/go/src/math/big/roundingmode_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..e2f13a63b7b535b6b27ac5acd096f5552a4a6cba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/roundingmode_string.go
@@ -0,0 +1,28 @@
+// Code generated by "stringer -type=RoundingMode"; DO NOT EDIT.
+
+package big
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[ToNearestEven-0]
+ _ = x[ToNearestAway-1]
+ _ = x[ToZero-2]
+ _ = x[AwayFromZero-3]
+ _ = x[ToNegativeInf-4]
+ _ = x[ToPositiveInf-5]
+}
+
+const _RoundingMode_name = "ToNearestEvenToNearestAwayToZeroAwayFromZeroToNegativeInfToPositiveInf"
+
+var _RoundingMode_index = [...]uint8{0, 13, 26, 32, 44, 57, 70}
+
+func (i RoundingMode) String() string {
+ if i >= RoundingMode(len(_RoundingMode_index)-1) {
+ return "RoundingMode(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _RoundingMode_name[_RoundingMode_index[i]:_RoundingMode_index[i+1]]
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/sqrt.go b/platform/dbops/binaries/go/go/src/math/big/sqrt.go
new file mode 100644
index 0000000000000000000000000000000000000000..b4b03743f4da71310bbaef1bcc16877183cec401
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/sqrt.go
@@ -0,0 +1,130 @@
+// 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 big
+
+import (
+ "math"
+ "sync"
+)
+
+var threeOnce struct {
+ sync.Once
+ v *Float
+}
+
+func three() *Float {
+ threeOnce.Do(func() {
+ threeOnce.v = NewFloat(3.0)
+ })
+ return threeOnce.v
+}
+
+// Sqrt sets z to the rounded square root of x, and returns it.
+//
+// If z's precision is 0, it is changed to x's precision before the
+// operation. Rounding is performed according to z's precision and
+// rounding mode, but z's accuracy is not computed. Specifically, the
+// result of z.Acc() is undefined.
+//
+// The function panics if z < 0. The value of z is undefined in that
+// case.
+func (z *Float) Sqrt(x *Float) *Float {
+ if debugFloat {
+ x.validate()
+ }
+
+ if z.prec == 0 {
+ z.prec = x.prec
+ }
+
+ if x.Sign() == -1 {
+ // following IEEE754-2008 (section 7.2)
+ panic(ErrNaN{"square root of negative operand"})
+ }
+
+ // handle ±0 and +∞
+ if x.form != finite {
+ z.acc = Exact
+ z.form = x.form
+ z.neg = x.neg // IEEE754-2008 requires √±0 = ±0
+ return z
+ }
+
+ // MantExp sets the argument's precision to the receiver's, and
+ // when z.prec > x.prec this will lower z.prec. Restore it after
+ // the MantExp call.
+ prec := z.prec
+ b := x.MantExp(z)
+ z.prec = prec
+
+ // Compute √(z·2**b) as
+ // √( z)·2**(½b) if b is even
+ // √(2z)·2**(⌊½b⌋) if b > 0 is odd
+ // √(½z)·2**(⌈½b⌉) if b < 0 is odd
+ switch b % 2 {
+ case 0:
+ // nothing to do
+ case 1:
+ z.exp++
+ case -1:
+ z.exp--
+ }
+ // 0.25 <= z < 2.0
+
+ // Solving 1/x² - z = 0 avoids Quo calls and is faster, especially
+ // for high precisions.
+ z.sqrtInverse(z)
+
+ // re-attach halved exponent
+ return z.SetMantExp(z, b/2)
+}
+
+// Compute √x (to z.prec precision) by solving
+//
+// 1/t² - x = 0
+//
+// for t (using Newton's method), and then inverting.
+func (z *Float) sqrtInverse(x *Float) {
+ // let
+ // f(t) = 1/t² - x
+ // then
+ // g(t) = f(t)/f'(t) = -½t(1 - xt²)
+ // and the next guess is given by
+ // t2 = t - g(t) = ½t(3 - xt²)
+ u := newFloat(z.prec)
+ v := newFloat(z.prec)
+ three := three()
+ ng := func(t *Float) *Float {
+ u.prec = t.prec
+ v.prec = t.prec
+ u.Mul(t, t) // u = t²
+ u.Mul(x, u) // = xt²
+ v.Sub(three, u) // v = 3 - xt²
+ u.Mul(t, v) // u = t(3 - xt²)
+ u.exp-- // = ½t(3 - xt²)
+ return t.Set(u)
+ }
+
+ xf, _ := x.Float64()
+ sqi := newFloat(z.prec)
+ sqi.SetFloat64(1 / math.Sqrt(xf))
+ for prec := z.prec + 32; sqi.prec < prec; {
+ sqi.prec *= 2
+ sqi = ng(sqi)
+ }
+ // sqi = 1/√x
+
+ // x/√x = √x
+ z.Mul(x, sqi)
+}
+
+// newFloat returns a new *Float with space for twice the given
+// precision.
+func newFloat(prec2 uint32) *Float {
+ z := new(Float)
+ // nat.make ensures the slice length is > 0
+ z.mant = z.mant.make(int(prec2/_W) * 2)
+ return z
+}
diff --git a/platform/dbops/binaries/go/go/src/math/big/sqrt_test.go b/platform/dbops/binaries/go/go/src/math/big/sqrt_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d314711d74c4cb3cc4cd17382162ae649afacb33
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/big/sqrt_test.go
@@ -0,0 +1,126 @@
+// 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 big
+
+import (
+ "fmt"
+ "math"
+ "math/rand"
+ "testing"
+)
+
+// TestFloatSqrt64 tests that Float.Sqrt of numbers with 53bit mantissa
+// behaves like float math.Sqrt.
+func TestFloatSqrt64(t *testing.T) {
+ for i := 0; i < 1e5; i++ {
+ if i == 1e2 && testing.Short() {
+ break
+ }
+ r := rand.Float64()
+
+ got := new(Float).SetPrec(53)
+ got.Sqrt(NewFloat(r))
+ want := NewFloat(math.Sqrt(r))
+ if got.Cmp(want) != 0 {
+ t.Fatalf("Sqrt(%g) =\n got %g;\nwant %g", r, got, want)
+ }
+ }
+}
+
+func TestFloatSqrt(t *testing.T) {
+ for _, test := range []struct {
+ x string
+ want string
+ }{
+ // Test values were generated on Wolfram Alpha using query
+ // 'sqrt(N) to 350 digits'
+ // 350 decimal digits give up to 1000 binary digits.
+ {"0.03125", "0.17677669529663688110021109052621225982120898442211850914708496724884155980776337985629844179095519659187673077886403712811560450698134215158051518713749197892665283324093819909447499381264409775757143376369499645074628431682460775184106467733011114982619404115381053858929018135497032545349940642599871090667456829147610370507757690729404938184321879"},
+ {"0.125", "0.35355339059327376220042218105242451964241796884423701829416993449768311961552675971259688358191039318375346155772807425623120901396268430316103037427498395785330566648187639818894998762528819551514286752738999290149256863364921550368212935466022229965238808230762107717858036270994065090699881285199742181334913658295220741015515381458809876368643757"},
+ {"0.5", "0.70710678118654752440084436210484903928483593768847403658833986899536623923105351942519376716382078636750692311545614851246241802792536860632206074854996791570661133296375279637789997525057639103028573505477998580298513726729843100736425870932044459930477616461524215435716072541988130181399762570399484362669827316590441482031030762917619752737287514"},
+ {"2.0", "1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457503"},
+ {"3.0", "1.7320508075688772935274463415058723669428052538103806280558069794519330169088000370811461867572485756756261414154067030299699450949989524788116555120943736485280932319023055820679748201010846749232650153123432669033228866506722546689218379712270471316603678615880190499865373798593894676503475065760507566183481296061009476021871903250831458295239598"},
+ {"4.0", "2.0"},
+
+ {"1p512", "1p256"},
+ {"4p1024", "2p512"},
+ {"9p2048", "3p1024"},
+
+ {"1p-1024", "1p-512"},
+ {"4p-2048", "2p-1024"},
+ {"9p-4096", "3p-2048"},
+ } {
+ for _, prec := range []uint{24, 53, 64, 65, 100, 128, 129, 200, 256, 400, 600, 800, 1000} {
+ x := new(Float).SetPrec(prec)
+ x.Parse(test.x, 10)
+
+ got := new(Float).SetPrec(prec).Sqrt(x)
+ want := new(Float).SetPrec(prec)
+ want.Parse(test.want, 10)
+ if got.Cmp(want) != 0 {
+ t.Errorf("prec = %d, Sqrt(%v) =\ngot %g;\nwant %g",
+ prec, test.x, got, want)
+ }
+
+ // Square test.
+ // If got holds the square root of x to precision p, then
+ // got = √x + k
+ // for some k such that |k| < 2**(-p). Thus,
+ // got² = (√x + k)² = x + 2k√n + k²
+ // and the error must satisfy
+ // err = |got² - x| ≈ | 2k√n | < 2**(-p+1)*√n
+ // Ignoring the k² term for simplicity.
+
+ // err = |got² - x|
+ // (but do intermediate steps with 32 guard digits to
+ // avoid introducing spurious rounding-related errors)
+ sq := new(Float).SetPrec(prec+32).Mul(got, got)
+ diff := new(Float).Sub(sq, x)
+ err := diff.Abs(diff).SetPrec(prec)
+
+ // maxErr = 2**(-p+1)*√x
+ one := new(Float).SetPrec(prec).SetInt64(1)
+ maxErr := new(Float).Mul(new(Float).SetMantExp(one, -int(prec)+1), got)
+
+ if err.Cmp(maxErr) >= 0 {
+ t.Errorf("prec = %d, Sqrt(%v) =\ngot err %g;\nwant maxErr %g",
+ prec, test.x, err, maxErr)
+ }
+ }
+ }
+}
+
+func TestFloatSqrtSpecial(t *testing.T) {
+ for _, test := range []struct {
+ x *Float
+ want *Float
+ }{
+ {NewFloat(+0), NewFloat(+0)},
+ {NewFloat(-0), NewFloat(-0)},
+ {NewFloat(math.Inf(+1)), NewFloat(math.Inf(+1))},
+ } {
+ got := new(Float).Sqrt(test.x)
+ if got.neg != test.want.neg || got.form != test.want.form {
+ t.Errorf("Sqrt(%v) = %v (neg: %v); want %v (neg: %v)",
+ test.x, got, got.neg, test.want, test.want.neg)
+ }
+ }
+
+}
+
+// Benchmarks
+
+func BenchmarkFloatSqrt(b *testing.B) {
+ for _, prec := range []uint{64, 128, 256, 1e3, 1e4, 1e5, 1e6} {
+ x := NewFloat(2)
+ z := new(Float).SetPrec(prec)
+ b.Run(fmt.Sprintf("%v", prec), func(b *testing.B) {
+ b.ReportAllocs()
+ for n := 0; n < b.N; n++ {
+ z.Sqrt(x)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/bits.go b/platform/dbops/binaries/go/go/src/math/bits/bits.go
new file mode 100644
index 0000000000000000000000000000000000000000..235d63e85bc53d3e14c46d6c07f8fa647c35aadd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/bits.go
@@ -0,0 +1,599 @@
+// 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:generate go run make_tables.go
+
+// Package bits implements bit counting and manipulation
+// functions for the predeclared unsigned integer types.
+//
+// Functions in this package may be implemented directly by
+// the compiler, for better performance. For those functions
+// the code in this package will not be used. Which
+// functions are implemented by the compiler depends on the
+// architecture and the Go release.
+package bits
+
+const uintSize = 32 << (^uint(0) >> 63) // 32 or 64
+
+// UintSize is the size of a uint in bits.
+const UintSize = uintSize
+
+// --- LeadingZeros ---
+
+// LeadingZeros returns the number of leading zero bits in x; the result is [UintSize] for x == 0.
+func LeadingZeros(x uint) int { return UintSize - Len(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) }
+
+// LeadingZeros16 returns the number of leading zero bits in x; the result is 16 for x == 0.
+func LeadingZeros16(x uint16) int { return 16 - Len16(x) }
+
+// LeadingZeros32 returns the number of leading zero bits in x; the result is 32 for x == 0.
+func LeadingZeros32(x uint32) int { return 32 - Len32(x) }
+
+// 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) }
+
+// --- TrailingZeros ---
+
+// See http://supertech.csail.mit.edu/papers/debruijn.pdf
+const deBruijn32 = 0x077CB531
+
+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 deBruijn64 = 0x03f79d71b4ca8b09
+
+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,
+}
+
+// TrailingZeros returns the number of trailing zero bits in x; the result is [UintSize] for x == 0.
+func TrailingZeros(x uint) int {
+ if UintSize == 32 {
+ return TrailingZeros32(uint32(x))
+ }
+ return TrailingZeros64(uint64(x))
+}
+
+// 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])
+}
+
+// TrailingZeros16 returns the number of trailing zero bits in x; the result is 16 for x == 0.
+func TrailingZeros16(x uint16) int {
+ if x == 0 {
+ return 16
+ }
+ // see comment in TrailingZeros64
+ return int(deBruijn32tab[uint32(x&-x)*deBruijn32>>(32-5)])
+}
+
+// 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)])
+}
+
+// --- OnesCount ---
+
+const m0 = 0x5555555555555555 // 01010101 ...
+const m1 = 0x3333333333333333 // 00110011 ...
+const m2 = 0x0f0f0f0f0f0f0f0f // 00001111 ...
+const m3 = 0x00ff00ff00ff00ff // etc.
+const m4 = 0x0000ffff0000ffff
+
+// OnesCount returns the number of one bits ("population count") in x.
+func OnesCount(x uint) int {
+ if UintSize == 32 {
+ return OnesCount32(uint32(x))
+ }
+ return OnesCount64(uint64(x))
+}
+
+// OnesCount8 returns the number of one bits ("population count") in x.
+func OnesCount8(x uint8) int {
+ return int(pop8tab[x])
+}
+
+// OnesCount16 returns the number of one bits ("population count") in x.
+func OnesCount16(x uint16) int {
+ return int(pop8tab[x>>8] + pop8tab[x&0xff])
+}
+
+// OnesCount32 returns the number of one bits ("population count") in x.
+func OnesCount32(x uint32) int {
+ return int(pop8tab[x>>24] + pop8tab[x>>16&0xff] + pop8tab[x>>8&0xff] + pop8tab[x&0xff])
+}
+
+// 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)
+}
+
+// --- RotateLeft ---
+
+// RotateLeft returns the value of x rotated left by (k mod [UintSize]) bits.
+// To rotate x right by k bits, call RotateLeft(x, -k).
+//
+// This function's execution time does not depend on the inputs.
+func RotateLeft(x uint, k int) uint {
+ if UintSize == 32 {
+ return uint(RotateLeft32(uint32(x), k))
+ }
+ return uint(RotateLeft64(uint64(x), k))
+}
+
+// RotateLeft8 returns the value of x rotated left by (k mod 8) bits.
+// To rotate x right by k bits, call RotateLeft8(x, -k).
+//
+// This function's execution time does not depend on the inputs.
+func RotateLeft8(x uint8, k int) uint8 {
+ const n = 8
+ s := uint(k) & (n - 1)
+ return x<>(n-s)
+}
+
+// RotateLeft16 returns the value of x rotated left by (k mod 16) bits.
+// To rotate x right by k bits, call RotateLeft16(x, -k).
+//
+// This function's execution time does not depend on the inputs.
+func RotateLeft16(x uint16, k int) uint16 {
+ const n = 16
+ s := uint(k) & (n - 1)
+ return x<>(n-s)
+}
+
+// RotateLeft32 returns the value of x rotated left by (k mod 32) bits.
+// To rotate x right by k bits, call RotateLeft32(x, -k).
+//
+// This function's execution time does not depend on the inputs.
+func RotateLeft32(x uint32, k int) uint32 {
+ const n = 32
+ s := uint(k) & (n - 1)
+ return x<>(n-s)
+}
+
+// RotateLeft64 returns the value of x rotated left by (k mod 64) bits.
+// To rotate x right by k bits, call RotateLeft64(x, -k).
+//
+// This function's execution time does not depend on the inputs.
+func RotateLeft64(x uint64, k int) uint64 {
+ const n = 64
+ s := uint(k) & (n - 1)
+ return x<>(n-s)
+}
+
+// --- Reverse ---
+
+// Reverse returns the value of x with its bits in reversed order.
+func Reverse(x uint) uint {
+ if UintSize == 32 {
+ return uint(Reverse32(uint32(x)))
+ }
+ return uint(Reverse64(uint64(x)))
+}
+
+// Reverse8 returns the value of x with its bits in reversed order.
+func Reverse8(x uint8) uint8 {
+ return rev8tab[x]
+}
+
+// Reverse16 returns the value of x with its bits in reversed order.
+func Reverse16(x uint16) uint16 {
+ return uint16(rev8tab[x>>8]) | uint16(rev8tab[x&0xff])<<8
+}
+
+// Reverse32 returns the value of x with its bits in reversed order.
+func Reverse32(x uint32) uint32 {
+ const m = 1<<32 - 1
+ x = x>>1&(m0&m) | x&(m0&m)<<1
+ x = x>>2&(m1&m) | x&(m1&m)<<2
+ x = x>>4&(m2&m) | x&(m2&m)<<4
+ return ReverseBytes32(x)
+}
+
+// Reverse64 returns the value of x with its bits in reversed order.
+func Reverse64(x uint64) uint64 {
+ const m = 1<<64 - 1
+ x = x>>1&(m0&m) | x&(m0&m)<<1
+ x = x>>2&(m1&m) | x&(m1&m)<<2
+ x = x>>4&(m2&m) | x&(m2&m)<<4
+ return ReverseBytes64(x)
+}
+
+// --- ReverseBytes ---
+
+// ReverseBytes returns the value of x with its bytes in reversed order.
+//
+// This function's execution time does not depend on the inputs.
+func ReverseBytes(x uint) uint {
+ if UintSize == 32 {
+ return uint(ReverseBytes32(uint32(x)))
+ }
+ return uint(ReverseBytes64(uint64(x)))
+}
+
+// ReverseBytes16 returns the value of x with its bytes in reversed order.
+//
+// This function's execution time does not depend on the inputs.
+func ReverseBytes16(x uint16) uint16 {
+ return x>>8 | x<<8
+}
+
+// ReverseBytes32 returns the value of x with its bytes in reversed order.
+//
+// This function's execution time does not depend on the inputs.
+func ReverseBytes32(x uint32) uint32 {
+ const m = 1<<32 - 1
+ x = x>>8&(m3&m) | x&(m3&m)<<8
+ return x>>16 | x<<16
+}
+
+// ReverseBytes64 returns the value of x with its bytes in reversed order.
+//
+// This function's execution time does not depend on the inputs.
+func ReverseBytes64(x uint64) uint64 {
+ const m = 1<<64 - 1
+ x = x>>8&(m3&m) | x&(m3&m)<<8
+ x = x>>16&(m4&m) | x&(m4&m)<<16
+ return x>>32 | x<<32
+}
+
+// --- Len ---
+
+// Len returns the minimum number of bits required to represent x; the result is 0 for x == 0.
+func Len(x uint) int {
+ if UintSize == 32 {
+ return Len32(uint32(x))
+ }
+ return Len64(uint64(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])
+}
+
+// Len16 returns the minimum number of bits required to represent x; the result is 0 for x == 0.
+func Len16(x uint16) (n int) {
+ if x >= 1<<8 {
+ x >>= 8
+ n = 8
+ }
+ return n + int(len8tab[x])
+}
+
+// Len32 returns the minimum number of bits required to represent x; the result is 0 for x == 0.
+func Len32(x uint32) (n int) {
+ if x >= 1<<16 {
+ x >>= 16
+ n = 16
+ }
+ if x >= 1<<8 {
+ x >>= 8
+ n += 8
+ }
+ return n + int(len8tab[x])
+}
+
+// Len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0.
+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])
+}
+
+// --- Add with carry ---
+
+// Add returns the sum with carry of x, y and carry: sum = x + y + carry.
+// The carry input must be 0 or 1; otherwise the behavior is undefined.
+// The carryOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Add(x, y, carry uint) (sum, carryOut uint) {
+ if UintSize == 32 {
+ s32, c32 := Add32(uint32(x), uint32(y), uint32(carry))
+ return uint(s32), uint(c32)
+ }
+ s64, c64 := Add64(uint64(x), uint64(y), uint64(carry))
+ return uint(s64), uint(c64)
+}
+
+// Add32 returns the sum with carry of x, y and carry: sum = x + y + carry.
+// The carry input must be 0 or 1; otherwise the behavior is undefined.
+// The carryOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Add32(x, y, carry uint32) (sum, carryOut uint32) {
+ sum64 := uint64(x) + uint64(y) + uint64(carry)
+ sum = uint32(sum64)
+ carryOut = uint32(sum64 >> 32)
+ return
+}
+
+// Add64 returns the sum with carry of x, y and carry: sum = x + y + carry.
+// The carry input must be 0 or 1; otherwise the behavior is undefined.
+// The carryOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Add64(x, y, carry uint64) (sum, carryOut uint64) {
+ sum = x + y + carry
+ // The sum will overflow if both top bits are set (x & y) or if one of them
+ // is (x | y), and a carry from the lower place happened. If such a carry
+ // happens, the top bit will be 1 + 0 + 1 = 0 (&^ sum).
+ carryOut = ((x & y) | ((x | y) &^ sum)) >> 63
+ return
+}
+
+// --- Subtract with borrow ---
+
+// Sub returns the difference of x, y and borrow: diff = x - y - borrow.
+// The borrow input must be 0 or 1; otherwise the behavior is undefined.
+// The borrowOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Sub(x, y, borrow uint) (diff, borrowOut uint) {
+ if UintSize == 32 {
+ d32, b32 := Sub32(uint32(x), uint32(y), uint32(borrow))
+ return uint(d32), uint(b32)
+ }
+ d64, b64 := Sub64(uint64(x), uint64(y), uint64(borrow))
+ return uint(d64), uint(b64)
+}
+
+// Sub32 returns the difference of x, y and borrow, diff = x - y - borrow.
+// The borrow input must be 0 or 1; otherwise the behavior is undefined.
+// The borrowOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Sub32(x, y, borrow uint32) (diff, borrowOut uint32) {
+ diff = x - y - borrow
+ // The difference will underflow if the top bit of x is not set and the top
+ // bit of y is set (^x & y) or if they are the same (^(x ^ y)) and a borrow
+ // from the lower place happens. If that borrow happens, the result will be
+ // 1 - 1 - 1 = 0 - 0 - 1 = 1 (& diff).
+ borrowOut = ((^x & y) | (^(x ^ y) & diff)) >> 31
+ return
+}
+
+// Sub64 returns the difference of x, y and borrow: diff = x - y - borrow.
+// The borrow input must be 0 or 1; otherwise the behavior is undefined.
+// The borrowOut output is guaranteed to be 0 or 1.
+//
+// This function's execution time does not depend on the inputs.
+func Sub64(x, y, borrow uint64) (diff, borrowOut uint64) {
+ diff = x - y - borrow
+ // See Sub32 for the bit logic.
+ borrowOut = ((^x & y) | (^(x ^ y) & diff)) >> 63
+ return
+}
+
+// --- Full-width multiply ---
+
+// Mul returns the full-width product of x and y: (hi, lo) = x * y
+// with the product bits' upper half returned in hi and the lower
+// half returned in lo.
+//
+// This function's execution time does not depend on the inputs.
+func Mul(x, y uint) (hi, lo uint) {
+ if UintSize == 32 {
+ h, l := Mul32(uint32(x), uint32(y))
+ return uint(h), uint(l)
+ }
+ h, l := Mul64(uint64(x), uint64(y))
+ return uint(h), uint(l)
+}
+
+// Mul32 returns the 64-bit product of x and y: (hi, lo) = x * y
+// with the product bits' upper half returned in hi and the lower
+// half returned in lo.
+//
+// This function's execution time does not depend on the inputs.
+func Mul32(x, y uint32) (hi, lo uint32) {
+ tmp := uint64(x) * uint64(y)
+ hi, lo = uint32(tmp>>32), uint32(tmp)
+ return
+}
+
+// Mul64 returns the 128-bit product of x and y: (hi, lo) = x * y
+// with the product bits' upper half returned in hi and the lower
+// half returned in lo.
+//
+// This function's execution time does not depend on the inputs.
+func Mul64(x, y uint64) (hi, lo uint64) {
+ const mask32 = 1<<32 - 1
+ x0 := x & mask32
+ x1 := x >> 32
+ y0 := y & mask32
+ y1 := y >> 32
+ w0 := x0 * y0
+ t := x1*y0 + w0>>32
+ w1 := t & mask32
+ w2 := t >> 32
+ w1 += x0 * y1
+ hi = x1*y1 + w2 + w1>>32
+ lo = x * y
+ return
+}
+
+// --- Full-width divide ---
+
+// Div returns the quotient and remainder of (hi, lo) divided by y:
+// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper
+// half in parameter hi and the lower half in parameter lo.
+// Div panics for y == 0 (division by zero) or y <= hi (quotient overflow).
+func Div(hi, lo, y uint) (quo, rem uint) {
+ if UintSize == 32 {
+ q, r := Div32(uint32(hi), uint32(lo), uint32(y))
+ return uint(q), uint(r)
+ }
+ q, r := Div64(uint64(hi), uint64(lo), uint64(y))
+ return uint(q), uint(r)
+}
+
+// Div32 returns the quotient and remainder of (hi, lo) divided by y:
+// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper
+// half in parameter hi and the lower half in parameter lo.
+// Div32 panics for y == 0 (division by zero) or y <= hi (quotient overflow).
+func Div32(hi, lo, y uint32) (quo, rem uint32) {
+ if y != 0 && y <= hi {
+ panic(overflowError)
+ }
+ z := uint64(hi)<<32 | uint64(lo)
+ quo, rem = uint32(z/uint64(y)), uint32(z%uint64(y))
+ return
+}
+
+// Div64 returns the quotient and remainder of (hi, lo) divided by y:
+// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper
+// half in parameter hi and the lower half in parameter lo.
+// Div64 panics for y == 0 (division by zero) or y <= hi (quotient overflow).
+func Div64(hi, lo, y uint64) (quo, rem uint64) {
+ if y == 0 {
+ panic(divideError)
+ }
+ if y <= hi {
+ panic(overflowError)
+ }
+
+ // If high part is zero, we can directly return the results.
+ if hi == 0 {
+ return lo / y, lo % y
+ }
+
+ s := uint(LeadingZeros64(y))
+ y <<= s
+
+ const (
+ two32 = 1 << 32
+ mask32 = two32 - 1
+ )
+ yn1 := y >> 32
+ yn0 := y & mask32
+ un32 := hi<>(64-s)
+ un10 := lo << s
+ un1 := un10 >> 32
+ un0 := un10 & mask32
+ q1 := un32 / yn1
+ rhat := un32 - q1*yn1
+
+ for q1 >= two32 || q1*yn0 > two32*rhat+un1 {
+ q1--
+ rhat += yn1
+ if rhat >= two32 {
+ break
+ }
+ }
+
+ un21 := un32*two32 + un1 - q1*y
+ q0 := un21 / yn1
+ rhat = un21 - q0*yn1
+
+ for q0 >= two32 || q0*yn0 > two32*rhat+un0 {
+ q0--
+ rhat += yn1
+ if rhat >= two32 {
+ break
+ }
+ }
+
+ return q1*two32 + q0, (un21*two32 + un0 - q0*y) >> s
+}
+
+// Rem returns the remainder of (hi, lo) divided by y. Rem panics for
+// y == 0 (division by zero) but, unlike Div, it doesn't panic on a
+// quotient overflow.
+func Rem(hi, lo, y uint) uint {
+ if UintSize == 32 {
+ return uint(Rem32(uint32(hi), uint32(lo), uint32(y)))
+ }
+ return uint(Rem64(uint64(hi), uint64(lo), uint64(y)))
+}
+
+// Rem32 returns the remainder of (hi, lo) divided by y. Rem32 panics
+// for y == 0 (division by zero) but, unlike [Div32], it doesn't panic
+// on a quotient overflow.
+func Rem32(hi, lo, y uint32) uint32 {
+ return uint32((uint64(hi)<<32 | uint64(lo)) % uint64(y))
+}
+
+// Rem64 returns the remainder of (hi, lo) divided by y. Rem64 panics
+// for y == 0 (division by zero) but, unlike [Div64], it doesn't panic
+// on a quotient overflow.
+func Rem64(hi, lo, y uint64) uint64 {
+ // We scale down hi so that hi < y, then use Div64 to compute the
+ // rem with the guarantee that it won't panic on quotient overflow.
+ // Given that
+ // hi ≡ hi%y (mod y)
+ // we have
+ // hi<<64 + lo ≡ (hi%y)<<64 + lo (mod y)
+ _, rem := Div64(hi%y, lo, y)
+ return rem
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/bits_errors.go b/platform/dbops/binaries/go/go/src/math/bits/bits_errors.go
new file mode 100644
index 0000000000000000000000000000000000000000..353d2f6ad3a27d6610993506e42389e9ea2e79de
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/bits_errors.go
@@ -0,0 +1,15 @@
+// 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 !compiler_bootstrap
+
+package bits
+
+import _ "unsafe"
+
+//go:linkname overflowError runtime.overflowError
+var overflowError error
+
+//go:linkname divideError runtime.divideError
+var divideError error
diff --git a/platform/dbops/binaries/go/go/src/math/bits/bits_errors_bootstrap.go b/platform/dbops/binaries/go/go/src/math/bits/bits_errors_bootstrap.go
new file mode 100644
index 0000000000000000000000000000000000000000..6b14e41f83c4d86010812e171f540867d684437d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/bits_errors_bootstrap.go
@@ -0,0 +1,22 @@
+// 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 compiler_bootstrap
+
+// This version used only for bootstrap (on this path we want
+// to avoid use of go:linkname as applied to variables).
+
+package bits
+
+type errorString string
+
+func (e errorString) RuntimeError() {}
+
+func (e errorString) Error() string {
+ return "runtime error: " + string(e)
+}
+
+var overflowError = error(errorString("integer overflow"))
+
+var divideError = error(errorString("integer divide by zero"))
diff --git a/platform/dbops/binaries/go/go/src/math/bits/bits_tables.go b/platform/dbops/binaries/go/go/src/math/bits/bits_tables.go
new file mode 100644
index 0000000000000000000000000000000000000000..f869b8d5c377d5540ec2208ba9321cf48bbcf316
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/bits_tables.go
@@ -0,0 +1,79 @@
+// 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.
+
+// Code generated by go run make_tables.go. DO NOT EDIT.
+
+package bits
+
+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"
+
+const pop8tab = "" +
+ "\x00\x01\x01\x02\x01\x02\x02\x03\x01\x02\x02\x03\x02\x03\x03\x04" +
+ "\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
+ "\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
+ "\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
+ "\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
+ "\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
+ "\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
+ "\x04\x05\x05\x06\x05\x06\x06\x07\x05\x06\x06\x07\x06\x07\x07\x08"
+
+const rev8tab = "" +
+ "\x00\x80\x40\xc0\x20\xa0\x60\xe0\x10\x90\x50\xd0\x30\xb0\x70\xf0" +
+ "\x08\x88\x48\xc8\x28\xa8\x68\xe8\x18\x98\x58\xd8\x38\xb8\x78\xf8" +
+ "\x04\x84\x44\xc4\x24\xa4\x64\xe4\x14\x94\x54\xd4\x34\xb4\x74\xf4" +
+ "\x0c\x8c\x4c\xcc\x2c\xac\x6c\xec\x1c\x9c\x5c\xdc\x3c\xbc\x7c\xfc" +
+ "\x02\x82\x42\xc2\x22\xa2\x62\xe2\x12\x92\x52\xd2\x32\xb2\x72\xf2" +
+ "\x0a\x8a\x4a\xca\x2a\xaa\x6a\xea\x1a\x9a\x5a\xda\x3a\xba\x7a\xfa" +
+ "\x06\x86\x46\xc6\x26\xa6\x66\xe6\x16\x96\x56\xd6\x36\xb6\x76\xf6" +
+ "\x0e\x8e\x4e\xce\x2e\xae\x6e\xee\x1e\x9e\x5e\xde\x3e\xbe\x7e\xfe" +
+ "\x01\x81\x41\xc1\x21\xa1\x61\xe1\x11\x91\x51\xd1\x31\xb1\x71\xf1" +
+ "\x09\x89\x49\xc9\x29\xa9\x69\xe9\x19\x99\x59\xd9\x39\xb9\x79\xf9" +
+ "\x05\x85\x45\xc5\x25\xa5\x65\xe5\x15\x95\x55\xd5\x35\xb5\x75\xf5" +
+ "\x0d\x8d\x4d\xcd\x2d\xad\x6d\xed\x1d\x9d\x5d\xdd\x3d\xbd\x7d\xfd" +
+ "\x03\x83\x43\xc3\x23\xa3\x63\xe3\x13\x93\x53\xd3\x33\xb3\x73\xf3" +
+ "\x0b\x8b\x4b\xcb\x2b\xab\x6b\xeb\x1b\x9b\x5b\xdb\x3b\xbb\x7b\xfb" +
+ "\x07\x87\x47\xc7\x27\xa7\x67\xe7\x17\x97\x57\xd7\x37\xb7\x77\xf7" +
+ "\x0f\x8f\x4f\xcf\x2f\xaf\x6f\xef\x1f\x9f\x5f\xdf\x3f\xbf\x7f\xff"
+
+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"
diff --git a/platform/dbops/binaries/go/go/src/math/bits/bits_test.go b/platform/dbops/binaries/go/go/src/math/bits/bits_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..23b4539fcd6ca4d374b96f4d372b777cb09e8219
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/bits_test.go
@@ -0,0 +1,1347 @@
+// 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 bits_test
+
+import (
+ . "math/bits"
+ "runtime"
+ "testing"
+ "unsafe"
+)
+
+func TestUintSize(t *testing.T) {
+ var x uint
+ if want := unsafe.Sizeof(x) * 8; UintSize != want {
+ t.Fatalf("UintSize = %d; want %d", UintSize, want)
+ }
+}
+
+func TestLeadingZeros(t *testing.T) {
+ for i := 0; i < 256; i++ {
+ nlz := tab[i].nlz
+ for k := 0; k < 64-8; k++ {
+ x := uint64(i) << uint(k)
+ if x <= 1<<8-1 {
+ got := LeadingZeros8(uint8(x))
+ want := nlz - k + (8 - 8)
+ if x == 0 {
+ want = 8
+ }
+ if got != want {
+ t.Fatalf("LeadingZeros8(%#02x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<16-1 {
+ got := LeadingZeros16(uint16(x))
+ want := nlz - k + (16 - 8)
+ if x == 0 {
+ want = 16
+ }
+ if got != want {
+ t.Fatalf("LeadingZeros16(%#04x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<32-1 {
+ got := LeadingZeros32(uint32(x))
+ want := nlz - k + (32 - 8)
+ if x == 0 {
+ want = 32
+ }
+ if got != want {
+ t.Fatalf("LeadingZeros32(%#08x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 32 {
+ got = LeadingZeros(uint(x))
+ if got != want {
+ t.Fatalf("LeadingZeros(%#08x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+
+ if x <= 1<<64-1 {
+ got := LeadingZeros64(uint64(x))
+ want := nlz - k + (64 - 8)
+ if x == 0 {
+ want = 64
+ }
+ if got != want {
+ t.Fatalf("LeadingZeros64(%#016x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 64 {
+ got = LeadingZeros(uint(x))
+ if got != want {
+ t.Fatalf("LeadingZeros(%#016x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+ }
+ }
+}
+
+// Exported (global) variable serving as input for some
+// of the benchmarks to ensure side-effect free calls
+// are not optimized away.
+var Input uint64 = DeBruijn64
+
+// Exported (global) variable to store function results
+// during benchmarking to ensure side-effect free calls
+// are not optimized away.
+var Output int
+
+func BenchmarkLeadingZeros(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += LeadingZeros(uint(Input) >> (uint(i) % UintSize))
+ }
+ Output = s
+}
+
+func BenchmarkLeadingZeros8(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += LeadingZeros8(uint8(Input) >> (uint(i) % 8))
+ }
+ Output = s
+}
+
+func BenchmarkLeadingZeros16(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += LeadingZeros16(uint16(Input) >> (uint(i) % 16))
+ }
+ Output = s
+}
+
+func BenchmarkLeadingZeros32(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += LeadingZeros32(uint32(Input) >> (uint(i) % 32))
+ }
+ Output = s
+}
+
+func BenchmarkLeadingZeros64(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += LeadingZeros64(uint64(Input) >> (uint(i) % 64))
+ }
+ Output = s
+}
+
+func TestTrailingZeros(t *testing.T) {
+ for i := 0; i < 256; i++ {
+ ntz := tab[i].ntz
+ for k := 0; k < 64-8; k++ {
+ x := uint64(i) << uint(k)
+ want := ntz + k
+ if x <= 1<<8-1 {
+ got := TrailingZeros8(uint8(x))
+ if x == 0 {
+ want = 8
+ }
+ if got != want {
+ t.Fatalf("TrailingZeros8(%#02x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<16-1 {
+ got := TrailingZeros16(uint16(x))
+ if x == 0 {
+ want = 16
+ }
+ if got != want {
+ t.Fatalf("TrailingZeros16(%#04x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<32-1 {
+ got := TrailingZeros32(uint32(x))
+ if x == 0 {
+ want = 32
+ }
+ if got != want {
+ t.Fatalf("TrailingZeros32(%#08x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 32 {
+ got = TrailingZeros(uint(x))
+ if got != want {
+ t.Fatalf("TrailingZeros(%#08x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+
+ if x <= 1<<64-1 {
+ got := TrailingZeros64(uint64(x))
+ if x == 0 {
+ want = 64
+ }
+ if got != want {
+ t.Fatalf("TrailingZeros64(%#016x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 64 {
+ got = TrailingZeros(uint(x))
+ if got != want {
+ t.Fatalf("TrailingZeros(%#016x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+ }
+ }
+}
+
+func BenchmarkTrailingZeros(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += TrailingZeros(uint(Input) << (uint(i) % UintSize))
+ }
+ Output = s
+}
+
+func BenchmarkTrailingZeros8(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += TrailingZeros8(uint8(Input) << (uint(i) % 8))
+ }
+ Output = s
+}
+
+func BenchmarkTrailingZeros16(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += TrailingZeros16(uint16(Input) << (uint(i) % 16))
+ }
+ Output = s
+}
+
+func BenchmarkTrailingZeros32(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += TrailingZeros32(uint32(Input) << (uint(i) % 32))
+ }
+ Output = s
+}
+
+func BenchmarkTrailingZeros64(b *testing.B) {
+ var s int
+ for i := 0; i < b.N; i++ {
+ s += TrailingZeros64(uint64(Input) << (uint(i) % 64))
+ }
+ Output = s
+}
+
+func TestOnesCount(t *testing.T) {
+ var x uint64
+ for i := 0; i <= 64; i++ {
+ testOnesCount(t, x, i)
+ x = x<<1 | 1
+ }
+
+ for i := 64; i >= 0; i-- {
+ testOnesCount(t, x, i)
+ x = x << 1
+ }
+
+ for i := 0; i < 256; i++ {
+ for k := 0; k < 64-8; k++ {
+ testOnesCount(t, uint64(i)<>(8-k&0x7)
+ if got8 != want8 {
+ t.Fatalf("RotateLeft8(%#02x, %d) == %#02x; want %#02x", x8, k, got8, want8)
+ }
+ got8 = RotateLeft8(want8, -int(k))
+ if got8 != x8 {
+ t.Fatalf("RotateLeft8(%#02x, -%d) == %#02x; want %#02x", want8, k, got8, x8)
+ }
+
+ x16 := uint16(m)
+ got16 := RotateLeft16(x16, int(k))
+ want16 := x16<<(k&0xf) | x16>>(16-k&0xf)
+ if got16 != want16 {
+ t.Fatalf("RotateLeft16(%#04x, %d) == %#04x; want %#04x", x16, k, got16, want16)
+ }
+ got16 = RotateLeft16(want16, -int(k))
+ if got16 != x16 {
+ t.Fatalf("RotateLeft16(%#04x, -%d) == %#04x; want %#04x", want16, k, got16, x16)
+ }
+
+ x32 := uint32(m)
+ got32 := RotateLeft32(x32, int(k))
+ want32 := x32<<(k&0x1f) | x32>>(32-k&0x1f)
+ if got32 != want32 {
+ t.Fatalf("RotateLeft32(%#08x, %d) == %#08x; want %#08x", x32, k, got32, want32)
+ }
+ got32 = RotateLeft32(want32, -int(k))
+ if got32 != x32 {
+ t.Fatalf("RotateLeft32(%#08x, -%d) == %#08x; want %#08x", want32, k, got32, x32)
+ }
+ if UintSize == 32 {
+ x := uint(m)
+ got := RotateLeft(x, int(k))
+ want := x<<(k&0x1f) | x>>(32-k&0x1f)
+ if got != want {
+ t.Fatalf("RotateLeft(%#08x, %d) == %#08x; want %#08x", x, k, got, want)
+ }
+ got = RotateLeft(want, -int(k))
+ if got != x {
+ t.Fatalf("RotateLeft(%#08x, -%d) == %#08x; want %#08x", want, k, got, x)
+ }
+ }
+
+ x64 := uint64(m)
+ got64 := RotateLeft64(x64, int(k))
+ want64 := x64<<(k&0x3f) | x64>>(64-k&0x3f)
+ if got64 != want64 {
+ t.Fatalf("RotateLeft64(%#016x, %d) == %#016x; want %#016x", x64, k, got64, want64)
+ }
+ got64 = RotateLeft64(want64, -int(k))
+ if got64 != x64 {
+ t.Fatalf("RotateLeft64(%#016x, -%d) == %#016x; want %#016x", want64, k, got64, x64)
+ }
+ if UintSize == 64 {
+ x := uint(m)
+ got := RotateLeft(x, int(k))
+ want := x<<(k&0x3f) | x>>(64-k&0x3f)
+ if got != want {
+ t.Fatalf("RotateLeft(%#016x, %d) == %#016x; want %#016x", x, k, got, want)
+ }
+ got = RotateLeft(want, -int(k))
+ if got != x {
+ t.Fatalf("RotateLeft(%#08x, -%d) == %#08x; want %#08x", want, k, got, x)
+ }
+ }
+ }
+}
+
+func BenchmarkRotateLeft(b *testing.B) {
+ var s uint
+ for i := 0; i < b.N; i++ {
+ s += RotateLeft(uint(Input), i)
+ }
+ Output = int(s)
+}
+
+func BenchmarkRotateLeft8(b *testing.B) {
+ var s uint8
+ for i := 0; i < b.N; i++ {
+ s += RotateLeft8(uint8(Input), i)
+ }
+ Output = int(s)
+}
+
+func BenchmarkRotateLeft16(b *testing.B) {
+ var s uint16
+ for i := 0; i < b.N; i++ {
+ s += RotateLeft16(uint16(Input), i)
+ }
+ Output = int(s)
+}
+
+func BenchmarkRotateLeft32(b *testing.B) {
+ var s uint32
+ for i := 0; i < b.N; i++ {
+ s += RotateLeft32(uint32(Input), i)
+ }
+ Output = int(s)
+}
+
+func BenchmarkRotateLeft64(b *testing.B) {
+ var s uint64
+ for i := 0; i < b.N; i++ {
+ s += RotateLeft64(uint64(Input), i)
+ }
+ Output = int(s)
+}
+
+func TestReverse(t *testing.T) {
+ // test each bit
+ for i := uint(0); i < 64; i++ {
+ testReverse(t, uint64(1)<> (64 - 8))
+ if got8 != want8 {
+ t.Fatalf("Reverse8(%#02x) == %#02x; want %#02x", x8, got8, want8)
+ }
+
+ x16 := uint16(x64)
+ got16 := Reverse16(x16)
+ want16 := uint16(want64 >> (64 - 16))
+ if got16 != want16 {
+ t.Fatalf("Reverse16(%#04x) == %#04x; want %#04x", x16, got16, want16)
+ }
+
+ x32 := uint32(x64)
+ got32 := Reverse32(x32)
+ want32 := uint32(want64 >> (64 - 32))
+ if got32 != want32 {
+ t.Fatalf("Reverse32(%#08x) == %#08x; want %#08x", x32, got32, want32)
+ }
+ if UintSize == 32 {
+ x := uint(x32)
+ got := Reverse(x)
+ want := uint(want32)
+ if got != want {
+ t.Fatalf("Reverse(%#08x) == %#08x; want %#08x", x, got, want)
+ }
+ }
+
+ got64 := Reverse64(x64)
+ if got64 != want64 {
+ t.Fatalf("Reverse64(%#016x) == %#016x; want %#016x", x64, got64, want64)
+ }
+ if UintSize == 64 {
+ x := uint(x64)
+ got := Reverse(x)
+ want := uint(want64)
+ if got != want {
+ t.Fatalf("Reverse(%#08x) == %#016x; want %#016x", x, got, want)
+ }
+ }
+}
+
+func BenchmarkReverse(b *testing.B) {
+ var s uint
+ for i := 0; i < b.N; i++ {
+ s += Reverse(uint(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverse8(b *testing.B) {
+ var s uint8
+ for i := 0; i < b.N; i++ {
+ s += Reverse8(uint8(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverse16(b *testing.B) {
+ var s uint16
+ for i := 0; i < b.N; i++ {
+ s += Reverse16(uint16(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverse32(b *testing.B) {
+ var s uint32
+ for i := 0; i < b.N; i++ {
+ s += Reverse32(uint32(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverse64(b *testing.B) {
+ var s uint64
+ for i := 0; i < b.N; i++ {
+ s += Reverse64(uint64(i))
+ }
+ Output = int(s)
+}
+
+func TestReverseBytes(t *testing.T) {
+ for _, test := range []struct {
+ x, r uint64
+ }{
+ {0, 0},
+ {0x01, 0x01 << 56},
+ {0x0123, 0x2301 << 48},
+ {0x012345, 0x452301 << 40},
+ {0x01234567, 0x67452301 << 32},
+ {0x0123456789, 0x8967452301 << 24},
+ {0x0123456789ab, 0xab8967452301 << 16},
+ {0x0123456789abcd, 0xcdab8967452301 << 8},
+ {0x0123456789abcdef, 0xefcdab8967452301 << 0},
+ } {
+ testReverseBytes(t, test.x, test.r)
+ testReverseBytes(t, test.r, test.x)
+ }
+}
+
+func testReverseBytes(t *testing.T, x64, want64 uint64) {
+ x16 := uint16(x64)
+ got16 := ReverseBytes16(x16)
+ want16 := uint16(want64 >> (64 - 16))
+ if got16 != want16 {
+ t.Fatalf("ReverseBytes16(%#04x) == %#04x; want %#04x", x16, got16, want16)
+ }
+
+ x32 := uint32(x64)
+ got32 := ReverseBytes32(x32)
+ want32 := uint32(want64 >> (64 - 32))
+ if got32 != want32 {
+ t.Fatalf("ReverseBytes32(%#08x) == %#08x; want %#08x", x32, got32, want32)
+ }
+ if UintSize == 32 {
+ x := uint(x32)
+ got := ReverseBytes(x)
+ want := uint(want32)
+ if got != want {
+ t.Fatalf("ReverseBytes(%#08x) == %#08x; want %#08x", x, got, want)
+ }
+ }
+
+ got64 := ReverseBytes64(x64)
+ if got64 != want64 {
+ t.Fatalf("ReverseBytes64(%#016x) == %#016x; want %#016x", x64, got64, want64)
+ }
+ if UintSize == 64 {
+ x := uint(x64)
+ got := ReverseBytes(x)
+ want := uint(want64)
+ if got != want {
+ t.Fatalf("ReverseBytes(%#016x) == %#016x; want %#016x", x, got, want)
+ }
+ }
+}
+
+func BenchmarkReverseBytes(b *testing.B) {
+ var s uint
+ for i := 0; i < b.N; i++ {
+ s += ReverseBytes(uint(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverseBytes16(b *testing.B) {
+ var s uint16
+ for i := 0; i < b.N; i++ {
+ s += ReverseBytes16(uint16(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverseBytes32(b *testing.B) {
+ var s uint32
+ for i := 0; i < b.N; i++ {
+ s += ReverseBytes32(uint32(i))
+ }
+ Output = int(s)
+}
+
+func BenchmarkReverseBytes64(b *testing.B) {
+ var s uint64
+ for i := 0; i < b.N; i++ {
+ s += ReverseBytes64(uint64(i))
+ }
+ Output = int(s)
+}
+
+func TestLen(t *testing.T) {
+ for i := 0; i < 256; i++ {
+ len := 8 - tab[i].nlz
+ for k := 0; k < 64-8; k++ {
+ x := uint64(i) << uint(k)
+ want := 0
+ if x != 0 {
+ want = len + k
+ }
+ if x <= 1<<8-1 {
+ got := Len8(uint8(x))
+ if got != want {
+ t.Fatalf("Len8(%#02x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<16-1 {
+ got := Len16(uint16(x))
+ if got != want {
+ t.Fatalf("Len16(%#04x) == %d; want %d", x, got, want)
+ }
+ }
+
+ if x <= 1<<32-1 {
+ got := Len32(uint32(x))
+ if got != want {
+ t.Fatalf("Len32(%#08x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 32 {
+ got := Len(uint(x))
+ if got != want {
+ t.Fatalf("Len(%#08x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+
+ if x <= 1<<64-1 {
+ got := Len64(uint64(x))
+ if got != want {
+ t.Fatalf("Len64(%#016x) == %d; want %d", x, got, want)
+ }
+ if UintSize == 64 {
+ got := Len(uint(x))
+ if got != want {
+ t.Fatalf("Len(%#016x) == %d; want %d", x, got, want)
+ }
+ }
+ }
+ }
+ }
+}
+
+const (
+ _M = 1< 0 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Add64(a, b, 0)
+ if c != 0 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Add64(a, b, 0)
+ if c == 1 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Add64(a, b, 0)
+ if c != 1 {
+ return x
+ }
+ panic("overflow")
+ },
+ func(a, b uint64) uint64 {
+ x, c := Add64(a, b, 0)
+ if c == 0 {
+ return x
+ }
+ panic("overflow")
+ },
+ }
+ for _, test := range tests {
+ shouldPanic := func(f func()) {
+ defer func() {
+ if err := recover(); err == nil {
+ t.Fatalf("expected panic")
+ }
+ }()
+ f()
+ }
+
+ // overflow
+ shouldPanic(func() { test(_M64, 1) })
+ shouldPanic(func() { test(1, _M64) })
+ shouldPanic(func() { test(_M64, _M64) })
+
+ // no overflow
+ test(_M64, 0)
+ test(0, 0)
+ test(1, 1)
+ }
+}
+
+func TestSub64OverflowPanic(t *testing.T) {
+ // Test that 64-bit overflow panics fire correctly.
+ // These are designed to improve coverage of compiler intrinsics.
+ tests := []func(uint64, uint64) uint64{
+ func(a, b uint64) uint64 {
+ x, c := Sub64(a, b, 0)
+ if c > 0 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Sub64(a, b, 0)
+ if c != 0 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Sub64(a, b, 0)
+ if c == 1 {
+ panic("overflow")
+ }
+ return x
+ },
+ func(a, b uint64) uint64 {
+ x, c := Sub64(a, b, 0)
+ if c != 1 {
+ return x
+ }
+ panic("overflow")
+ },
+ func(a, b uint64) uint64 {
+ x, c := Sub64(a, b, 0)
+ if c == 0 {
+ return x
+ }
+ panic("overflow")
+ },
+ }
+ for _, test := range tests {
+ shouldPanic := func(f func()) {
+ defer func() {
+ if err := recover(); err == nil {
+ t.Fatalf("expected panic")
+ }
+ }()
+ f()
+ }
+
+ // overflow
+ shouldPanic(func() { test(0, 1) })
+ shouldPanic(func() { test(1, _M64) })
+ shouldPanic(func() { test(_M64-1, _M64) })
+
+ // no overflow
+ test(_M64, 0)
+ test(0, 0)
+ test(1, 1)
+ }
+}
+
+func TestMulDiv(t *testing.T) {
+ testMul := func(msg string, f func(x, y uint) (hi, lo uint), x, y, hi, lo uint) {
+ hi1, lo1 := f(x, y)
+ if hi1 != hi || lo1 != lo {
+ t.Errorf("%s: got hi:lo = %#x:%#x; want %#x:%#x", msg, hi1, lo1, hi, lo)
+ }
+ }
+ testDiv := func(msg string, f func(hi, lo, y uint) (q, r uint), hi, lo, y, q, r uint) {
+ q1, r1 := f(hi, lo, y)
+ if q1 != q || r1 != r {
+ t.Errorf("%s: got q:r = %#x:%#x; want %#x:%#x", msg, q1, r1, q, r)
+ }
+ }
+ for _, a := range []struct {
+ x, y uint
+ hi, lo, r uint
+ }{
+ {1 << (UintSize - 1), 2, 1, 0, 1},
+ {_M, _M, _M - 1, 1, 42},
+ } {
+ testMul("Mul", Mul, a.x, a.y, a.hi, a.lo)
+ testMul("Mul symmetric", Mul, a.y, a.x, a.hi, a.lo)
+ testDiv("Div", Div, a.hi, a.lo+a.r, a.y, a.x, a.r)
+ testDiv("Div symmetric", Div, a.hi, a.lo+a.r, a.x, a.y, a.r)
+ // The above code can't test intrinsic implementation, because the passed function is not called directly.
+ // The following code uses a closure to test the intrinsic version in case the function is intrinsified.
+ testMul("Mul intrinsic", func(x, y uint) (uint, uint) { return Mul(x, y) }, a.x, a.y, a.hi, a.lo)
+ testMul("Mul intrinsic symmetric", func(x, y uint) (uint, uint) { return Mul(x, y) }, a.y, a.x, a.hi, a.lo)
+ testDiv("Div intrinsic", func(hi, lo, y uint) (uint, uint) { return Div(hi, lo, y) }, a.hi, a.lo+a.r, a.y, a.x, a.r)
+ testDiv("Div intrinsic symmetric", func(hi, lo, y uint) (uint, uint) { return Div(hi, lo, y) }, a.hi, a.lo+a.r, a.x, a.y, a.r)
+ }
+}
+
+func TestMulDiv32(t *testing.T) {
+ testMul := func(msg string, f func(x, y uint32) (hi, lo uint32), x, y, hi, lo uint32) {
+ hi1, lo1 := f(x, y)
+ if hi1 != hi || lo1 != lo {
+ t.Errorf("%s: got hi:lo = %#x:%#x; want %#x:%#x", msg, hi1, lo1, hi, lo)
+ }
+ }
+ testDiv := func(msg string, f func(hi, lo, y uint32) (q, r uint32), hi, lo, y, q, r uint32) {
+ q1, r1 := f(hi, lo, y)
+ if q1 != q || r1 != r {
+ t.Errorf("%s: got q:r = %#x:%#x; want %#x:%#x", msg, q1, r1, q, r)
+ }
+ }
+ for _, a := range []struct {
+ x, y uint32
+ hi, lo, r uint32
+ }{
+ {1 << 31, 2, 1, 0, 1},
+ {0xc47dfa8c, 50911, 0x98a4, 0x998587f4, 13},
+ {_M32, _M32, _M32 - 1, 1, 42},
+ } {
+ testMul("Mul32", Mul32, a.x, a.y, a.hi, a.lo)
+ testMul("Mul32 symmetric", Mul32, a.y, a.x, a.hi, a.lo)
+ testDiv("Div32", Div32, a.hi, a.lo+a.r, a.y, a.x, a.r)
+ testDiv("Div32 symmetric", Div32, a.hi, a.lo+a.r, a.x, a.y, a.r)
+ }
+}
+
+func TestMulDiv64(t *testing.T) {
+ testMul := func(msg string, f func(x, y uint64) (hi, lo uint64), x, y, hi, lo uint64) {
+ hi1, lo1 := f(x, y)
+ if hi1 != hi || lo1 != lo {
+ t.Errorf("%s: got hi:lo = %#x:%#x; want %#x:%#x", msg, hi1, lo1, hi, lo)
+ }
+ }
+ testDiv := func(msg string, f func(hi, lo, y uint64) (q, r uint64), hi, lo, y, q, r uint64) {
+ q1, r1 := f(hi, lo, y)
+ if q1 != q || r1 != r {
+ t.Errorf("%s: got q:r = %#x:%#x; want %#x:%#x", msg, q1, r1, q, r)
+ }
+ }
+ for _, a := range []struct {
+ x, y uint64
+ hi, lo, r uint64
+ }{
+ {1 << 63, 2, 1, 0, 1},
+ {0x3626229738a3b9, 0xd8988a9f1cc4a61, 0x2dd0712657fe8, 0x9dd6a3364c358319, 13},
+ {_M64, _M64, _M64 - 1, 1, 42},
+ } {
+ testMul("Mul64", Mul64, a.x, a.y, a.hi, a.lo)
+ testMul("Mul64 symmetric", Mul64, a.y, a.x, a.hi, a.lo)
+ testDiv("Div64", Div64, a.hi, a.lo+a.r, a.y, a.x, a.r)
+ testDiv("Div64 symmetric", Div64, a.hi, a.lo+a.r, a.x, a.y, a.r)
+ // The above code can't test intrinsic implementation, because the passed function is not called directly.
+ // The following code uses a closure to test the intrinsic version in case the function is intrinsified.
+ testMul("Mul64 intrinsic", func(x, y uint64) (uint64, uint64) { return Mul64(x, y) }, a.x, a.y, a.hi, a.lo)
+ testMul("Mul64 intrinsic symmetric", func(x, y uint64) (uint64, uint64) { return Mul64(x, y) }, a.y, a.x, a.hi, a.lo)
+ testDiv("Div64 intrinsic", func(hi, lo, y uint64) (uint64, uint64) { return Div64(hi, lo, y) }, a.hi, a.lo+a.r, a.y, a.x, a.r)
+ testDiv("Div64 intrinsic symmetric", func(hi, lo, y uint64) (uint64, uint64) { return Div64(hi, lo, y) }, a.hi, a.lo+a.r, a.x, a.y, a.r)
+ }
+}
+
+const (
+ divZeroError = "runtime error: integer divide by zero"
+ overflowError = "runtime error: integer overflow"
+)
+
+func TestDivPanicOverflow(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div should have panicked when y<=hi")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != overflowError {
+ t.Errorf("Div expected panic: %q, got: %q ", overflowError, e.Error())
+ }
+ }()
+ q, r := Div(1, 0, 1)
+ t.Errorf("undefined q, r = %v, %v calculated when Div should have panicked", q, r)
+}
+
+func TestDiv32PanicOverflow(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div32 should have panicked when y<=hi")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != overflowError {
+ t.Errorf("Div32 expected panic: %q, got: %q ", overflowError, e.Error())
+ }
+ }()
+ q, r := Div32(1, 0, 1)
+ t.Errorf("undefined q, r = %v, %v calculated when Div32 should have panicked", q, r)
+}
+
+func TestDiv64PanicOverflow(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div64 should have panicked when y<=hi")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != overflowError {
+ t.Errorf("Div64 expected panic: %q, got: %q ", overflowError, e.Error())
+ }
+ }()
+ q, r := Div64(1, 0, 1)
+ t.Errorf("undefined q, r = %v, %v calculated when Div64 should have panicked", q, r)
+}
+
+func TestDivPanicZero(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div should have panicked when y==0")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != divZeroError {
+ t.Errorf("Div expected panic: %q, got: %q ", divZeroError, e.Error())
+ }
+ }()
+ q, r := Div(1, 1, 0)
+ t.Errorf("undefined q, r = %v, %v calculated when Div should have panicked", q, r)
+}
+
+func TestDiv32PanicZero(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div32 should have panicked when y==0")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != divZeroError {
+ t.Errorf("Div32 expected panic: %q, got: %q ", divZeroError, e.Error())
+ }
+ }()
+ q, r := Div32(1, 1, 0)
+ t.Errorf("undefined q, r = %v, %v calculated when Div32 should have panicked", q, r)
+}
+
+func TestDiv64PanicZero(t *testing.T) {
+ // Expect a panic
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("Div64 should have panicked when y==0")
+ } else if e, ok := err.(runtime.Error); !ok || e.Error() != divZeroError {
+ t.Errorf("Div64 expected panic: %q, got: %q ", divZeroError, e.Error())
+ }
+ }()
+ q, r := Div64(1, 1, 0)
+ t.Errorf("undefined q, r = %v, %v calculated when Div64 should have panicked", q, r)
+}
+
+func TestRem32(t *testing.T) {
+ // Sanity check: for non-oveflowing dividends, the result is the
+ // same as the rem returned by Div32
+ hi, lo, y := uint32(510510), uint32(9699690), uint32(510510+1) // ensure hi < y
+ for i := 0; i < 1000; i++ {
+ r := Rem32(hi, lo, y)
+ _, r2 := Div32(hi, lo, y)
+ if r != r2 {
+ t.Errorf("Rem32(%v, %v, %v) returned %v, but Div32 returned rem %v", hi, lo, y, r, r2)
+ }
+ y += 13
+ }
+}
+
+func TestRem32Overflow(t *testing.T) {
+ // To trigger a quotient overflow, we need y <= hi
+ hi, lo, y := uint32(510510), uint32(9699690), uint32(7)
+ for i := 0; i < 1000; i++ {
+ r := Rem32(hi, lo, y)
+ _, r2 := Div64(0, uint64(hi)<<32|uint64(lo), uint64(y))
+ if r != uint32(r2) {
+ t.Errorf("Rem32(%v, %v, %v) returned %v, but Div64 returned rem %v", hi, lo, y, r, r2)
+ }
+ y += 13
+ }
+}
+
+func TestRem64(t *testing.T) {
+ // Sanity check: for non-oveflowing dividends, the result is the
+ // same as the rem returned by Div64
+ hi, lo, y := uint64(510510), uint64(9699690), uint64(510510+1) // ensure hi < y
+ for i := 0; i < 1000; i++ {
+ r := Rem64(hi, lo, y)
+ _, r2 := Div64(hi, lo, y)
+ if r != r2 {
+ t.Errorf("Rem64(%v, %v, %v) returned %v, but Div64 returned rem %v", hi, lo, y, r, r2)
+ }
+ y += 13
+ }
+}
+
+func TestRem64Overflow(t *testing.T) {
+ Rem64Tests := []struct {
+ hi, lo, y uint64
+ rem uint64
+ }{
+ // Testcases computed using Python 3, as:
+ // >>> hi = 42; lo = 1119; y = 42
+ // >>> ((hi<<64)+lo) % y
+ {42, 1119, 42, 27},
+ {42, 1119, 38, 9},
+ {42, 1119, 26, 23},
+ {469, 0, 467, 271},
+ {469, 0, 113, 58},
+ {111111, 111111, 1171, 803},
+ {3968194946088682615, 3192705705065114702, 1000037, 56067},
+ }
+
+ for _, rt := range Rem64Tests {
+ if rt.hi < rt.y {
+ t.Fatalf("Rem64(%v, %v, %v) is not a test with quo overflow", rt.hi, rt.lo, rt.y)
+ }
+ rem := Rem64(rt.hi, rt.lo, rt.y)
+ if rem != rt.rem {
+ t.Errorf("Rem64(%v, %v, %v) returned %v, wanted %v",
+ rt.hi, rt.lo, rt.y, rem, rt.rem)
+ }
+ }
+}
+
+func BenchmarkAdd(b *testing.B) {
+ var z, c uint
+ for i := 0; i < b.N; i++ {
+ z, c = Add(uint(Input), uint(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkAdd32(b *testing.B) {
+ var z, c uint32
+ for i := 0; i < b.N; i++ {
+ z, c = Add32(uint32(Input), uint32(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkAdd64(b *testing.B) {
+ var z, c uint64
+ for i := 0; i < b.N; i++ {
+ z, c = Add64(uint64(Input), uint64(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkAdd64multiple(b *testing.B) {
+ var z0 = uint64(Input)
+ var z1 = uint64(Input)
+ var z2 = uint64(Input)
+ var z3 = uint64(Input)
+ for i := 0; i < b.N; i++ {
+ var c uint64
+ z0, c = Add64(z0, uint64(i), c)
+ z1, c = Add64(z1, uint64(i), c)
+ z2, c = Add64(z2, uint64(i), c)
+ z3, _ = Add64(z3, uint64(i), c)
+ }
+ Output = int(z0 + z1 + z2 + z3)
+}
+
+func BenchmarkSub(b *testing.B) {
+ var z, c uint
+ for i := 0; i < b.N; i++ {
+ z, c = Sub(uint(Input), uint(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkSub32(b *testing.B) {
+ var z, c uint32
+ for i := 0; i < b.N; i++ {
+ z, c = Sub32(uint32(Input), uint32(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkSub64(b *testing.B) {
+ var z, c uint64
+ for i := 0; i < b.N; i++ {
+ z, c = Sub64(uint64(Input), uint64(i), c)
+ }
+ Output = int(z + c)
+}
+
+func BenchmarkSub64multiple(b *testing.B) {
+ var z0 = uint64(Input)
+ var z1 = uint64(Input)
+ var z2 = uint64(Input)
+ var z3 = uint64(Input)
+ for i := 0; i < b.N; i++ {
+ var c uint64
+ z0, c = Sub64(z0, uint64(i), c)
+ z1, c = Sub64(z1, uint64(i), c)
+ z2, c = Sub64(z2, uint64(i), c)
+ z3, _ = Sub64(z3, uint64(i), c)
+ }
+ Output = int(z0 + z1 + z2 + z3)
+}
+
+func BenchmarkMul(b *testing.B) {
+ var hi, lo uint
+ for i := 0; i < b.N; i++ {
+ hi, lo = Mul(uint(Input), uint(i))
+ }
+ Output = int(hi + lo)
+}
+
+func BenchmarkMul32(b *testing.B) {
+ var hi, lo uint32
+ for i := 0; i < b.N; i++ {
+ hi, lo = Mul32(uint32(Input), uint32(i))
+ }
+ Output = int(hi + lo)
+}
+
+func BenchmarkMul64(b *testing.B) {
+ var hi, lo uint64
+ for i := 0; i < b.N; i++ {
+ hi, lo = Mul64(uint64(Input), uint64(i))
+ }
+ Output = int(hi + lo)
+}
+
+func BenchmarkDiv(b *testing.B) {
+ var q, r uint
+ for i := 0; i < b.N; i++ {
+ q, r = Div(1, uint(i), uint(Input))
+ }
+ Output = int(q + r)
+}
+
+func BenchmarkDiv32(b *testing.B) {
+ var q, r uint32
+ for i := 0; i < b.N; i++ {
+ q, r = Div32(1, uint32(i), uint32(Input))
+ }
+ Output = int(q + r)
+}
+
+func BenchmarkDiv64(b *testing.B) {
+ var q, r uint64
+ for i := 0; i < b.N; i++ {
+ q, r = Div64(1, uint64(i), uint64(Input))
+ }
+ Output = int(q + r)
+}
+
+// ----------------------------------------------------------------------------
+// Testing support
+
+type entry = struct {
+ nlz, ntz, pop int
+}
+
+// tab contains results for all uint8 values
+var tab [256]entry
+
+func init() {
+ tab[0] = entry{8, 8, 0}
+ for i := 1; i < len(tab); i++ {
+ // nlz
+ x := i // x != 0
+ n := 0
+ for x&0x80 == 0 {
+ n++
+ x <<= 1
+ }
+ tab[i].nlz = n
+
+ // ntz
+ x = i // x != 0
+ n = 0
+ for x&1 == 0 {
+ n++
+ x >>= 1
+ }
+ tab[i].ntz = n
+
+ // pop
+ x = i // x != 0
+ n = 0
+ for x != 0 {
+ n += int(x & 1)
+ x >>= 1
+ }
+ tab[i].pop = n
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/example_math_test.go b/platform/dbops/binaries/go/go/src/math/bits/example_math_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4bb466f85cd8f088b03474a009ff4ff80da54ae0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/example_math_test.go
@@ -0,0 +1,202 @@
+// 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 bits_test
+
+import (
+ "fmt"
+ "math/bits"
+)
+
+func ExampleAdd32() {
+ // First number is 33<<32 + 12
+ n1 := []uint32{33, 12}
+ // Second number is 21<<32 + 23
+ n2 := []uint32{21, 23}
+ // Add them together without producing carry.
+ d1, carry := bits.Add32(n1[1], n2[1], 0)
+ d0, _ := bits.Add32(n1[0], n2[0], carry)
+ nsum := []uint32{d0, d1}
+ fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+ // First number is 1<<32 + 2147483648
+ n1 = []uint32{1, 0x80000000}
+ // Second number is 1<<32 + 2147483648
+ n2 = []uint32{1, 0x80000000}
+ // Add them together producing carry.
+ d1, carry = bits.Add32(n1[1], n2[1], 0)
+ d0, _ = bits.Add32(n1[0], n2[0], carry)
+ nsum = []uint32{d0, d1}
+ fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+ // Output:
+ // [33 12] + [21 23] = [54 35] (carry bit was 0)
+ // [1 2147483648] + [1 2147483648] = [3 0] (carry bit was 1)
+}
+
+func ExampleAdd64() {
+ // First number is 33<<64 + 12
+ n1 := []uint64{33, 12}
+ // Second number is 21<<64 + 23
+ n2 := []uint64{21, 23}
+ // Add them together without producing carry.
+ d1, carry := bits.Add64(n1[1], n2[1], 0)
+ d0, _ := bits.Add64(n1[0], n2[0], carry)
+ nsum := []uint64{d0, d1}
+ fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+ // First number is 1<<64 + 9223372036854775808
+ n1 = []uint64{1, 0x8000000000000000}
+ // Second number is 1<<64 + 9223372036854775808
+ n2 = []uint64{1, 0x8000000000000000}
+ // Add them together producing carry.
+ d1, carry = bits.Add64(n1[1], n2[1], 0)
+ d0, _ = bits.Add64(n1[0], n2[0], carry)
+ nsum = []uint64{d0, d1}
+ fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+ // Output:
+ // [33 12] + [21 23] = [54 35] (carry bit was 0)
+ // [1 9223372036854775808] + [1 9223372036854775808] = [3 0] (carry bit was 1)
+}
+
+func ExampleSub32() {
+ // First number is 33<<32 + 23
+ n1 := []uint32{33, 23}
+ // Second number is 21<<32 + 12
+ n2 := []uint32{21, 12}
+ // Sub them together without producing carry.
+ d1, carry := bits.Sub32(n1[1], n2[1], 0)
+ d0, _ := bits.Sub32(n1[0], n2[0], carry)
+ nsum := []uint32{d0, d1}
+ fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+ // First number is 3<<32 + 2147483647
+ n1 = []uint32{3, 0x7fffffff}
+ // Second number is 1<<32 + 2147483648
+ n2 = []uint32{1, 0x80000000}
+ // Sub them together producing carry.
+ d1, carry = bits.Sub32(n1[1], n2[1], 0)
+ d0, _ = bits.Sub32(n1[0], n2[0], carry)
+ nsum = []uint32{d0, d1}
+ fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+ // Output:
+ // [33 23] - [21 12] = [12 11] (carry bit was 0)
+ // [3 2147483647] - [1 2147483648] = [1 4294967295] (carry bit was 1)
+}
+
+func ExampleSub64() {
+ // First number is 33<<64 + 23
+ n1 := []uint64{33, 23}
+ // Second number is 21<<64 + 12
+ n2 := []uint64{21, 12}
+ // Sub them together without producing carry.
+ d1, carry := bits.Sub64(n1[1], n2[1], 0)
+ d0, _ := bits.Sub64(n1[0], n2[0], carry)
+ nsum := []uint64{d0, d1}
+ fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+
+ // First number is 3<<64 + 9223372036854775807
+ n1 = []uint64{3, 0x7fffffffffffffff}
+ // Second number is 1<<64 + 9223372036854775808
+ n2 = []uint64{1, 0x8000000000000000}
+ // Sub them together producing carry.
+ d1, carry = bits.Sub64(n1[1], n2[1], 0)
+ d0, _ = bits.Sub64(n1[0], n2[0], carry)
+ nsum = []uint64{d0, d1}
+ fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
+ // Output:
+ // [33 23] - [21 12] = [12 11] (carry bit was 0)
+ // [3 9223372036854775807] - [1 9223372036854775808] = [1 18446744073709551615] (carry bit was 1)
+}
+
+func ExampleMul32() {
+ // First number is 0<<32 + 12
+ n1 := []uint32{0, 12}
+ // Second number is 0<<32 + 12
+ n2 := []uint32{0, 12}
+ // Multiply them together without producing overflow.
+ hi, lo := bits.Mul32(n1[1], n2[1])
+ nsum := []uint32{hi, lo}
+ fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+
+ // First number is 0<<32 + 2147483648
+ n1 = []uint32{0, 0x80000000}
+ // Second number is 0<<32 + 2
+ n2 = []uint32{0, 2}
+ // Multiply them together producing overflow.
+ hi, lo = bits.Mul32(n1[1], n2[1])
+ nsum = []uint32{hi, lo}
+ fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+ // Output:
+ // 12 * 12 = [0 144]
+ // 2147483648 * 2 = [1 0]
+}
+
+func ExampleMul64() {
+ // First number is 0<<64 + 12
+ n1 := []uint64{0, 12}
+ // Second number is 0<<64 + 12
+ n2 := []uint64{0, 12}
+ // Multiply them together without producing overflow.
+ hi, lo := bits.Mul64(n1[1], n2[1])
+ nsum := []uint64{hi, lo}
+ fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+
+ // First number is 0<<64 + 9223372036854775808
+ n1 = []uint64{0, 0x8000000000000000}
+ // Second number is 0<<64 + 2
+ n2 = []uint64{0, 2}
+ // Multiply them together producing overflow.
+ hi, lo = bits.Mul64(n1[1], n2[1])
+ nsum = []uint64{hi, lo}
+ fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
+ // Output:
+ // 12 * 12 = [0 144]
+ // 9223372036854775808 * 2 = [1 0]
+}
+
+func ExampleDiv32() {
+ // First number is 0<<32 + 6
+ n1 := []uint32{0, 6}
+ // Second number is 0<<32 + 3
+ n2 := []uint32{0, 3}
+ // Divide them together.
+ quo, rem := bits.Div32(n1[0], n1[1], n2[1])
+ nsum := []uint32{quo, rem}
+ fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+
+ // First number is 2<<32 + 2147483648
+ n1 = []uint32{2, 0x80000000}
+ // Second number is 0<<32 + 2147483648
+ n2 = []uint32{0, 0x80000000}
+ // Divide them together.
+ quo, rem = bits.Div32(n1[0], n1[1], n2[1])
+ nsum = []uint32{quo, rem}
+ fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+ // Output:
+ // [0 6] / 3 = [2 0]
+ // [2 2147483648] / 2147483648 = [5 0]
+}
+
+func ExampleDiv64() {
+ // First number is 0<<64 + 6
+ n1 := []uint64{0, 6}
+ // Second number is 0<<64 + 3
+ n2 := []uint64{0, 3}
+ // Divide them together.
+ quo, rem := bits.Div64(n1[0], n1[1], n2[1])
+ nsum := []uint64{quo, rem}
+ fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+
+ // First number is 2<<64 + 9223372036854775808
+ n1 = []uint64{2, 0x8000000000000000}
+ // Second number is 0<<64 + 9223372036854775808
+ n2 = []uint64{0, 0x8000000000000000}
+ // Divide them together.
+ quo, rem = bits.Div64(n1[0], n1[1], n2[1])
+ nsum = []uint64{quo, rem}
+ fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
+ // Output:
+ // [0 6] / 3 = [2 0]
+ // [2 9223372036854775808] / 9223372036854775808 = [5 0]
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/example_test.go b/platform/dbops/binaries/go/go/src/math/bits/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b2ed2cba4bfb72287dd1189382684baf41995e51
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/example_test.go
@@ -0,0 +1,210 @@
+// 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.
+
+// Code generated by go run make_examples.go. DO NOT EDIT.
+
+package bits_test
+
+import (
+ "fmt"
+ "math/bits"
+)
+
+func ExampleLeadingZeros8() {
+ fmt.Printf("LeadingZeros8(%08b) = %d\n", 1, bits.LeadingZeros8(1))
+ // Output:
+ // LeadingZeros8(00000001) = 7
+}
+
+func ExampleLeadingZeros16() {
+ fmt.Printf("LeadingZeros16(%016b) = %d\n", 1, bits.LeadingZeros16(1))
+ // Output:
+ // LeadingZeros16(0000000000000001) = 15
+}
+
+func ExampleLeadingZeros32() {
+ fmt.Printf("LeadingZeros32(%032b) = %d\n", 1, bits.LeadingZeros32(1))
+ // Output:
+ // LeadingZeros32(00000000000000000000000000000001) = 31
+}
+
+func ExampleLeadingZeros64() {
+ fmt.Printf("LeadingZeros64(%064b) = %d\n", 1, bits.LeadingZeros64(1))
+ // Output:
+ // LeadingZeros64(0000000000000000000000000000000000000000000000000000000000000001) = 63
+}
+
+func ExampleTrailingZeros8() {
+ fmt.Printf("TrailingZeros8(%08b) = %d\n", 14, bits.TrailingZeros8(14))
+ // Output:
+ // TrailingZeros8(00001110) = 1
+}
+
+func ExampleTrailingZeros16() {
+ fmt.Printf("TrailingZeros16(%016b) = %d\n", 14, bits.TrailingZeros16(14))
+ // Output:
+ // TrailingZeros16(0000000000001110) = 1
+}
+
+func ExampleTrailingZeros32() {
+ fmt.Printf("TrailingZeros32(%032b) = %d\n", 14, bits.TrailingZeros32(14))
+ // Output:
+ // TrailingZeros32(00000000000000000000000000001110) = 1
+}
+
+func ExampleTrailingZeros64() {
+ fmt.Printf("TrailingZeros64(%064b) = %d\n", 14, bits.TrailingZeros64(14))
+ // Output:
+ // TrailingZeros64(0000000000000000000000000000000000000000000000000000000000001110) = 1
+}
+
+func ExampleOnesCount() {
+ fmt.Printf("OnesCount(%b) = %d\n", 14, bits.OnesCount(14))
+ // Output:
+ // OnesCount(1110) = 3
+}
+
+func ExampleOnesCount8() {
+ fmt.Printf("OnesCount8(%08b) = %d\n", 14, bits.OnesCount8(14))
+ // Output:
+ // OnesCount8(00001110) = 3
+}
+
+func ExampleOnesCount16() {
+ fmt.Printf("OnesCount16(%016b) = %d\n", 14, bits.OnesCount16(14))
+ // Output:
+ // OnesCount16(0000000000001110) = 3
+}
+
+func ExampleOnesCount32() {
+ fmt.Printf("OnesCount32(%032b) = %d\n", 14, bits.OnesCount32(14))
+ // Output:
+ // OnesCount32(00000000000000000000000000001110) = 3
+}
+
+func ExampleOnesCount64() {
+ fmt.Printf("OnesCount64(%064b) = %d\n", 14, bits.OnesCount64(14))
+ // Output:
+ // OnesCount64(0000000000000000000000000000000000000000000000000000000000001110) = 3
+}
+
+func ExampleRotateLeft8() {
+ fmt.Printf("%08b\n", 15)
+ fmt.Printf("%08b\n", bits.RotateLeft8(15, 2))
+ fmt.Printf("%08b\n", bits.RotateLeft8(15, -2))
+ // Output:
+ // 00001111
+ // 00111100
+ // 11000011
+}
+
+func ExampleRotateLeft16() {
+ fmt.Printf("%016b\n", 15)
+ fmt.Printf("%016b\n", bits.RotateLeft16(15, 2))
+ fmt.Printf("%016b\n", bits.RotateLeft16(15, -2))
+ // Output:
+ // 0000000000001111
+ // 0000000000111100
+ // 1100000000000011
+}
+
+func ExampleRotateLeft32() {
+ fmt.Printf("%032b\n", 15)
+ fmt.Printf("%032b\n", bits.RotateLeft32(15, 2))
+ fmt.Printf("%032b\n", bits.RotateLeft32(15, -2))
+ // Output:
+ // 00000000000000000000000000001111
+ // 00000000000000000000000000111100
+ // 11000000000000000000000000000011
+}
+
+func ExampleRotateLeft64() {
+ fmt.Printf("%064b\n", 15)
+ fmt.Printf("%064b\n", bits.RotateLeft64(15, 2))
+ fmt.Printf("%064b\n", bits.RotateLeft64(15, -2))
+ // Output:
+ // 0000000000000000000000000000000000000000000000000000000000001111
+ // 0000000000000000000000000000000000000000000000000000000000111100
+ // 1100000000000000000000000000000000000000000000000000000000000011
+}
+
+func ExampleReverse8() {
+ fmt.Printf("%08b\n", 19)
+ fmt.Printf("%08b\n", bits.Reverse8(19))
+ // Output:
+ // 00010011
+ // 11001000
+}
+
+func ExampleReverse16() {
+ fmt.Printf("%016b\n", 19)
+ fmt.Printf("%016b\n", bits.Reverse16(19))
+ // Output:
+ // 0000000000010011
+ // 1100100000000000
+}
+
+func ExampleReverse32() {
+ fmt.Printf("%032b\n", 19)
+ fmt.Printf("%032b\n", bits.Reverse32(19))
+ // Output:
+ // 00000000000000000000000000010011
+ // 11001000000000000000000000000000
+}
+
+func ExampleReverse64() {
+ fmt.Printf("%064b\n", 19)
+ fmt.Printf("%064b\n", bits.Reverse64(19))
+ // Output:
+ // 0000000000000000000000000000000000000000000000000000000000010011
+ // 1100100000000000000000000000000000000000000000000000000000000000
+}
+
+func ExampleReverseBytes16() {
+ fmt.Printf("%016b\n", 15)
+ fmt.Printf("%016b\n", bits.ReverseBytes16(15))
+ // Output:
+ // 0000000000001111
+ // 0000111100000000
+}
+
+func ExampleReverseBytes32() {
+ fmt.Printf("%032b\n", 15)
+ fmt.Printf("%032b\n", bits.ReverseBytes32(15))
+ // Output:
+ // 00000000000000000000000000001111
+ // 00001111000000000000000000000000
+}
+
+func ExampleReverseBytes64() {
+ fmt.Printf("%064b\n", 15)
+ fmt.Printf("%064b\n", bits.ReverseBytes64(15))
+ // Output:
+ // 0000000000000000000000000000000000000000000000000000000000001111
+ // 0000111100000000000000000000000000000000000000000000000000000000
+}
+
+func ExampleLen8() {
+ fmt.Printf("Len8(%08b) = %d\n", 8, bits.Len8(8))
+ // Output:
+ // Len8(00001000) = 4
+}
+
+func ExampleLen16() {
+ fmt.Printf("Len16(%016b) = %d\n", 8, bits.Len16(8))
+ // Output:
+ // Len16(0000000000001000) = 4
+}
+
+func ExampleLen32() {
+ fmt.Printf("Len32(%032b) = %d\n", 8, bits.Len32(8))
+ // Output:
+ // Len32(00000000000000000000000000001000) = 4
+}
+
+func ExampleLen64() {
+ fmt.Printf("Len64(%064b) = %d\n", 8, bits.Len64(8))
+ // Output:
+ // Len64(0000000000000000000000000000000000000000000000000000000000001000) = 4
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/export_test.go b/platform/dbops/binaries/go/go/src/math/bits/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8c6f9332cca775d1639204ac0f2e45d1aa536f5e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/export_test.go
@@ -0,0 +1,7 @@
+// 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 bits
+
+const DeBruijn64 = deBruijn64
diff --git a/platform/dbops/binaries/go/go/src/math/bits/make_examples.go b/platform/dbops/binaries/go/go/src/math/bits/make_examples.go
new file mode 100644
index 0000000000000000000000000000000000000000..4bd7f581479d360e99e8788ebfec2074a3195d8c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/make_examples.go
@@ -0,0 +1,112 @@
+// 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 ignore
+
+// This program generates example_test.go.
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "math/bits"
+ "os"
+)
+
+const header = `// 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.
+
+// Code generated by go run make_examples.go. DO NOT EDIT.
+
+package bits_test
+
+import (
+ "fmt"
+ "math/bits"
+)
+`
+
+func main() {
+ w := bytes.NewBuffer([]byte(header))
+
+ for _, e := range []struct {
+ name string
+ in int
+ out [4]any
+ out2 [4]any
+ }{
+ {
+ name: "LeadingZeros",
+ in: 1,
+ out: [4]any{bits.LeadingZeros8(1), bits.LeadingZeros16(1), bits.LeadingZeros32(1), bits.LeadingZeros64(1)},
+ },
+ {
+ name: "TrailingZeros",
+ in: 14,
+ out: [4]any{bits.TrailingZeros8(14), bits.TrailingZeros16(14), bits.TrailingZeros32(14), bits.TrailingZeros64(14)},
+ },
+ {
+ name: "OnesCount",
+ in: 14,
+ out: [4]any{bits.OnesCount8(14), bits.OnesCount16(14), bits.OnesCount32(14), bits.OnesCount64(14)},
+ },
+ {
+ name: "RotateLeft",
+ in: 15,
+ out: [4]any{bits.RotateLeft8(15, 2), bits.RotateLeft16(15, 2), bits.RotateLeft32(15, 2), bits.RotateLeft64(15, 2)},
+ out2: [4]any{bits.RotateLeft8(15, -2), bits.RotateLeft16(15, -2), bits.RotateLeft32(15, -2), bits.RotateLeft64(15, -2)},
+ },
+ {
+ name: "Reverse",
+ in: 19,
+ out: [4]any{bits.Reverse8(19), bits.Reverse16(19), bits.Reverse32(19), bits.Reverse64(19)},
+ },
+ {
+ name: "ReverseBytes",
+ in: 15,
+ out: [4]any{nil, bits.ReverseBytes16(15), bits.ReverseBytes32(15), bits.ReverseBytes64(15)},
+ },
+ {
+ name: "Len",
+ in: 8,
+ out: [4]any{bits.Len8(8), bits.Len16(8), bits.Len32(8), bits.Len64(8)},
+ },
+ } {
+ for i, size := range []int{8, 16, 32, 64} {
+ if e.out[i] == nil {
+ continue // function doesn't exist
+ }
+ f := fmt.Sprintf("%s%d", e.name, size)
+ fmt.Fprintf(w, "\nfunc Example%s() {\n", f)
+ switch e.name {
+ case "RotateLeft", "Reverse", "ReverseBytes":
+ fmt.Fprintf(w, "\tfmt.Printf(\"%%0%db\\n\", %d)\n", size, e.in)
+ if e.name == "RotateLeft" {
+ fmt.Fprintf(w, "\tfmt.Printf(\"%%0%db\\n\", bits.%s(%d, 2))\n", size, f, e.in)
+ fmt.Fprintf(w, "\tfmt.Printf(\"%%0%db\\n\", bits.%s(%d, -2))\n", size, f, e.in)
+ } else {
+ fmt.Fprintf(w, "\tfmt.Printf(\"%%0%db\\n\", bits.%s(%d))\n", size, f, e.in)
+ }
+ fmt.Fprintf(w, "\t// Output:\n")
+ fmt.Fprintf(w, "\t// %0*b\n", size, e.in)
+ fmt.Fprintf(w, "\t// %0*b\n", size, e.out[i])
+ if e.name == "RotateLeft" && e.out2[i] != nil {
+ fmt.Fprintf(w, "\t// %0*b\n", size, e.out2[i])
+ }
+ default:
+ fmt.Fprintf(w, "\tfmt.Printf(\"%s(%%0%db) = %%d\\n\", %d, bits.%s(%d))\n", f, size, e.in, f, e.in)
+ fmt.Fprintf(w, "\t// Output:\n")
+ fmt.Fprintf(w, "\t// %s(%0*b) = %d\n", f, size, e.in, e.out[i])
+ }
+ fmt.Fprintf(w, "}\n")
+ }
+ }
+
+ if err := os.WriteFile("example_test.go", w.Bytes(), 0666); err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/bits/make_tables.go b/platform/dbops/binaries/go/go/src/math/bits/make_tables.go
new file mode 100644
index 0000000000000000000000000000000000000000..d067361a12358226ae654b468a8bed1e4a290cac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits/make_tables.go
@@ -0,0 +1,91 @@
+// 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 ignore
+
+// This program generates bits_tables.go.
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "go/format"
+ "io"
+ "log"
+ "os"
+)
+
+var header = []byte(`// 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.
+
+// Code generated by go run make_tables.go. DO NOT EDIT.
+
+package bits
+
+`)
+
+func main() {
+ buf := bytes.NewBuffer(header)
+
+ gen(buf, "ntz8tab", ntz8)
+ gen(buf, "pop8tab", pop8)
+ gen(buf, "rev8tab", rev8)
+ gen(buf, "len8tab", len8)
+
+ out, err := format.Source(buf.Bytes())
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ err = os.WriteFile("bits_tables.go", out, 0666)
+ if err != nil {
+ log.Fatal(err)
+ }
+}
+
+func gen(w io.Writer, name string, f func(uint8) uint8) {
+ // Use a const string to allow the compiler to constant-evaluate lookups at constant index.
+ fmt.Fprintf(w, "const %s = \"\"+\n\"", name)
+ for i := 0; i < 256; i++ {
+ fmt.Fprintf(w, "\\x%02x", f(uint8(i)))
+ if i%16 == 15 && i != 255 {
+ fmt.Fprint(w, "\"+\n\"")
+ }
+ }
+ fmt.Fprint(w, "\"\n\n")
+}
+
+func ntz8(x uint8) (n uint8) {
+ for x&1 == 0 && n < 8 {
+ x >>= 1
+ n++
+ }
+ return
+}
+
+func pop8(x uint8) (n uint8) {
+ for x != 0 {
+ x &= x - 1
+ n++
+ }
+ return
+}
+
+func rev8(x uint8) (r uint8) {
+ for i := 8; i > 0; i-- {
+ r = r<<1 | x&1
+ x >>= 1
+ }
+ return
+}
+
+func len8(x uint8) (n uint8) {
+ for x != 0 {
+ x >>= 1
+ n++
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/abs.go b/platform/dbops/binaries/go/go/src/math/cmplx/abs.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f89d1bcfc721e9ce7d9647771c3cca929915f4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/abs.go
@@ -0,0 +1,13 @@
+// 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 cmplx provides basic constants and mathematical functions for
+// complex numbers. Special case handling conforms to the C99 standard
+// Annex G IEC 60559-compatible complex arithmetic.
+package cmplx
+
+import "math"
+
+// Abs returns the absolute value (also called the modulus) of x.
+func Abs(x complex128) float64 { return math.Hypot(real(x), imag(x)) }
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/asin.go b/platform/dbops/binaries/go/go/src/math/cmplx/asin.go
new file mode 100644
index 0000000000000000000000000000000000000000..30d019e9d470524d34718358a9e8b015e92462f4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/asin.go
@@ -0,0 +1,221 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex circular arc sine
+//
+// DESCRIPTION:
+//
+// Inverse complex sine:
+// 2
+// w = -i clog( iz + csqrt( 1 - z ) ).
+//
+// casin(z) = -i casinh(iz)
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 10100 2.1e-15 3.4e-16
+// IEEE -10,+10 30000 2.2e-14 2.7e-15
+// Larger relative error can be observed for z near zero.
+// Also tested by csin(casin(z)) = z.
+
+// Asin returns the inverse sine of x.
+func Asin(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case im == 0 && math.Abs(re) <= 1:
+ return complex(math.Asin(re), im)
+ case re == 0 && math.Abs(im) <= 1:
+ return complex(re, math.Asinh(im))
+ case math.IsNaN(im):
+ switch {
+ case re == 0:
+ return complex(re, math.NaN())
+ case math.IsInf(re, 0):
+ return complex(math.NaN(), re)
+ default:
+ return NaN()
+ }
+ case math.IsInf(im, 0):
+ switch {
+ case math.IsNaN(re):
+ return x
+ case math.IsInf(re, 0):
+ return complex(math.Copysign(math.Pi/4, re), im)
+ default:
+ return complex(math.Copysign(0, re), im)
+ }
+ case math.IsInf(re, 0):
+ return complex(math.Copysign(math.Pi/2, re), math.Copysign(re, im))
+ }
+ ct := complex(-imag(x), real(x)) // i * x
+ xx := x * x
+ x1 := complex(1-real(xx), -imag(xx)) // 1 - x*x
+ x2 := Sqrt(x1) // x2 = sqrt(1 - x*x)
+ w := Log(ct + x2)
+ return complex(imag(w), -real(w)) // -i * w
+}
+
+// Asinh returns the inverse hyperbolic sine of x.
+func Asinh(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case im == 0 && math.Abs(re) <= 1:
+ return complex(math.Asinh(re), im)
+ case re == 0 && math.Abs(im) <= 1:
+ return complex(re, math.Asin(im))
+ case math.IsInf(re, 0):
+ switch {
+ case math.IsInf(im, 0):
+ return complex(re, math.Copysign(math.Pi/4, im))
+ case math.IsNaN(im):
+ return x
+ default:
+ return complex(re, math.Copysign(0.0, im))
+ }
+ case math.IsNaN(re):
+ switch {
+ case im == 0:
+ return x
+ case math.IsInf(im, 0):
+ return complex(im, re)
+ default:
+ return NaN()
+ }
+ case math.IsInf(im, 0):
+ return complex(math.Copysign(im, re), math.Copysign(math.Pi/2, im))
+ }
+ xx := x * x
+ x1 := complex(1+real(xx), imag(xx)) // 1 + x*x
+ return Log(x + Sqrt(x1)) // log(x + sqrt(1 + x*x))
+}
+
+// Complex circular arc cosine
+//
+// DESCRIPTION:
+//
+// w = arccos z = PI/2 - arcsin z.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 5200 1.6e-15 2.8e-16
+// IEEE -10,+10 30000 1.8e-14 2.2e-15
+
+// Acos returns the inverse cosine of x.
+func Acos(x complex128) complex128 {
+ w := Asin(x)
+ return complex(math.Pi/2-real(w), -imag(w))
+}
+
+// Acosh returns the inverse hyperbolic cosine of x.
+func Acosh(x complex128) complex128 {
+ if x == 0 {
+ return complex(0, math.Copysign(math.Pi/2, imag(x)))
+ }
+ w := Acos(x)
+ if imag(w) <= 0 {
+ return complex(-imag(w), real(w)) // i * w
+ }
+ return complex(imag(w), -real(w)) // -i * w
+}
+
+// Complex circular arc tangent
+//
+// DESCRIPTION:
+//
+// If
+// z = x + iy,
+//
+// then
+// 1 ( 2x )
+// Re w = - arctan(-----------) + k PI
+// 2 ( 2 2)
+// (1 - x - y )
+//
+// ( 2 2)
+// 1 (x + (y+1) )
+// Im w = - log(------------)
+// 4 ( 2 2)
+// (x + (y-1) )
+//
+// Where k is an arbitrary integer.
+//
+// catan(z) = -i catanh(iz).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 5900 1.3e-16 7.8e-18
+// IEEE -10,+10 30000 2.3e-15 8.5e-17
+// The check catan( ctan(z) ) = z, with |x| and |y| < PI/2,
+// had peak relative error 1.5e-16, rms relative error
+// 2.9e-17. See also clog().
+
+// Atan returns the inverse tangent of x.
+func Atan(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case im == 0:
+ return complex(math.Atan(re), im)
+ case re == 0 && math.Abs(im) <= 1:
+ return complex(re, math.Atanh(im))
+ case math.IsInf(im, 0) || math.IsInf(re, 0):
+ if math.IsNaN(re) {
+ return complex(math.NaN(), math.Copysign(0, im))
+ }
+ return complex(math.Copysign(math.Pi/2, re), math.Copysign(0, im))
+ case math.IsNaN(re) || math.IsNaN(im):
+ return NaN()
+ }
+ x2 := real(x) * real(x)
+ a := 1 - x2 - imag(x)*imag(x)
+ if a == 0 {
+ return NaN()
+ }
+ t := 0.5 * math.Atan2(2*real(x), a)
+ w := reducePi(t)
+
+ t = imag(x) - 1
+ b := x2 + t*t
+ if b == 0 {
+ return NaN()
+ }
+ t = imag(x) + 1
+ c := (x2 + t*t) / b
+ return complex(w, 0.25*math.Log(c))
+}
+
+// Atanh returns the inverse hyperbolic tangent of x.
+func Atanh(x complex128) complex128 {
+ z := complex(-imag(x), real(x)) // z = i * x
+ z = Atan(z)
+ return complex(imag(z), -real(z)) // z = -i * z
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/cmath_test.go b/platform/dbops/binaries/go/go/src/math/cmplx/cmath_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3011e8327d54eb59848b8bfd2d767e493a01892e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/cmath_test.go
@@ -0,0 +1,1589 @@
+// 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 cmplx
+
+import (
+ "math"
+ "testing"
+)
+
+// The higher-precision values in vc26 were used to derive the
+// input arguments vc (see also comment below). For reference
+// only (do not delete).
+var vc26 = []complex128{
+ (4.97901192488367350108546816 + 7.73887247457810456552351752i),
+ (7.73887247457810456552351752 - 0.27688005719200159404635997i),
+ (-0.27688005719200159404635997 - 5.01060361827107492160848778i),
+ (-5.01060361827107492160848778 + 9.63629370719841737980004837i),
+ (9.63629370719841737980004837 + 2.92637723924396464525443662i),
+ (2.92637723924396464525443662 + 5.22908343145930665230025625i),
+ (5.22908343145930665230025625 + 2.72793991043601025126008608i),
+ (2.72793991043601025126008608 + 1.82530809168085506044576505i),
+ (1.82530809168085506044576505 - 8.68592476857560136238589621i),
+ (-8.68592476857560136238589621 + 4.97901192488367350108546816i),
+}
+
+var vc = []complex128{
+ (4.9790119248836735e+00 + 7.7388724745781045e+00i),
+ (7.7388724745781045e+00 - 2.7688005719200159e-01i),
+ (-2.7688005719200159e-01 - 5.0106036182710749e+00i),
+ (-5.0106036182710749e+00 + 9.6362937071984173e+00i),
+ (9.6362937071984173e+00 + 2.9263772392439646e+00i),
+ (2.9263772392439646e+00 + 5.2290834314593066e+00i),
+ (5.2290834314593066e+00 + 2.7279399104360102e+00i),
+ (2.7279399104360102e+00 + 1.8253080916808550e+00i),
+ (1.8253080916808550e+00 - 8.6859247685756013e+00i),
+ (-8.6859247685756013e+00 + 4.9790119248836735e+00i),
+}
+
+// The expected results below were computed by the high precision calculators
+// at https://keisan.casio.com/. More exact input values (array vc[], above)
+// were obtained by printing them with "%.26f". The answers were calculated
+// to 26 digits (by using the "Digit number" drop-down control of each
+// calculator).
+
+var abs = []float64{
+ 9.2022120669932650313380972e+00,
+ 7.7438239742296106616261394e+00,
+ 5.0182478202557746902556648e+00,
+ 1.0861137372799545160704002e+01,
+ 1.0070841084922199607011905e+01,
+ 5.9922447613166942183705192e+00,
+ 5.8978784056736762299945176e+00,
+ 3.2822866700678709020367184e+00,
+ 8.8756430028990417290744307e+00,
+ 1.0011785496777731986390856e+01,
+}
+
+var acos = []complex128{
+ (1.0017679804707456328694569 - 2.9138232718554953784519807i),
+ (0.03606427612041407369636057 + 2.7358584434576260925091256i),
+ (1.6249365462333796703711823 + 2.3159537454335901187730929i),
+ (2.0485650849650740120660391 - 3.0795576791204117911123886i),
+ (0.29621132089073067282488147 - 3.0007392508200622519398814i),
+ (1.0664555914934156601503632 - 2.4872865024796011364747111i),
+ (0.48681307452231387690013905 - 2.463655912283054555225301i),
+ (0.6116977071277574248407752 - 1.8734458851737055262693056i),
+ (1.3649311280370181331184214 + 2.8793528632328795424123832i),
+ (2.6189310485682988308904501 - 2.9956543302898767795858704i),
+}
+var acosh = []complex128{
+ (2.9138232718554953784519807 + 1.0017679804707456328694569i),
+ (2.7358584434576260925091256 - 0.03606427612041407369636057i),
+ (2.3159537454335901187730929 - 1.6249365462333796703711823i),
+ (3.0795576791204117911123886 + 2.0485650849650740120660391i),
+ (3.0007392508200622519398814 + 0.29621132089073067282488147i),
+ (2.4872865024796011364747111 + 1.0664555914934156601503632i),
+ (2.463655912283054555225301 + 0.48681307452231387690013905i),
+ (1.8734458851737055262693056 + 0.6116977071277574248407752i),
+ (2.8793528632328795424123832 - 1.3649311280370181331184214i),
+ (2.9956543302898767795858704 + 2.6189310485682988308904501i),
+}
+var asin = []complex128{
+ (0.56902834632415098636186476 + 2.9138232718554953784519807i),
+ (1.5347320506744825455349611 - 2.7358584434576260925091256i),
+ (-0.054140219438483051139860579 - 2.3159537454335901187730929i),
+ (-0.47776875817017739283471738 + 3.0795576791204117911123886i),
+ (1.2745850059041659464064402 + 3.0007392508200622519398814i),
+ (0.50434073530148095908095852 + 2.4872865024796011364747111i),
+ (1.0839832522725827423311826 + 2.463655912283054555225301i),
+ (0.9590986196671391943905465 + 1.8734458851737055262693056i),
+ (0.20586519875787848611290031 - 2.8793528632328795424123832i),
+ (-1.0481347217734022116591284 + 2.9956543302898767795858704i),
+}
+var asinh = []complex128{
+ (2.9113760469415295679342185 + 0.99639459545704326759805893i),
+ (2.7441755423994259061579029 - 0.035468308789000500601119392i),
+ (-2.2962136462520690506126678 - 1.5144663565690151885726707i),
+ (-3.0771233459295725965402455 + 1.0895577967194013849422294i),
+ (3.0048366100923647417557027 + 0.29346979169819220036454168i),
+ (2.4800059370795363157364643 + 1.0545868606049165710424232i),
+ (2.4718773838309585611141821 + 0.47502344364250803363708842i),
+ (1.8910743588080159144378396 + 0.56882925572563602341139174i),
+ (2.8735426423367341878069406 - 1.362376149648891420997548i),
+ (-2.9981750586172477217567878 + 0.5183571985225367505624207i),
+}
+var atan = []complex128{
+ (1.5115747079332741358607654 + 0.091324403603954494382276776i),
+ (1.4424504323482602560806727 - 0.0045416132642803911503770933i),
+ (-1.5593488703630532674484026 - 0.20163295409248362456446431i),
+ (-1.5280619472445889867794105 + 0.081721556230672003746956324i),
+ (1.4759909163240799678221039 + 0.028602969320691644358773586i),
+ (1.4877353772046548932715555 + 0.14566877153207281663773599i),
+ (1.4206983927779191889826 + 0.076830486127880702249439993i),
+ (1.3162236060498933364869556 + 0.16031313000467530644933363i),
+ (1.5473450684303703578810093 - 0.11064907507939082484935782i),
+ (-1.4841462340185253987375812 + 0.049341850305024399493142411i),
+}
+var atanh = []complex128{
+ (0.058375027938968509064640438 + 1.4793488495105334458167782i),
+ (0.12977343497790381229915667 - 1.5661009410463561327262499i),
+ (-0.010576456067347252072200088 - 1.3743698658402284549750563i),
+ (-0.042218595678688358882784918 + 1.4891433968166405606692604i),
+ (0.095218997991316722061828397 + 1.5416884098777110330499698i),
+ (0.079965459366890323857556487 + 1.4252510353873192700350435i),
+ (0.15051245471980726221708301 + 1.4907432533016303804884461i),
+ (0.25082072933993987714470373 + 1.392057665392187516442986i),
+ (0.022896108815797135846276662 - 1.4609224989282864208963021i),
+ (-0.08665624101841876130537396 + 1.5207902036935093480142159i),
+}
+var conj = []complex128{
+ (4.9790119248836735e+00 - 7.7388724745781045e+00i),
+ (7.7388724745781045e+00 + 2.7688005719200159e-01i),
+ (-2.7688005719200159e-01 + 5.0106036182710749e+00i),
+ (-5.0106036182710749e+00 - 9.6362937071984173e+00i),
+ (9.6362937071984173e+00 - 2.9263772392439646e+00i),
+ (2.9263772392439646e+00 - 5.2290834314593066e+00i),
+ (5.2290834314593066e+00 - 2.7279399104360102e+00i),
+ (2.7279399104360102e+00 - 1.8253080916808550e+00i),
+ (1.8253080916808550e+00 + 8.6859247685756013e+00i),
+ (-8.6859247685756013e+00 - 4.9790119248836735e+00i),
+}
+var cos = []complex128{
+ (3.024540920601483938336569e+02 + 1.1073797572517071650045357e+03i),
+ (1.192858682649064973252758e-01 + 2.7857554122333065540970207e-01i),
+ (7.2144394304528306603857962e+01 - 2.0500129667076044169954205e+01i),
+ (2.24921952538403984190541e+03 - 7.317363745602773587049329e+03i),
+ (-9.148222970032421760015498e+00 + 1.953124661113563541862227e+00i),
+ (-9.116081175857732248227078e+01 - 1.992669213569952232487371e+01i),
+ (3.795639179042704640002918e+00 + 6.623513350981458399309662e+00i),
+ (-2.9144840732498869560679084e+00 - 1.214620271628002917638748e+00i),
+ (-7.45123482501299743872481e+02 + 2.8641692314488080814066734e+03i),
+ (-5.371977967039319076416747e+01 + 4.893348341339375830564624e+01i),
+}
+var cosh = []complex128{
+ (8.34638383523018249366948e+00 + 7.2181057886425846415112064e+01i),
+ (1.10421967379919366952251e+03 - 3.1379638689277575379469861e+02i),
+ (3.051485206773701584738512e-01 - 2.6805384730105297848044485e-01i),
+ (-7.33294728684187933370938e+01 + 1.574445942284918251038144e+01i),
+ (-7.478643293945957535757355e+03 + 1.6348382209913353929473321e+03i),
+ (4.622316522966235701630926e+00 - 8.088695185566375256093098e+00i),
+ (-8.544333183278877406197712e+01 + 3.7505836120128166455231717e+01i),
+ (-1.934457815021493925115198e+00 + 7.3725859611767228178358673e+00i),
+ (-2.352958770061749348353548e+00 - 2.034982010440878358915409e+00i),
+ (7.79756457532134748165069e+02 + 2.8549350716819176560377717e+03i),
+}
+var exp = []complex128{
+ (1.669197736864670815125146e+01 + 1.4436895109507663689174096e+02i),
+ (2.2084389286252583447276212e+03 - 6.2759289284909211238261917e+02i),
+ (2.227538273122775173434327e-01 + 7.2468284028334191250470034e-01i),
+ (-6.5182985958153548997881627e-03 - 1.39965837915193860879044e-03i),
+ (-1.4957286524084015746110777e+04 + 3.269676455931135688988042e+03i),
+ (9.218158701983105935659273e+00 - 1.6223985291084956009304582e+01i),
+ (-1.7088175716853040841444505e+02 + 7.501382609870410713795546e+01i),
+ (-3.852461315830959613132505e+00 + 1.4808420423156073221970892e+01i),
+ (-4.586775503301407379786695e+00 - 4.178501081246873415144744e+00i),
+ (4.451337963005453491095747e-05 - 1.62977574205442915935263e-04i),
+}
+var log = []complex128{
+ (2.2194438972179194425697051e+00 + 9.9909115046919291062461269e-01i),
+ (2.0468956191154167256337289e+00 - 3.5762575021856971295156489e-02i),
+ (1.6130808329853860438751244e+00 - 1.6259990074019058442232221e+00i),
+ (2.3851910394823008710032651e+00 + 2.0502936359659111755031062e+00i),
+ (2.3096442270679923004800651e+00 + 2.9483213155446756211881774e-01i),
+ (1.7904660933974656106951860e+00 + 1.0605860367252556281902109e+00i),
+ (1.7745926939841751666177512e+00 + 4.8084556083358307819310911e-01i),
+ (1.1885403350045342425648780e+00 + 5.8969634164776659423195222e-01i),
+ (2.1833107837679082586772505e+00 - 1.3636647724582455028314573e+00i),
+ (2.3037629487273259170991671e+00 + 2.6210913895386013290915234e+00i),
+}
+var log10 = []complex128{
+ (9.6389223745559042474184943e-01 + 4.338997735671419492599631e-01i),
+ (8.8895547241376579493490892e-01 - 1.5531488990643548254864806e-02i),
+ (7.0055210462945412305244578e-01 - 7.0616239649481243222248404e-01i),
+ (1.0358753067322445311676952e+00 + 8.9043121238134980156490909e-01i),
+ (1.003065742975330237172029e+00 + 1.2804396782187887479857811e-01i),
+ (7.7758954439739162532085157e-01 + 4.6060666333341810869055108e-01i),
+ (7.7069581462315327037689152e-01 + 2.0882857371769952195512475e-01i),
+ (5.1617650901191156135137239e-01 + 2.5610186717615977620363299e-01i),
+ (9.4819982567026639742663212e-01 - 5.9223208584446952284914289e-01i),
+ (1.0005115362454417135973429e+00 + 1.1383255270407412817250921e+00i),
+}
+
+type ff struct {
+ r, theta float64
+}
+
+var polar = []ff{
+ {9.2022120669932650313380972e+00, 9.9909115046919291062461269e-01},
+ {7.7438239742296106616261394e+00, -3.5762575021856971295156489e-02},
+ {5.0182478202557746902556648e+00, -1.6259990074019058442232221e+00},
+ {1.0861137372799545160704002e+01, 2.0502936359659111755031062e+00},
+ {1.0070841084922199607011905e+01, 2.9483213155446756211881774e-01},
+ {5.9922447613166942183705192e+00, 1.0605860367252556281902109e+00},
+ {5.8978784056736762299945176e+00, 4.8084556083358307819310911e-01},
+ {3.2822866700678709020367184e+00, 5.8969634164776659423195222e-01},
+ {8.8756430028990417290744307e+00, -1.3636647724582455028314573e+00},
+ {1.0011785496777731986390856e+01, 2.6210913895386013290915234e+00},
+}
+var pow = []complex128{
+ (-2.499956739197529585028819e+00 + 1.759751724335650228957144e+00i),
+ (7.357094338218116311191939e+04 - 5.089973412479151648145882e+04i),
+ (1.320777296067768517259592e+01 - 3.165621914333901498921986e+01i),
+ (-3.123287828297300934072149e-07 - 1.9849567521490553032502223e-7i),
+ (8.0622651468477229614813e+04 - 7.80028727944573092944363e+04i),
+ (-1.0268824572103165858577141e+00 - 4.716844738244989776610672e-01i),
+ (-4.35953819012244175753187e+01 + 2.2036445974645306917648585e+02i),
+ (8.3556092283250594950239e-01 - 1.2261571947167240272593282e+01i),
+ (1.582292972120769306069625e+03 + 1.273564263524278244782512e+04i),
+ (6.592208301642122149025369e-08 + 2.584887236651661903526389e-08i),
+}
+var sin = []complex128{
+ (-1.1073801774240233539648544e+03 + 3.024539773002502192425231e+02i),
+ (1.0317037521400759359744682e+00 - 3.2208979799929570242818e-02i),
+ (-2.0501952097271429804261058e+01 - 7.2137981348240798841800967e+01i),
+ (7.3173638080346338642193078e+03 + 2.249219506193664342566248e+03i),
+ (-1.964375633631808177565226e+00 - 9.0958264713870404464159683e+00i),
+ (1.992783647158514838337674e+01 - 9.11555769410191350416942e+01i),
+ (-6.680335650741921444300349e+00 + 3.763353833142432513086117e+00i),
+ (1.2794028166657459148245993e+00 - 2.7669092099795781155109602e+00i),
+ (2.8641693949535259594188879e+03 + 7.451234399649871202841615e+02i),
+ (-4.893811726244659135553033e+01 - 5.371469305562194635957655e+01i),
+}
+var sinh = []complex128{
+ (8.34559353341652565758198e+00 + 7.2187893208650790476628899e+01i),
+ (1.1042192548260646752051112e+03 - 3.1379650595631635858792056e+02i),
+ (-8.239469336509264113041849e-02 + 9.9273668758439489098514519e-01i),
+ (7.332295456982297798219401e+01 - 1.574585908122833444899023e+01i),
+ (-7.4786432301380582103534216e+03 + 1.63483823493980029604071e+03i),
+ (4.595842179016870234028347e+00 - 8.135290105518580753211484e+00i),
+ (-8.543842533574163435246793e+01 + 3.750798997857594068272375e+01i),
+ (-1.918003500809465688017307e+00 + 7.4358344619793504041350251e+00i),
+ (-2.233816733239658031433147e+00 - 2.143519070805995056229335e+00i),
+ (-7.797564130187551181105341e+02 - 2.8549352346594918614806877e+03i),
+}
+var sqrt = []complex128{
+ (2.6628203086086130543813948e+00 + 1.4531345674282185229796902e+00i),
+ (2.7823278427251986247149295e+00 - 4.9756907317005224529115567e-02i),
+ (1.5397025302089642757361015e+00 - 1.6271336573016637535695727e+00i),
+ (1.7103411581506875260277898e+00 + 2.8170677122737589676157029e+00i),
+ (3.1390392472953103383607947e+00 + 4.6612625849858653248980849e-01i),
+ (2.1117080764822417640789287e+00 + 1.2381170223514273234967850e+00i),
+ (2.3587032281672256703926939e+00 + 5.7827111903257349935720172e-01i),
+ (1.7335262588873410476661577e+00 + 5.2647258220721269141550382e-01i),
+ (2.3131094974708716531499282e+00 - 1.8775429304303785570775490e+00i),
+ (8.1420535745048086240947359e-01 + 3.0575897587277248522656113e+00i),
+}
+var tan = []complex128{
+ (-1.928757919086441129134525e-07 + 1.0000003267499169073251826e+00i),
+ (1.242412685364183792138948e+00 - 3.17149693883133370106696e+00i),
+ (-4.6745126251587795225571826e-05 - 9.9992439225263959286114298e-01i),
+ (4.792363401193648192887116e-09 + 1.0000000070589333451557723e+00i),
+ (2.345740824080089140287315e-03 + 9.947733046570988661022763e-01i),
+ (-2.396030789494815566088809e-05 + 9.9994781345418591429826779e-01i),
+ (-7.370204836644931340905303e-03 + 1.0043553413417138987717748e+00i),
+ (-3.691803847992048527007457e-02 + 9.6475071993469548066328894e-01i),
+ (-2.781955256713729368401878e-08 - 1.000000049848910609006646e+00i),
+ (9.4281590064030478879791249e-05 + 9.9999119340863718183758545e-01i),
+}
+var tanh = []complex128{
+ (1.0000921981225144748819918e+00 + 2.160986245871518020231507e-05i),
+ (9.9999967727531993209562591e-01 - 1.9953763222959658873657676e-07i),
+ (-1.765485739548037260789686e+00 + 1.7024216325552852445168471e+00i),
+ (-9.999189442732736452807108e-01 + 3.64906070494473701938098e-05i),
+ (9.9999999224622333738729767e-01 - 3.560088949517914774813046e-09i),
+ (1.0029324933367326862499343e+00 - 4.948790309797102353137528e-03i),
+ (9.9996113064788012488693567e-01 - 4.226995742097032481451259e-05i),
+ (1.0074784189316340029873945e+00 - 4.194050814891697808029407e-03i),
+ (9.9385534229718327109131502e-01 + 5.144217985914355502713437e-02i),
+ (-1.0000000491604982429364892e+00 - 2.901873195374433112227349e-08i),
+}
+
+// huge values along the real axis for testing reducePi in Tan
+var hugeIn = []complex128{
+ 1 << 28,
+ 1 << 29,
+ 1 << 30,
+ 1 << 35,
+ -1 << 120,
+ 1 << 240,
+ 1 << 300,
+ -1 << 480,
+ 1234567891234567 << 180,
+ -1234567891234567 << 300,
+}
+
+// Results for tanHuge[i] calculated with https://github.com/robpike/ivy
+// using 4096 bits of working precision.
+var tanHuge = []complex128{
+ 5.95641897939639421,
+ -0.34551069233430392,
+ -0.78469661331920043,
+ 0.84276385870875983,
+ 0.40806638884180424,
+ -0.37603456702698076,
+ 4.60901287677810962,
+ 3.39135965054779932,
+ -6.76813854009065030,
+ -0.76417695016604922,
+}
+
+// special cases conform to C99 standard appendix G.6 Complex arithmetic
+var inf, nan = math.Inf(1), math.NaN()
+
+var vcAbsSC = []complex128{
+ NaN(),
+}
+var absSC = []float64{
+ math.NaN(),
+}
+var acosSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.1.1
+ {complex(zero, zero),
+ complex(math.Pi/2, -zero)},
+ {complex(-zero, zero),
+ complex(math.Pi/2, -zero)},
+ {complex(zero, nan),
+ complex(math.Pi/2, nan)},
+ {complex(-zero, nan),
+ complex(math.Pi/2, nan)},
+ {complex(1.0, inf),
+ complex(math.Pi/2, -inf)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(-inf, 1.0),
+ complex(math.Pi, -inf)},
+ {complex(inf, 1.0),
+ complex(0.0, -inf)},
+ {complex(-inf, inf),
+ complex(3*math.Pi/4, -inf)},
+ {complex(inf, inf),
+ complex(math.Pi/4, -inf)},
+ {complex(inf, nan),
+ complex(nan, -inf)}, // imaginary sign unspecified
+ {complex(-inf, nan),
+ complex(nan, inf)}, // imaginary sign unspecified
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(nan, -inf)},
+ {NaN(),
+ NaN()},
+}
+var acoshSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.1
+ {complex(zero, zero),
+ complex(zero, math.Pi/2)},
+ {complex(-zero, zero),
+ complex(zero, math.Pi/2)},
+ {complex(1.0, inf),
+ complex(inf, math.Pi/2)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(-inf, 1.0),
+ complex(inf, math.Pi)},
+ {complex(inf, 1.0),
+ complex(inf, zero)},
+ {complex(-inf, inf),
+ complex(inf, 3*math.Pi/4)},
+ {complex(inf, inf),
+ complex(inf, math.Pi/4)},
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(-inf, nan),
+ complex(inf, nan)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(inf, nan)},
+ {NaN(),
+ NaN()},
+}
+var asinSC = []struct {
+ in,
+ want complex128
+}{
+ // Derived from Asin(z) = -i * Asinh(i * z), G.6 #7
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(1.0, inf),
+ complex(0, inf)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1),
+ complex(math.Pi/2, inf)},
+ {complex(inf, inf),
+ complex(math.Pi/4, inf)},
+ {complex(inf, nan),
+ complex(nan, inf)}, // imaginary sign unspecified
+ {complex(nan, zero),
+ NaN()},
+ {complex(nan, 1),
+ NaN()},
+ {complex(nan, inf),
+ complex(nan, inf)},
+ {NaN(),
+ NaN()},
+}
+var asinhSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.2
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(1.0, inf),
+ complex(inf, math.Pi/2)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1.0),
+ complex(inf, zero)},
+ {complex(inf, inf),
+ complex(inf, math.Pi/4)},
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(nan, zero),
+ complex(nan, zero)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(inf, nan)}, // sign of real part unspecified
+ {NaN(),
+ NaN()},
+}
+var atanSC = []struct {
+ in,
+ want complex128
+}{
+ // Derived from Atan(z) = -i * Atanh(i * z), G.6 #7
+ {complex(0, zero),
+ complex(0, zero)},
+ {complex(0, nan),
+ NaN()},
+ {complex(1.0, zero),
+ complex(math.Pi/4, zero)},
+ {complex(1.0, inf),
+ complex(math.Pi/2, zero)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1),
+ complex(math.Pi/2, zero)},
+ {complex(inf, inf),
+ complex(math.Pi/2, zero)},
+ {complex(inf, nan),
+ complex(math.Pi/2, zero)},
+ {complex(nan, 1),
+ NaN()},
+ {complex(nan, inf),
+ complex(nan, zero)},
+ {NaN(),
+ NaN()},
+}
+var atanhSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.3
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(zero, nan),
+ complex(zero, nan)},
+ {complex(1.0, zero),
+ complex(inf, zero)},
+ {complex(1.0, inf),
+ complex(0, math.Pi/2)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1.0),
+ complex(zero, math.Pi/2)},
+ {complex(inf, inf),
+ complex(zero, math.Pi/2)},
+ {complex(inf, nan),
+ complex(0, nan)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(zero, math.Pi/2)}, // sign of real part not specified.
+ {NaN(),
+ NaN()},
+}
+var vcConjSC = []complex128{
+ NaN(),
+}
+var conjSC = []complex128{
+ NaN(),
+}
+var cosSC = []struct {
+ in,
+ want complex128
+}{
+ // Derived from Cos(z) = Cosh(i * z), G.6 #7
+ {complex(zero, zero),
+ complex(1.0, -zero)},
+ {complex(zero, inf),
+ complex(inf, -zero)},
+ {complex(zero, nan),
+ complex(nan, zero)}, // imaginary sign unspecified
+ {complex(1.0, inf),
+ complex(inf, -inf)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, zero),
+ complex(nan, -zero)},
+ {complex(inf, 1.0),
+ NaN()},
+ {complex(inf, inf),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(inf, nan),
+ NaN()},
+ {complex(nan, zero),
+ complex(nan, -zero)}, // imaginary sign unspecified
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(inf, nan)},
+ {NaN(),
+ NaN()},
+}
+var coshSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.4
+ {complex(zero, zero),
+ complex(1.0, zero)},
+ {complex(zero, inf),
+ complex(nan, zero)}, // imaginary sign unspecified
+ {complex(zero, nan),
+ complex(nan, zero)}, // imaginary sign unspecified
+ {complex(1.0, inf),
+ NaN()},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, zero),
+ complex(inf, zero)},
+ {complex(inf, 1.0),
+ complex(inf*math.Cos(1.0), inf*math.Sin(1.0))}, // +inf cis(y)
+ {complex(inf, inf),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(nan, zero),
+ complex(nan, zero)}, // imaginary sign unspecified
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ NaN()},
+ {NaN(),
+ NaN()},
+}
+var expSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.3.1
+ {complex(zero, zero),
+ complex(1.0, zero)},
+ {complex(-zero, zero),
+ complex(1.0, zero)},
+ {complex(1.0, inf),
+ NaN()},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, zero),
+ complex(inf, zero)},
+ {complex(-inf, 1.0),
+ complex(math.Copysign(0.0, math.Cos(1.0)), math.Copysign(0.0, math.Sin(1.0)))}, // +0 cis(y)
+ {complex(inf, 1.0),
+ complex(inf*math.Cos(1.0), inf*math.Sin(1.0))}, // +inf cis(y)
+ {complex(-inf, inf),
+ complex(zero, zero)}, // real and imaginary sign unspecified
+ {complex(inf, inf),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(-inf, nan),
+ complex(zero, zero)}, // real and imaginary sign unspecified
+ {complex(inf, nan),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(nan, zero),
+ complex(nan, zero)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ NaN()},
+ {NaN(),
+ NaN()},
+}
+var vcIsNaNSC = []complex128{
+ complex(math.Inf(-1), math.Inf(-1)),
+ complex(math.Inf(-1), math.NaN()),
+ complex(math.NaN(), math.Inf(-1)),
+ complex(0, math.NaN()),
+ complex(math.NaN(), 0),
+ complex(math.Inf(1), math.Inf(1)),
+ complex(math.Inf(1), math.NaN()),
+ complex(math.NaN(), math.Inf(1)),
+ complex(math.NaN(), math.NaN()),
+}
+var isNaNSC = []bool{
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ true,
+}
+
+var logSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.3.2
+ {complex(zero, zero),
+ complex(-inf, zero)},
+ {complex(-zero, zero),
+ complex(-inf, math.Pi)},
+ {complex(1.0, inf),
+ complex(inf, math.Pi/2)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(-inf, 1.0),
+ complex(inf, math.Pi)},
+ {complex(inf, 1.0),
+ complex(inf, 0.0)},
+ {complex(-inf, inf),
+ complex(inf, 3*math.Pi/4)},
+ {complex(inf, inf),
+ complex(inf, math.Pi/4)},
+ {complex(-inf, nan),
+ complex(inf, nan)},
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(inf, nan)},
+ {NaN(),
+ NaN()},
+}
+var log10SC = []struct {
+ in,
+ want complex128
+}{
+ // derived from Log special cases via Log10(x) = math.Log10E*Log(x)
+ {complex(zero, zero),
+ complex(-inf, zero)},
+ {complex(-zero, zero),
+ complex(-inf, float64(math.Log10E)*float64(math.Pi))},
+ {complex(1.0, inf),
+ complex(inf, float64(math.Log10E)*float64(math.Pi/2))},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(-inf, 1.0),
+ complex(inf, float64(math.Log10E)*float64(math.Pi))},
+ {complex(inf, 1.0),
+ complex(inf, 0.0)},
+ {complex(-inf, inf),
+ complex(inf, float64(math.Log10E)*float64(3*math.Pi/4))},
+ {complex(inf, inf),
+ complex(inf, float64(math.Log10E)*float64(math.Pi/4))},
+ {complex(-inf, nan),
+ complex(inf, nan)},
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(inf, nan)},
+ {NaN(),
+ NaN()},
+}
+var vcPolarSC = []complex128{
+ NaN(),
+}
+var polarSC = []ff{
+ {math.NaN(), math.NaN()},
+}
+var vcPowSC = [][2]complex128{
+ {NaN(), NaN()},
+ {0, NaN()},
+}
+var powSC = []complex128{
+ NaN(),
+ NaN(),
+}
+var sinSC = []struct {
+ in,
+ want complex128
+}{
+ // Derived from Sin(z) = -i * Sinh(i * z), G.6 #7
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(zero, inf),
+ complex(zero, inf)},
+ {complex(zero, nan),
+ complex(zero, nan)},
+ {complex(1.0, inf),
+ complex(inf, inf)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, zero),
+ complex(nan, zero)},
+ {complex(inf, 1.0),
+ NaN()},
+ {complex(inf, inf),
+ complex(nan, inf)},
+ {complex(inf, nan),
+ NaN()},
+ {complex(nan, zero),
+ complex(nan, zero)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(nan, inf)},
+ {NaN(),
+ NaN()},
+}
+
+var sinhSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.5
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(zero, inf),
+ complex(zero, nan)}, // real sign unspecified
+ {complex(zero, nan),
+ complex(zero, nan)}, // real sign unspecified
+ {complex(1.0, inf),
+ NaN()},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, zero),
+ complex(inf, zero)},
+ {complex(inf, 1.0),
+ complex(inf*math.Cos(1.0), inf*math.Sin(1.0))}, // +inf cis(y)
+ {complex(inf, inf),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(inf, nan),
+ complex(inf, nan)}, // real sign unspecified
+ {complex(nan, zero),
+ complex(nan, zero)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ NaN()},
+ {NaN(),
+ NaN()},
+}
+
+var sqrtSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.4.2
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(-zero, zero),
+ complex(zero, zero)},
+ {complex(1.0, inf),
+ complex(inf, inf)},
+ {complex(nan, inf),
+ complex(inf, inf)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(-inf, 1.0),
+ complex(zero, inf)},
+ {complex(inf, 1.0),
+ complex(inf, zero)},
+ {complex(-inf, nan),
+ complex(nan, inf)}, // imaginary sign unspecified
+ {complex(inf, nan),
+ complex(inf, nan)},
+ {complex(nan, 1.0),
+ NaN()},
+ {NaN(),
+ NaN()},
+}
+var tanSC = []struct {
+ in,
+ want complex128
+}{
+ // Derived from Tan(z) = -i * Tanh(i * z), G.6 #7
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(zero, nan),
+ complex(zero, nan)},
+ {complex(1.0, inf),
+ complex(zero, 1.0)},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1.0),
+ NaN()},
+ {complex(inf, inf),
+ complex(zero, 1.0)},
+ {complex(inf, nan),
+ NaN()},
+ {complex(nan, zero),
+ NaN()},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ complex(zero, 1.0)},
+ {NaN(),
+ NaN()},
+}
+var tanhSC = []struct {
+ in,
+ want complex128
+}{
+ // G.6.2.6
+ {complex(zero, zero),
+ complex(zero, zero)},
+ {complex(1.0, inf),
+ NaN()},
+ {complex(1.0, nan),
+ NaN()},
+ {complex(inf, 1.0),
+ complex(1.0, math.Copysign(0.0, math.Sin(2*1.0)))}, // 1 + i 0 sin(2y)
+ {complex(inf, inf),
+ complex(1.0, zero)}, // imaginary sign unspecified
+ {complex(inf, nan),
+ complex(1.0, zero)}, // imaginary sign unspecified
+ {complex(nan, zero),
+ complex(nan, zero)},
+ {complex(nan, 1.0),
+ NaN()},
+ {complex(nan, inf),
+ NaN()},
+ {NaN(),
+ NaN()},
+}
+
+// branch cut continuity checks
+// points on each axis at |z| > 1 are checked for one-sided continuity from both the positive and negative side
+// all possible branch cuts for the elementary functions are at one of these points
+
+var zero = 0.0
+var eps = 1.0 / (1 << 53)
+
+var branchPoints = [][2]complex128{
+ {complex(2.0, zero), complex(2.0, eps)},
+ {complex(2.0, -zero), complex(2.0, -eps)},
+ {complex(-2.0, zero), complex(-2.0, eps)},
+ {complex(-2.0, -zero), complex(-2.0, -eps)},
+ {complex(zero, 2.0), complex(eps, 2.0)},
+ {complex(-zero, 2.0), complex(-eps, 2.0)},
+ {complex(zero, -2.0), complex(eps, -2.0)},
+ {complex(-zero, -2.0), complex(-eps, -2.0)},
+}
+
+// functions borrowed from pkg/math/all_test.go
+func tolerance(a, b, e float64) bool {
+ d := a - b
+ if d < 0 {
+ d = -d
+ }
+
+ // note: b is correct (expected) value, a is actual value.
+ // make error tolerance a fraction of b, not a.
+ if b != 0 {
+ e = e * b
+ if e < 0 {
+ e = -e
+ }
+ }
+ return d < e
+}
+func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) }
+func alike(a, b float64) bool {
+ switch {
+ case a != a && b != b: // math.IsNaN(a) && math.IsNaN(b):
+ return true
+ case a == b:
+ return math.Signbit(a) == math.Signbit(b)
+ }
+ return false
+}
+
+func cTolerance(a, b complex128, e float64) bool {
+ d := Abs(a - b)
+ if b != 0 {
+ e = e * Abs(b)
+ if e < 0 {
+ e = -e
+ }
+ }
+ return d < e
+}
+func cSoclose(a, b complex128, e float64) bool { return cTolerance(a, b, e) }
+func cVeryclose(a, b complex128) bool { return cTolerance(a, b, 4e-16) }
+func cAlike(a, b complex128) bool {
+ var realAlike, imagAlike bool
+ if isExact(real(b)) {
+ realAlike = alike(real(a), real(b))
+ } else {
+ // Allow non-exact special cases to have errors in ULP.
+ realAlike = veryclose(real(a), real(b))
+ }
+ if isExact(imag(b)) {
+ imagAlike = alike(imag(a), imag(b))
+ } else {
+ // Allow non-exact special cases to have errors in ULP.
+ imagAlike = veryclose(imag(a), imag(b))
+ }
+ return realAlike && imagAlike
+}
+func isExact(x float64) bool {
+ // Special cases that should match exactly. Other cases are multiples
+ // of Pi that may not be last bit identical on all platforms.
+ return math.IsNaN(x) || math.IsInf(x, 0) || x == 0 || x == 1 || x == -1
+}
+
+func TestAbs(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Abs(vc[i]); !veryclose(abs[i], f) {
+ t.Errorf("Abs(%g) = %g, want %g", vc[i], f, abs[i])
+ }
+ }
+ for i := 0; i < len(vcAbsSC); i++ {
+ if f := Abs(vcAbsSC[i]); !alike(absSC[i], f) {
+ t.Errorf("Abs(%g) = %g, want %g", vcAbsSC[i], f, absSC[i])
+ }
+ }
+}
+func TestAcos(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Acos(vc[i]); !cSoclose(acos[i], f, 1e-14) {
+ t.Errorf("Acos(%g) = %g, want %g", vc[i], f, acos[i])
+ }
+ }
+ for _, v := range acosSC {
+ if f := Acos(v.in); !cAlike(v.want, f) {
+ t.Errorf("Acos(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Acos(Conj(z)) == Conj(Acos(z))
+ if f := Acos(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Acos(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Acos(pt[0]), Acos(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Acos(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestAcosh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Acosh(vc[i]); !cSoclose(acosh[i], f, 1e-14) {
+ t.Errorf("Acosh(%g) = %g, want %g", vc[i], f, acosh[i])
+ }
+ }
+ for _, v := range acoshSC {
+ if f := Acosh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Acosh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Acosh(Conj(z)) == Conj(Acosh(z))
+ if f := Acosh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Acosh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Acosh(pt[0]), Acosh(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Acosh(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestAsin(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Asin(vc[i]); !cSoclose(asin[i], f, 1e-14) {
+ t.Errorf("Asin(%g) = %g, want %g", vc[i], f, asin[i])
+ }
+ }
+ for _, v := range asinSC {
+ if f := Asin(v.in); !cAlike(v.want, f) {
+ t.Errorf("Asin(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Asin(Conj(z)) == Asin(Sinh(z))
+ if f := Asin(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Asin(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Asin(-z) == -Asin(z)
+ if f := Asin(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Asin(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Asin(pt[0]), Asin(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Asin(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestAsinh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Asinh(vc[i]); !cSoclose(asinh[i], f, 4e-15) {
+ t.Errorf("Asinh(%g) = %g, want %g", vc[i], f, asinh[i])
+ }
+ }
+ for _, v := range asinhSC {
+ if f := Asinh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Asinh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Asinh(Conj(z)) == Asinh(Sinh(z))
+ if f := Asinh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Asinh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Asinh(-z) == -Asinh(z)
+ if f := Asinh(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Asinh(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Asinh(pt[0]), Asinh(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Asinh(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestAtan(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Atan(vc[i]); !cVeryclose(atan[i], f) {
+ t.Errorf("Atan(%g) = %g, want %g", vc[i], f, atan[i])
+ }
+ }
+ for _, v := range atanSC {
+ if f := Atan(v.in); !cAlike(v.want, f) {
+ t.Errorf("Atan(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Atan(Conj(z)) == Conj(Atan(z))
+ if f := Atan(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Atan(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Atan(-z) == -Atan(z)
+ if f := Atan(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Atan(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Atan(pt[0]), Atan(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Atan(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestAtanh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Atanh(vc[i]); !cVeryclose(atanh[i], f) {
+ t.Errorf("Atanh(%g) = %g, want %g", vc[i], f, atanh[i])
+ }
+ }
+ for _, v := range atanhSC {
+ if f := Atanh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Atanh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Atanh(Conj(z)) == Conj(Atanh(z))
+ if f := Atanh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Atanh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Atanh(-z) == -Atanh(z)
+ if f := Atanh(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Atanh(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Atanh(pt[0]), Atanh(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Atanh(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestConj(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Conj(vc[i]); !cVeryclose(conj[i], f) {
+ t.Errorf("Conj(%g) = %g, want %g", vc[i], f, conj[i])
+ }
+ }
+ for i := 0; i < len(vcConjSC); i++ {
+ if f := Conj(vcConjSC[i]); !cAlike(conjSC[i], f) {
+ t.Errorf("Conj(%g) = %g, want %g", vcConjSC[i], f, conjSC[i])
+ }
+ }
+}
+func TestCos(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Cos(vc[i]); !cSoclose(cos[i], f, 3e-15) {
+ t.Errorf("Cos(%g) = %g, want %g", vc[i], f, cos[i])
+ }
+ }
+ for _, v := range cosSC {
+ if f := Cos(v.in); !cAlike(v.want, f) {
+ t.Errorf("Cos(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Cos(Conj(z)) == Cos(Cosh(z))
+ if f := Cos(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Cos(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Cos(-z) == Cos(z)
+ if f := Cos(-v.in); !cAlike(v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Cos(%g) = %g, want %g", -v.in, f, v.want)
+ }
+ }
+}
+func TestCosh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Cosh(vc[i]); !cSoclose(cosh[i], f, 2e-15) {
+ t.Errorf("Cosh(%g) = %g, want %g", vc[i], f, cosh[i])
+ }
+ }
+ for _, v := range coshSC {
+ if f := Cosh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Cosh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Cosh(Conj(z)) == Conj(Cosh(z))
+ if f := Cosh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Cosh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Cosh(-z) == Cosh(z)
+ if f := Cosh(-v.in); !cAlike(v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Cosh(%g) = %g, want %g", -v.in, f, v.want)
+ }
+ }
+}
+func TestExp(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Exp(vc[i]); !cSoclose(exp[i], f, 1e-15) {
+ t.Errorf("Exp(%g) = %g, want %g", vc[i], f, exp[i])
+ }
+ }
+ for _, v := range expSC {
+ if f := Exp(v.in); !cAlike(v.want, f) {
+ t.Errorf("Exp(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Exp(Conj(z)) == Exp(Cosh(z))
+ if f := Exp(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Exp(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ }
+}
+func TestIsNaN(t *testing.T) {
+ for i := 0; i < len(vcIsNaNSC); i++ {
+ if f := IsNaN(vcIsNaNSC[i]); isNaNSC[i] != f {
+ t.Errorf("IsNaN(%v) = %v, want %v", vcIsNaNSC[i], f, isNaNSC[i])
+ }
+ }
+}
+func TestLog(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Log(vc[i]); !cVeryclose(log[i], f) {
+ t.Errorf("Log(%g) = %g, want %g", vc[i], f, log[i])
+ }
+ }
+ for _, v := range logSC {
+ if f := Log(v.in); !cAlike(v.want, f) {
+ t.Errorf("Log(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Log(Conj(z)) == Conj(Log(z))
+ if f := Log(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Log(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Log(pt[0]), Log(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Log(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestLog10(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Log10(vc[i]); !cVeryclose(log10[i], f) {
+ t.Errorf("Log10(%g) = %g, want %g", vc[i], f, log10[i])
+ }
+ }
+ for _, v := range log10SC {
+ if f := Log10(v.in); !cAlike(v.want, f) {
+ t.Errorf("Log10(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Log10(Conj(z)) == Conj(Log10(z))
+ if f := Log10(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Log10(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ }
+}
+func TestPolar(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if r, theta := Polar(vc[i]); !veryclose(polar[i].r, r) && !veryclose(polar[i].theta, theta) {
+ t.Errorf("Polar(%g) = %g, %g want %g, %g", vc[i], r, theta, polar[i].r, polar[i].theta)
+ }
+ }
+ for i := 0; i < len(vcPolarSC); i++ {
+ if r, theta := Polar(vcPolarSC[i]); !alike(polarSC[i].r, r) && !alike(polarSC[i].theta, theta) {
+ t.Errorf("Polar(%g) = %g, %g, want %g, %g", vcPolarSC[i], r, theta, polarSC[i].r, polarSC[i].theta)
+ }
+ }
+}
+func TestPow(t *testing.T) {
+ // Special cases for Pow(0, c).
+ var zero = complex(0, 0)
+ zeroPowers := [][2]complex128{
+ {0, 1 + 0i},
+ {1.5, 0 + 0i},
+ {-1.5, complex(math.Inf(0), 0)},
+ {-1.5 + 1.5i, Inf()},
+ }
+ for _, zp := range zeroPowers {
+ if f := Pow(zero, zp[0]); f != zp[1] {
+ t.Errorf("Pow(%g, %g) = %g, want %g", zero, zp[0], f, zp[1])
+ }
+ }
+ var a = complex(3.0, 3.0)
+ for i := 0; i < len(vc); i++ {
+ if f := Pow(a, vc[i]); !cSoclose(pow[i], f, 4e-15) {
+ t.Errorf("Pow(%g, %g) = %g, want %g", a, vc[i], f, pow[i])
+ }
+ }
+ for i := 0; i < len(vcPowSC); i++ {
+ if f := Pow(vcPowSC[i][0], vcPowSC[i][1]); !cAlike(powSC[i], f) {
+ t.Errorf("Pow(%g, %g) = %g, want %g", vcPowSC[i][0], vcPowSC[i][1], f, powSC[i])
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Pow(pt[0], 0.1), Pow(pt[1], 0.1); !cVeryclose(f0, f1) {
+ t.Errorf("Pow(%g, 0.1) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestRect(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Rect(polar[i].r, polar[i].theta); !cVeryclose(vc[i], f) {
+ t.Errorf("Rect(%g, %g) = %g want %g", polar[i].r, polar[i].theta, f, vc[i])
+ }
+ }
+ for i := 0; i < len(vcPolarSC); i++ {
+ if f := Rect(polarSC[i].r, polarSC[i].theta); !cAlike(vcPolarSC[i], f) {
+ t.Errorf("Rect(%g, %g) = %g, want %g", polarSC[i].r, polarSC[i].theta, f, vcPolarSC[i])
+ }
+ }
+}
+func TestSin(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Sin(vc[i]); !cSoclose(sin[i], f, 2e-15) {
+ t.Errorf("Sin(%g) = %g, want %g", vc[i], f, sin[i])
+ }
+ }
+ for _, v := range sinSC {
+ if f := Sin(v.in); !cAlike(v.want, f) {
+ t.Errorf("Sin(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Sin(Conj(z)) == Conj(Sin(z))
+ if f := Sin(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Sinh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Sin(-z) == -Sin(z)
+ if f := Sin(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Sinh(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+}
+func TestSinh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Sinh(vc[i]); !cSoclose(sinh[i], f, 2e-15) {
+ t.Errorf("Sinh(%g) = %g, want %g", vc[i], f, sinh[i])
+ }
+ }
+ for _, v := range sinhSC {
+ if f := Sinh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Sinh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Sinh(Conj(z)) == Conj(Sinh(z))
+ if f := Sinh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Sinh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Sinh(-z) == -Sinh(z)
+ if f := Sinh(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Sinh(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+}
+func TestSqrt(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Sqrt(vc[i]); !cVeryclose(sqrt[i], f) {
+ t.Errorf("Sqrt(%g) = %g, want %g", vc[i], f, sqrt[i])
+ }
+ }
+ for _, v := range sqrtSC {
+ if f := Sqrt(v.in); !cAlike(v.want, f) {
+ t.Errorf("Sqrt(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Sqrt(Conj(z)) == Conj(Sqrt(z))
+ if f := Sqrt(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Sqrt(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ }
+ for _, pt := range branchPoints {
+ if f0, f1 := Sqrt(pt[0]), Sqrt(pt[1]); !cVeryclose(f0, f1) {
+ t.Errorf("Sqrt(%g) not continuous, got %g want %g", pt[0], f0, f1)
+ }
+ }
+}
+func TestTan(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Tan(vc[i]); !cSoclose(tan[i], f, 3e-15) {
+ t.Errorf("Tan(%g) = %g, want %g", vc[i], f, tan[i])
+ }
+ }
+ for _, v := range tanSC {
+ if f := Tan(v.in); !cAlike(v.want, f) {
+ t.Errorf("Tan(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Tan(Conj(z)) == Conj(Tan(z))
+ if f := Tan(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Tan(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Tan(-z) == -Tan(z)
+ if f := Tan(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Tan(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+}
+func TestTanh(t *testing.T) {
+ for i := 0; i < len(vc); i++ {
+ if f := Tanh(vc[i]); !cSoclose(tanh[i], f, 2e-15) {
+ t.Errorf("Tanh(%g) = %g, want %g", vc[i], f, tanh[i])
+ }
+ }
+ for _, v := range tanhSC {
+ if f := Tanh(v.in); !cAlike(v.want, f) {
+ t.Errorf("Tanh(%g) = %g, want %g", v.in, f, v.want)
+ }
+ if math.IsNaN(imag(v.in)) || math.IsNaN(imag(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Tanh(Conj(z)) == Conj(Tanh(z))
+ if f := Tanh(Conj(v.in)); !cAlike(Conj(v.want), f) && !cAlike(v.in, Conj(v.in)) {
+ t.Errorf("Tanh(%g) = %g, want %g", Conj(v.in), f, Conj(v.want))
+ }
+ if math.IsNaN(real(v.in)) || math.IsNaN(real(v.want)) {
+ // Negating NaN is undefined with regard to the sign bit produced.
+ continue
+ }
+ // Tanh(-z) == -Tanh(z)
+ if f := Tanh(-v.in); !cAlike(-v.want, f) && !cAlike(v.in, -v.in) {
+ t.Errorf("Tanh(%g) = %g, want %g", -v.in, f, -v.want)
+ }
+ }
+}
+
+// See issue 17577
+func TestInfiniteLoopIntanSeries(t *testing.T) {
+ want := Inf()
+ if got := Cot(0); got != want {
+ t.Errorf("Cot(0): got %g, want %g", got, want)
+ }
+}
+
+func BenchmarkAbs(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Abs(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAcos(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Acos(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAcosh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Acosh(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAsin(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Asin(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAsinh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Asinh(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAtan(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Atan(complex(2.5, 3.5))
+ }
+}
+func BenchmarkAtanh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Atanh(complex(2.5, 3.5))
+ }
+}
+func BenchmarkConj(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Conj(complex(2.5, 3.5))
+ }
+}
+func BenchmarkCos(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Cos(complex(2.5, 3.5))
+ }
+}
+func BenchmarkCosh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Cosh(complex(2.5, 3.5))
+ }
+}
+func BenchmarkExp(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Exp(complex(2.5, 3.5))
+ }
+}
+func BenchmarkLog(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Log(complex(2.5, 3.5))
+ }
+}
+func BenchmarkLog10(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Log10(complex(2.5, 3.5))
+ }
+}
+func BenchmarkPhase(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Phase(complex(2.5, 3.5))
+ }
+}
+func BenchmarkPolar(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Polar(complex(2.5, 3.5))
+ }
+}
+func BenchmarkPow(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Pow(complex(2.5, 3.5), complex(2.5, 3.5))
+ }
+}
+func BenchmarkRect(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Rect(2.5, 1.5)
+ }
+}
+func BenchmarkSin(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Sin(complex(2.5, 3.5))
+ }
+}
+func BenchmarkSinh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Sinh(complex(2.5, 3.5))
+ }
+}
+func BenchmarkSqrt(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Sqrt(complex(2.5, 3.5))
+ }
+}
+func BenchmarkTan(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Tan(complex(2.5, 3.5))
+ }
+}
+func BenchmarkTanh(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Tanh(complex(2.5, 3.5))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/conj.go b/platform/dbops/binaries/go/go/src/math/cmplx/conj.go
new file mode 100644
index 0000000000000000000000000000000000000000..34a4277c11746dcdd80b4edf5185ec3daf10c06a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/conj.go
@@ -0,0 +1,8 @@
+// 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 cmplx
+
+// Conj returns the complex conjugate of x.
+func Conj(x complex128) complex128 { return complex(real(x), -imag(x)) }
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/example_test.go b/platform/dbops/binaries/go/go/src/math/cmplx/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0ed9631142295458aee9e3430ec0df0cf67333a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/example_test.go
@@ -0,0 +1,28 @@
+// 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 cmplx_test
+
+import (
+ "fmt"
+ "math"
+ "math/cmplx"
+)
+
+func ExampleAbs() {
+ fmt.Printf("%.1f", cmplx.Abs(3+4i))
+ // Output: 5.0
+}
+
+// ExampleExp computes Euler's identity.
+func ExampleExp() {
+ fmt.Printf("%.1f", cmplx.Exp(1i*math.Pi)+1)
+ // Output: (0.0+0.0i)
+}
+
+func ExamplePolar() {
+ r, theta := cmplx.Polar(2i)
+ fmt.Printf("r: %.1f, θ: %.1f*π", r, theta/math.Pi)
+ // Output: r: 2.0, θ: 0.5*π
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/exp.go b/platform/dbops/binaries/go/go/src/math/cmplx/exp.go
new file mode 100644
index 0000000000000000000000000000000000000000..d5d0a5d470c05defe6c29fd690d69b9ac2df8526
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/exp.go
@@ -0,0 +1,72 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex exponential function
+//
+// DESCRIPTION:
+//
+// Returns the complex exponential of the complex argument z.
+//
+// If
+// z = x + iy,
+// r = exp(x),
+// then
+// w = r cos y + i r sin y.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 8700 3.7e-17 1.1e-17
+// IEEE -10,+10 30000 3.0e-16 8.7e-17
+
+// Exp returns e**x, the base-e exponential of x.
+func Exp(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case math.IsInf(re, 0):
+ switch {
+ case re > 0 && im == 0:
+ return x
+ case math.IsInf(im, 0) || math.IsNaN(im):
+ if re < 0 {
+ return complex(0, math.Copysign(0, im))
+ } else {
+ return complex(math.Inf(1.0), math.NaN())
+ }
+ }
+ case math.IsNaN(re):
+ if im == 0 {
+ return complex(math.NaN(), im)
+ }
+ }
+ r := math.Exp(real(x))
+ s, c := math.Sincos(imag(x))
+ return complex(r*c, r*s)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/huge_test.go b/platform/dbops/binaries/go/go/src/math/cmplx/huge_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e794cf281abe6d24764d50390d80c5d9ad1f82f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/huge_test.go
@@ -0,0 +1,22 @@
+// 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.
+
+// Disabled for s390x because it uses assembly routines that are not
+// accurate for huge arguments.
+
+//go:build !s390x
+
+package cmplx
+
+import (
+ "testing"
+)
+
+func TestTanHuge(t *testing.T) {
+ for i, x := range hugeIn {
+ if f := Tan(x); !cSoclose(tanHuge[i], f, 3e-15) {
+ t.Errorf("Tan(%g) = %g, want %g", x, f, tanHuge[i])
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/isinf.go b/platform/dbops/binaries/go/go/src/math/cmplx/isinf.go
new file mode 100644
index 0000000000000000000000000000000000000000..6273cd3a6c16ba336c4eb8dda082173bde87e342
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/isinf.go
@@ -0,0 +1,21 @@
+// 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 cmplx
+
+import "math"
+
+// IsInf reports whether either real(x) or imag(x) is an infinity.
+func IsInf(x complex128) bool {
+ if math.IsInf(real(x), 0) || math.IsInf(imag(x), 0) {
+ return true
+ }
+ return false
+}
+
+// Inf returns a complex infinity, complex(+Inf, +Inf).
+func Inf() complex128 {
+ inf := math.Inf(1)
+ return complex(inf, inf)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/isnan.go b/platform/dbops/binaries/go/go/src/math/cmplx/isnan.go
new file mode 100644
index 0000000000000000000000000000000000000000..fed442cb483672306c0604f913c628c9fa16c798
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/isnan.go
@@ -0,0 +1,25 @@
+// 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 cmplx
+
+import "math"
+
+// IsNaN reports whether either real(x) or imag(x) is NaN
+// and neither is an infinity.
+func IsNaN(x complex128) bool {
+ switch {
+ case math.IsInf(real(x), 0) || math.IsInf(imag(x), 0):
+ return false
+ case math.IsNaN(real(x)) || math.IsNaN(imag(x)):
+ return true
+ }
+ return false
+}
+
+// NaN returns a complex “not-a-number” value.
+func NaN() complex128 {
+ nan := math.NaN()
+ return complex(nan, nan)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/log.go b/platform/dbops/binaries/go/go/src/math/cmplx/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd39c76cde10ee08963e3dac39e97b19ffa8e46e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/log.go
@@ -0,0 +1,65 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex natural logarithm
+//
+// DESCRIPTION:
+//
+// Returns complex logarithm to the base e (2.718...) of
+// the complex argument z.
+//
+// If
+// z = x + iy, r = sqrt( x**2 + y**2 ),
+// then
+// w = log(r) + i arctan(y/x).
+//
+// The arctangent ranges from -PI to +PI.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 7000 8.5e-17 1.9e-17
+// IEEE -10,+10 30000 5.0e-15 1.1e-16
+//
+// Larger relative error can be observed for z near 1 +i0.
+// In IEEE arithmetic the peak absolute error is 5.2e-16, rms
+// absolute error 1.0e-16.
+
+// Log returns the natural logarithm of x.
+func Log(x complex128) complex128 {
+ return complex(math.Log(Abs(x)), Phase(x))
+}
+
+// Log10 returns the decimal logarithm of x.
+func Log10(x complex128) complex128 {
+ z := Log(x)
+ return complex(math.Log10E*real(z), math.Log10E*imag(z))
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/phase.go b/platform/dbops/binaries/go/go/src/math/cmplx/phase.go
new file mode 100644
index 0000000000000000000000000000000000000000..03cece8a570060aef8c1a0143a486f60c2fe6a86
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/phase.go
@@ -0,0 +1,11 @@
+// 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 cmplx
+
+import "math"
+
+// Phase returns the phase (also called the argument) of x.
+// The returned value is in the range [-Pi, Pi].
+func Phase(x complex128) float64 { return math.Atan2(imag(x), real(x)) }
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/polar.go b/platform/dbops/binaries/go/go/src/math/cmplx/polar.go
new file mode 100644
index 0000000000000000000000000000000000000000..9b192bc6240b4a79c64a9313dd778e9026a227c9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/polar.go
@@ -0,0 +1,12 @@
+// 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 cmplx
+
+// Polar returns the absolute value r and phase θ of x,
+// such that x = r * e**θi.
+// The phase is in the range [-Pi, Pi].
+func Polar(x complex128) (r, θ float64) {
+ return Abs(x), Phase(x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/pow.go b/platform/dbops/binaries/go/go/src/math/cmplx/pow.go
new file mode 100644
index 0000000000000000000000000000000000000000..434f80f4cb18d480f072be78c55d381f2a7b168d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/pow.go
@@ -0,0 +1,82 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex power function
+//
+// DESCRIPTION:
+//
+// Raises complex A to the complex Zth power.
+// Definition is per AMS55 # 4.2.8,
+// analytically equivalent to cpow(a,z) = cexp(z clog(a)).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -10,+10 30000 9.4e-15 1.5e-15
+
+// Pow returns x**y, the base-x exponential of y.
+// For generalized compatibility with [math.Pow]:
+//
+// Pow(0, ±0) returns 1+0i
+// Pow(0, c) for real(c)<0 returns Inf+0i if imag(c) is zero, otherwise Inf+Inf i.
+func Pow(x, y complex128) complex128 {
+ if x == 0 { // Guaranteed also true for x == -0.
+ if IsNaN(y) {
+ return NaN()
+ }
+ r, i := real(y), imag(y)
+ switch {
+ case r == 0:
+ return 1
+ case r < 0:
+ if i == 0 {
+ return complex(math.Inf(1), 0)
+ }
+ return Inf()
+ case r > 0:
+ return 0
+ }
+ panic("not reached")
+ }
+ modulus := Abs(x)
+ if modulus == 0 {
+ return complex(0, 0)
+ }
+ r := math.Pow(modulus, real(y))
+ arg := Phase(x)
+ theta := real(y) * arg
+ if imag(y) != 0 {
+ r *= math.Exp(-imag(y) * arg)
+ theta += imag(y) * math.Log(modulus)
+ }
+ s, c := math.Sincos(theta)
+ return complex(r*c, r*s)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/rect.go b/platform/dbops/binaries/go/go/src/math/cmplx/rect.go
new file mode 100644
index 0000000000000000000000000000000000000000..bf94d787ea402966effccd155f49dd667355eb8e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/rect.go
@@ -0,0 +1,13 @@
+// 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 cmplx
+
+import "math"
+
+// Rect returns the complex number x with polar coordinates r, θ.
+func Rect(r, θ float64) complex128 {
+ s, c := math.Sincos(θ)
+ return complex(r*c, r*s)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/sin.go b/platform/dbops/binaries/go/go/src/math/cmplx/sin.go
new file mode 100644
index 0000000000000000000000000000000000000000..51cf40566dc6129279ac3c454ce3563731f1242f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/sin.go
@@ -0,0 +1,184 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex circular sine
+//
+// DESCRIPTION:
+//
+// If
+// z = x + iy,
+//
+// then
+//
+// w = sin x cosh y + i cos x sinh y.
+//
+// csin(z) = -i csinh(iz).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 8400 5.3e-17 1.3e-17
+// IEEE -10,+10 30000 3.8e-16 1.0e-16
+// Also tested by csin(casin(z)) = z.
+
+// Sin returns the sine of x.
+func Sin(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case im == 0 && (math.IsInf(re, 0) || math.IsNaN(re)):
+ return complex(math.NaN(), im)
+ case math.IsInf(im, 0):
+ switch {
+ case re == 0:
+ return x
+ case math.IsInf(re, 0) || math.IsNaN(re):
+ return complex(math.NaN(), im)
+ }
+ case re == 0 && math.IsNaN(im):
+ return x
+ }
+ s, c := math.Sincos(real(x))
+ sh, ch := sinhcosh(imag(x))
+ return complex(s*ch, c*sh)
+}
+
+// Complex hyperbolic sine
+//
+// DESCRIPTION:
+//
+// csinh z = (cexp(z) - cexp(-z))/2
+// = sinh x * cos y + i cosh x * sin y .
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -10,+10 30000 3.1e-16 8.2e-17
+
+// Sinh returns the hyperbolic sine of x.
+func Sinh(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case re == 0 && (math.IsInf(im, 0) || math.IsNaN(im)):
+ return complex(re, math.NaN())
+ case math.IsInf(re, 0):
+ switch {
+ case im == 0:
+ return complex(re, im)
+ case math.IsInf(im, 0) || math.IsNaN(im):
+ return complex(re, math.NaN())
+ }
+ case im == 0 && math.IsNaN(re):
+ return complex(math.NaN(), im)
+ }
+ s, c := math.Sincos(imag(x))
+ sh, ch := sinhcosh(real(x))
+ return complex(c*sh, s*ch)
+}
+
+// Complex circular cosine
+//
+// DESCRIPTION:
+//
+// If
+// z = x + iy,
+//
+// then
+//
+// w = cos x cosh y - i sin x sinh y.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 8400 4.5e-17 1.3e-17
+// IEEE -10,+10 30000 3.8e-16 1.0e-16
+
+// Cos returns the cosine of x.
+func Cos(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case im == 0 && (math.IsInf(re, 0) || math.IsNaN(re)):
+ return complex(math.NaN(), -im*math.Copysign(0, re))
+ case math.IsInf(im, 0):
+ switch {
+ case re == 0:
+ return complex(math.Inf(1), -re*math.Copysign(0, im))
+ case math.IsInf(re, 0) || math.IsNaN(re):
+ return complex(math.Inf(1), math.NaN())
+ }
+ case re == 0 && math.IsNaN(im):
+ return complex(math.NaN(), 0)
+ }
+ s, c := math.Sincos(real(x))
+ sh, ch := sinhcosh(imag(x))
+ return complex(c*ch, -s*sh)
+}
+
+// Complex hyperbolic cosine
+//
+// DESCRIPTION:
+//
+// ccosh(z) = cosh x cos y + i sinh x sin y .
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -10,+10 30000 2.9e-16 8.1e-17
+
+// Cosh returns the hyperbolic cosine of x.
+func Cosh(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case re == 0 && (math.IsInf(im, 0) || math.IsNaN(im)):
+ return complex(math.NaN(), re*math.Copysign(0, im))
+ case math.IsInf(re, 0):
+ switch {
+ case im == 0:
+ return complex(math.Inf(1), im*math.Copysign(0, re))
+ case math.IsInf(im, 0) || math.IsNaN(im):
+ return complex(math.Inf(1), math.NaN())
+ }
+ case im == 0 && math.IsNaN(re):
+ return complex(math.NaN(), im)
+ }
+ s, c := math.Sincos(imag(x))
+ sh, ch := sinhcosh(real(x))
+ return complex(c*ch, s*sh)
+}
+
+// calculate sinh and cosh.
+func sinhcosh(x float64) (sh, ch float64) {
+ if math.Abs(x) <= 0.5 {
+ return math.Sinh(x), math.Cosh(x)
+ }
+ e := math.Exp(x)
+ ei := 0.5 / e
+ e *= 0.5
+ return e - ei, e + ei
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/sqrt.go b/platform/dbops/binaries/go/go/src/math/cmplx/sqrt.go
new file mode 100644
index 0000000000000000000000000000000000000000..eddce2fdfbd46f6095a8985df49a329400972846
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/sqrt.go
@@ -0,0 +1,107 @@
+// 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 cmplx
+
+import "math"
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex square root
+//
+// DESCRIPTION:
+//
+// If z = x + iy, r = |z|, then
+//
+// 1/2
+// Re w = [ (r + x)/2 ] ,
+//
+// 1/2
+// Im w = [ (r - x)/2 ] .
+//
+// Cancellation error in r-x or r+x is avoided by using the
+// identity 2 Re w Im w = y.
+//
+// Note that -w is also a square root of z. The root chosen
+// is always in the right half plane and Im w has the same sign as y.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 25000 3.2e-17 9.6e-18
+// IEEE -10,+10 1,000,000 2.9e-16 6.1e-17
+
+// Sqrt returns the square root of x.
+// The result r is chosen so that real(r) ≥ 0 and imag(r) has the same sign as imag(x).
+func Sqrt(x complex128) complex128 {
+ if imag(x) == 0 {
+ // Ensure that imag(r) has the same sign as imag(x) for imag(x) == signed zero.
+ if real(x) == 0 {
+ return complex(0, imag(x))
+ }
+ if real(x) < 0 {
+ return complex(0, math.Copysign(math.Sqrt(-real(x)), imag(x)))
+ }
+ return complex(math.Sqrt(real(x)), imag(x))
+ } else if math.IsInf(imag(x), 0) {
+ return complex(math.Inf(1.0), imag(x))
+ }
+ if real(x) == 0 {
+ if imag(x) < 0 {
+ r := math.Sqrt(-0.5 * imag(x))
+ return complex(r, -r)
+ }
+ r := math.Sqrt(0.5 * imag(x))
+ return complex(r, r)
+ }
+ a := real(x)
+ b := imag(x)
+ var scale float64
+ // Rescale to avoid internal overflow or underflow.
+ if math.Abs(a) > 4 || math.Abs(b) > 4 {
+ a *= 0.25
+ b *= 0.25
+ scale = 2
+ } else {
+ a *= 1.8014398509481984e16 // 2**54
+ b *= 1.8014398509481984e16
+ scale = 7.450580596923828125e-9 // 2**-27
+ }
+ r := math.Hypot(a, b)
+ var t float64
+ if a > 0 {
+ t = math.Sqrt(0.5*r + 0.5*a)
+ r = scale * math.Abs((0.5*b)/t)
+ t *= scale
+ } else {
+ r = math.Sqrt(0.5*r - 0.5*a)
+ t = scale * math.Abs((0.5*b)/r)
+ r *= scale
+ }
+ if b < 0 {
+ return complex(t, -r)
+ }
+ return complex(t, r)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cmplx/tan.go b/platform/dbops/binaries/go/go/src/math/cmplx/tan.go
new file mode 100644
index 0000000000000000000000000000000000000000..67a1133a6f432280690b935d2018a1d3689c0b57
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cmplx/tan.go
@@ -0,0 +1,297 @@
+// 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 cmplx
+
+import (
+ "math"
+ "math/bits"
+)
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
+// The go code is a simplified version of the original C.
+//
+// Cephes Math Library Release 2.8: June, 2000
+// Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+//
+// The readme file at http://netlib.sandia.gov/cephes/ says:
+// Some software in this archive may be from the book _Methods and
+// Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
+// International, 1989) or from the Cephes Mathematical Library, a
+// commercial product. In either event, it is copyrighted by the author.
+// What you see here may be used freely but it comes with no support or
+// guarantee.
+//
+// The two known misprints in the book are repaired here in the
+// source listings for the gamma function and the incomplete beta
+// integral.
+//
+// Stephen L. Moshier
+// moshier@na-net.ornl.gov
+
+// Complex circular tangent
+//
+// DESCRIPTION:
+//
+// If
+// z = x + iy,
+//
+// then
+//
+// sin 2x + i sinh 2y
+// w = --------------------.
+// cos 2x + cosh 2y
+//
+// On the real axis the denominator is zero at odd multiples
+// of PI/2. The denominator is evaluated by its Taylor
+// series near these points.
+//
+// ctan(z) = -i ctanh(iz).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 5200 7.1e-17 1.6e-17
+// IEEE -10,+10 30000 7.2e-16 1.2e-16
+// Also tested by ctan * ccot = 1 and catan(ctan(z)) = z.
+
+// Tan returns the tangent of x.
+func Tan(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case math.IsInf(im, 0):
+ switch {
+ case math.IsInf(re, 0) || math.IsNaN(re):
+ return complex(math.Copysign(0, re), math.Copysign(1, im))
+ }
+ return complex(math.Copysign(0, math.Sin(2*re)), math.Copysign(1, im))
+ case re == 0 && math.IsNaN(im):
+ return x
+ }
+ d := math.Cos(2*real(x)) + math.Cosh(2*imag(x))
+ if math.Abs(d) < 0.25 {
+ d = tanSeries(x)
+ }
+ if d == 0 {
+ return Inf()
+ }
+ return complex(math.Sin(2*real(x))/d, math.Sinh(2*imag(x))/d)
+}
+
+// Complex hyperbolic tangent
+//
+// DESCRIPTION:
+//
+// tanh z = (sinh 2x + i sin 2y) / (cosh 2x + cos 2y) .
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -10,+10 30000 1.7e-14 2.4e-16
+
+// Tanh returns the hyperbolic tangent of x.
+func Tanh(x complex128) complex128 {
+ switch re, im := real(x), imag(x); {
+ case math.IsInf(re, 0):
+ switch {
+ case math.IsInf(im, 0) || math.IsNaN(im):
+ return complex(math.Copysign(1, re), math.Copysign(0, im))
+ }
+ return complex(math.Copysign(1, re), math.Copysign(0, math.Sin(2*im)))
+ case im == 0 && math.IsNaN(re):
+ return x
+ }
+ d := math.Cosh(2*real(x)) + math.Cos(2*imag(x))
+ if d == 0 {
+ return Inf()
+ }
+ return complex(math.Sinh(2*real(x))/d, math.Sin(2*imag(x))/d)
+}
+
+// reducePi reduces the input argument x to the range (-Pi/2, Pi/2].
+// x must be greater than or equal to 0. For small arguments it
+// uses Cody-Waite reduction in 3 float64 parts based on:
+// "Elementary Function Evaluation: Algorithms and Implementation"
+// Jean-Michel Muller, 1997.
+// For very large arguments it uses Payne-Hanek range reduction based on:
+// "ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit"
+// K. C. Ng et al, March 24, 1992.
+func reducePi(x float64) float64 {
+ // reduceThreshold is the maximum value of x where the reduction using
+ // Cody-Waite reduction still gives accurate results. This threshold
+ // is set by t*PIn being representable as a float64 without error
+ // where t is given by t = floor(x * (1 / Pi)) and PIn are the leading partial
+ // terms of Pi. Since the leading terms, PI1 and PI2 below, have 30 and 32
+ // trailing zero bits respectively, t should have less than 30 significant bits.
+ // t < 1<<30 -> floor(x*(1/Pi)+0.5) < 1<<30 -> x < (1<<30-1) * Pi - 0.5
+ // So, conservatively we can take x < 1<<30.
+ const reduceThreshold float64 = 1 << 30
+ if math.Abs(x) < reduceThreshold {
+ // Use Cody-Waite reduction in three parts.
+ const (
+ // PI1, PI2 and PI3 comprise an extended precision value of PI
+ // such that PI ~= PI1 + PI2 + PI3. The parts are chosen so
+ // that PI1 and PI2 have an approximately equal number of trailing
+ // zero bits. This ensures that t*PI1 and t*PI2 are exact for
+ // large integer values of t. The full precision PI3 ensures the
+ // approximation of PI is accurate to 102 bits to handle cancellation
+ // during subtraction.
+ PI1 = 3.141592502593994 // 0x400921fb40000000
+ PI2 = 1.5099578831723193e-07 // 0x3e84442d00000000
+ PI3 = 1.0780605716316238e-14 // 0x3d08469898cc5170
+ )
+ t := x / math.Pi
+ t += 0.5
+ t = float64(int64(t)) // int64(t) = the multiple
+ return ((x - t*PI1) - t*PI2) - t*PI3
+ }
+ // Must apply Payne-Hanek range reduction
+ const (
+ mask = 0x7FF
+ shift = 64 - 11 - 1
+ bias = 1023
+ fracMask = 1<>shift&mask) - bias - shift
+ ix &= fracMask
+ ix |= 1 << shift
+
+ // mPi is the binary digits of 1/Pi as a uint64 array,
+ // that is, 1/Pi = Sum mPi[i]*2^(-64*i).
+ // 19 64-bit digits give 1216 bits of precision
+ // to handle the largest possible float64 exponent.
+ var mPi = [...]uint64{
+ 0x0000000000000000,
+ 0x517cc1b727220a94,
+ 0xfe13abe8fa9a6ee0,
+ 0x6db14acc9e21c820,
+ 0xff28b1d5ef5de2b0,
+ 0xdb92371d2126e970,
+ 0x0324977504e8c90e,
+ 0x7f0ef58e5894d39f,
+ 0x74411afa975da242,
+ 0x74ce38135a2fbf20,
+ 0x9cc8eb1cc1a99cfa,
+ 0x4e422fc5defc941d,
+ 0x8ffc4bffef02cc07,
+ 0xf79788c5ad05368f,
+ 0xb69b3f6793e584db,
+ 0xa7a31fb34f2ff516,
+ 0xba93dd63f5f2f8bd,
+ 0x9e839cfbc5294975,
+ 0x35fdafd88fc6ae84,
+ 0x2b0198237e3db5d5,
+ }
+ // Use the exponent to extract the 3 appropriate uint64 digits from mPi,
+ // B ~ (z0, z1, z2), such that the product leading digit has the exponent -64.
+ // Note, exp >= 50 since x >= reduceThreshold and exp < 971 for maximum float64.
+ digit, bitshift := uint(exp+64)/64, uint(exp+64)%64
+ z0 := (mPi[digit] << bitshift) | (mPi[digit+1] >> (64 - bitshift))
+ z1 := (mPi[digit+1] << bitshift) | (mPi[digit+2] >> (64 - bitshift))
+ z2 := (mPi[digit+2] << bitshift) | (mPi[digit+3] >> (64 - bitshift))
+ // Multiply mantissa by the digits and extract the upper two digits (hi, lo).
+ z2hi, _ := bits.Mul64(z2, ix)
+ z1hi, z1lo := bits.Mul64(z1, ix)
+ z0lo := z0 * ix
+ lo, c := bits.Add64(z1lo, z2hi, 0)
+ hi, _ := bits.Add64(z0lo, z1hi, c)
+ // Find the magnitude of the fraction.
+ lz := uint(bits.LeadingZeros64(hi))
+ e := uint64(bias - (lz + 1))
+ // Clear implicit mantissa bit and shift into place.
+ hi = (hi << (lz + 1)) | (lo >> (64 - (lz + 1)))
+ hi >>= 64 - shift
+ // Include the exponent and convert to a float.
+ hi |= e << shift
+ x = math.Float64frombits(hi)
+ // map to (-Pi/2, Pi/2]
+ if x > 0.5 {
+ x--
+ }
+ return math.Pi * x
+}
+
+// Taylor series expansion for cosh(2y) - cos(2x)
+func tanSeries(z complex128) float64 {
+ const MACHEP = 1.0 / (1 << 53)
+ x := math.Abs(2 * real(z))
+ y := math.Abs(2 * imag(z))
+ x = reducePi(x)
+ x = x * x
+ y = y * y
+ x2 := 1.0
+ y2 := 1.0
+ f := 1.0
+ rn := 0.0
+ d := 0.0
+ for {
+ rn++
+ f *= rn
+ rn++
+ f *= rn
+ x2 *= x
+ y2 *= y
+ t := y2 + x2
+ t /= f
+ d += t
+
+ rn++
+ f *= rn
+ rn++
+ f *= rn
+ x2 *= x
+ y2 *= y
+ t = y2 - x2
+ t /= f
+ d += t
+ if !(math.Abs(t/d) > MACHEP) {
+ // Caution: Use ! and > instead of <= for correct behavior if t/d is NaN.
+ // See issue 17577.
+ break
+ }
+ }
+ return d
+}
+
+// Complex circular cotangent
+//
+// DESCRIPTION:
+//
+// If
+// z = x + iy,
+//
+// then
+//
+// sin 2x - i sinh 2y
+// w = --------------------.
+// cosh 2y - cos 2x
+//
+// On the real axis, the denominator has zeros at even
+// multiples of PI/2. Near these points it is evaluated
+// by a Taylor series.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10,+10 3000 6.5e-17 1.6e-17
+// IEEE -10,+10 30000 9.2e-16 1.2e-16
+// Also tested by ctan * ccot = 1 + i0.
+
+// Cot returns the cotangent of x.
+func Cot(x complex128) complex128 {
+ d := math.Cosh(2*imag(x)) - math.Cos(2*real(x))
+ if math.Abs(d) < 0.25 {
+ d = tanSeries(x)
+ }
+ if d == 0 {
+ return Inf()
+ }
+ return complex(math.Sin(2*real(x))/d, -math.Sinh(2*imag(x))/d)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/auto_test.go b/platform/dbops/binaries/go/go/src/math/rand/auto_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b057370eea95ce522b65cc43f1bef0aed9f8d62a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/auto_test.go
@@ -0,0 +1,40 @@
+// 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 rand_test
+
+import (
+ . "math/rand"
+ "testing"
+)
+
+// This test is first, in its own file with an alphabetically early name,
+// to try to make sure that it runs early. It has the best chance of
+// detecting deterministic seeding if it's the first test that runs.
+
+func TestAuto(t *testing.T) {
+ // Pull out 10 int64s from the global source
+ // and then check that they don't appear in that
+ // order in the deterministic Seed(1) result.
+ var out []int64
+ for i := 0; i < 10; i++ {
+ out = append(out, Int63())
+ }
+
+ // Look for out in Seed(1)'s output.
+ // Strictly speaking, we should look for them in order,
+ // but this is good enough and not significantly more
+ // likely to have a false positive.
+ Seed(1)
+ found := 0
+ for i := 0; i < 1000; i++ {
+ x := Int63()
+ if x == out[found] {
+ found++
+ if found == len(out) {
+ t.Fatalf("found unseeded output in Seed(1) output")
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/default_test.go b/platform/dbops/binaries/go/go/src/math/rand/default_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..19fd75dfd1770a21e0165cfbcc7feeddcf171e4e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/default_test.go
@@ -0,0 +1,148 @@
+// 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 rand_test
+
+import (
+ "fmt"
+ "internal/race"
+ "internal/testenv"
+ . "math/rand"
+ "os"
+ "runtime"
+ "strconv"
+ "sync"
+ "testing"
+)
+
+// Test that racy access to the default functions behaves reasonably.
+func TestDefaultRace(t *testing.T) {
+ // Skip the test in short mode, but even in short mode run
+ // the test if we are using the race detector, because part
+ // of this is to see whether the race detector reports any problems.
+ if testing.Short() && !race.Enabled {
+ t.Skip("skipping starting another executable in short mode")
+ }
+
+ const env = "GO_RAND_TEST_HELPER_CODE"
+ if v := os.Getenv(env); v != "" {
+ doDefaultTest(t, v)
+ return
+ }
+
+ t.Parallel()
+
+ for i := 0; i < 6; i++ {
+ i := i
+ t.Run(strconv.Itoa(i), func(t *testing.T) {
+ t.Parallel()
+ exe, err := os.Executable()
+ if err != nil {
+ exe = os.Args[0]
+ }
+ cmd := testenv.Command(t, exe, "-test.run=TestDefaultRace")
+ cmd = testenv.CleanCmdEnv(cmd)
+ cmd.Env = append(cmd.Env, fmt.Sprintf("GO_RAND_TEST_HELPER_CODE=%d", i/2))
+ if i%2 != 0 {
+ cmd.Env = append(cmd.Env, "GODEBUG=randautoseed=0")
+ }
+ out, err := cmd.CombinedOutput()
+ if len(out) > 0 {
+ t.Logf("%s", out)
+ }
+ if err != nil {
+ t.Error(err)
+ }
+ })
+ }
+}
+
+// doDefaultTest should be run before there have been any calls to the
+// top-level math/rand functions. Make sure that we can make concurrent
+// calls to top-level functions and to Seed without any duplicate values.
+// This will also give the race detector a change to report any problems.
+func doDefaultTest(t *testing.T, v string) {
+ code, err := strconv.Atoi(v)
+ if err != nil {
+ t.Fatalf("internal error: unrecognized code %q", v)
+ }
+
+ goroutines := runtime.GOMAXPROCS(0)
+ if goroutines < 4 {
+ goroutines = 4
+ }
+
+ ch := make(chan uint64, goroutines*3)
+ var wg sync.WaitGroup
+
+ // The various tests below should not cause race detector reports
+ // and should not produce duplicate results.
+ //
+ // Note: these tests can theoretically fail when using fastrand64
+ // in that it is possible to coincidentally get the same random
+ // number twice. That could happen something like 1 / 2**64 times,
+ // which is rare enough that it may never happen. We don't worry
+ // about that case.
+
+ switch code {
+ case 0:
+ // Call Seed and Uint64 concurrently.
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func(s int64) {
+ defer wg.Done()
+ Seed(s)
+ }(int64(i) + 100)
+ }
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ ch <- Uint64()
+ }()
+ }
+ case 1:
+ // Call Uint64 concurrently with no Seed.
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ ch <- Uint64()
+ }()
+ }
+ case 2:
+ // Start with Uint64 to pick the fast source, then call
+ // Seed and Uint64 concurrently.
+ ch <- Uint64()
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func(s int64) {
+ defer wg.Done()
+ Seed(s)
+ }(int64(i) + 100)
+ }
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ ch <- Uint64()
+ }()
+ }
+ default:
+ t.Fatalf("internal error: unrecognized code %d", code)
+ }
+
+ go func() {
+ wg.Wait()
+ close(ch)
+ }()
+
+ m := make(map[uint64]bool)
+ for i := range ch {
+ if m[i] {
+ t.Errorf("saw %d twice", i)
+ }
+ m[i] = true
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/example_test.go b/platform/dbops/binaries/go/go/src/math/rand/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d656f470ebbfd66f5f7a9c1f5bd91510112f2b91
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/example_test.go
@@ -0,0 +1,133 @@
+// 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 rand_test
+
+import (
+ "fmt"
+ "math/rand"
+ "os"
+ "strings"
+ "text/tabwriter"
+)
+
+// These tests serve as an example but also make sure we don't change
+// the output of the random number generator when given a fixed seed.
+
+func Example() {
+ answers := []string{
+ "It is certain",
+ "It is decidedly so",
+ "Without a doubt",
+ "Yes definitely",
+ "You may rely on it",
+ "As I see it yes",
+ "Most likely",
+ "Outlook good",
+ "Yes",
+ "Signs point to yes",
+ "Reply hazy try again",
+ "Ask again later",
+ "Better not tell you now",
+ "Cannot predict now",
+ "Concentrate and ask again",
+ "Don't count on it",
+ "My reply is no",
+ "My sources say no",
+ "Outlook not so good",
+ "Very doubtful",
+ }
+ fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])
+}
+
+// This example shows the use of each of the methods on a *Rand.
+// The use of the global functions is the same, without the receiver.
+func Example_rand() {
+ // Create and seed the generator.
+ // Typically a non-fixed seed should be used, such as time.Now().UnixNano().
+ // Using a fixed seed will produce the same output on every run.
+ r := rand.New(rand.NewSource(99))
+
+ // The tabwriter here helps us generate aligned output.
+ w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
+ defer w.Flush()
+ show := func(name string, v1, v2, v3 any) {
+ fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
+ }
+
+ // Float32 and Float64 values are in [0, 1).
+ show("Float32", r.Float32(), r.Float32(), r.Float32())
+ show("Float64", r.Float64(), r.Float64(), r.Float64())
+
+ // ExpFloat64 values have an average of 1 but decay exponentially.
+ show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
+
+ // NormFloat64 values have an average of 0 and a standard deviation of 1.
+ show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
+
+ // Int31, Int63, and Uint32 generate values of the given width.
+ // The Int method (not shown) is like either Int31 or Int63
+ // depending on the size of 'int'.
+ show("Int31", r.Int31(), r.Int31(), r.Int31())
+ show("Int63", r.Int63(), r.Int63(), r.Int63())
+ show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
+
+ // Intn, Int31n, and Int63n limit their output to be < n.
+ // They do so more carefully than using r.Int()%n.
+ show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
+ show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
+ show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))
+
+ // Perm generates a random permutation of the numbers [0, n).
+ show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
+ // Output:
+ // Float32 0.2635776 0.6358173 0.6718283
+ // Float64 0.628605430454327 0.4504798828572669 0.9562755949377957
+ // ExpFloat64 0.3362240648200941 1.4256072328483647 0.24354758816173044
+ // NormFloat64 0.17233959114940064 1.577014951434847 0.04259129641113857
+ // Int31 1501292890 1486668269 182840835
+ // Int63 3546343826724305832 5724354148158589552 5239846799706671610
+ // Uint32 2760229429 296659907 1922395059
+ // Intn(10) 1 2 5
+ // Int31n(10) 4 7 8
+ // Int63n(10) 7 6 3
+ // Perm [1 4 2 3 0] [4 2 1 3 0] [1 2 4 0 3]
+}
+
+func ExamplePerm() {
+ for _, value := range rand.Perm(3) {
+ fmt.Println(value)
+ }
+
+ // Unordered output: 1
+ // 2
+ // 0
+}
+
+func ExampleShuffle() {
+ words := strings.Fields("ink runs from the corners of my mouth")
+ rand.Shuffle(len(words), func(i, j int) {
+ words[i], words[j] = words[j], words[i]
+ })
+ fmt.Println(words)
+}
+
+func ExampleShuffle_slicesInUnison() {
+ numbers := []byte("12345")
+ letters := []byte("ABCDE")
+ // Shuffle numbers, swapping corresponding entries in letters at the same time.
+ rand.Shuffle(len(numbers), func(i, j int) {
+ numbers[i], numbers[j] = numbers[j], numbers[i]
+ letters[i], letters[j] = letters[j], letters[i]
+ })
+ for i := range numbers {
+ fmt.Printf("%c: %c\n", letters[i], numbers[i])
+ }
+}
+
+func ExampleIntn() {
+ fmt.Println(rand.Intn(100))
+ fmt.Println(rand.Intn(100))
+ fmt.Println(rand.Intn(100))
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/exp.go b/platform/dbops/binaries/go/go/src/math/rand/exp.go
new file mode 100644
index 0000000000000000000000000000000000000000..55d7d7de8ac5d641e38a467887d302199bc08a19
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/exp.go
@@ -0,0 +1,221 @@
+// 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 rand
+
+import (
+ "math"
+)
+
+/*
+ * Exponential distribution
+ *
+ * See "The Ziggurat Method for Generating Random Variables"
+ * (Marsaglia & Tsang, 2000)
+ * https://www.jstatsoft.org/v05/i08/paper [pdf]
+ */
+
+const (
+ re = 7.69711747013104972
+)
+
+// ExpFloat64 returns an exponentially distributed float64 in the range
+// (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter
+// (lambda) is 1 and whose mean is 1/lambda (1).
+// To produce a distribution with a different rate parameter,
+// callers can adjust the output using:
+//
+// sample = ExpFloat64() / desiredRateParameter
+func (r *Rand) ExpFloat64() float64 {
+ for {
+ j := r.Uint32()
+ i := j & 0xFF
+ x := float64(j) * float64(we[i])
+ if j < ke[i] {
+ return x
+ }
+ if i == 0 {
+ return re - math.Log(r.Float64())
+ }
+ if fe[i]+float32(r.Float64())*(fe[i-1]-fe[i]) < float32(math.Exp(-x)) {
+ return x
+ }
+ }
+}
+
+var ke = [256]uint32{
+ 0xe290a139, 0x0, 0x9beadebc, 0xc377ac71, 0xd4ddb990,
+ 0xde893fb8, 0xe4a8e87c, 0xe8dff16a, 0xebf2deab, 0xee49a6e8,
+ 0xf0204efd, 0xf19bdb8e, 0xf2d458bb, 0xf3da104b, 0xf4b86d78,
+ 0xf577ad8a, 0xf61de83d, 0xf6afb784, 0xf730a573, 0xf7a37651,
+ 0xf80a5bb6, 0xf867189d, 0xf8bb1b4f, 0xf9079062, 0xf94d70ca,
+ 0xf98d8c7d, 0xf9c8928a, 0xf9ff175b, 0xfa319996, 0xfa6085f8,
+ 0xfa8c3a62, 0xfab5084e, 0xfadb36c8, 0xfaff0410, 0xfb20a6ea,
+ 0xfb404fb4, 0xfb5e2951, 0xfb7a59e9, 0xfb95038c, 0xfbae44ba,
+ 0xfbc638d8, 0xfbdcf892, 0xfbf29a30, 0xfc0731df, 0xfc1ad1ed,
+ 0xfc2d8b02, 0xfc3f6c4d, 0xfc5083ac, 0xfc60ddd1, 0xfc708662,
+ 0xfc7f8810, 0xfc8decb4, 0xfc9bbd62, 0xfca9027c, 0xfcb5c3c3,
+ 0xfcc20864, 0xfccdd70a, 0xfcd935e3, 0xfce42ab0, 0xfceebace,
+ 0xfcf8eb3b, 0xfd02c0a0, 0xfd0c3f59, 0xfd156b7b, 0xfd1e48d6,
+ 0xfd26daff, 0xfd2f2552, 0xfd372af7, 0xfd3eeee5, 0xfd4673e7,
+ 0xfd4dbc9e, 0xfd54cb85, 0xfd5ba2f2, 0xfd62451b, 0xfd68b415,
+ 0xfd6ef1da, 0xfd750047, 0xfd7ae120, 0xfd809612, 0xfd8620b4,
+ 0xfd8b8285, 0xfd90bcf5, 0xfd95d15e, 0xfd9ac10b, 0xfd9f8d36,
+ 0xfda43708, 0xfda8bf9e, 0xfdad2806, 0xfdb17141, 0xfdb59c46,
+ 0xfdb9a9fd, 0xfdbd9b46, 0xfdc170f6, 0xfdc52bd8, 0xfdc8ccac,
+ 0xfdcc542d, 0xfdcfc30b, 0xfdd319ef, 0xfdd6597a, 0xfdd98245,
+ 0xfddc94e5, 0xfddf91e6, 0xfde279ce, 0xfde54d1f, 0xfde80c52,
+ 0xfdeab7de, 0xfded5034, 0xfdefd5be, 0xfdf248e3, 0xfdf4aa06,
+ 0xfdf6f984, 0xfdf937b6, 0xfdfb64f4, 0xfdfd818d, 0xfdff8dd0,
+ 0xfe018a08, 0xfe03767a, 0xfe05536c, 0xfe07211c, 0xfe08dfc9,
+ 0xfe0a8fab, 0xfe0c30fb, 0xfe0dc3ec, 0xfe0f48b1, 0xfe10bf76,
+ 0xfe122869, 0xfe1383b4, 0xfe14d17c, 0xfe1611e7, 0xfe174516,
+ 0xfe186b2a, 0xfe19843e, 0xfe1a9070, 0xfe1b8fd6, 0xfe1c8289,
+ 0xfe1d689b, 0xfe1e4220, 0xfe1f0f26, 0xfe1fcfbc, 0xfe2083ed,
+ 0xfe212bc3, 0xfe21c745, 0xfe225678, 0xfe22d95f, 0xfe234ffb,
+ 0xfe23ba4a, 0xfe241849, 0xfe2469f2, 0xfe24af3c, 0xfe24e81e,
+ 0xfe25148b, 0xfe253474, 0xfe2547c7, 0xfe254e70, 0xfe25485a,
+ 0xfe25356a, 0xfe251586, 0xfe24e88f, 0xfe24ae64, 0xfe2466e1,
+ 0xfe2411df, 0xfe23af34, 0xfe233eb4, 0xfe22c02c, 0xfe22336b,
+ 0xfe219838, 0xfe20ee58, 0xfe20358c, 0xfe1f6d92, 0xfe1e9621,
+ 0xfe1daef0, 0xfe1cb7ac, 0xfe1bb002, 0xfe1a9798, 0xfe196e0d,
+ 0xfe1832fd, 0xfe16e5fe, 0xfe15869d, 0xfe141464, 0xfe128ed3,
+ 0xfe10f565, 0xfe0f478c, 0xfe0d84b1, 0xfe0bac36, 0xfe09bd73,
+ 0xfe07b7b5, 0xfe059a40, 0xfe03644c, 0xfe011504, 0xfdfeab88,
+ 0xfdfc26e9, 0xfdf98629, 0xfdf6c83b, 0xfdf3ec01, 0xfdf0f04a,
+ 0xfdedd3d1, 0xfdea953d, 0xfde7331e, 0xfde3abe9, 0xfddffdfb,
+ 0xfddc2791, 0xfdd826cd, 0xfdd3f9a8, 0xfdcf9dfc, 0xfdcb1176,
+ 0xfdc65198, 0xfdc15bb3, 0xfdbc2ce2, 0xfdb6c206, 0xfdb117be,
+ 0xfdab2a63, 0xfda4f5fd, 0xfd9e7640, 0xfd97a67a, 0xfd908192,
+ 0xfd8901f2, 0xfd812182, 0xfd78d98e, 0xfd7022bb, 0xfd66f4ed,
+ 0xfd5d4732, 0xfd530f9c, 0xfd48432b, 0xfd3cd59a, 0xfd30b936,
+ 0xfd23dea4, 0xfd16349e, 0xfd07a7a3, 0xfcf8219b, 0xfce7895b,
+ 0xfcd5c220, 0xfcc2aadb, 0xfcae1d5e, 0xfc97ed4e, 0xfc7fe6d4,
+ 0xfc65ccf3, 0xfc495762, 0xfc2a2fc8, 0xfc07ee19, 0xfbe213c1,
+ 0xfbb8051a, 0xfb890078, 0xfb5411a5, 0xfb180005, 0xfad33482,
+ 0xfa839276, 0xfa263b32, 0xf9b72d1c, 0xf930a1a2, 0xf889f023,
+ 0xf7b577d2, 0xf69c650c, 0xf51530f0, 0xf2cb0e3c, 0xeeefb15d,
+ 0xe6da6ecf,
+}
+var we = [256]float32{
+ 2.0249555e-09, 1.486674e-11, 2.4409617e-11, 3.1968806e-11,
+ 3.844677e-11, 4.4228204e-11, 4.9516443e-11, 5.443359e-11,
+ 5.905944e-11, 6.344942e-11, 6.7643814e-11, 7.1672945e-11,
+ 7.556032e-11, 7.932458e-11, 8.298079e-11, 8.654132e-11,
+ 9.0016515e-11, 9.3415074e-11, 9.674443e-11, 1.0001099e-10,
+ 1.03220314e-10, 1.06377254e-10, 1.09486115e-10, 1.1255068e-10,
+ 1.1557435e-10, 1.1856015e-10, 1.2151083e-10, 1.2442886e-10,
+ 1.2731648e-10, 1.3017575e-10, 1.3300853e-10, 1.3581657e-10,
+ 1.3860142e-10, 1.4136457e-10, 1.4410738e-10, 1.4683108e-10,
+ 1.4953687e-10, 1.5222583e-10, 1.54899e-10, 1.5755733e-10,
+ 1.6020171e-10, 1.6283301e-10, 1.6545203e-10, 1.6805951e-10,
+ 1.7065617e-10, 1.732427e-10, 1.7581973e-10, 1.7838787e-10,
+ 1.8094774e-10, 1.8349985e-10, 1.8604476e-10, 1.8858298e-10,
+ 1.9111498e-10, 1.9364126e-10, 1.9616223e-10, 1.9867835e-10,
+ 2.0119004e-10, 2.0369768e-10, 2.0620168e-10, 2.087024e-10,
+ 2.1120022e-10, 2.136955e-10, 2.1618855e-10, 2.1867974e-10,
+ 2.2116936e-10, 2.2365775e-10, 2.261452e-10, 2.2863202e-10,
+ 2.311185e-10, 2.3360494e-10, 2.360916e-10, 2.3857874e-10,
+ 2.4106667e-10, 2.4355562e-10, 2.4604588e-10, 2.485377e-10,
+ 2.5103128e-10, 2.5352695e-10, 2.560249e-10, 2.585254e-10,
+ 2.6102867e-10, 2.6353494e-10, 2.6604446e-10, 2.6855745e-10,
+ 2.7107416e-10, 2.7359479e-10, 2.761196e-10, 2.7864877e-10,
+ 2.8118255e-10, 2.8372119e-10, 2.8626485e-10, 2.888138e-10,
+ 2.9136826e-10, 2.939284e-10, 2.9649452e-10, 2.9906677e-10,
+ 3.016454e-10, 3.0423064e-10, 3.0682268e-10, 3.0942177e-10,
+ 3.1202813e-10, 3.1464195e-10, 3.1726352e-10, 3.19893e-10,
+ 3.2253064e-10, 3.251767e-10, 3.2783135e-10, 3.3049485e-10,
+ 3.3316744e-10, 3.3584938e-10, 3.3854083e-10, 3.4124212e-10,
+ 3.4395342e-10, 3.46675e-10, 3.4940711e-10, 3.5215003e-10,
+ 3.5490397e-10, 3.5766917e-10, 3.6044595e-10, 3.6323455e-10,
+ 3.660352e-10, 3.6884823e-10, 3.7167386e-10, 3.745124e-10,
+ 3.773641e-10, 3.802293e-10, 3.8310827e-10, 3.860013e-10,
+ 3.8890866e-10, 3.918307e-10, 3.9476775e-10, 3.9772008e-10,
+ 4.0068804e-10, 4.0367196e-10, 4.0667217e-10, 4.09689e-10,
+ 4.1272286e-10, 4.1577405e-10, 4.1884296e-10, 4.2192994e-10,
+ 4.250354e-10, 4.281597e-10, 4.313033e-10, 4.3446652e-10,
+ 4.3764986e-10, 4.408537e-10, 4.4407847e-10, 4.4732465e-10,
+ 4.5059267e-10, 4.5388301e-10, 4.571962e-10, 4.6053267e-10,
+ 4.6389292e-10, 4.6727755e-10, 4.70687e-10, 4.741219e-10,
+ 4.7758275e-10, 4.810702e-10, 4.845848e-10, 4.8812715e-10,
+ 4.9169796e-10, 4.9529775e-10, 4.989273e-10, 5.0258725e-10,
+ 5.0627835e-10, 5.100013e-10, 5.1375687e-10, 5.1754584e-10,
+ 5.21369e-10, 5.2522725e-10, 5.2912136e-10, 5.330522e-10,
+ 5.370208e-10, 5.4102806e-10, 5.45075e-10, 5.491625e-10,
+ 5.532918e-10, 5.5746385e-10, 5.616799e-10, 5.6594107e-10,
+ 5.7024857e-10, 5.746037e-10, 5.7900773e-10, 5.834621e-10,
+ 5.8796823e-10, 5.925276e-10, 5.971417e-10, 6.018122e-10,
+ 6.065408e-10, 6.113292e-10, 6.1617933e-10, 6.2109295e-10,
+ 6.260722e-10, 6.3111916e-10, 6.3623595e-10, 6.4142497e-10,
+ 6.4668854e-10, 6.5202926e-10, 6.5744976e-10, 6.6295286e-10,
+ 6.6854156e-10, 6.742188e-10, 6.79988e-10, 6.858526e-10,
+ 6.9181616e-10, 6.978826e-10, 7.04056e-10, 7.103407e-10,
+ 7.167412e-10, 7.2326256e-10, 7.2990985e-10, 7.366886e-10,
+ 7.4360473e-10, 7.5066453e-10, 7.5787476e-10, 7.6524265e-10,
+ 7.7277595e-10, 7.80483e-10, 7.883728e-10, 7.9645507e-10,
+ 8.047402e-10, 8.1323964e-10, 8.219657e-10, 8.309319e-10,
+ 8.401528e-10, 8.496445e-10, 8.594247e-10, 8.6951274e-10,
+ 8.799301e-10, 8.9070046e-10, 9.018503e-10, 9.134092e-10,
+ 9.254101e-10, 9.378904e-10, 9.508923e-10, 9.644638e-10,
+ 9.786603e-10, 9.935448e-10, 1.0091913e-09, 1.025686e-09,
+ 1.0431306e-09, 1.0616465e-09, 1.08138e-09, 1.1025096e-09,
+ 1.1252564e-09, 1.1498986e-09, 1.1767932e-09, 1.206409e-09,
+ 1.2393786e-09, 1.276585e-09, 1.3193139e-09, 1.3695435e-09,
+ 1.4305498e-09, 1.508365e-09, 1.6160854e-09, 1.7921248e-09,
+}
+var fe = [256]float32{
+ 1, 0.9381437, 0.90046996, 0.87170434, 0.8477855, 0.8269933,
+ 0.8084217, 0.7915276, 0.77595687, 0.7614634, 0.7478686,
+ 0.7350381, 0.72286767, 0.71127474, 0.70019263, 0.6895665,
+ 0.67935055, 0.6695063, 0.66000086, 0.65080583, 0.6418967,
+ 0.63325197, 0.6248527, 0.6166822, 0.60872537, 0.60096896,
+ 0.5934009, 0.58601034, 0.5787874, 0.57172304, 0.5648092,
+ 0.5580383, 0.5514034, 0.5448982, 0.5385169, 0.53225386,
+ 0.5261042, 0.52006316, 0.5141264, 0.50828975, 0.5025495,
+ 0.496902, 0.49134386, 0.485872, 0.48048335, 0.4751752,
+ 0.46994483, 0.46478975, 0.45970762, 0.45469615, 0.44975325,
+ 0.44487688, 0.44006512, 0.43531612, 0.43062815, 0.42599955,
+ 0.42142874, 0.4169142, 0.41245446, 0.40804818, 0.403694,
+ 0.3993907, 0.39513698, 0.39093173, 0.38677382, 0.38266218,
+ 0.37859577, 0.37457356, 0.37059465, 0.3666581, 0.362763,
+ 0.35890847, 0.35509375, 0.351318, 0.3475805, 0.34388044,
+ 0.34021714, 0.3365899, 0.33299807, 0.32944095, 0.32591796,
+ 0.3224285, 0.3189719, 0.31554767, 0.31215525, 0.30879408,
+ 0.3054636, 0.3021634, 0.29889292, 0.2956517, 0.29243928,
+ 0.28925523, 0.28609908, 0.28297043, 0.27986884, 0.27679393,
+ 0.2737453, 0.2707226, 0.2677254, 0.26475343, 0.26180625,
+ 0.25888354, 0.25598502, 0.2531103, 0.25025907, 0.24743107,
+ 0.24462597, 0.24184346, 0.23908329, 0.23634516, 0.23362878,
+ 0.23093392, 0.2282603, 0.22560766, 0.22297576, 0.22036438,
+ 0.21777324, 0.21520215, 0.21265087, 0.21011916, 0.20760682,
+ 0.20511365, 0.20263945, 0.20018397, 0.19774707, 0.19532852,
+ 0.19292815, 0.19054577, 0.1881812, 0.18583426, 0.18350479,
+ 0.1811926, 0.17889754, 0.17661946, 0.17435817, 0.17211354,
+ 0.1698854, 0.16767362, 0.16547804, 0.16329853, 0.16113494,
+ 0.15898713, 0.15685499, 0.15473837, 0.15263714, 0.15055119,
+ 0.14848037, 0.14642459, 0.14438373, 0.14235765, 0.14034624,
+ 0.13834943, 0.13636707, 0.13439907, 0.13244532, 0.13050574,
+ 0.1285802, 0.12666863, 0.12477092, 0.12288698, 0.12101672,
+ 0.119160056, 0.1173169, 0.115487166, 0.11367077, 0.11186763,
+ 0.11007768, 0.10830083, 0.10653701, 0.10478614, 0.10304816,
+ 0.101323, 0.09961058, 0.09791085, 0.09622374, 0.09454919,
+ 0.09288713, 0.091237515, 0.08960028, 0.087975375, 0.08636274,
+ 0.08476233, 0.083174095, 0.081597984, 0.08003395, 0.07848195,
+ 0.076941945, 0.07541389, 0.07389775, 0.072393484, 0.07090106,
+ 0.069420435, 0.06795159, 0.066494495, 0.06504912, 0.063615434,
+ 0.062193416, 0.060783047, 0.059384305, 0.057997175,
+ 0.05662164, 0.05525769, 0.053905312, 0.052564494, 0.051235236,
+ 0.049917534, 0.048611384, 0.047316793, 0.046033762, 0.0447623,
+ 0.043502413, 0.042254124, 0.041017443, 0.039792392,
+ 0.038578995, 0.037377283, 0.036187284, 0.035009038,
+ 0.033842582, 0.032687962, 0.031545233, 0.030414443, 0.02929566,
+ 0.02818895, 0.027094385, 0.026012046, 0.024942026, 0.023884421,
+ 0.022839336, 0.021806888, 0.020787204, 0.019780423, 0.0187867,
+ 0.0178062, 0.016839107, 0.015885621, 0.014945968, 0.014020392,
+ 0.013109165, 0.012212592, 0.011331013, 0.01046481, 0.009614414,
+ 0.008780315, 0.007963077, 0.0071633533, 0.006381906,
+ 0.0056196423, 0.0048776558, 0.004157295, 0.0034602648,
+ 0.0027887989, 0.0021459677, 0.0015362998, 0.0009672693,
+ 0.00045413437,
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/export_test.go b/platform/dbops/binaries/go/go/src/math/rand/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..560010be6b3b5357b39a779f93fd3d1302c75ef8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/export_test.go
@@ -0,0 +1,17 @@
+// 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 rand
+
+func Int31nForTest(r *Rand, n int32) int32 {
+ return r.int31n(n)
+}
+
+func GetNormalDistributionParameters() (float64, [128]uint32, [128]float32, [128]float32) {
+ return rn, kn, wn, fn
+}
+
+func GetExponentialDistributionParameters() (float64, [256]uint32, [256]float32, [256]float32) {
+ return re, ke, we, fe
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/gen_cooked.go b/platform/dbops/binaries/go/go/src/math/rand/gen_cooked.go
new file mode 100644
index 0000000000000000000000000000000000000000..782bb6671d2e933943980d7faa8fc1e4487cb21a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/gen_cooked.go
@@ -0,0 +1,89 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build ignore
+
+// This program computes the value of rngCooked in rng.go,
+// which is used for seeding all instances of rand.Source.
+// a 64bit and a 63bit version of the array is printed to
+// the standard output.
+
+package main
+
+import "fmt"
+
+const (
+ length = 607
+ tap = 273
+ mask = (1 << 63) - 1
+ a = 48271
+ m = (1 << 31) - 1
+ q = 44488
+ r = 3399
+)
+
+var (
+ rngVec [length]int64
+ rngTap, rngFeed int
+)
+
+func seedrand(x int32) int32 {
+ hi := x / q
+ lo := x % q
+ x = a*lo - r*hi
+ if x < 0 {
+ x += m
+ }
+ return x
+}
+
+func srand(seed int32) {
+ rngTap = 0
+ rngFeed = length - tap
+ seed %= m
+ if seed < 0 {
+ seed += m
+ } else if seed == 0 {
+ seed = 89482311
+ }
+ x := seed
+ for i := -20; i < length; i++ {
+ x = seedrand(x)
+ if i >= 0 {
+ var u int64
+ u = int64(x) << 20
+ x = seedrand(x)
+ u ^= int64(x) << 10
+ x = seedrand(x)
+ u ^= int64(x)
+ rngVec[i] = u
+ }
+ }
+}
+
+func vrand() int64 {
+ rngTap--
+ if rngTap < 0 {
+ rngTap += length
+ }
+ rngFeed--
+ if rngFeed < 0 {
+ rngFeed += length
+ }
+ x := (rngVec[rngFeed] + rngVec[rngTap])
+ rngVec[rngFeed] = x
+ return x
+}
+
+func main() {
+ srand(1)
+ for i := uint64(0); i < 7.8e12; i++ {
+ vrand()
+ }
+ fmt.Printf("rngVec after 7.8e12 calls to vrand:\n%#v\n", rngVec)
+ for i := range rngVec {
+ rngVec[i] &= mask
+ }
+ fmt.Printf("lower 63bit of rngVec after 7.8e12 calls to vrand:\n%#v\n", rngVec)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/normal.go b/platform/dbops/binaries/go/go/src/math/rand/normal.go
new file mode 100644
index 0000000000000000000000000000000000000000..4d441d4505dbbb062d86125de1e8aa7506e85f44
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/normal.go
@@ -0,0 +1,156 @@
+// 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 rand
+
+import (
+ "math"
+)
+
+/*
+ * Normal distribution
+ *
+ * See "The Ziggurat Method for Generating Random Variables"
+ * (Marsaglia & Tsang, 2000)
+ * http://www.jstatsoft.org/v05/i08/paper [pdf]
+ */
+
+const (
+ rn = 3.442619855899
+)
+
+func absInt32(i int32) uint32 {
+ if i < 0 {
+ return uint32(-i)
+ }
+ return uint32(i)
+}
+
+// NormFloat64 returns a normally distributed float64 in
+// the range -[math.MaxFloat64] through +[math.MaxFloat64] inclusive,
+// with standard normal distribution (mean = 0, stddev = 1).
+// To produce a different normal distribution, callers can
+// adjust the output using:
+//
+// sample = NormFloat64() * desiredStdDev + desiredMean
+func (r *Rand) NormFloat64() float64 {
+ for {
+ j := int32(r.Uint32()) // Possibly negative
+ i := j & 0x7F
+ x := float64(j) * float64(wn[i])
+ if absInt32(j) < kn[i] {
+ // This case should be hit better than 99% of the time.
+ return x
+ }
+
+ if i == 0 {
+ // This extra work is only required for the base strip.
+ for {
+ x = -math.Log(r.Float64()) * (1.0 / rn)
+ y := -math.Log(r.Float64())
+ if y+y >= x*x {
+ break
+ }
+ }
+ if j > 0 {
+ return rn + x
+ }
+ return -rn - x
+ }
+ if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) {
+ return x
+ }
+ }
+}
+
+var kn = [128]uint32{
+ 0x76ad2212, 0x0, 0x600f1b53, 0x6ce447a6, 0x725b46a2,
+ 0x7560051d, 0x774921eb, 0x789a25bd, 0x799045c3, 0x7a4bce5d,
+ 0x7adf629f, 0x7b5682a6, 0x7bb8a8c6, 0x7c0ae722, 0x7c50cce7,
+ 0x7c8cec5b, 0x7cc12cd6, 0x7ceefed2, 0x7d177e0b, 0x7d3b8883,
+ 0x7d5bce6c, 0x7d78dd64, 0x7d932886, 0x7dab0e57, 0x7dc0dd30,
+ 0x7dd4d688, 0x7de73185, 0x7df81cea, 0x7e07c0a3, 0x7e163efa,
+ 0x7e23b587, 0x7e303dfd, 0x7e3beec2, 0x7e46db77, 0x7e51155d,
+ 0x7e5aabb3, 0x7e63abf7, 0x7e6c222c, 0x7e741906, 0x7e7b9a18,
+ 0x7e82adfa, 0x7e895c63, 0x7e8fac4b, 0x7e95a3fb, 0x7e9b4924,
+ 0x7ea0a0ef, 0x7ea5b00d, 0x7eaa7ac3, 0x7eaf04f3, 0x7eb3522a,
+ 0x7eb765a5, 0x7ebb4259, 0x7ebeeafd, 0x7ec2620a, 0x7ec5a9c4,
+ 0x7ec8c441, 0x7ecbb365, 0x7ece78ed, 0x7ed11671, 0x7ed38d62,
+ 0x7ed5df12, 0x7ed80cb4, 0x7eda175c, 0x7edc0005, 0x7eddc78e,
+ 0x7edf6ebf, 0x7ee0f647, 0x7ee25ebe, 0x7ee3a8a9, 0x7ee4d473,
+ 0x7ee5e276, 0x7ee6d2f5, 0x7ee7a620, 0x7ee85c10, 0x7ee8f4cd,
+ 0x7ee97047, 0x7ee9ce59, 0x7eea0eca, 0x7eea3147, 0x7eea3568,
+ 0x7eea1aab, 0x7ee9e071, 0x7ee98602, 0x7ee90a88, 0x7ee86d08,
+ 0x7ee7ac6a, 0x7ee6c769, 0x7ee5bc9c, 0x7ee48a67, 0x7ee32efc,
+ 0x7ee1a857, 0x7edff42f, 0x7ede0ffa, 0x7edbf8d9, 0x7ed9ab94,
+ 0x7ed7248d, 0x7ed45fae, 0x7ed1585c, 0x7ece095f, 0x7eca6ccb,
+ 0x7ec67be2, 0x7ec22eee, 0x7ebd7d1a, 0x7eb85c35, 0x7eb2c075,
+ 0x7eac9c20, 0x7ea5df27, 0x7e9e769f, 0x7e964c16, 0x7e8d44ba,
+ 0x7e834033, 0x7e781728, 0x7e6b9933, 0x7e5d8a1a, 0x7e4d9ded,
+ 0x7e3b737a, 0x7e268c2f, 0x7e0e3ff5, 0x7df1aa5d, 0x7dcf8c72,
+ 0x7da61a1e, 0x7d72a0fb, 0x7d30e097, 0x7cd9b4ab, 0x7c600f1a,
+ 0x7ba90bdc, 0x7a722176, 0x77d664e5,
+}
+var wn = [128]float32{
+ 1.7290405e-09, 1.2680929e-10, 1.6897518e-10, 1.9862688e-10,
+ 2.2232431e-10, 2.4244937e-10, 2.601613e-10, 2.7611988e-10,
+ 2.9073963e-10, 3.042997e-10, 3.1699796e-10, 3.289802e-10,
+ 3.4035738e-10, 3.5121603e-10, 3.616251e-10, 3.7164058e-10,
+ 3.8130857e-10, 3.9066758e-10, 3.9975012e-10, 4.08584e-10,
+ 4.1719309e-10, 4.2559822e-10, 4.338176e-10, 4.418672e-10,
+ 4.497613e-10, 4.5751258e-10, 4.651324e-10, 4.7263105e-10,
+ 4.8001775e-10, 4.87301e-10, 4.944885e-10, 5.015873e-10,
+ 5.0860405e-10, 5.155446e-10, 5.2241467e-10, 5.2921934e-10,
+ 5.359635e-10, 5.426517e-10, 5.4928817e-10, 5.5587696e-10,
+ 5.624219e-10, 5.6892646e-10, 5.753941e-10, 5.818282e-10,
+ 5.882317e-10, 5.946077e-10, 6.00959e-10, 6.072884e-10,
+ 6.135985e-10, 6.19892e-10, 6.2617134e-10, 6.3243905e-10,
+ 6.386974e-10, 6.449488e-10, 6.511956e-10, 6.5744005e-10,
+ 6.6368433e-10, 6.699307e-10, 6.7618144e-10, 6.824387e-10,
+ 6.8870465e-10, 6.949815e-10, 7.012715e-10, 7.075768e-10,
+ 7.1389966e-10, 7.202424e-10, 7.266073e-10, 7.329966e-10,
+ 7.394128e-10, 7.4585826e-10, 7.5233547e-10, 7.58847e-10,
+ 7.653954e-10, 7.719835e-10, 7.7861395e-10, 7.852897e-10,
+ 7.920138e-10, 7.987892e-10, 8.0561924e-10, 8.125073e-10,
+ 8.194569e-10, 8.2647167e-10, 8.3355556e-10, 8.407127e-10,
+ 8.479473e-10, 8.55264e-10, 8.6266755e-10, 8.7016316e-10,
+ 8.777562e-10, 8.8545243e-10, 8.932582e-10, 9.0117996e-10,
+ 9.09225e-10, 9.174008e-10, 9.2571584e-10, 9.341788e-10,
+ 9.427997e-10, 9.515889e-10, 9.605579e-10, 9.697193e-10,
+ 9.790869e-10, 9.88676e-10, 9.985036e-10, 1.0085882e-09,
+ 1.0189509e-09, 1.0296151e-09, 1.0406069e-09, 1.0519566e-09,
+ 1.063698e-09, 1.0758702e-09, 1.0885183e-09, 1.1016947e-09,
+ 1.1154611e-09, 1.1298902e-09, 1.1450696e-09, 1.1611052e-09,
+ 1.1781276e-09, 1.1962995e-09, 1.2158287e-09, 1.2369856e-09,
+ 1.2601323e-09, 1.2857697e-09, 1.3146202e-09, 1.347784e-09,
+ 1.3870636e-09, 1.4357403e-09, 1.5008659e-09, 1.6030948e-09,
+}
+var fn = [128]float32{
+ 1, 0.9635997, 0.9362827, 0.9130436, 0.89228165, 0.87324303,
+ 0.8555006, 0.8387836, 0.8229072, 0.8077383, 0.793177,
+ 0.7791461, 0.7655842, 0.7524416, 0.73967725, 0.7272569,
+ 0.7151515, 0.7033361, 0.69178915, 0.68049186, 0.6694277,
+ 0.658582, 0.6479418, 0.63749546, 0.6272325, 0.6171434,
+ 0.6072195, 0.5974532, 0.58783704, 0.5783647, 0.56903,
+ 0.5598274, 0.5507518, 0.54179835, 0.5329627, 0.52424055,
+ 0.5156282, 0.50712204, 0.49871865, 0.49041483, 0.48220766,
+ 0.4740943, 0.46607214, 0.4581387, 0.45029163, 0.44252872,
+ 0.43484783, 0.427247, 0.41972435, 0.41227803, 0.40490642,
+ 0.39760786, 0.3903808, 0.3832238, 0.37613547, 0.36911446,
+ 0.3621595, 0.35526937, 0.34844297, 0.34167916, 0.33497685,
+ 0.3283351, 0.3217529, 0.3152294, 0.30876362, 0.30235484,
+ 0.29600215, 0.28970486, 0.2834622, 0.2772735, 0.27113807,
+ 0.2650553, 0.25902456, 0.2530453, 0.24711695, 0.241239,
+ 0.23541094, 0.22963232, 0.2239027, 0.21822165, 0.21258877,
+ 0.20700371, 0.20146611, 0.19597565, 0.19053204, 0.18513499,
+ 0.17978427, 0.17447963, 0.1692209, 0.16400786, 0.15884037,
+ 0.15371831, 0.14864157, 0.14361008, 0.13862377, 0.13368265,
+ 0.12878671, 0.12393598, 0.119130544, 0.11437051, 0.10965602,
+ 0.104987256, 0.10036444, 0.095787846, 0.0912578, 0.08677467,
+ 0.0823389, 0.077950984, 0.073611505, 0.06932112, 0.06508058,
+ 0.06089077, 0.056752663, 0.0526674, 0.048636295, 0.044660863,
+ 0.040742867, 0.03688439, 0.033087887, 0.029356318,
+ 0.025693292, 0.022103304, 0.018592102, 0.015167298,
+ 0.011839478, 0.008624485, 0.005548995, 0.0026696292,
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/race_test.go b/platform/dbops/binaries/go/go/src/math/rand/race_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e7d103664bba6fd7aca911c14eb3b8ac2a297596
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/race_test.go
@@ -0,0 +1,49 @@
+// 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 rand_test
+
+import (
+ . "math/rand"
+ "sync"
+ "testing"
+)
+
+// TestConcurrent exercises the rand API concurrently, triggering situations
+// where the race detector is likely to detect issues.
+func TestConcurrent(t *testing.T) {
+ const (
+ numRoutines = 10
+ numCycles = 10
+ )
+ var wg sync.WaitGroup
+ defer wg.Wait()
+ wg.Add(numRoutines)
+ for i := 0; i < numRoutines; i++ {
+ go func(i int) {
+ defer wg.Done()
+ buf := make([]byte, 997)
+ for j := 0; j < numCycles; j++ {
+ var seed int64
+ seed += int64(ExpFloat64())
+ seed += int64(Float32())
+ seed += int64(Float64())
+ seed += int64(Intn(Int()))
+ seed += int64(Int31n(Int31()))
+ seed += int64(Int63n(Int63()))
+ seed += int64(NormFloat64())
+ seed += int64(Uint32())
+ seed += int64(Uint64())
+ for _, p := range Perm(10) {
+ seed += int64(p)
+ }
+ Read(buf)
+ for _, b := range buf {
+ seed += int64(b)
+ }
+ Seed(int64(i*j) * seed)
+ }
+ }(i)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/rand.go b/platform/dbops/binaries/go/go/src/math/rand/rand.go
new file mode 100644
index 0000000000000000000000000000000000000000..a8ed9c0cb7cfa9beed536cc146294e9e79f5d30a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/rand.go
@@ -0,0 +1,547 @@
+// 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 rand implements pseudo-random number generators suitable for tasks
+// such as simulation, but it should not be used for security-sensitive work.
+//
+// Random numbers are generated by a [Source], usually wrapped in a [Rand].
+// Both types should be used by a single goroutine at a time: sharing among
+// multiple goroutines requires some kind of synchronization.
+//
+// Top-level functions, such as [Float64] and [Int],
+// are safe for concurrent use by multiple goroutines.
+//
+// This package's outputs might be easily predictable regardless of how it's
+// seeded. For random numbers suitable for security-sensitive work, see the
+// crypto/rand package.
+package rand
+
+import (
+ "internal/godebug"
+ "sync"
+ "sync/atomic"
+ _ "unsafe" // for go:linkname
+)
+
+// A Source represents a source of uniformly-distributed
+// pseudo-random int64 values in the range [0, 1<<63).
+//
+// A Source is not safe for concurrent use by multiple goroutines.
+type Source interface {
+ Int63() int64
+ Seed(seed int64)
+}
+
+// A Source64 is a [Source] that can also generate
+// uniformly-distributed pseudo-random uint64 values in
+// the range [0, 1<<64) directly.
+// If a [Rand] r's underlying [Source] s implements Source64,
+// then r.Uint64 returns the result of one call to s.Uint64
+// instead of making two calls to s.Int63.
+type Source64 interface {
+ Source
+ Uint64() uint64
+}
+
+// NewSource returns a new pseudo-random [Source] seeded with the given value.
+// Unlike the default [Source] used by top-level functions, this source is not
+// safe for concurrent use by multiple goroutines.
+// The returned [Source] implements [Source64].
+func NewSource(seed int64) Source {
+ return newSource(seed)
+}
+
+func newSource(seed int64) *rngSource {
+ var rng rngSource
+ rng.Seed(seed)
+ return &rng
+}
+
+// A Rand is a source of random numbers.
+type Rand struct {
+ src Source
+ s64 Source64 // non-nil if src is source64
+
+ // readVal contains remainder of 63-bit integer used for bytes
+ // generation during most recent Read call.
+ // It is saved so next Read call can start where the previous
+ // one finished.
+ readVal int64
+ // readPos indicates the number of low-order bytes of readVal
+ // that are still valid.
+ readPos int8
+}
+
+// New returns a new [Rand] that uses random values from src
+// to generate other random values.
+func New(src Source) *Rand {
+ s64, _ := src.(Source64)
+ return &Rand{src: src, s64: s64}
+}
+
+// Seed uses the provided seed value to initialize the generator to a deterministic state.
+// Seed should not be called concurrently with any other [Rand] method.
+func (r *Rand) Seed(seed int64) {
+ if lk, ok := r.src.(*lockedSource); ok {
+ lk.seedPos(seed, &r.readPos)
+ return
+ }
+
+ r.src.Seed(seed)
+ r.readPos = 0
+}
+
+// Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
+func (r *Rand) Int63() int64 { return r.src.Int63() }
+
+// Uint32 returns a pseudo-random 32-bit value as a uint32.
+func (r *Rand) Uint32() uint32 { return uint32(r.Int63() >> 31) }
+
+// Uint64 returns a pseudo-random 64-bit value as a uint64.
+func (r *Rand) Uint64() uint64 {
+ if r.s64 != nil {
+ return r.s64.Uint64()
+ }
+ return uint64(r.Int63())>>31 | uint64(r.Int63())<<32
+}
+
+// Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
+func (r *Rand) Int31() int32 { return int32(r.Int63() >> 32) }
+
+// Int returns a non-negative pseudo-random int.
+func (r *Rand) Int() int {
+ u := uint(r.Int63())
+ return int(u << 1 >> 1) // clear sign bit if int == int32
+}
+
+// Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) Int63n(n int64) int64 {
+ if n <= 0 {
+ panic("invalid argument to Int63n")
+ }
+ if n&(n-1) == 0 { // n is power of two, can mask
+ return r.Int63() & (n - 1)
+ }
+ max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
+ v := r.Int63()
+ for v > max {
+ v = r.Int63()
+ }
+ return v % n
+}
+
+// Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) Int31n(n int32) int32 {
+ if n <= 0 {
+ panic("invalid argument to Int31n")
+ }
+ if n&(n-1) == 0 { // n is power of two, can mask
+ return r.Int31() & (n - 1)
+ }
+ max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
+ v := r.Int31()
+ for v > max {
+ v = r.Int31()
+ }
+ return v % n
+}
+
+// int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
+// n must be > 0, but int31n does not check this; the caller must ensure it.
+// int31n exists because Int31n is inefficient, but Go 1 compatibility
+// requires that the stream of values produced by math/rand remain unchanged.
+// int31n can thus only be used internally, by newly introduced APIs.
+//
+// For implementation details, see:
+// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
+// https://lemire.me/blog/2016/06/30/fast-random-shuffling
+func (r *Rand) int31n(n int32) int32 {
+ v := r.Uint32()
+ prod := uint64(v) * uint64(n)
+ low := uint32(prod)
+ if low < uint32(n) {
+ thresh := uint32(-n) % uint32(n)
+ for low < thresh {
+ v = r.Uint32()
+ prod = uint64(v) * uint64(n)
+ low = uint32(prod)
+ }
+ }
+ return int32(prod >> 32)
+}
+
+// Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) Intn(n int) int {
+ if n <= 0 {
+ panic("invalid argument to Intn")
+ }
+ if n <= 1<<31-1 {
+ return int(r.Int31n(int32(n)))
+ }
+ return int(r.Int63n(int64(n)))
+}
+
+// Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
+func (r *Rand) Float64() float64 {
+ // A clearer, simpler implementation would be:
+ // return float64(r.Int63n(1<<53)) / (1<<53)
+ // However, Go 1 shipped with
+ // return float64(r.Int63()) / (1 << 63)
+ // and we want to preserve that value stream.
+ //
+ // There is one bug in the value stream: r.Int63() may be so close
+ // to 1<<63 that the division rounds up to 1.0, and we've guaranteed
+ // that the result is always less than 1.0.
+ //
+ // We tried to fix this by mapping 1.0 back to 0.0, but since float64
+ // values near 0 are much denser than near 1, mapping 1 to 0 caused
+ // a theoretically significant overshoot in the probability of returning 0.
+ // Instead of that, if we round up to 1, just try again.
+ // Getting 1 only happens 1/2⁵³ of the time, so most clients
+ // will not observe it anyway.
+again:
+ f := float64(r.Int63()) / (1 << 63)
+ if f == 1 {
+ goto again // resample; this branch is taken O(never)
+ }
+ return f
+}
+
+// Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
+func (r *Rand) Float32() float32 {
+ // Same rationale as in Float64: we want to preserve the Go 1 value
+ // stream except we want to fix it not to return 1.0
+ // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64).
+again:
+ f := float32(r.Float64())
+ if f == 1 {
+ goto again // resample; this branch is taken O(very rarely)
+ }
+ return f
+}
+
+// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
+// in the half-open interval [0,n).
+func (r *Rand) Perm(n int) []int {
+ m := make([]int, n)
+ // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
+ // A change to remove this useless iteration is to assign 1 to i in the init
+ // statement. But Perm also effects r. Making this change will affect
+ // the final state of r. So this change can't be made for compatibility
+ // reasons for Go 1.
+ for i := 0; i < n; i++ {
+ j := r.Intn(i + 1)
+ m[i] = m[j]
+ m[j] = i
+ }
+ return m
+}
+
+// Shuffle pseudo-randomizes the order of elements.
+// n is the number of elements. Shuffle panics if n < 0.
+// swap swaps the elements with indexes i and j.
+func (r *Rand) Shuffle(n int, swap func(i, j int)) {
+ if n < 0 {
+ panic("invalid argument to Shuffle")
+ }
+
+ // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
+ // Shuffle really ought not be called with n that doesn't fit in 32 bits.
+ // Not only will it take a very long time, but with 2³¹! possible permutations,
+ // there's no way that any PRNG can have a big enough internal state to
+ // generate even a minuscule percentage of the possible permutations.
+ // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
+ i := n - 1
+ for ; i > 1<<31-1-1; i-- {
+ j := int(r.Int63n(int64(i + 1)))
+ swap(i, j)
+ }
+ for ; i > 0; i-- {
+ j := int(r.int31n(int32(i + 1)))
+ swap(i, j)
+ }
+}
+
+// Read generates len(p) random bytes and writes them into p. It
+// always returns len(p) and a nil error.
+// Read should not be called concurrently with any other Rand method.
+func (r *Rand) Read(p []byte) (n int, err error) {
+ switch src := r.src.(type) {
+ case *lockedSource:
+ return src.read(p, &r.readVal, &r.readPos)
+ case *runtimeSource:
+ return src.read(p, &r.readVal, &r.readPos)
+ }
+ return read(p, r.src, &r.readVal, &r.readPos)
+}
+
+func read(p []byte, src Source, readVal *int64, readPos *int8) (n int, err error) {
+ pos := *readPos
+ val := *readVal
+ rng, _ := src.(*rngSource)
+ for n = 0; n < len(p); n++ {
+ if pos == 0 {
+ if rng != nil {
+ val = rng.Int63()
+ } else {
+ val = src.Int63()
+ }
+ pos = 7
+ }
+ p[n] = byte(val)
+ val >>= 8
+ pos--
+ }
+ *readPos = pos
+ *readVal = val
+ return
+}
+
+/*
+ * Top-level convenience functions
+ */
+
+// globalRandGenerator is the source of random numbers for the top-level
+// convenience functions. When possible it uses the runtime fastrand64
+// function to avoid locking. This is not possible if the user called Seed,
+// either explicitly or implicitly via GODEBUG=randautoseed=0.
+var globalRandGenerator atomic.Pointer[Rand]
+
+var randautoseed = godebug.New("randautoseed")
+
+// globalRand returns the generator to use for the top-level convenience
+// functions.
+func globalRand() *Rand {
+ if r := globalRandGenerator.Load(); r != nil {
+ return r
+ }
+
+ // This is the first call. Initialize based on GODEBUG.
+ var r *Rand
+ if randautoseed.Value() == "0" {
+ randautoseed.IncNonDefault()
+ r = New(new(lockedSource))
+ r.Seed(1)
+ } else {
+ r = &Rand{
+ src: &runtimeSource{},
+ s64: &runtimeSource{},
+ }
+ }
+
+ if !globalRandGenerator.CompareAndSwap(nil, r) {
+ // Two different goroutines called some top-level
+ // function at the same time. While the results in
+ // that case are unpredictable, if we just use r here,
+ // and we are using a seed, we will most likely return
+ // the same value for both calls. That doesn't seem ideal.
+ // Just use the first one to get in.
+ return globalRandGenerator.Load()
+ }
+
+ return r
+}
+
+//go:linkname runtime_rand runtime.rand
+func runtime_rand() uint64
+
+// runtimeSource is an implementation of Source64 that uses the runtime
+// fastrand functions.
+type runtimeSource struct {
+ // The mutex is used to avoid race conditions in Read.
+ mu sync.Mutex
+}
+
+func (*runtimeSource) Int63() int64 {
+ return int64(runtime_rand() & rngMask)
+}
+
+func (*runtimeSource) Seed(int64) {
+ panic("internal error: call to runtimeSource.Seed")
+}
+
+func (*runtimeSource) Uint64() uint64 {
+ return runtime_rand()
+}
+
+func (fs *runtimeSource) read(p []byte, readVal *int64, readPos *int8) (n int, err error) {
+ fs.mu.Lock()
+ n, err = read(p, fs, readVal, readPos)
+ fs.mu.Unlock()
+ return
+}
+
+// Seed uses the provided seed value to initialize the default Source to a
+// deterministic state. Seed values that have the same remainder when
+// divided by 2³¹-1 generate the same pseudo-random sequence.
+// Seed, unlike the [Rand.Seed] method, is safe for concurrent use.
+//
+// If Seed is not called, the generator is seeded randomly at program startup.
+//
+// Prior to Go 1.20, the generator was seeded like Seed(1) at program startup.
+// To force the old behavior, call Seed(1) at program startup.
+// Alternately, set GODEBUG=randautoseed=0 in the environment
+// before making any calls to functions in this package.
+//
+// Deprecated: As of Go 1.20 there is no reason to call Seed with
+// a random value. Programs that call Seed with a known value to get
+// a specific sequence of results should use New(NewSource(seed)) to
+// obtain a local random generator.
+func Seed(seed int64) {
+ orig := globalRandGenerator.Load()
+
+ // If we are already using a lockedSource, we can just re-seed it.
+ if orig != nil {
+ if _, ok := orig.src.(*lockedSource); ok {
+ orig.Seed(seed)
+ return
+ }
+ }
+
+ // Otherwise either
+ // 1) orig == nil, which is the normal case when Seed is the first
+ // top-level function to be called, or
+ // 2) orig is already a runtimeSource, in which case we need to change
+ // to a lockedSource.
+ // Either way we do the same thing.
+
+ r := New(new(lockedSource))
+ r.Seed(seed)
+
+ if !globalRandGenerator.CompareAndSwap(orig, r) {
+ // Something changed underfoot. Retry to be safe.
+ Seed(seed)
+ }
+}
+
+// Int63 returns a non-negative pseudo-random 63-bit integer as an int64
+// from the default [Source].
+func Int63() int64 { return globalRand().Int63() }
+
+// Uint32 returns a pseudo-random 32-bit value as a uint32
+// from the default [Source].
+func Uint32() uint32 { return globalRand().Uint32() }
+
+// Uint64 returns a pseudo-random 64-bit value as a uint64
+// from the default [Source].
+func Uint64() uint64 { return globalRand().Uint64() }
+
+// Int31 returns a non-negative pseudo-random 31-bit integer as an int32
+// from the default [Source].
+func Int31() int32 { return globalRand().Int31() }
+
+// Int returns a non-negative pseudo-random int from the default [Source].
+func Int() int { return globalRand().Int() }
+
+// Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n)
+// from the default [Source].
+// It panics if n <= 0.
+func Int63n(n int64) int64 { return globalRand().Int63n(n) }
+
+// Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n)
+// from the default [Source].
+// It panics if n <= 0.
+func Int31n(n int32) int32 { return globalRand().Int31n(n) }
+
+// Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n)
+// from the default [Source].
+// It panics if n <= 0.
+func Intn(n int) int { return globalRand().Intn(n) }
+
+// Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
+// from the default [Source].
+func Float64() float64 { return globalRand().Float64() }
+
+// Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
+// from the default [Source].
+func Float32() float32 { return globalRand().Float32() }
+
+// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
+// in the half-open interval [0,n) from the default [Source].
+func Perm(n int) []int { return globalRand().Perm(n) }
+
+// Shuffle pseudo-randomizes the order of elements using the default [Source].
+// n is the number of elements. Shuffle panics if n < 0.
+// swap swaps the elements with indexes i and j.
+func Shuffle(n int, swap func(i, j int)) { globalRand().Shuffle(n, swap) }
+
+// Read generates len(p) random bytes from the default [Source] and
+// writes them into p. It always returns len(p) and a nil error.
+// Read, unlike the [Rand.Read] method, is safe for concurrent use.
+//
+// Deprecated: For almost all use cases, [crypto/rand.Read] is more appropriate.
+func Read(p []byte) (n int, err error) { return globalRand().Read(p) }
+
+// NormFloat64 returns a normally distributed float64 in the range
+// [-[math.MaxFloat64], +[math.MaxFloat64]] with
+// standard normal distribution (mean = 0, stddev = 1)
+// from the default [Source].
+// To produce a different normal distribution, callers can
+// adjust the output using:
+//
+// sample = NormFloat64() * desiredStdDev + desiredMean
+func NormFloat64() float64 { return globalRand().NormFloat64() }
+
+// ExpFloat64 returns an exponentially distributed float64 in the range
+// (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter
+// (lambda) is 1 and whose mean is 1/lambda (1) from the default [Source].
+// To produce a distribution with a different rate parameter,
+// callers can adjust the output using:
+//
+// sample = ExpFloat64() / desiredRateParameter
+func ExpFloat64() float64 { return globalRand().ExpFloat64() }
+
+type lockedSource struct {
+ lk sync.Mutex
+ s *rngSource
+}
+
+func (r *lockedSource) Int63() (n int64) {
+ r.lk.Lock()
+ n = r.s.Int63()
+ r.lk.Unlock()
+ return
+}
+
+func (r *lockedSource) Uint64() (n uint64) {
+ r.lk.Lock()
+ n = r.s.Uint64()
+ r.lk.Unlock()
+ return
+}
+
+func (r *lockedSource) Seed(seed int64) {
+ r.lk.Lock()
+ r.seed(seed)
+ r.lk.Unlock()
+}
+
+// seedPos implements Seed for a lockedSource without a race condition.
+func (r *lockedSource) seedPos(seed int64, readPos *int8) {
+ r.lk.Lock()
+ r.seed(seed)
+ *readPos = 0
+ r.lk.Unlock()
+}
+
+// seed seeds the underlying source.
+// The caller must have locked r.lk.
+func (r *lockedSource) seed(seed int64) {
+ if r.s == nil {
+ r.s = newSource(seed)
+ } else {
+ r.s.Seed(seed)
+ }
+}
+
+// read implements Read for a lockedSource without a race condition.
+func (r *lockedSource) read(p []byte, readVal *int64, readPos *int8) (n int, err error) {
+ r.lk.Lock()
+ n, err = read(p, r.s, readVal, readPos)
+ r.lk.Unlock()
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/rand_test.go b/platform/dbops/binaries/go/go/src/math/rand/rand_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9f074fea009a8b7969d83ef192206363e6670889
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/rand_test.go
@@ -0,0 +1,695 @@
+// 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 rand_test
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "math"
+ . "math/rand"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "testing/iotest"
+)
+
+const (
+ numTestSamples = 10000
+)
+
+var rn, kn, wn, fn = GetNormalDistributionParameters()
+var re, ke, we, fe = GetExponentialDistributionParameters()
+
+type statsResults struct {
+ mean float64
+ stddev float64
+ closeEnough float64
+ maxError float64
+}
+
+func nearEqual(a, b, closeEnough, maxError float64) bool {
+ absDiff := math.Abs(a - b)
+ if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
+ return true
+ }
+ return absDiff/max(math.Abs(a), math.Abs(b)) < maxError
+}
+
+var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961}
+
+// checkSimilarDistribution returns success if the mean and stddev of the
+// two statsResults are similar.
+func (this *statsResults) checkSimilarDistribution(expected *statsResults) error {
+ if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
+ s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
+ fmt.Println(s)
+ return errors.New(s)
+ }
+ if !nearEqual(this.stddev, expected.stddev, expected.closeEnough, expected.maxError) {
+ s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
+ fmt.Println(s)
+ return errors.New(s)
+ }
+ return nil
+}
+
+func getStatsResults(samples []float64) *statsResults {
+ res := new(statsResults)
+ var sum, squaresum float64
+ for _, s := range samples {
+ sum += s
+ squaresum += s * s
+ }
+ res.mean = sum / float64(len(samples))
+ res.stddev = math.Sqrt(squaresum/float64(len(samples)) - res.mean*res.mean)
+ return res
+}
+
+func checkSampleDistribution(t *testing.T, samples []float64, expected *statsResults) {
+ t.Helper()
+ actual := getStatsResults(samples)
+ err := actual.checkSimilarDistribution(expected)
+ if err != nil {
+ t.Errorf(err.Error())
+ }
+}
+
+func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) {
+ t.Helper()
+ chunk := len(samples) / nslices
+ for i := 0; i < nslices; i++ {
+ low := i * chunk
+ var high int
+ if i == nslices-1 {
+ high = len(samples) - 1
+ } else {
+ high = (i + 1) * chunk
+ }
+ checkSampleDistribution(t, samples[low:high], expected)
+ }
+}
+
+//
+// Normal distribution tests
+//
+
+func generateNormalSamples(nsamples int, mean, stddev float64, seed int64) []float64 {
+ r := New(NewSource(seed))
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ samples[i] = r.NormFloat64()*stddev + mean
+ }
+ return samples
+}
+
+func testNormalDistribution(t *testing.T, nsamples int, mean, stddev float64, seed int64) {
+ //fmt.Printf("testing nsamples=%v mean=%v stddev=%v seed=%v\n", nsamples, mean, stddev, seed);
+
+ samples := generateNormalSamples(nsamples, mean, stddev, seed)
+ errorScale := max(1.0, stddev) // Error scales with stddev
+ expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
+
+ // Make sure that the entire set matches the expected distribution.
+ checkSampleDistribution(t, samples, expected)
+
+ // Make sure that each half of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 2, expected)
+
+ // Make sure that each 7th of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 7, expected)
+}
+
+// Actual tests
+
+func TestStandardNormalValues(t *testing.T) {
+ for _, seed := range testSeeds {
+ testNormalDistribution(t, numTestSamples, 0, 1, seed)
+ }
+}
+
+func TestNonStandardNormalValues(t *testing.T) {
+ sdmax := 1000.0
+ mmax := 1000.0
+ if testing.Short() {
+ sdmax = 5
+ mmax = 5
+ }
+ for sd := 0.5; sd < sdmax; sd *= 2 {
+ for m := 0.5; m < mmax; m *= 2 {
+ for _, seed := range testSeeds {
+ testNormalDistribution(t, numTestSamples, m, sd, seed)
+ if testing.Short() {
+ break
+ }
+ }
+ }
+ }
+}
+
+//
+// Exponential distribution tests
+//
+
+func generateExponentialSamples(nsamples int, rate float64, seed int64) []float64 {
+ r := New(NewSource(seed))
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ samples[i] = r.ExpFloat64() / rate
+ }
+ return samples
+}
+
+func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed int64) {
+ //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed);
+
+ mean := 1 / rate
+ stddev := mean
+
+ samples := generateExponentialSamples(nsamples, rate, seed)
+ errorScale := max(1.0, 1/rate) // Error scales with the inverse of the rate
+ expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.20 * errorScale}
+
+ // Make sure that the entire set matches the expected distribution.
+ checkSampleDistribution(t, samples, expected)
+
+ // Make sure that each half of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 2, expected)
+
+ // Make sure that each 7th of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 7, expected)
+}
+
+// Actual tests
+
+func TestStandardExponentialValues(t *testing.T) {
+ for _, seed := range testSeeds {
+ testExponentialDistribution(t, numTestSamples, 1, seed)
+ }
+}
+
+func TestNonStandardExponentialValues(t *testing.T) {
+ for rate := 0.05; rate < 10; rate *= 2 {
+ for _, seed := range testSeeds {
+ testExponentialDistribution(t, numTestSamples, rate, seed)
+ if testing.Short() {
+ break
+ }
+ }
+ }
+}
+
+//
+// Table generation tests
+//
+
+func initNorm() (testKn []uint32, testWn, testFn []float32) {
+ const m1 = 1 << 31
+ var (
+ dn float64 = rn
+ tn = dn
+ vn float64 = 9.91256303526217e-3
+ )
+
+ testKn = make([]uint32, 128)
+ testWn = make([]float32, 128)
+ testFn = make([]float32, 128)
+
+ q := vn / math.Exp(-0.5*dn*dn)
+ testKn[0] = uint32((dn / q) * m1)
+ testKn[1] = 0
+ testWn[0] = float32(q / m1)
+ testWn[127] = float32(dn / m1)
+ testFn[0] = 1.0
+ testFn[127] = float32(math.Exp(-0.5 * dn * dn))
+ for i := 126; i >= 1; i-- {
+ dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn)))
+ testKn[i+1] = uint32((dn / tn) * m1)
+ tn = dn
+ testFn[i] = float32(math.Exp(-0.5 * dn * dn))
+ testWn[i] = float32(dn / m1)
+ }
+ return
+}
+
+func initExp() (testKe []uint32, testWe, testFe []float32) {
+ const m2 = 1 << 32
+ var (
+ de float64 = re
+ te = de
+ ve float64 = 3.9496598225815571993e-3
+ )
+
+ testKe = make([]uint32, 256)
+ testWe = make([]float32, 256)
+ testFe = make([]float32, 256)
+
+ q := ve / math.Exp(-de)
+ testKe[0] = uint32((de / q) * m2)
+ testKe[1] = 0
+ testWe[0] = float32(q / m2)
+ testWe[255] = float32(de / m2)
+ testFe[0] = 1.0
+ testFe[255] = float32(math.Exp(-de))
+ for i := 254; i >= 1; i-- {
+ de = -math.Log(ve/de + math.Exp(-de))
+ testKe[i+1] = uint32((de / te) * m2)
+ te = de
+ testFe[i] = float32(math.Exp(-de))
+ testWe[i] = float32(de / m2)
+ }
+ return
+}
+
+// compareUint32Slices returns the first index where the two slices
+// disagree, or <0 if the lengths are the same and all elements
+// are identical.
+func compareUint32Slices(s1, s2 []uint32) int {
+ if len(s1) != len(s2) {
+ if len(s1) > len(s2) {
+ return len(s2) + 1
+ }
+ return len(s1) + 1
+ }
+ for i := range s1 {
+ if s1[i] != s2[i] {
+ return i
+ }
+ }
+ return -1
+}
+
+// compareFloat32Slices returns the first index where the two slices
+// disagree, or <0 if the lengths are the same and all elements
+// are identical.
+func compareFloat32Slices(s1, s2 []float32) int {
+ if len(s1) != len(s2) {
+ if len(s1) > len(s2) {
+ return len(s2) + 1
+ }
+ return len(s1) + 1
+ }
+ for i := range s1 {
+ if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) {
+ return i
+ }
+ }
+ return -1
+}
+
+func TestNormTables(t *testing.T) {
+ testKn, testWn, testFn := initNorm()
+ if i := compareUint32Slices(kn[0:], testKn); i >= 0 {
+ t.Errorf("kn disagrees at index %v; %v != %v", i, kn[i], testKn[i])
+ }
+ if i := compareFloat32Slices(wn[0:], testWn); i >= 0 {
+ t.Errorf("wn disagrees at index %v; %v != %v", i, wn[i], testWn[i])
+ }
+ if i := compareFloat32Slices(fn[0:], testFn); i >= 0 {
+ t.Errorf("fn disagrees at index %v; %v != %v", i, fn[i], testFn[i])
+ }
+}
+
+func TestExpTables(t *testing.T) {
+ testKe, testWe, testFe := initExp()
+ if i := compareUint32Slices(ke[0:], testKe); i >= 0 {
+ t.Errorf("ke disagrees at index %v; %v != %v", i, ke[i], testKe[i])
+ }
+ if i := compareFloat32Slices(we[0:], testWe); i >= 0 {
+ t.Errorf("we disagrees at index %v; %v != %v", i, we[i], testWe[i])
+ }
+ if i := compareFloat32Slices(fe[0:], testFe); i >= 0 {
+ t.Errorf("fe disagrees at index %v; %v != %v", i, fe[i], testFe[i])
+ }
+}
+
+func hasSlowFloatingPoint() bool {
+ switch runtime.GOARCH {
+ case "arm":
+ return os.Getenv("GOARM") == "5" || strings.HasSuffix(os.Getenv("GOARM"), ",softfloat")
+ case "mips", "mipsle", "mips64", "mips64le":
+ // Be conservative and assume that all mips boards
+ // have emulated floating point.
+ // TODO: detect what it actually has.
+ return true
+ }
+ return false
+}
+
+func TestFloat32(t *testing.T) {
+ // For issue 6721, the problem came after 7533753 calls, so check 10e6.
+ num := int(10e6)
+ // But do the full amount only on builders (not locally).
+ // But ARM5 floating point emulation is slow (Issue 10749), so
+ // do less for that builder:
+ if testing.Short() && (testenv.Builder() == "" || hasSlowFloatingPoint()) {
+ num /= 100 // 1.72 seconds instead of 172 seconds
+ }
+
+ r := New(NewSource(1))
+ for ct := 0; ct < num; ct++ {
+ f := r.Float32()
+ if f >= 1 {
+ t.Fatal("Float32() should be in range [0,1). ct:", ct, "f:", f)
+ }
+ }
+}
+
+func testReadUniformity(t *testing.T, n int, seed int64) {
+ r := New(NewSource(seed))
+ buf := make([]byte, n)
+ nRead, err := r.Read(buf)
+ if err != nil {
+ t.Errorf("Read err %v", err)
+ }
+ if nRead != n {
+ t.Errorf("Read returned unexpected n; %d != %d", nRead, n)
+ }
+
+ // Expect a uniform distribution of byte values, which lie in [0, 255].
+ var (
+ mean = 255.0 / 2
+ stddev = 256.0 / math.Sqrt(12.0)
+ errorScale = stddev / math.Sqrt(float64(n))
+ )
+
+ expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
+
+ // Cast bytes as floats to use the common distribution-validity checks.
+ samples := make([]float64, n)
+ for i, val := range buf {
+ samples[i] = float64(val)
+ }
+ // Make sure that the entire set matches the expected distribution.
+ checkSampleDistribution(t, samples, expected)
+}
+
+func TestReadUniformity(t *testing.T) {
+ testBufferSizes := []int{
+ 2, 4, 7, 64, 1024, 1 << 16, 1 << 20,
+ }
+ for _, seed := range testSeeds {
+ for _, n := range testBufferSizes {
+ testReadUniformity(t, n, seed)
+ }
+ }
+}
+
+func TestReadEmpty(t *testing.T) {
+ r := New(NewSource(1))
+ buf := make([]byte, 0)
+ n, err := r.Read(buf)
+ if err != nil {
+ t.Errorf("Read err into empty buffer; %v", err)
+ }
+ if n != 0 {
+ t.Errorf("Read into empty buffer returned unexpected n of %d", n)
+ }
+}
+
+func TestReadByOneByte(t *testing.T) {
+ r := New(NewSource(1))
+ b1 := make([]byte, 100)
+ _, err := io.ReadFull(iotest.OneByteReader(r), b1)
+ if err != nil {
+ t.Errorf("read by one byte: %v", err)
+ }
+ r = New(NewSource(1))
+ b2 := make([]byte, 100)
+ _, err = r.Read(b2)
+ if err != nil {
+ t.Errorf("read: %v", err)
+ }
+ if !bytes.Equal(b1, b2) {
+ t.Errorf("read by one byte vs single read:\n%x\n%x", b1, b2)
+ }
+}
+
+func TestReadSeedReset(t *testing.T) {
+ r := New(NewSource(42))
+ b1 := make([]byte, 128)
+ _, err := r.Read(b1)
+ if err != nil {
+ t.Errorf("read: %v", err)
+ }
+ r.Seed(42)
+ b2 := make([]byte, 128)
+ _, err = r.Read(b2)
+ if err != nil {
+ t.Errorf("read: %v", err)
+ }
+ if !bytes.Equal(b1, b2) {
+ t.Errorf("mismatch after re-seed:\n%x\n%x", b1, b2)
+ }
+}
+
+func TestShuffleSmall(t *testing.T) {
+ // Check that Shuffle allows n=0 and n=1, but that swap is never called for them.
+ r := New(NewSource(1))
+ for n := 0; n <= 1; n++ {
+ r.Shuffle(n, func(i, j int) { t.Fatalf("swap called, n=%d i=%d j=%d", n, i, j) })
+ }
+}
+
+// encodePerm converts from a permuted slice of length n, such as Perm generates, to an int in [0, n!).
+// See https://en.wikipedia.org/wiki/Lehmer_code.
+// encodePerm modifies the input slice.
+func encodePerm(s []int) int {
+ // Convert to Lehmer code.
+ for i, x := range s {
+ r := s[i+1:]
+ for j, y := range r {
+ if y > x {
+ r[j]--
+ }
+ }
+ }
+ // Convert to int in [0, n!).
+ m := 0
+ fact := 1
+ for i := len(s) - 1; i >= 0; i-- {
+ m += s[i] * fact
+ fact *= len(s) - i
+ }
+ return m
+}
+
+// TestUniformFactorial tests several ways of generating a uniform value in [0, n!).
+func TestUniformFactorial(t *testing.T) {
+ r := New(NewSource(testSeeds[0]))
+ top := 6
+ if testing.Short() {
+ top = 3
+ }
+ for n := 3; n <= top; n++ {
+ t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
+ // Calculate n!.
+ nfact := 1
+ for i := 2; i <= n; i++ {
+ nfact *= i
+ }
+
+ // Test a few different ways to generate a uniform distribution.
+ p := make([]int, n) // re-usable slice for Shuffle generator
+ tests := [...]struct {
+ name string
+ fn func() int
+ }{
+ {name: "Int31n", fn: func() int { return int(r.Int31n(int32(nfact))) }},
+ {name: "int31n", fn: func() int { return int(Int31nForTest(r, int32(nfact))) }},
+ {name: "Perm", fn: func() int { return encodePerm(r.Perm(n)) }},
+ {name: "Shuffle", fn: func() int {
+ // Generate permutation using Shuffle.
+ for i := range p {
+ p[i] = i
+ }
+ r.Shuffle(n, func(i, j int) { p[i], p[j] = p[j], p[i] })
+ return encodePerm(p)
+ }},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ // Gather chi-squared values and check that they follow
+ // the expected normal distribution given n!-1 degrees of freedom.
+ // See https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test and
+ // https://www.johndcook.com/Beautiful_Testing_ch10.pdf.
+ nsamples := 10 * nfact
+ if nsamples < 200 {
+ nsamples = 200
+ }
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ // Generate some uniformly distributed values and count their occurrences.
+ const iters = 1000
+ counts := make([]int, nfact)
+ for i := 0; i < iters; i++ {
+ counts[test.fn()]++
+ }
+ // Calculate chi-squared and add to samples.
+ want := iters / float64(nfact)
+ var χ2 float64
+ for _, have := range counts {
+ err := float64(have) - want
+ χ2 += err * err
+ }
+ χ2 /= want
+ samples[i] = χ2
+ }
+
+ // Check that our samples approximate the appropriate normal distribution.
+ dof := float64(nfact - 1)
+ expected := &statsResults{mean: dof, stddev: math.Sqrt(2 * dof)}
+ errorScale := max(1.0, expected.stddev)
+ expected.closeEnough = 0.10 * errorScale
+ expected.maxError = 0.08 // TODO: What is the right value here? See issue 21211.
+ checkSampleDistribution(t, samples, expected)
+ })
+ }
+ })
+ }
+}
+
+// Benchmarks
+
+func BenchmarkInt63Threadsafe(b *testing.B) {
+ for n := b.N; n > 0; n-- {
+ Int63()
+ }
+}
+
+func BenchmarkInt63ThreadsafeParallel(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ Int63()
+ }
+ })
+}
+
+func BenchmarkInt63Unthreadsafe(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Int63()
+ }
+}
+
+func BenchmarkIntn1000(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Intn(1000)
+ }
+}
+
+func BenchmarkInt63n1000(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Int63n(1000)
+ }
+}
+
+func BenchmarkInt31n1000(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Int31n(1000)
+ }
+}
+
+func BenchmarkFloat32(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Float32()
+ }
+}
+
+func BenchmarkFloat64(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Float64()
+ }
+}
+
+func BenchmarkPerm3(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Perm(3)
+ }
+}
+
+func BenchmarkPerm30(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Perm(30)
+ }
+}
+
+func BenchmarkPerm30ViaShuffle(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ p := make([]int, 30)
+ for i := range p {
+ p[i] = i
+ }
+ r.Shuffle(30, func(i, j int) { p[i], p[j] = p[j], p[i] })
+ }
+}
+
+// BenchmarkShuffleOverhead uses a minimal swap function
+// to measure just the shuffling overhead.
+func BenchmarkShuffleOverhead(b *testing.B) {
+ r := New(NewSource(1))
+ for n := b.N; n > 0; n-- {
+ r.Shuffle(52, func(i, j int) {
+ if i < 0 || i >= 52 || j < 0 || j >= 52 {
+ b.Fatalf("bad swap(%d, %d)", i, j)
+ }
+ })
+ }
+}
+
+func BenchmarkRead3(b *testing.B) {
+ r := New(NewSource(1))
+ buf := make([]byte, 3)
+ b.ResetTimer()
+ for n := b.N; n > 0; n-- {
+ r.Read(buf)
+ }
+}
+
+func BenchmarkRead64(b *testing.B) {
+ r := New(NewSource(1))
+ buf := make([]byte, 64)
+ b.ResetTimer()
+ for n := b.N; n > 0; n-- {
+ r.Read(buf)
+ }
+}
+
+func BenchmarkRead1000(b *testing.B) {
+ r := New(NewSource(1))
+ buf := make([]byte, 1000)
+ b.ResetTimer()
+ for n := b.N; n > 0; n-- {
+ r.Read(buf)
+ }
+}
+
+func BenchmarkConcurrent(b *testing.B) {
+ const goroutines = 4
+ var wg sync.WaitGroup
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ for n := b.N; n > 0; n-- {
+ Int63()
+ }
+ }()
+ }
+ wg.Wait()
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/regress_test.go b/platform/dbops/binaries/go/go/src/math/rand/regress_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..813098ec9c5a7bc1413f1ec6c65feaf837e30283
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/regress_test.go
@@ -0,0 +1,404 @@
+// Copyright 2014 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 that random number sequences generated by a specific seed
+// do not change from version to version.
+//
+// Do NOT make changes to the golden outputs. If bugs need to be fixed
+// in the underlying code, find ways to fix them that do not affect the
+// outputs.
+
+package rand_test
+
+import (
+ "flag"
+ "fmt"
+ . "math/rand"
+ "reflect"
+ "testing"
+)
+
+var printgolden = flag.Bool("printgolden", false, "print golden results for regression test")
+
+func TestRegress(t *testing.T) {
+ var int32s = []int32{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1}
+ var int64s = []int64{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1, 1000000000000000000, 1 << 60, 1<<63 - 2, 1<<63 - 1}
+ var permSizes = []int{0, 1, 5, 8, 9, 10, 16}
+ var readBufferSizes = []int{1, 7, 8, 9, 10}
+ r := New(NewSource(0))
+
+ rv := reflect.ValueOf(r)
+ n := rv.NumMethod()
+ p := 0
+ if *printgolden {
+ fmt.Printf("var regressGolden = []interface{}{\n")
+ }
+ for i := 0; i < n; i++ {
+ m := rv.Type().Method(i)
+ mv := rv.Method(i)
+ mt := mv.Type()
+ if mt.NumOut() == 0 {
+ continue
+ }
+ r.Seed(0)
+ for repeat := 0; repeat < 20; repeat++ {
+ var args []reflect.Value
+ var argstr string
+ if mt.NumIn() == 1 {
+ var x any
+ switch mt.In(0).Kind() {
+ default:
+ t.Fatalf("unexpected argument type for r.%s", m.Name)
+
+ case reflect.Int:
+ if m.Name == "Perm" {
+ x = permSizes[repeat%len(permSizes)]
+ break
+ }
+ big := int64s[repeat%len(int64s)]
+ if int64(int(big)) != big {
+ r.Int63n(big) // what would happen on 64-bit machine, to keep stream in sync
+ if *printgolden {
+ fmt.Printf("\tskipped, // must run printgolden on 64-bit machine\n")
+ }
+ p++
+ continue
+ }
+ x = int(big)
+
+ case reflect.Int32:
+ x = int32s[repeat%len(int32s)]
+
+ case reflect.Int64:
+ x = int64s[repeat%len(int64s)]
+
+ case reflect.Slice:
+ if m.Name == "Read" {
+ n := readBufferSizes[repeat%len(readBufferSizes)]
+ x = make([]byte, n)
+ }
+ }
+ argstr = fmt.Sprint(x)
+ args = append(args, reflect.ValueOf(x))
+ }
+
+ var out any
+ out = mv.Call(args)[0].Interface()
+ if m.Name == "Int" || m.Name == "Intn" {
+ out = int64(out.(int))
+ }
+ if m.Name == "Read" {
+ out = args[0].Interface().([]byte)
+ }
+ if *printgolden {
+ var val string
+ big := int64(1 << 60)
+ if int64(int(big)) != big && (m.Name == "Int" || m.Name == "Intn") {
+ // 32-bit machine cannot print 64-bit results
+ val = "truncated"
+ } else if reflect.TypeOf(out).Kind() == reflect.Slice {
+ val = fmt.Sprintf("%#v", out)
+ } else {
+ val = fmt.Sprintf("%T(%v)", out, out)
+ }
+ fmt.Printf("\t%s, // %s(%s)\n", val, m.Name, argstr)
+ } else {
+ want := regressGolden[p]
+ if m.Name == "Int" {
+ want = int64(int(uint(want.(int64)) << 1 >> 1))
+ }
+ if !reflect.DeepEqual(out, want) {
+ t.Errorf("r.%s(%s) = %v, want %v", m.Name, argstr, out, want)
+ }
+ }
+ p++
+ }
+ }
+ if *printgolden {
+ fmt.Printf("}\n")
+ }
+}
+
+var regressGolden = []any{
+ float64(4.668112973579268), // ExpFloat64()
+ float64(0.1601593871172866), // ExpFloat64()
+ float64(3.0465834105636), // ExpFloat64()
+ float64(0.06385839451671879), // ExpFloat64()
+ float64(1.8578917487258961), // ExpFloat64()
+ float64(0.784676123472182), // ExpFloat64()
+ float64(0.11225477361256932), // ExpFloat64()
+ float64(0.20173283329802255), // ExpFloat64()
+ float64(0.3468619496201105), // ExpFloat64()
+ float64(0.35601103454384536), // ExpFloat64()
+ float64(0.888376329507869), // ExpFloat64()
+ float64(1.4081362450365698), // ExpFloat64()
+ float64(1.0077753823151994), // ExpFloat64()
+ float64(0.23594100766227588), // ExpFloat64()
+ float64(2.777245612300007), // ExpFloat64()
+ float64(0.5202997830662377), // ExpFloat64()
+ float64(1.2842705247770294), // ExpFloat64()
+ float64(0.030307408362776206), // ExpFloat64()
+ float64(2.204156824853721), // ExpFloat64()
+ float64(2.09891923895058), // ExpFloat64()
+ float32(0.94519615), // Float32()
+ float32(0.24496509), // Float32()
+ float32(0.65595627), // Float32()
+ float32(0.05434384), // Float32()
+ float32(0.3675872), // Float32()
+ float32(0.28948045), // Float32()
+ float32(0.1924386), // Float32()
+ float32(0.65533215), // Float32()
+ float32(0.8971697), // Float32()
+ float32(0.16735445), // Float32()
+ float32(0.28858566), // Float32()
+ float32(0.9026048), // Float32()
+ float32(0.84978026), // Float32()
+ float32(0.2730468), // Float32()
+ float32(0.6090802), // Float32()
+ float32(0.253656), // Float32()
+ float32(0.7746542), // Float32()
+ float32(0.017480763), // Float32()
+ float32(0.78707397), // Float32()
+ float32(0.7993937), // Float32()
+ float64(0.9451961492941164), // Float64()
+ float64(0.24496508529377975), // Float64()
+ float64(0.6559562651954052), // Float64()
+ float64(0.05434383959970039), // Float64()
+ float64(0.36758720663245853), // Float64()
+ float64(0.2894804331565928), // Float64()
+ float64(0.19243860967493215), // Float64()
+ float64(0.6553321508148324), // Float64()
+ float64(0.897169713149801), // Float64()
+ float64(0.16735444255905835), // Float64()
+ float64(0.2885856518054551), // Float64()
+ float64(0.9026048462705047), // Float64()
+ float64(0.8497802817628735), // Float64()
+ float64(0.2730468047134829), // Float64()
+ float64(0.6090801919903561), // Float64()
+ float64(0.25365600644283687), // Float64()
+ float64(0.7746542391859803), // Float64()
+ float64(0.017480762156647272), // Float64()
+ float64(0.7870739563039942), // Float64()
+ float64(0.7993936979594545), // Float64()
+ int64(8717895732742165505), // Int()
+ int64(2259404117704393152), // Int()
+ int64(6050128673802995827), // Int()
+ int64(501233450539197794), // Int()
+ int64(3390393562759376202), // Int()
+ int64(2669985732393126063), // Int()
+ int64(1774932891286980153), // Int()
+ int64(6044372234677422456), // Int()
+ int64(8274930044578894929), // Int()
+ int64(1543572285742637646), // Int()
+ int64(2661732831099943416), // Int()
+ int64(8325060299420976708), // Int()
+ int64(7837839688282259259), // Int()
+ int64(2518412263346885298), // Int()
+ int64(5617773211005988520), // Int()
+ int64(2339563716805116249), // Int()
+ int64(7144924247938981575), // Int()
+ int64(161231572858529631), // Int()
+ int64(7259475919510918339), // Int()
+ int64(7373105480197164748), // Int()
+ int32(2029793274), // Int31()
+ int32(526058514), // Int31()
+ int32(1408655353), // Int31()
+ int32(116702506), // Int31()
+ int32(789387515), // Int31()
+ int32(621654496), // Int31()
+ int32(413258767), // Int31()
+ int32(1407315077), // Int31()
+ int32(1926657288), // Int31()
+ int32(359390928), // Int31()
+ int32(619732968), // Int31()
+ int32(1938329147), // Int31()
+ int32(1824889259), // Int31()
+ int32(586363548), // Int31()
+ int32(1307989752), // Int31()
+ int32(544722126), // Int31()
+ int32(1663557311), // Int31()
+ int32(37539650), // Int31()
+ int32(1690228450), // Int31()
+ int32(1716684894), // Int31()
+ int32(0), // Int31n(1)
+ int32(4), // Int31n(10)
+ int32(25), // Int31n(32)
+ int32(310570), // Int31n(1048576)
+ int32(857611), // Int31n(1048577)
+ int32(621654496), // Int31n(1000000000)
+ int32(413258767), // Int31n(1073741824)
+ int32(1407315077), // Int31n(2147483646)
+ int32(1926657288), // Int31n(2147483647)
+ int32(0), // Int31n(1)
+ int32(8), // Int31n(10)
+ int32(27), // Int31n(32)
+ int32(367019), // Int31n(1048576)
+ int32(209005), // Int31n(1048577)
+ int32(307989752), // Int31n(1000000000)
+ int32(544722126), // Int31n(1073741824)
+ int32(1663557311), // Int31n(2147483646)
+ int32(37539650), // Int31n(2147483647)
+ int32(0), // Int31n(1)
+ int32(4), // Int31n(10)
+ int64(8717895732742165505), // Int63()
+ int64(2259404117704393152), // Int63()
+ int64(6050128673802995827), // Int63()
+ int64(501233450539197794), // Int63()
+ int64(3390393562759376202), // Int63()
+ int64(2669985732393126063), // Int63()
+ int64(1774932891286980153), // Int63()
+ int64(6044372234677422456), // Int63()
+ int64(8274930044578894929), // Int63()
+ int64(1543572285742637646), // Int63()
+ int64(2661732831099943416), // Int63()
+ int64(8325060299420976708), // Int63()
+ int64(7837839688282259259), // Int63()
+ int64(2518412263346885298), // Int63()
+ int64(5617773211005988520), // Int63()
+ int64(2339563716805116249), // Int63()
+ int64(7144924247938981575), // Int63()
+ int64(161231572858529631), // Int63()
+ int64(7259475919510918339), // Int63()
+ int64(7373105480197164748), // Int63()
+ int64(0), // Int63n(1)
+ int64(2), // Int63n(10)
+ int64(19), // Int63n(32)
+ int64(959842), // Int63n(1048576)
+ int64(688912), // Int63n(1048577)
+ int64(393126063), // Int63n(1000000000)
+ int64(89212473), // Int63n(1073741824)
+ int64(834026388), // Int63n(2147483646)
+ int64(1577188963), // Int63n(2147483647)
+ int64(543572285742637646), // Int63n(1000000000000000000)
+ int64(355889821886249464), // Int63n(1152921504606846976)
+ int64(8325060299420976708), // Int63n(9223372036854775806)
+ int64(7837839688282259259), // Int63n(9223372036854775807)
+ int64(0), // Int63n(1)
+ int64(0), // Int63n(10)
+ int64(25), // Int63n(32)
+ int64(679623), // Int63n(1048576)
+ int64(882178), // Int63n(1048577)
+ int64(510918339), // Int63n(1000000000)
+ int64(782454476), // Int63n(1073741824)
+ int64(0), // Intn(1)
+ int64(4), // Intn(10)
+ int64(25), // Intn(32)
+ int64(310570), // Intn(1048576)
+ int64(857611), // Intn(1048577)
+ int64(621654496), // Intn(1000000000)
+ int64(413258767), // Intn(1073741824)
+ int64(1407315077), // Intn(2147483646)
+ int64(1926657288), // Intn(2147483647)
+ int64(543572285742637646), // Intn(1000000000000000000)
+ int64(355889821886249464), // Intn(1152921504606846976)
+ int64(8325060299420976708), // Intn(9223372036854775806)
+ int64(7837839688282259259), // Intn(9223372036854775807)
+ int64(0), // Intn(1)
+ int64(2), // Intn(10)
+ int64(14), // Intn(32)
+ int64(515775), // Intn(1048576)
+ int64(839455), // Intn(1048577)
+ int64(690228450), // Intn(1000000000)
+ int64(642943070), // Intn(1073741824)
+ float64(-0.28158587086436215), // NormFloat64()
+ float64(0.570933095808067), // NormFloat64()
+ float64(-1.6920196326157044), // NormFloat64()
+ float64(0.1996229111693099), // NormFloat64()
+ float64(1.9195199291234621), // NormFloat64()
+ float64(0.8954838794918353), // NormFloat64()
+ float64(0.41457072128813166), // NormFloat64()
+ float64(-0.48700161491544713), // NormFloat64()
+ float64(-0.1684059662402393), // NormFloat64()
+ float64(0.37056410998929545), // NormFloat64()
+ float64(1.0156889027029008), // NormFloat64()
+ float64(-0.5174422210625114), // NormFloat64()
+ float64(-0.5565834214413804), // NormFloat64()
+ float64(0.778320596648391), // NormFloat64()
+ float64(-1.8970718197702225), // NormFloat64()
+ float64(0.5229525761688676), // NormFloat64()
+ float64(-1.5515595563231523), // NormFloat64()
+ float64(0.0182029289376123), // NormFloat64()
+ float64(-0.6820951356608795), // NormFloat64()
+ float64(-0.5987943422687668), // NormFloat64()
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{0, 4, 1, 3, 2}, // Perm(5)
+ []int{3, 1, 0, 4, 7, 5, 2, 6}, // Perm(8)
+ []int{5, 0, 3, 6, 7, 4, 2, 1, 8}, // Perm(9)
+ []int{4, 5, 0, 2, 6, 9, 3, 1, 8, 7}, // Perm(10)
+ []int{14, 2, 0, 8, 3, 5, 13, 12, 1, 4, 6, 7, 11, 9, 15, 10}, // Perm(16)
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{3, 0, 1, 2, 4}, // Perm(5)
+ []int{5, 1, 2, 0, 4, 7, 3, 6}, // Perm(8)
+ []int{4, 0, 6, 8, 1, 5, 2, 7, 3}, // Perm(9)
+ []int{8, 6, 1, 7, 5, 4, 3, 2, 9, 0}, // Perm(10)
+ []int{0, 3, 13, 2, 15, 4, 10, 1, 8, 14, 7, 6, 12, 9, 5, 11}, // Perm(16)
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{0, 4, 2, 1, 3}, // Perm(5)
+ []int{2, 1, 7, 0, 6, 3, 4, 5}, // Perm(8)
+ []int{8, 7, 5, 3, 4, 6, 0, 1, 2}, // Perm(9)
+ []int{1, 0, 2, 5, 7, 6, 9, 8, 3, 4}, // Perm(10)
+ []byte{0x1}, // Read([0])
+ []byte{0x94, 0xfd, 0xc2, 0xfa, 0x2f, 0xfc, 0xc0}, // Read([0 0 0 0 0 0 0])
+ []byte{0x41, 0xd3, 0xff, 0x12, 0x4, 0x5b, 0x73, 0xc8}, // Read([0 0 0 0 0 0 0 0])
+ []byte{0x6e, 0x4f, 0xf9, 0x5f, 0xf6, 0x62, 0xa5, 0xee, 0xe8}, // Read([0 0 0 0 0 0 0 0 0])
+ []byte{0x2a, 0xbd, 0xf4, 0x4a, 0x2d, 0xb, 0x75, 0xfb, 0x18, 0xd}, // Read([0 0 0 0 0 0 0 0 0 0])
+ []byte{0xaf}, // Read([0])
+ []byte{0x48, 0xa7, 0x9e, 0xe0, 0xb1, 0xd, 0x39}, // Read([0 0 0 0 0 0 0])
+ []byte{0x46, 0x51, 0x85, 0xf, 0xd4, 0xa1, 0x78, 0x89}, // Read([0 0 0 0 0 0 0 0])
+ []byte{0x2e, 0xe2, 0x85, 0xec, 0xe1, 0x51, 0x14, 0x55, 0x78}, // Read([0 0 0 0 0 0 0 0 0])
+ []byte{0x8, 0x75, 0xd6, 0x4e, 0xe2, 0xd3, 0xd0, 0xd0, 0xde, 0x6b}, // Read([0 0 0 0 0 0 0 0 0 0])
+ []byte{0xf8}, // Read([0])
+ []byte{0xf9, 0xb4, 0x4c, 0xe8, 0x5f, 0xf0, 0x44}, // Read([0 0 0 0 0 0 0])
+ []byte{0xc6, 0xb1, 0xf8, 0x3b, 0x8e, 0x88, 0x3b, 0xbf}, // Read([0 0 0 0 0 0 0 0])
+ []byte{0x85, 0x7a, 0xab, 0x99, 0xc5, 0xb2, 0x52, 0xc7, 0x42}, // Read([0 0 0 0 0 0 0 0 0])
+ []byte{0x9c, 0x32, 0xf3, 0xa8, 0xae, 0xb7, 0x9e, 0xf8, 0x56, 0xf6}, // Read([0 0 0 0 0 0 0 0 0 0])
+ []byte{0x59}, // Read([0])
+ []byte{0xc1, 0x8f, 0xd, 0xce, 0xcc, 0x77, 0xc7}, // Read([0 0 0 0 0 0 0])
+ []byte{0x5e, 0x7a, 0x81, 0xbf, 0xde, 0x27, 0x5f, 0x67}, // Read([0 0 0 0 0 0 0 0])
+ []byte{0xcf, 0xe2, 0x42, 0xcf, 0x3c, 0xc3, 0x54, 0xf3, 0xed}, // Read([0 0 0 0 0 0 0 0 0])
+ []byte{0xe2, 0xd6, 0xbe, 0xcc, 0x4e, 0xa3, 0xae, 0x5e, 0x88, 0x52}, // Read([0 0 0 0 0 0 0 0 0 0])
+ uint32(4059586549), // Uint32()
+ uint32(1052117029), // Uint32()
+ uint32(2817310706), // Uint32()
+ uint32(233405013), // Uint32()
+ uint32(1578775030), // Uint32()
+ uint32(1243308993), // Uint32()
+ uint32(826517535), // Uint32()
+ uint32(2814630155), // Uint32()
+ uint32(3853314576), // Uint32()
+ uint32(718781857), // Uint32()
+ uint32(1239465936), // Uint32()
+ uint32(3876658295), // Uint32()
+ uint32(3649778518), // Uint32()
+ uint32(1172727096), // Uint32()
+ uint32(2615979505), // Uint32()
+ uint32(1089444252), // Uint32()
+ uint32(3327114623), // Uint32()
+ uint32(75079301), // Uint32()
+ uint32(3380456901), // Uint32()
+ uint32(3433369789), // Uint32()
+ uint64(8717895732742165505), // Uint64()
+ uint64(2259404117704393152), // Uint64()
+ uint64(6050128673802995827), // Uint64()
+ uint64(9724605487393973602), // Uint64()
+ uint64(12613765599614152010), // Uint64()
+ uint64(11893357769247901871), // Uint64()
+ uint64(1774932891286980153), // Uint64()
+ uint64(15267744271532198264), // Uint64()
+ uint64(17498302081433670737), // Uint64()
+ uint64(1543572285742637646), // Uint64()
+ uint64(11885104867954719224), // Uint64()
+ uint64(17548432336275752516), // Uint64()
+ uint64(7837839688282259259), // Uint64()
+ uint64(2518412263346885298), // Uint64()
+ uint64(5617773211005988520), // Uint64()
+ uint64(11562935753659892057), // Uint64()
+ uint64(16368296284793757383), // Uint64()
+ uint64(161231572858529631), // Uint64()
+ uint64(16482847956365694147), // Uint64()
+ uint64(16596477517051940556), // Uint64()
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/rng.go b/platform/dbops/binaries/go/go/src/math/rand/rng.go
new file mode 100644
index 0000000000000000000000000000000000000000..1e4a9e014fa78beb82a43e6b34f42c0cf29e152c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/rng.go
@@ -0,0 +1,252 @@
+// 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 rand
+
+/*
+ * Uniform distribution
+ *
+ * algorithm by
+ * DP Mitchell and JA Reeds
+ */
+
+const (
+ rngLen = 607
+ rngTap = 273
+ rngMax = 1 << 63
+ rngMask = rngMax - 1
+ int32max = (1 << 31) - 1
+)
+
+var (
+ // rngCooked used for seeding. See gen_cooked.go for details.
+ rngCooked [rngLen]int64 = [...]int64{
+ -4181792142133755926, -4576982950128230565, 1395769623340756751, 5333664234075297259,
+ -6347679516498800754, 9033628115061424579, 7143218595135194537, 4812947590706362721,
+ 7937252194349799378, 5307299880338848416, 8209348851763925077, -7107630437535961764,
+ 4593015457530856296, 8140875735541888011, -5903942795589686782, -603556388664454774,
+ -7496297993371156308, 113108499721038619, 4569519971459345583, -4160538177779461077,
+ -6835753265595711384, -6507240692498089696, 6559392774825876886, 7650093201692370310,
+ 7684323884043752161, -8965504200858744418, -2629915517445760644, 271327514973697897,
+ -6433985589514657524, 1065192797246149621, 3344507881999356393, -4763574095074709175,
+ 7465081662728599889, 1014950805555097187, -4773931307508785033, -5742262670416273165,
+ 2418672789110888383, 5796562887576294778, 4484266064449540171, 3738982361971787048,
+ -4699774852342421385, 10530508058128498, -589538253572429690, -6598062107225984180,
+ 8660405965245884302, 10162832508971942, -2682657355892958417, 7031802312784620857,
+ 6240911277345944669, 831864355460801054, -1218937899312622917, 2116287251661052151,
+ 2202309800992166967, 9161020366945053561, 4069299552407763864, 4936383537992622449,
+ 457351505131524928, -8881176990926596454, -6375600354038175299, -7155351920868399290,
+ 4368649989588021065, 887231587095185257, -3659780529968199312, -2407146836602825512,
+ 5616972787034086048, -751562733459939242, 1686575021641186857, -5177887698780513806,
+ -4979215821652996885, -1375154703071198421, 5632136521049761902, -8390088894796940536,
+ -193645528485698615, -5979788902190688516, -4907000935050298721, -285522056888777828,
+ -2776431630044341707, 1679342092332374735, 6050638460742422078, -2229851317345194226,
+ -1582494184340482199, 5881353426285907985, 812786550756860885, 4541845584483343330,
+ -6497901820577766722, 4980675660146853729, -4012602956251539747, -329088717864244987,
+ -2896929232104691526, 1495812843684243920, -2153620458055647789, 7370257291860230865,
+ -2466442761497833547, 4706794511633873654, -1398851569026877145, 8549875090542453214,
+ -9189721207376179652, -7894453601103453165, 7297902601803624459, 1011190183918857495,
+ -6985347000036920864, 5147159997473910359, -8326859945294252826, 2659470849286379941,
+ 6097729358393448602, -7491646050550022124, -5117116194870963097, -896216826133240300,
+ -745860416168701406, 5803876044675762232, -787954255994554146, -3234519180203704564,
+ -4507534739750823898, -1657200065590290694, 505808562678895611, -4153273856159712438,
+ -8381261370078904295, 572156825025677802, 1791881013492340891, 3393267094866038768,
+ -5444650186382539299, 2352769483186201278, -7930912453007408350, -325464993179687389,
+ -3441562999710612272, -6489413242825283295, 5092019688680754699, -227247482082248967,
+ 4234737173186232084, 5027558287275472836, 4635198586344772304, -536033143587636457,
+ 5907508150730407386, -8438615781380831356, 972392927514829904, -3801314342046600696,
+ -4064951393885491917, -174840358296132583, 2407211146698877100, -1640089820333676239,
+ 3940796514530962282, -5882197405809569433, 3095313889586102949, -1818050141166537098,
+ 5832080132947175283, 7890064875145919662, 8184139210799583195, -8073512175445549678,
+ -7758774793014564506, -4581724029666783935, 3516491885471466898, -8267083515063118116,
+ 6657089965014657519, 5220884358887979358, 1796677326474620641, 5340761970648932916,
+ 1147977171614181568, 5066037465548252321, 2574765911837859848, 1085848279845204775,
+ -5873264506986385449, 6116438694366558490, 2107701075971293812, -7420077970933506541,
+ 2469478054175558874, -1855128755834809824, -5431463669011098282, -9038325065738319171,
+ -6966276280341336160, 7217693971077460129, -8314322083775271549, 7196649268545224266,
+ -3585711691453906209, -5267827091426810625, 8057528650917418961, -5084103596553648165,
+ -2601445448341207749, -7850010900052094367, 6527366231383600011, 3507654575162700890,
+ 9202058512774729859, 1954818376891585542, -2582991129724600103, 8299563319178235687,
+ -5321504681635821435, 7046310742295574065, -2376176645520785576, -7650733936335907755,
+ 8850422670118399721, 3631909142291992901, 5158881091950831288, -6340413719511654215,
+ 4763258931815816403, 6280052734341785344, -4979582628649810958, 2043464728020827976,
+ -2678071570832690343, 4562580375758598164, 5495451168795427352, -7485059175264624713,
+ 553004618757816492, 6895160632757959823, -989748114590090637, 7139506338801360852,
+ -672480814466784139, 5535668688139305547, 2430933853350256242, -3821430778991574732,
+ -1063731997747047009, -3065878205254005442, 7632066283658143750, 6308328381617103346,
+ 3681878764086140361, 3289686137190109749, 6587997200611086848, 244714774258135476,
+ -5143583659437639708, 8090302575944624335, 2945117363431356361, -8359047641006034763,
+ 3009039260312620700, -793344576772241777, 401084700045993341, -1968749590416080887,
+ 4707864159563588614, -3583123505891281857, -3240864324164777915, -5908273794572565703,
+ -3719524458082857382, -5281400669679581926, 8118566580304798074, 3839261274019871296,
+ 7062410411742090847, -8481991033874568140, 6027994129690250817, -6725542042704711878,
+ -2971981702428546974, -7854441788951256975, 8809096399316380241, 6492004350391900708,
+ 2462145737463489636, -8818543617934476634, -5070345602623085213, -8961586321599299868,
+ -3758656652254704451, -8630661632476012791, 6764129236657751224, -709716318315418359,
+ -3403028373052861600, -8838073512170985897, -3999237033416576341, -2920240395515973663,
+ -2073249475545404416, 368107899140673753, -6108185202296464250, -6307735683270494757,
+ 4782583894627718279, 6718292300699989587, 8387085186914375220, 3387513132024756289,
+ 4654329375432538231, -292704475491394206, -3848998599978456535, 7623042350483453954,
+ 7725442901813263321, 9186225467561587250, -5132344747257272453, -6865740430362196008,
+ 2530936820058611833, 1636551876240043639, -3658707362519810009, 1452244145334316253,
+ -7161729655835084979, -7943791770359481772, 9108481583171221009, -3200093350120725999,
+ 5007630032676973346, 2153168792952589781, 6720334534964750538, -3181825545719981703,
+ 3433922409283786309, 2285479922797300912, 3110614940896576130, -2856812446131932915,
+ -3804580617188639299, 7163298419643543757, 4891138053923696990, 580618510277907015,
+ 1684034065251686769, 4429514767357295841, -8893025458299325803, -8103734041042601133,
+ 7177515271653460134, 4589042248470800257, -1530083407795771245, 143607045258444228,
+ 246994305896273627, -8356954712051676521, 6473547110565816071, 3092379936208876896,
+ 2058427839513754051, -4089587328327907870, 8785882556301281247, -3074039370013608197,
+ -637529855400303673, 6137678347805511274, -7152924852417805802, 5708223427705576541,
+ -3223714144396531304, 4358391411789012426, 325123008708389849, 6837621693887290924,
+ 4843721905315627004, -3212720814705499393, -3825019837890901156, 4602025990114250980,
+ 1044646352569048800, 9106614159853161675, -8394115921626182539, -4304087667751778808,
+ 2681532557646850893, 3681559472488511871, -3915372517896561773, -2889241648411946534,
+ -6564663803938238204, -8060058171802589521, 581945337509520675, 3648778920718647903,
+ -4799698790548231394, -7602572252857820065, 220828013409515943, -1072987336855386047,
+ 4287360518296753003, -4633371852008891965, 5513660857261085186, -2258542936462001533,
+ -8744380348503999773, 8746140185685648781, 228500091334420247, 1356187007457302238,
+ 3019253992034194581, 3152601605678500003, -8793219284148773595, 5559581553696971176,
+ 4916432985369275664, -8559797105120221417, -5802598197927043732, 2868348622579915573,
+ -7224052902810357288, -5894682518218493085, 2587672709781371173, -7706116723325376475,
+ 3092343956317362483, -5561119517847711700, 972445599196498113, -1558506600978816441,
+ 1708913533482282562, -2305554874185907314, -6005743014309462908, -6653329009633068701,
+ -483583197311151195, 2488075924621352812, -4529369641467339140, -4663743555056261452,
+ 2997203966153298104, 1282559373026354493, 240113143146674385, 8665713329246516443,
+ 628141331766346752, -4651421219668005332, -7750560848702540400, 7596648026010355826,
+ -3132152619100351065, 7834161864828164065, 7103445518877254909, 4390861237357459201,
+ -4780718172614204074, -319889632007444440, 622261699494173647, -3186110786557562560,
+ -8718967088789066690, -1948156510637662747, -8212195255998774408, -7028621931231314745,
+ 2623071828615234808, -4066058308780939700, -5484966924888173764, -6683604512778046238,
+ -6756087640505506466, 5256026990536851868, 7841086888628396109, 6640857538655893162,
+ -8021284697816458310, -7109857044414059830, -1689021141511844405, -4298087301956291063,
+ -4077748265377282003, -998231156719803476, 2719520354384050532, 9132346697815513771,
+ 4332154495710163773, -2085582442760428892, 6994721091344268833, -2556143461985726874,
+ -8567931991128098309, 59934747298466858, -3098398008776739403, -265597256199410390,
+ 2332206071942466437, -7522315324568406181, 3154897383618636503, -7585605855467168281,
+ -6762850759087199275, 197309393502684135, -8579694182469508493, 2543179307861934850,
+ 4350769010207485119, -4468719947444108136, -7207776534213261296, -1224312577878317200,
+ 4287946071480840813, 8362686366770308971, 6486469209321732151, -5605644191012979782,
+ -1669018511020473564, 4450022655153542367, -7618176296641240059, -3896357471549267421,
+ -4596796223304447488, -6531150016257070659, -8982326463137525940, -4125325062227681798,
+ -1306489741394045544, -8338554946557245229, 5329160409530630596, 7790979528857726136,
+ 4955070238059373407, -4304834761432101506, -6215295852904371179, 3007769226071157901,
+ -6753025801236972788, 8928702772696731736, 7856187920214445904, -4748497451462800923,
+ 7900176660600710914, -7082800908938549136, -6797926979589575837, -6737316883512927978,
+ 4186670094382025798, 1883939007446035042, -414705992779907823, 3734134241178479257,
+ 4065968871360089196, 6953124200385847784, -7917685222115876751, -7585632937840318161,
+ -5567246375906782599, -5256612402221608788, 3106378204088556331, -2894472214076325998,
+ 4565385105440252958, 1979884289539493806, -6891578849933910383, 3783206694208922581,
+ 8464961209802336085, 2843963751609577687, 3030678195484896323, -4429654462759003204,
+ 4459239494808162889, 402587895800087237, 8057891408711167515, 4541888170938985079,
+ 1042662272908816815, -3666068979732206850, 2647678726283249984, 2144477441549833761,
+ -3417019821499388721, -2105601033380872185, 5916597177708541638, -8760774321402454447,
+ 8833658097025758785, 5970273481425315300, 563813119381731307, -6455022486202078793,
+ 1598828206250873866, -4016978389451217698, -2988328551145513985, -6071154634840136312,
+ 8469693267274066490, 125672920241807416, -3912292412830714870, -2559617104544284221,
+ -486523741806024092, -4735332261862713930, 5923302823487327109, -9082480245771672572,
+ -1808429243461201518, 7990420780896957397, 4317817392807076702, 3625184369705367340,
+ -6482649271566653105, -3480272027152017464, -3225473396345736649, -368878695502291645,
+ -3981164001421868007, -8522033136963788610, 7609280429197514109, 3020985755112334161,
+ -2572049329799262942, 2635195723621160615, 5144520864246028816, -8188285521126945980,
+ 1567242097116389047, 8172389260191636581, -2885551685425483535, -7060359469858316883,
+ -6480181133964513127, -7317004403633452381, 6011544915663598137, 5932255307352610768,
+ 2241128460406315459, -8327867140638080220, 3094483003111372717, 4583857460292963101,
+ 9079887171656594975, -384082854924064405, -3460631649611717935, 4225072055348026230,
+ -7385151438465742745, 3801620336801580414, -399845416774701952, -7446754431269675473,
+ 7899055018877642622, 5421679761463003041, 5521102963086275121, -4975092593295409910,
+ 8735487530905098534, -7462844945281082830, -2080886987197029914, -1000715163927557685,
+ -4253840471931071485, -5828896094657903328, 6424174453260338141, 359248545074932887,
+ -5949720754023045210, -2426265837057637212, 3030918217665093212, -9077771202237461772,
+ -3186796180789149575, 740416251634527158, -2142944401404840226, 6951781370868335478,
+ 399922722363687927, -8928469722407522623, -1378421100515597285, -8343051178220066766,
+ -3030716356046100229, -8811767350470065420, 9026808440365124461, 6440783557497587732,
+ 4615674634722404292, 539897290441580544, 2096238225866883852, 8751955639408182687,
+ -7316147128802486205, 7381039757301768559, 6157238513393239656, -1473377804940618233,
+ 8629571604380892756, 5280433031239081479, 7101611890139813254, 2479018537985767835,
+ 7169176924412769570, -1281305539061572506, -7865612307799218120, 2278447439451174845,
+ 3625338785743880657, 6477479539006708521, 8976185375579272206, -3712000482142939688,
+ 1326024180520890843, 7537449876596048829, 5464680203499696154, 3189671183162196045,
+ 6346751753565857109, -8982212049534145501, -6127578587196093755, -245039190118465649,
+ -6320577374581628592, 7208698530190629697, 7276901792339343736, -7490986807540332668,
+ 4133292154170828382, 2918308698224194548, -7703910638917631350, -3929437324238184044,
+ -4300543082831323144, -6344160503358350167, 5896236396443472108, -758328221503023383,
+ -1894351639983151068, -307900319840287220, -6278469401177312761, -2171292963361310674,
+ 8382142935188824023, 9103922860780351547, 4152330101494654406,
+ }
+)
+
+type rngSource struct {
+ tap int // index into vec
+ feed int // index into vec
+ vec [rngLen]int64 // current feedback register
+}
+
+// seed rng x[n+1] = 48271 * x[n] mod (2**31 - 1)
+func seedrand(x int32) int32 {
+ const (
+ A = 48271
+ Q = 44488
+ R = 3399
+ )
+
+ hi := x / Q
+ lo := x % Q
+ x = A*lo - R*hi
+ if x < 0 {
+ x += int32max
+ }
+ return x
+}
+
+// Seed uses the provided seed value to initialize the generator to a deterministic state.
+func (rng *rngSource) Seed(seed int64) {
+ rng.tap = 0
+ rng.feed = rngLen - rngTap
+
+ seed = seed % int32max
+ if seed < 0 {
+ seed += int32max
+ }
+ if seed == 0 {
+ seed = 89482311
+ }
+
+ x := int32(seed)
+ for i := -20; i < rngLen; i++ {
+ x = seedrand(x)
+ if i >= 0 {
+ var u int64
+ u = int64(x) << 40
+ x = seedrand(x)
+ u ^= int64(x) << 20
+ x = seedrand(x)
+ u ^= int64(x)
+ u ^= rngCooked[i]
+ rng.vec[i] = u
+ }
+ }
+}
+
+// Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
+func (rng *rngSource) Int63() int64 {
+ return int64(rng.Uint64() & rngMask)
+}
+
+// Uint64 returns a non-negative pseudo-random 64-bit integer as a uint64.
+func (rng *rngSource) Uint64() uint64 {
+ rng.tap--
+ if rng.tap < 0 {
+ rng.tap += rngLen
+ }
+
+ rng.feed--
+ if rng.feed < 0 {
+ rng.feed += rngLen
+ }
+
+ x := rng.vec[rng.feed] + rng.vec[rng.tap]
+ rng.vec[rng.feed] = x
+ return uint64(x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/auto_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/auto_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f689733d1ed2ef18b33bc04226959d261ff40e9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/auto_test.go
@@ -0,0 +1,40 @@
+// 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 rand_test
+
+import (
+ . "math/rand/v2"
+ "testing"
+)
+
+// This test is first, in its own file with an alphabetically early name,
+// to try to make sure that it runs early. It has the best chance of
+// detecting deterministic seeding if it's the first test that runs.
+
+func TestAuto(t *testing.T) {
+ // Pull out 10 int64s from the global source
+ // and then check that they don't appear in that
+ // order in the deterministic seeded result.
+ var out []int64
+ for i := 0; i < 10; i++ {
+ out = append(out, Int64())
+ }
+
+ // Look for out in seeded output.
+ // Strictly speaking, we should look for them in order,
+ // but this is good enough and not significantly more
+ // likely to have a false positive.
+ r := New(NewPCG(1, 0))
+ found := 0
+ for i := 0; i < 1000; i++ {
+ x := r.Int64()
+ if x == out[found] {
+ found++
+ if found == len(out) {
+ t.Fatalf("found unseeded output in Seed(1) output")
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8.go b/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8.go
new file mode 100644
index 0000000000000000000000000000000000000000..6b9aa7278250f81b99e19ebbed7b8a2ce8f76afe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8.go
@@ -0,0 +1,46 @@
+// 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 rand
+
+import "internal/chacha8rand"
+
+// A ChaCha8 is a ChaCha8-based cryptographically strong
+// random number generator.
+type ChaCha8 struct {
+ state chacha8rand.State
+}
+
+// NewChaCha8 returns a new ChaCha8 seeded with the given seed.
+func NewChaCha8(seed [32]byte) *ChaCha8 {
+ c := new(ChaCha8)
+ c.state.Init(seed)
+ return c
+}
+
+// Seed resets the ChaCha8 to behave the same way as NewChaCha8(seed).
+func (c *ChaCha8) Seed(seed [32]byte) {
+ c.state.Init(seed)
+}
+
+// Uint64 returns a uniformly distributed random uint64 value.
+func (c *ChaCha8) Uint64() uint64 {
+ for {
+ x, ok := c.state.Next()
+ if ok {
+ return x
+ }
+ c.state.Refill()
+ }
+}
+
+// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
+func (c *ChaCha8) UnmarshalBinary(data []byte) error {
+ return chacha8rand.Unmarshal(&c.state, data)
+}
+
+// MarshalBinary implements the encoding.BinaryMarshaler interface.
+func (c *ChaCha8) MarshalBinary() ([]byte, error) {
+ return chacha8rand.Marshal(&c.state), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2c55b479b25fe720d62d5a7af1c8630c3a32d608
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/chacha8_test.go
@@ -0,0 +1,531 @@
+// 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 rand_test
+
+import (
+ . "math/rand/v2"
+ "testing"
+)
+
+func TestChaCha8(t *testing.T) {
+ p := NewChaCha8(chacha8seed)
+ for i, x := range chacha8output {
+ if u := p.Uint64(); u != x {
+ t.Errorf("ChaCha8 #%d = %#x, want %#x", i, u, x)
+ }
+ }
+
+ p.Seed(chacha8seed)
+ for i, x := range chacha8output {
+ if u := p.Uint64(); u != x {
+ t.Errorf("ChaCha8 #%d = %#x, want %#x", i, u, x)
+ }
+ }
+}
+
+func TestChaCha8Marshal(t *testing.T) {
+ p := NewChaCha8(chacha8seed)
+ for i, x := range chacha8output {
+ enc, err := p.MarshalBinary()
+ if err != nil {
+ t.Fatalf("#%d: MarshalBinary: %v", i, err)
+ }
+ if string(enc) != chacha8marshal[i] {
+ t.Fatalf("#%d: MarshalBinary=%q, want %q", i, enc, chacha8marshal[i])
+ }
+ *p = ChaCha8{}
+ if err := p.UnmarshalBinary(enc); err != nil {
+ t.Fatalf("#%d: UnmarshalBinary: %v", i, err)
+ }
+ if u := p.Uint64(); u != x {
+ t.Errorf("ChaCha8 #%d = %#x, want %#x", i, u, x)
+ }
+ }
+}
+
+func BenchmarkChaCha8(b *testing.B) {
+ p := NewChaCha8([32]byte{1, 2, 3, 4, 5})
+ var t uint64
+ for n := b.N; n > 0; n-- {
+ t += p.Uint64()
+ }
+ Sink = t
+}
+
+// Golden output test to make sure algorithm never changes,
+// so that its use in math/rand/v2 stays stable.
+
+var chacha8seed = [32]byte([]byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"))
+
+var chacha8output = []uint64{
+ 0xb773b6063d4616a5, 0x1160af22a66abc3c, 0x8c2599d9418d287c, 0x7ee07e037edc5cd6,
+ 0xcfaa9ee02d1c16ad, 0x0e090eef8febea79, 0x3c82d271128b5b3e, 0x9c5addc11252a34f,
+ 0xdf79bb617d6ceea6, 0x36d553591f9d736a, 0xeef0d14e181ee01f, 0x089bfc760ae58436,
+ 0xd9e52b59cc2ad268, 0xeb2fb4444b1b8aba, 0x4f95c8a692c46661, 0xc3c6323217cae62c,
+ 0x91ebb4367f4e2e7e, 0x784cf2c6a0ec9bc6, 0x5c34ec5c34eabe20, 0x4f0a8f515570daa8,
+ 0xfc35dcb4113d6bf2, 0x5b0da44c645554bc, 0x6d963da3db21d9e1, 0xeeaefc3150e500f3,
+ 0x2d37923dda3750a5, 0x380d7a626d4bc8b0, 0xeeaf68ede3d7ee49, 0xf4356695883b717c,
+ 0x846a9021392495a4, 0x8e8510549630a61b, 0x18dc02545dbae493, 0x0f8f9ff0a65a3d43,
+ 0xccf065f7190ff080, 0xfd76d1aa39673330, 0x95d232936cba6433, 0x6c7456d1070cbd17,
+ 0x462acfdaff8c6562, 0x5bafab866d34fc6a, 0x0c862f78030a2988, 0xd39a83e407c3163d,
+ 0xc00a2b7b45f22ebf, 0x564307c62466b1a9, 0x257e0424b0c072d4, 0x6fb55e99496c28fe,
+ 0xae9873a88f5cd4e0, 0x4657362ac60d3773, 0x1c83f91ecdf23e8e, 0x6fdc0792c15387c0,
+ 0x36dad2a30dfd2b5c, 0xa4b593290595bdb7, 0x4de18934e4cc02c5, 0xcdc0d604f015e3a7,
+ 0xfba0dbf69ad80321, 0x60e8bea3d139de87, 0xd18a4d851ef48756, 0x6366447c2215f34a,
+ 0x05682e97d3d007ee, 0x4c0e8978c6d54ab2, 0xcf1e9f6a6712edc2, 0x061439414c80cfd3,
+ 0xd1a8b6e2745c0ead, 0x31a7918d45c410e8, 0xabcc61ad90216eec, 0x4040d92d2032a71a,
+ 0x3cd2f66ffb40cd68, 0xdcd051c07295857a, 0xeab55cbcd9ab527e, 0x18471dce781bdaac,
+ 0xf7f08cd144dc7252, 0x5804e0b13d7f40d1, 0x5cb1a446e4b2d35b, 0xe6d4a728d2138a06,
+ 0x05223e40ca60dad8, 0x2d61ec3206ac6a68, 0xab692356874c17b8, 0xc30954417676de1c,
+ 0x4f1ace3732225624, 0xfba9510813988338, 0x997f200f52752e11, 0x1116aaafe86221fa,
+ 0x07ce3b5cb2a13519, 0x2956bc72bc458314, 0x4188b7926140eb78, 0x56ca6dbfd4adea4d,
+ 0x7fe3c22349340ce5, 0x35c08f9c37675f8a, 0x11e1c7fbef5ed521, 0x98adc8464ec1bc75,
+ 0xd163b2c73d1203f8, 0x8c761ee043a2f3f3, 0x24b99d6accecd7b7, 0x793e31aa112f0370,
+ 0x8e87dc2a19285139, 0x4247ae04f7096e25, 0x514f3122926fe20f, 0xdc6fb3f045d2a7e9,
+ 0x15cb30cecdd18eba, 0xcbc7fdecf6900274, 0x3fb5c696dc8ba021, 0xd1664417c8d274e6,
+ 0x05f7e445ea457278, 0xf920bbca1b9db657, 0x0c1950b4da22cb99, 0xf875baf1af09e292,
+ 0xbed3d7b84250f838, 0xf198e8080fd74160, 0xc9eda51d9b7ea703, 0xf709ef55439bf8f6,
+ 0xd20c74feebf116fc, 0x305668eb146d7546, 0x829af3ec10d89787, 0x15b8f9697b551dbc,
+ 0xfc823c6c8e64b8c9, 0x345585e8183b40bc, 0x674b4171d6581368, 0x1234d81cd670e9f7,
+ 0x0e505210d8a55e19, 0xe8258d69eeeca0dc, 0x05d4c452e8baf67e, 0xe8dbe30116a45599,
+ 0x1cf08ce1b1176f00, 0xccf7d0a4b81ecb49, 0x303fea136b2c430e, 0x861d6c139c06c871,
+ 0x5f41df72e05e0487, 0x25bd7e1e1ae26b1d, 0xbe9f4004d662a41d, 0x65bf58d483188546,
+ 0xd1b27cff69db13cc, 0x01a6663372c1bb36, 0x578dd7577b727f4d, 0x19c78f066c083cf6,
+ 0xdbe014d4f9c391bb, 0x97fbb2dd1d13ffb3, 0x31c91e0af9ef8d4f, 0x094dfc98402a43ba,
+ 0x069bd61bea37b752, 0x5b72d762e8d986ca, 0x72ee31865904bc85, 0xd1f5fdc5cd36c33e,
+ 0xba9b4980a8947cad, 0xece8f05eac49ab43, 0x65fe1184abae38e7, 0x2d7cb9dea5d31452,
+ 0xcc71489476e467e3, 0x4c03a258a578c68c, 0x00efdf9ecb0fd8fc, 0x9924cad471e2666d,
+ 0x87f8668318f765e9, 0xcb4dc57c1b55f5d8, 0xd373835a86604859, 0xe526568b5540e482,
+ 0x1f39040f08586fec, 0xb764f3f00293f8e6, 0x049443a2f6bd50a8, 0x76fec88697d3941a,
+ 0x3efb70d039bae7a2, 0xe2f4611368eca8a8, 0x7c007a96e01d2425, 0xbbcce5768e69c5bf,
+ 0x784fb4985c42aac3, 0xf72b5091aa223874, 0x3630333fb1e62e07, 0x8e7319ebdebbb8de,
+ 0x2a3982bca959fa00, 0xb2b98b9f964ba9b3, 0xf7e31014adb71951, 0xebd0fca3703acc82,
+ 0xec654e2a2fe6419a, 0xb326132d55a52e2c, 0x2248c57f44502978, 0x32710c2f342daf16,
+ 0x0517b47b5acb2bec, 0x4c7a718fca270937, 0xd69142bed0bcc541, 0xe40ebcb8ff52ce88,
+ 0x3e44a2dbc9f828d4, 0xc74c2f4f8f873f58, 0x3dbf648eb799e45b, 0x33f22475ee0e86f8,
+ 0x1eb4f9ee16d47f65, 0x40f8d2b8712744e3, 0xb886b4da3cb14572, 0x2086326fbdd6f64d,
+ 0xcc3de5907dd882b9, 0xa2e8b49a5ee909df, 0xdbfb8e7823964c10, 0x70dd6089ef0df8d5,
+ 0x30141663cdd9c99f, 0x04b805325c240365, 0x7483d80314ac12d6, 0x2b271cb91aa7f5f9,
+ 0x97e2245362abddf0, 0x5a84f614232a9fab, 0xf71125fcda4b7fa2, 0x1ca5a61d74b27267,
+ 0x38cc6a9b3adbcb45, 0xdde1bb85dc653e39, 0xe9d0c8fa64f89fd4, 0x02c5fb1ecd2b4188,
+ 0xf2bd137bca5756e5, 0xadefe25d121be155, 0x56cd1c3c5d893a8e, 0x4c50d337beb65bb9,
+ 0x918c5151675cf567, 0xaba649ffcfb56a1e, 0x20c74ab26a2247cd, 0x71166bac853c08da,
+ 0xb07befe2e584fc5d, 0xda45ff2a588dbf32, 0xdb98b03c4d75095e, 0x60285ae1aaa65a4c,
+ 0xf93b686a263140b8, 0xde469752ee1c180e, 0xcec232dc04129aae, 0xeb916baa1835ea04,
+ 0xd49c21c8b64388ff, 0x72a82d9658864888, 0x003348ef7eac66a8, 0x7f6f67e655b209eb,
+ 0x532ffb0b7a941b25, 0xd940ade6128deede, 0xdf24f2a1af89fe23, 0x95aa3b4988195ae0,
+ 0x3da649404f94be4a, 0x692dad132c3f7e27, 0x40aee76ecaaa9eb8, 0x1294a01e09655024,
+ 0x6df797abdba4e4f5, 0xea2fb6024c1d7032, 0x5f4e0492295489fc, 0x57972914ea22e06a,
+ 0x9a8137d133aad473, 0xa2e6dd6ae7cdf2f3, 0x9f42644f18086647, 0x16d03301c170bd3e,
+ 0x908c416fa546656d, 0xe081503be22e123e, 0x077cf09116c4cc72, 0xcbd25cd264b7f229,
+ 0x3db2f468ec594031, 0x46c00e734c9badd5, 0xd0ec0ac72075d861, 0x3037cb3cf80b7630,
+ 0x574c3d7b3a2721c6, 0xae99906a0076824b, 0xb175a5418b532e70, 0xd8b3e251ee231ddd,
+ 0xb433eec25dca1966, 0x530f30dc5cff9a93, 0x9ff03d98b53cd335, 0xafc4225076558cdf,
+ 0xef81d3a28284402a, 0x110bdbf51c110a28, 0x9ae1b255d027e8f6, 0x7de3e0aa24688332,
+ 0xe483c3ecd2067ee2, 0xf829328b276137e6, 0xa413ccad57562cad, 0xe6118e8b496acb1f,
+ 0x8288dca6da5ec01f, 0xa53777dc88c17255, 0x8a00f1e0d5716eda, 0x618e6f47b7a720a8,
+ 0x9e3907b0c692a841, 0x978b42ca963f34f3, 0x75e4b0cd98a7d7ef, 0xde4dbd6e0b5f4752,
+ 0x0252e4153f34493f, 0x50f0e7d803734ef9, 0x237766a38ed167ee, 0x4124414001ee39a0,
+ 0xd08df643e535bb21, 0x34f575b5a9a80b74, 0x2c343af87297f755, 0xcd8b6d99d821f7cb,
+ 0xe376fd7256fc48ae, 0xe1b06e7334352885, 0xfa87b26f86c169eb, 0x36c1604665a971de,
+ 0xdba147c2239c8e80, 0x6b208e69fc7f0e24, 0x8795395b6f2b60c3, 0x05dabee9194907f4,
+ 0xb98175142f5ed902, 0x5e1701e2021ddc81, 0x0875aba2755eed08, 0x778d83289251de95,
+ 0x3bfbe46a039ecb31, 0xb24704fce4cbd7f9, 0x6985ffe9a7c91e3d, 0xc8efb13df249dabb,
+ 0xb1037e64b0f4c9f6, 0x55f69fd197d6b7c3, 0x672589d71d68a90c, 0xbebdb8224f50a77e,
+ 0x3f589f80007374a7, 0xd307f4635954182a, 0xcff5850c10d4fd90, 0xc6da02dfb6408e15,
+ 0x93daeef1e2b1a485, 0x65d833208aeea625, 0xe2b13fa13ed3b5fa, 0x67053538130fb68e,
+ 0xc1042f6598218fa9, 0xee5badca749b8a2e, 0x6d22a3f947dae37d, 0xb62c6d1657f4dbaf,
+ 0x6e007de69704c20b, 0x1af2b913fc3841d8, 0xdc0e47348e2e8e22, 0x9b1ddef1cf958b22,
+ 0x632ed6b0233066b8, 0xddd02d3311bed8f2, 0xf147cfe1834656e9, 0x399aaa49d511597a,
+ 0x6b14886979ec0309, 0x64fc4ac36b5afb97, 0xb82f78e07f7cf081, 0x10925c9a323d0e1b,
+ 0xf451c79ee13c63f6, 0x7c2fc180317876c7, 0x35a12bd9eecb7d22, 0x335654a539621f90,
+ 0xcc32a3f35db581f0, 0xc60748a80b2369cb, 0x7c4dd3b08591156b, 0xac1ced4b6de22291,
+ 0xa32cfa2df134def5, 0x627108918dea2a53, 0x0555b1608fcb4ff4, 0x143ee7ac43aaa33c,
+ 0xdae90ce7cf4fc218, 0x4d68fc2582bcf4b5, 0x37094e1849135d71, 0xf7857e09f3d49fd8,
+ 0x007538c503768be7, 0xedf648ba2f6be601, 0xaa347664dd72513e, 0xbe63893c6ef23b86,
+ 0x130b85710605af97, 0xdd765c6b1ef6ab56, 0xf3249a629a97dc6b, 0x2a114f9020fab8e5,
+ 0x5a69e027cfc6ad08, 0x3c4ccb36f1a5e050, 0x2e9e7d596834f0a5, 0x2430be6858fce789,
+ 0xe90b862f2466e597, 0x895e2884f159a9ec, 0x26ab8fa4902fcb57, 0xa6efff5c54e1fa50,
+ 0x333ac4e5811a8255, 0xa58d515f02498611, 0xfe5a09dcb25c6ef4, 0x03898988ab5f5818,
+ 0x289ff6242af6c617, 0x3d9dd59fd381ea23, 0x52d7d93d8a8aae51, 0xc76a123d511f786f,
+ 0xf68901edaf00c46c, 0x8c630871b590de80, 0x05209c308991e091, 0x1f809f99b4788177,
+ 0x11170c2eb6c19fd8, 0x44433c779062ba58, 0xc0acb51af1874c45, 0x9f2e134284809fa1,
+ 0xedb523bd15c619fa, 0x02d97fd53ecc23c0, 0xacaf05a34462374c, 0xddd9c6d34bffa11f,
+}
+
+var chacha8marshal = []string{
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x00ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x01ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x02ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x03ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x04ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x05ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x06ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\aABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\bABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\tABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\nABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\vABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\fABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\rABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0eABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0fABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x10ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x11ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x12ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x13ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x14ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x15ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x16ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x17ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x18ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x19ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1aABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1bABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1cABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1dABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1eABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1fABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00 ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00!ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00#ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00$ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00%ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00&ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00(ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00)ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00*ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00+ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00,ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00-ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00.ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00/ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x000ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x001ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x002ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x003ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x004ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x005ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x006ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x007ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x008ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x009ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00:ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00;ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00?ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00@ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00AABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00BABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00CABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00DABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00EABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00FABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00GABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00HABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00IABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00JABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00KABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00LABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00MABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00NABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00OABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00PABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00QABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00RABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00SABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00TABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00UABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00VABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00WABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00XABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00YABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00ZABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00[ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\\ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00]ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00^ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00`ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00aABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00bABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00cABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00dABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00eABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00fABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00gABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00hABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00iABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00jABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00kABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00lABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00mABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00nABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00oABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00pABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00qABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00rABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00sABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00tABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00uABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00vABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00wABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00xABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00yABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00zABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00{ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00|ABCDEFGHIJKLMNOPQRSTUVWXYZ123456",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x01>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x02>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x03>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x04>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x05>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x06>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\a>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\b>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\t>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\n>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\v>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\f>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\r>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0e>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0f>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x10>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x11>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x12>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x13>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x14>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x15>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x16>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x17>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x18>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x19>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1a>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1b>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1c>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1d>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1e>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1f>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00 >\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00!>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\">\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00#>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00$>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00%>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00&>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00'>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00(>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00)>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00*>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00+>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00,>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00->\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00.>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00/>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x000>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x001>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x002>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x003>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x004>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x005>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x006>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x007>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x008>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x009>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00:>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00;>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00<>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00=>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00>>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00?>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00@>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00A>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00B>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00C>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00D>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00E>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00F>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00G>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00H>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00I>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00J>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00K>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00L>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00M>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00N>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00O>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00P>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00Q>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00R>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00S>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00T>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00U>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00V>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00W>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00X>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00Y>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00Z>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00[>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\\>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00]>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00^>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00_>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00`>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00a>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00b>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00c>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00d>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00e>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00f>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00g>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00h>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00i>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00j>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00k>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00l>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00m>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00n>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00o>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00p>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00q>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00r>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00s>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00t>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00u>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00v>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00w>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00x>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00y>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00z>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00{>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00|>\x15\x0e\xacHk4O\x11a\xa8R\xcd5\x9atr\x8cXO\x9c]\x10\xdf\xf61\xea\x11\x18\x06\x8a\xaa",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x01K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x02K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x03K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x04K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x05K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x06K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\aK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\bK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\tK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\nK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\vK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\fK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\rK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0eK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x0fK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x10K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x11K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x12K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x13K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x14K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x15K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x16K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x17K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x18K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x19K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1aK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1bK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1cK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1dK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1eK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\x1fK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00 K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00!K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\"K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00#K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00$K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00%K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00&K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00'K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00(K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00)K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00*K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00+K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00,K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00-K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00.K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00/K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x000K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x001K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x002K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x003K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x004K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x005K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x006K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x007K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x008K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x009K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00:K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00;K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00?K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00@K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00AK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00BK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00CK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00DK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00EK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00FK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00GK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00HK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00IK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00JK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00KK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00LK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00MK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00NK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00OK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00PK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00QK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00RK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00SK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00TK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00UK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00VK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00WK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00XK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00YK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00ZK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00[K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00\\K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00]K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00^K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00_K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00`K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00aK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00bK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00cK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00dK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00eK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00fK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00gK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00hK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00iK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00jK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00kK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00lK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00mK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00nK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00oK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00pK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00qK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00rK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00sK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00tK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00uK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00vK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00wK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00xK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00yK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00zK3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+ "chacha8:\x00\x00\x00\x00\x00\x00\x00{K3\x9bB!,\x94\x9d\x975\xce'O_t\xee|\xb21\x87\xbb\xbb\xfd)\x8f\xe52\x01\vP\fk",
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/example_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..070b0ad0be6a5440fdd1617affcfc1a7623c11c6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/example_test.go
@@ -0,0 +1,142 @@
+// 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 rand_test
+
+import (
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "strings"
+ "text/tabwriter"
+ "time"
+)
+
+// These tests serve as an example but also make sure we don't change
+// the output of the random number generator when given a fixed seed.
+
+func Example() {
+ answers := []string{
+ "It is certain",
+ "It is decidedly so",
+ "Without a doubt",
+ "Yes definitely",
+ "You may rely on it",
+ "As I see it yes",
+ "Most likely",
+ "Outlook good",
+ "Yes",
+ "Signs point to yes",
+ "Reply hazy try again",
+ "Ask again later",
+ "Better not tell you now",
+ "Cannot predict now",
+ "Concentrate and ask again",
+ "Don't count on it",
+ "My reply is no",
+ "My sources say no",
+ "Outlook not so good",
+ "Very doubtful",
+ }
+ fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))])
+}
+
+// This example shows the use of each of the methods on a *Rand.
+// The use of the global functions is the same, without the receiver.
+func Example_rand() {
+ // Create and seed the generator.
+ // Typically a non-fixed seed should be used, such as Uint64(), Uint64().
+ // Using a fixed seed will produce the same output on every run.
+ r := rand.New(rand.NewPCG(1, 2))
+
+ // The tabwriter here helps us generate aligned output.
+ w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
+ defer w.Flush()
+ show := func(name string, v1, v2, v3 any) {
+ fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
+ }
+
+ // Float32 and Float64 values are in [0, 1).
+ show("Float32", r.Float32(), r.Float32(), r.Float32())
+ show("Float64", r.Float64(), r.Float64(), r.Float64())
+
+ // ExpFloat64 values have an average of 1 but decay exponentially.
+ show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
+
+ // NormFloat64 values have an average of 0 and a standard deviation of 1.
+ show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
+
+ // Int32, Int64, and Uint32 generate values of the given width.
+ // The Int method (not shown) is like either Int32 or Int64
+ // depending on the size of 'int'.
+ show("Int32", r.Int32(), r.Int32(), r.Int32())
+ show("Int64", r.Int64(), r.Int64(), r.Int64())
+ show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
+
+ // IntN, Int32N, and Int64N limit their output to be < n.
+ // They do so more carefully than using r.Int()%n.
+ show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10))
+ show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10))
+ show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10))
+
+ // Perm generates a random permutation of the numbers [0, n).
+ show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
+ // Output:
+ // Float32 0.95955694 0.8076733 0.8135684
+ // Float64 0.4297927436037299 0.797802349388613 0.3883664855410056
+ // ExpFloat64 0.43463410545541104 0.5513632046504593 0.7426404617374481
+ // NormFloat64 -0.9303318111676635 -0.04750789419852852 0.22248301107582735
+ // Int32 2020777787 260808523 851126509
+ // Int64 5231057920893523323 4257872588489500903 158397175702351138
+ // Uint32 314478343 1418758728 208955345
+ // IntN(10) 6 2 0
+ // Int32N(10) 3 7 7
+ // Int64N(10) 8 9 4
+ // Perm [0 3 1 4 2] [4 1 2 0 3] [4 3 2 0 1]
+}
+
+func ExamplePerm() {
+ for _, value := range rand.Perm(3) {
+ fmt.Println(value)
+ }
+
+ // Unordered output: 1
+ // 2
+ // 0
+}
+
+func ExampleN() {
+ // Print an int64 in the half-open interval [0, 100).
+ fmt.Println(rand.N(int64(100)))
+
+ // Sleep for a random duration between 0 and 100 milliseconds.
+ time.Sleep(rand.N(100 * time.Millisecond))
+}
+
+func ExampleShuffle() {
+ words := strings.Fields("ink runs from the corners of my mouth")
+ rand.Shuffle(len(words), func(i, j int) {
+ words[i], words[j] = words[j], words[i]
+ })
+ fmt.Println(words)
+}
+
+func ExampleShuffle_slicesInUnison() {
+ numbers := []byte("12345")
+ letters := []byte("ABCDE")
+ // Shuffle numbers, swapping corresponding entries in letters at the same time.
+ rand.Shuffle(len(numbers), func(i, j int) {
+ numbers[i], numbers[j] = numbers[j], numbers[i]
+ letters[i], letters[j] = letters[j], letters[i]
+ })
+ for i := range numbers {
+ fmt.Printf("%c: %c\n", letters[i], numbers[i])
+ }
+}
+
+func ExampleIntN() {
+ fmt.Println(rand.IntN(100))
+ fmt.Println(rand.IntN(100))
+ fmt.Println(rand.IntN(100))
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/exp.go b/platform/dbops/binaries/go/go/src/math/rand/v2/exp.go
new file mode 100644
index 0000000000000000000000000000000000000000..ed7f7277bc591ee1977a50fe4f6d62339e9c64a4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/exp.go
@@ -0,0 +1,222 @@
+// 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 rand
+
+import (
+ "math"
+)
+
+/*
+ * Exponential distribution
+ *
+ * See "The Ziggurat Method for Generating Random Variables"
+ * (Marsaglia & Tsang, 2000)
+ * https://www.jstatsoft.org/v05/i08/paper [pdf]
+ */
+
+const (
+ re = 7.69711747013104972
+)
+
+// ExpFloat64 returns an exponentially distributed float64 in the range
+// (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
+// (lambda) is 1 and whose mean is 1/lambda (1).
+// To produce a distribution with a different rate parameter,
+// callers can adjust the output using:
+//
+// sample = ExpFloat64() / desiredRateParameter
+func (r *Rand) ExpFloat64() float64 {
+ for {
+ u := r.Uint64()
+ j := uint32(u)
+ i := uint8(u >> 32)
+ x := float64(j) * float64(we[i])
+ if j < ke[i] {
+ return x
+ }
+ if i == 0 {
+ return re - math.Log(r.Float64())
+ }
+ if fe[i]+float32(r.Float64())*(fe[i-1]-fe[i]) < float32(math.Exp(-x)) {
+ return x
+ }
+ }
+}
+
+var ke = [256]uint32{
+ 0xe290a139, 0x0, 0x9beadebc, 0xc377ac71, 0xd4ddb990,
+ 0xde893fb8, 0xe4a8e87c, 0xe8dff16a, 0xebf2deab, 0xee49a6e8,
+ 0xf0204efd, 0xf19bdb8e, 0xf2d458bb, 0xf3da104b, 0xf4b86d78,
+ 0xf577ad8a, 0xf61de83d, 0xf6afb784, 0xf730a573, 0xf7a37651,
+ 0xf80a5bb6, 0xf867189d, 0xf8bb1b4f, 0xf9079062, 0xf94d70ca,
+ 0xf98d8c7d, 0xf9c8928a, 0xf9ff175b, 0xfa319996, 0xfa6085f8,
+ 0xfa8c3a62, 0xfab5084e, 0xfadb36c8, 0xfaff0410, 0xfb20a6ea,
+ 0xfb404fb4, 0xfb5e2951, 0xfb7a59e9, 0xfb95038c, 0xfbae44ba,
+ 0xfbc638d8, 0xfbdcf892, 0xfbf29a30, 0xfc0731df, 0xfc1ad1ed,
+ 0xfc2d8b02, 0xfc3f6c4d, 0xfc5083ac, 0xfc60ddd1, 0xfc708662,
+ 0xfc7f8810, 0xfc8decb4, 0xfc9bbd62, 0xfca9027c, 0xfcb5c3c3,
+ 0xfcc20864, 0xfccdd70a, 0xfcd935e3, 0xfce42ab0, 0xfceebace,
+ 0xfcf8eb3b, 0xfd02c0a0, 0xfd0c3f59, 0xfd156b7b, 0xfd1e48d6,
+ 0xfd26daff, 0xfd2f2552, 0xfd372af7, 0xfd3eeee5, 0xfd4673e7,
+ 0xfd4dbc9e, 0xfd54cb85, 0xfd5ba2f2, 0xfd62451b, 0xfd68b415,
+ 0xfd6ef1da, 0xfd750047, 0xfd7ae120, 0xfd809612, 0xfd8620b4,
+ 0xfd8b8285, 0xfd90bcf5, 0xfd95d15e, 0xfd9ac10b, 0xfd9f8d36,
+ 0xfda43708, 0xfda8bf9e, 0xfdad2806, 0xfdb17141, 0xfdb59c46,
+ 0xfdb9a9fd, 0xfdbd9b46, 0xfdc170f6, 0xfdc52bd8, 0xfdc8ccac,
+ 0xfdcc542d, 0xfdcfc30b, 0xfdd319ef, 0xfdd6597a, 0xfdd98245,
+ 0xfddc94e5, 0xfddf91e6, 0xfde279ce, 0xfde54d1f, 0xfde80c52,
+ 0xfdeab7de, 0xfded5034, 0xfdefd5be, 0xfdf248e3, 0xfdf4aa06,
+ 0xfdf6f984, 0xfdf937b6, 0xfdfb64f4, 0xfdfd818d, 0xfdff8dd0,
+ 0xfe018a08, 0xfe03767a, 0xfe05536c, 0xfe07211c, 0xfe08dfc9,
+ 0xfe0a8fab, 0xfe0c30fb, 0xfe0dc3ec, 0xfe0f48b1, 0xfe10bf76,
+ 0xfe122869, 0xfe1383b4, 0xfe14d17c, 0xfe1611e7, 0xfe174516,
+ 0xfe186b2a, 0xfe19843e, 0xfe1a9070, 0xfe1b8fd6, 0xfe1c8289,
+ 0xfe1d689b, 0xfe1e4220, 0xfe1f0f26, 0xfe1fcfbc, 0xfe2083ed,
+ 0xfe212bc3, 0xfe21c745, 0xfe225678, 0xfe22d95f, 0xfe234ffb,
+ 0xfe23ba4a, 0xfe241849, 0xfe2469f2, 0xfe24af3c, 0xfe24e81e,
+ 0xfe25148b, 0xfe253474, 0xfe2547c7, 0xfe254e70, 0xfe25485a,
+ 0xfe25356a, 0xfe251586, 0xfe24e88f, 0xfe24ae64, 0xfe2466e1,
+ 0xfe2411df, 0xfe23af34, 0xfe233eb4, 0xfe22c02c, 0xfe22336b,
+ 0xfe219838, 0xfe20ee58, 0xfe20358c, 0xfe1f6d92, 0xfe1e9621,
+ 0xfe1daef0, 0xfe1cb7ac, 0xfe1bb002, 0xfe1a9798, 0xfe196e0d,
+ 0xfe1832fd, 0xfe16e5fe, 0xfe15869d, 0xfe141464, 0xfe128ed3,
+ 0xfe10f565, 0xfe0f478c, 0xfe0d84b1, 0xfe0bac36, 0xfe09bd73,
+ 0xfe07b7b5, 0xfe059a40, 0xfe03644c, 0xfe011504, 0xfdfeab88,
+ 0xfdfc26e9, 0xfdf98629, 0xfdf6c83b, 0xfdf3ec01, 0xfdf0f04a,
+ 0xfdedd3d1, 0xfdea953d, 0xfde7331e, 0xfde3abe9, 0xfddffdfb,
+ 0xfddc2791, 0xfdd826cd, 0xfdd3f9a8, 0xfdcf9dfc, 0xfdcb1176,
+ 0xfdc65198, 0xfdc15bb3, 0xfdbc2ce2, 0xfdb6c206, 0xfdb117be,
+ 0xfdab2a63, 0xfda4f5fd, 0xfd9e7640, 0xfd97a67a, 0xfd908192,
+ 0xfd8901f2, 0xfd812182, 0xfd78d98e, 0xfd7022bb, 0xfd66f4ed,
+ 0xfd5d4732, 0xfd530f9c, 0xfd48432b, 0xfd3cd59a, 0xfd30b936,
+ 0xfd23dea4, 0xfd16349e, 0xfd07a7a3, 0xfcf8219b, 0xfce7895b,
+ 0xfcd5c220, 0xfcc2aadb, 0xfcae1d5e, 0xfc97ed4e, 0xfc7fe6d4,
+ 0xfc65ccf3, 0xfc495762, 0xfc2a2fc8, 0xfc07ee19, 0xfbe213c1,
+ 0xfbb8051a, 0xfb890078, 0xfb5411a5, 0xfb180005, 0xfad33482,
+ 0xfa839276, 0xfa263b32, 0xf9b72d1c, 0xf930a1a2, 0xf889f023,
+ 0xf7b577d2, 0xf69c650c, 0xf51530f0, 0xf2cb0e3c, 0xeeefb15d,
+ 0xe6da6ecf,
+}
+var we = [256]float32{
+ 2.0249555e-09, 1.486674e-11, 2.4409617e-11, 3.1968806e-11,
+ 3.844677e-11, 4.4228204e-11, 4.9516443e-11, 5.443359e-11,
+ 5.905944e-11, 6.344942e-11, 6.7643814e-11, 7.1672945e-11,
+ 7.556032e-11, 7.932458e-11, 8.298079e-11, 8.654132e-11,
+ 9.0016515e-11, 9.3415074e-11, 9.674443e-11, 1.0001099e-10,
+ 1.03220314e-10, 1.06377254e-10, 1.09486115e-10, 1.1255068e-10,
+ 1.1557435e-10, 1.1856015e-10, 1.2151083e-10, 1.2442886e-10,
+ 1.2731648e-10, 1.3017575e-10, 1.3300853e-10, 1.3581657e-10,
+ 1.3860142e-10, 1.4136457e-10, 1.4410738e-10, 1.4683108e-10,
+ 1.4953687e-10, 1.5222583e-10, 1.54899e-10, 1.5755733e-10,
+ 1.6020171e-10, 1.6283301e-10, 1.6545203e-10, 1.6805951e-10,
+ 1.7065617e-10, 1.732427e-10, 1.7581973e-10, 1.7838787e-10,
+ 1.8094774e-10, 1.8349985e-10, 1.8604476e-10, 1.8858298e-10,
+ 1.9111498e-10, 1.9364126e-10, 1.9616223e-10, 1.9867835e-10,
+ 2.0119004e-10, 2.0369768e-10, 2.0620168e-10, 2.087024e-10,
+ 2.1120022e-10, 2.136955e-10, 2.1618855e-10, 2.1867974e-10,
+ 2.2116936e-10, 2.2365775e-10, 2.261452e-10, 2.2863202e-10,
+ 2.311185e-10, 2.3360494e-10, 2.360916e-10, 2.3857874e-10,
+ 2.4106667e-10, 2.4355562e-10, 2.4604588e-10, 2.485377e-10,
+ 2.5103128e-10, 2.5352695e-10, 2.560249e-10, 2.585254e-10,
+ 2.6102867e-10, 2.6353494e-10, 2.6604446e-10, 2.6855745e-10,
+ 2.7107416e-10, 2.7359479e-10, 2.761196e-10, 2.7864877e-10,
+ 2.8118255e-10, 2.8372119e-10, 2.8626485e-10, 2.888138e-10,
+ 2.9136826e-10, 2.939284e-10, 2.9649452e-10, 2.9906677e-10,
+ 3.016454e-10, 3.0423064e-10, 3.0682268e-10, 3.0942177e-10,
+ 3.1202813e-10, 3.1464195e-10, 3.1726352e-10, 3.19893e-10,
+ 3.2253064e-10, 3.251767e-10, 3.2783135e-10, 3.3049485e-10,
+ 3.3316744e-10, 3.3584938e-10, 3.3854083e-10, 3.4124212e-10,
+ 3.4395342e-10, 3.46675e-10, 3.4940711e-10, 3.5215003e-10,
+ 3.5490397e-10, 3.5766917e-10, 3.6044595e-10, 3.6323455e-10,
+ 3.660352e-10, 3.6884823e-10, 3.7167386e-10, 3.745124e-10,
+ 3.773641e-10, 3.802293e-10, 3.8310827e-10, 3.860013e-10,
+ 3.8890866e-10, 3.918307e-10, 3.9476775e-10, 3.9772008e-10,
+ 4.0068804e-10, 4.0367196e-10, 4.0667217e-10, 4.09689e-10,
+ 4.1272286e-10, 4.1577405e-10, 4.1884296e-10, 4.2192994e-10,
+ 4.250354e-10, 4.281597e-10, 4.313033e-10, 4.3446652e-10,
+ 4.3764986e-10, 4.408537e-10, 4.4407847e-10, 4.4732465e-10,
+ 4.5059267e-10, 4.5388301e-10, 4.571962e-10, 4.6053267e-10,
+ 4.6389292e-10, 4.6727755e-10, 4.70687e-10, 4.741219e-10,
+ 4.7758275e-10, 4.810702e-10, 4.845848e-10, 4.8812715e-10,
+ 4.9169796e-10, 4.9529775e-10, 4.989273e-10, 5.0258725e-10,
+ 5.0627835e-10, 5.100013e-10, 5.1375687e-10, 5.1754584e-10,
+ 5.21369e-10, 5.2522725e-10, 5.2912136e-10, 5.330522e-10,
+ 5.370208e-10, 5.4102806e-10, 5.45075e-10, 5.491625e-10,
+ 5.532918e-10, 5.5746385e-10, 5.616799e-10, 5.6594107e-10,
+ 5.7024857e-10, 5.746037e-10, 5.7900773e-10, 5.834621e-10,
+ 5.8796823e-10, 5.925276e-10, 5.971417e-10, 6.018122e-10,
+ 6.065408e-10, 6.113292e-10, 6.1617933e-10, 6.2109295e-10,
+ 6.260722e-10, 6.3111916e-10, 6.3623595e-10, 6.4142497e-10,
+ 6.4668854e-10, 6.5202926e-10, 6.5744976e-10, 6.6295286e-10,
+ 6.6854156e-10, 6.742188e-10, 6.79988e-10, 6.858526e-10,
+ 6.9181616e-10, 6.978826e-10, 7.04056e-10, 7.103407e-10,
+ 7.167412e-10, 7.2326256e-10, 7.2990985e-10, 7.366886e-10,
+ 7.4360473e-10, 7.5066453e-10, 7.5787476e-10, 7.6524265e-10,
+ 7.7277595e-10, 7.80483e-10, 7.883728e-10, 7.9645507e-10,
+ 8.047402e-10, 8.1323964e-10, 8.219657e-10, 8.309319e-10,
+ 8.401528e-10, 8.496445e-10, 8.594247e-10, 8.6951274e-10,
+ 8.799301e-10, 8.9070046e-10, 9.018503e-10, 9.134092e-10,
+ 9.254101e-10, 9.378904e-10, 9.508923e-10, 9.644638e-10,
+ 9.786603e-10, 9.935448e-10, 1.0091913e-09, 1.025686e-09,
+ 1.0431306e-09, 1.0616465e-09, 1.08138e-09, 1.1025096e-09,
+ 1.1252564e-09, 1.1498986e-09, 1.1767932e-09, 1.206409e-09,
+ 1.2393786e-09, 1.276585e-09, 1.3193139e-09, 1.3695435e-09,
+ 1.4305498e-09, 1.508365e-09, 1.6160854e-09, 1.7921248e-09,
+}
+var fe = [256]float32{
+ 1, 0.9381437, 0.90046996, 0.87170434, 0.8477855, 0.8269933,
+ 0.8084217, 0.7915276, 0.77595687, 0.7614634, 0.7478686,
+ 0.7350381, 0.72286767, 0.71127474, 0.70019263, 0.6895665,
+ 0.67935055, 0.6695063, 0.66000086, 0.65080583, 0.6418967,
+ 0.63325197, 0.6248527, 0.6166822, 0.60872537, 0.60096896,
+ 0.5934009, 0.58601034, 0.5787874, 0.57172304, 0.5648092,
+ 0.5580383, 0.5514034, 0.5448982, 0.5385169, 0.53225386,
+ 0.5261042, 0.52006316, 0.5141264, 0.50828975, 0.5025495,
+ 0.496902, 0.49134386, 0.485872, 0.48048335, 0.4751752,
+ 0.46994483, 0.46478975, 0.45970762, 0.45469615, 0.44975325,
+ 0.44487688, 0.44006512, 0.43531612, 0.43062815, 0.42599955,
+ 0.42142874, 0.4169142, 0.41245446, 0.40804818, 0.403694,
+ 0.3993907, 0.39513698, 0.39093173, 0.38677382, 0.38266218,
+ 0.37859577, 0.37457356, 0.37059465, 0.3666581, 0.362763,
+ 0.35890847, 0.35509375, 0.351318, 0.3475805, 0.34388044,
+ 0.34021714, 0.3365899, 0.33299807, 0.32944095, 0.32591796,
+ 0.3224285, 0.3189719, 0.31554767, 0.31215525, 0.30879408,
+ 0.3054636, 0.3021634, 0.29889292, 0.2956517, 0.29243928,
+ 0.28925523, 0.28609908, 0.28297043, 0.27986884, 0.27679393,
+ 0.2737453, 0.2707226, 0.2677254, 0.26475343, 0.26180625,
+ 0.25888354, 0.25598502, 0.2531103, 0.25025907, 0.24743107,
+ 0.24462597, 0.24184346, 0.23908329, 0.23634516, 0.23362878,
+ 0.23093392, 0.2282603, 0.22560766, 0.22297576, 0.22036438,
+ 0.21777324, 0.21520215, 0.21265087, 0.21011916, 0.20760682,
+ 0.20511365, 0.20263945, 0.20018397, 0.19774707, 0.19532852,
+ 0.19292815, 0.19054577, 0.1881812, 0.18583426, 0.18350479,
+ 0.1811926, 0.17889754, 0.17661946, 0.17435817, 0.17211354,
+ 0.1698854, 0.16767362, 0.16547804, 0.16329853, 0.16113494,
+ 0.15898713, 0.15685499, 0.15473837, 0.15263714, 0.15055119,
+ 0.14848037, 0.14642459, 0.14438373, 0.14235765, 0.14034624,
+ 0.13834943, 0.13636707, 0.13439907, 0.13244532, 0.13050574,
+ 0.1285802, 0.12666863, 0.12477092, 0.12288698, 0.12101672,
+ 0.119160056, 0.1173169, 0.115487166, 0.11367077, 0.11186763,
+ 0.11007768, 0.10830083, 0.10653701, 0.10478614, 0.10304816,
+ 0.101323, 0.09961058, 0.09791085, 0.09622374, 0.09454919,
+ 0.09288713, 0.091237515, 0.08960028, 0.087975375, 0.08636274,
+ 0.08476233, 0.083174095, 0.081597984, 0.08003395, 0.07848195,
+ 0.076941945, 0.07541389, 0.07389775, 0.072393484, 0.07090106,
+ 0.069420435, 0.06795159, 0.066494495, 0.06504912, 0.063615434,
+ 0.062193416, 0.060783047, 0.059384305, 0.057997175,
+ 0.05662164, 0.05525769, 0.053905312, 0.052564494, 0.051235236,
+ 0.049917534, 0.048611384, 0.047316793, 0.046033762, 0.0447623,
+ 0.043502413, 0.042254124, 0.041017443, 0.039792392,
+ 0.038578995, 0.037377283, 0.036187284, 0.035009038,
+ 0.033842582, 0.032687962, 0.031545233, 0.030414443, 0.02929566,
+ 0.02818895, 0.027094385, 0.026012046, 0.024942026, 0.023884421,
+ 0.022839336, 0.021806888, 0.020787204, 0.019780423, 0.0187867,
+ 0.0178062, 0.016839107, 0.015885621, 0.014945968, 0.014020392,
+ 0.013109165, 0.012212592, 0.011331013, 0.01046481, 0.009614414,
+ 0.008780315, 0.007963077, 0.0071633533, 0.006381906,
+ 0.0056196423, 0.0048776558, 0.004157295, 0.0034602648,
+ 0.0027887989, 0.0021459677, 0.0015362998, 0.0009672693,
+ 0.00045413437,
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/export_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..16ecb20227ba3bf4f309a2b1b1de1db52ecb56e4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/export_test.go
@@ -0,0 +1,13 @@
+// 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 rand
+
+func GetNormalDistributionParameters() (float64, [128]uint32, [128]float32, [128]float32) {
+ return rn, kn, wn, fn
+}
+
+func GetExponentialDistributionParameters() (float64, [256]uint32, [256]float32, [256]float32) {
+ return re, ke, we, fe
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/normal.go b/platform/dbops/binaries/go/go/src/math/rand/v2/normal.go
new file mode 100644
index 0000000000000000000000000000000000000000..ea1ae409b4cbdf5f5489add24d53f632816f7e9f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/normal.go
@@ -0,0 +1,157 @@
+// 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 rand
+
+import (
+ "math"
+)
+
+/*
+ * Normal distribution
+ *
+ * See "The Ziggurat Method for Generating Random Variables"
+ * (Marsaglia & Tsang, 2000)
+ * http://www.jstatsoft.org/v05/i08/paper [pdf]
+ */
+
+const (
+ rn = 3.442619855899
+)
+
+func absInt32(i int32) uint32 {
+ if i < 0 {
+ return uint32(-i)
+ }
+ return uint32(i)
+}
+
+// NormFloat64 returns a normally distributed float64 in
+// the range -math.MaxFloat64 through +math.MaxFloat64 inclusive,
+// with standard normal distribution (mean = 0, stddev = 1).
+// To produce a different normal distribution, callers can
+// adjust the output using:
+//
+// sample = NormFloat64() * desiredStdDev + desiredMean
+func (r *Rand) NormFloat64() float64 {
+ for {
+ u := r.Uint64()
+ j := int32(u) // Possibly negative
+ i := u >> 32 & 0x7F
+ x := float64(j) * float64(wn[i])
+ if absInt32(j) < kn[i] {
+ // This case should be hit better than 99% of the time.
+ return x
+ }
+
+ if i == 0 {
+ // This extra work is only required for the base strip.
+ for {
+ x = -math.Log(r.Float64()) * (1.0 / rn)
+ y := -math.Log(r.Float64())
+ if y+y >= x*x {
+ break
+ }
+ }
+ if j > 0 {
+ return rn + x
+ }
+ return -rn - x
+ }
+ if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) {
+ return x
+ }
+ }
+}
+
+var kn = [128]uint32{
+ 0x76ad2212, 0x0, 0x600f1b53, 0x6ce447a6, 0x725b46a2,
+ 0x7560051d, 0x774921eb, 0x789a25bd, 0x799045c3, 0x7a4bce5d,
+ 0x7adf629f, 0x7b5682a6, 0x7bb8a8c6, 0x7c0ae722, 0x7c50cce7,
+ 0x7c8cec5b, 0x7cc12cd6, 0x7ceefed2, 0x7d177e0b, 0x7d3b8883,
+ 0x7d5bce6c, 0x7d78dd64, 0x7d932886, 0x7dab0e57, 0x7dc0dd30,
+ 0x7dd4d688, 0x7de73185, 0x7df81cea, 0x7e07c0a3, 0x7e163efa,
+ 0x7e23b587, 0x7e303dfd, 0x7e3beec2, 0x7e46db77, 0x7e51155d,
+ 0x7e5aabb3, 0x7e63abf7, 0x7e6c222c, 0x7e741906, 0x7e7b9a18,
+ 0x7e82adfa, 0x7e895c63, 0x7e8fac4b, 0x7e95a3fb, 0x7e9b4924,
+ 0x7ea0a0ef, 0x7ea5b00d, 0x7eaa7ac3, 0x7eaf04f3, 0x7eb3522a,
+ 0x7eb765a5, 0x7ebb4259, 0x7ebeeafd, 0x7ec2620a, 0x7ec5a9c4,
+ 0x7ec8c441, 0x7ecbb365, 0x7ece78ed, 0x7ed11671, 0x7ed38d62,
+ 0x7ed5df12, 0x7ed80cb4, 0x7eda175c, 0x7edc0005, 0x7eddc78e,
+ 0x7edf6ebf, 0x7ee0f647, 0x7ee25ebe, 0x7ee3a8a9, 0x7ee4d473,
+ 0x7ee5e276, 0x7ee6d2f5, 0x7ee7a620, 0x7ee85c10, 0x7ee8f4cd,
+ 0x7ee97047, 0x7ee9ce59, 0x7eea0eca, 0x7eea3147, 0x7eea3568,
+ 0x7eea1aab, 0x7ee9e071, 0x7ee98602, 0x7ee90a88, 0x7ee86d08,
+ 0x7ee7ac6a, 0x7ee6c769, 0x7ee5bc9c, 0x7ee48a67, 0x7ee32efc,
+ 0x7ee1a857, 0x7edff42f, 0x7ede0ffa, 0x7edbf8d9, 0x7ed9ab94,
+ 0x7ed7248d, 0x7ed45fae, 0x7ed1585c, 0x7ece095f, 0x7eca6ccb,
+ 0x7ec67be2, 0x7ec22eee, 0x7ebd7d1a, 0x7eb85c35, 0x7eb2c075,
+ 0x7eac9c20, 0x7ea5df27, 0x7e9e769f, 0x7e964c16, 0x7e8d44ba,
+ 0x7e834033, 0x7e781728, 0x7e6b9933, 0x7e5d8a1a, 0x7e4d9ded,
+ 0x7e3b737a, 0x7e268c2f, 0x7e0e3ff5, 0x7df1aa5d, 0x7dcf8c72,
+ 0x7da61a1e, 0x7d72a0fb, 0x7d30e097, 0x7cd9b4ab, 0x7c600f1a,
+ 0x7ba90bdc, 0x7a722176, 0x77d664e5,
+}
+var wn = [128]float32{
+ 1.7290405e-09, 1.2680929e-10, 1.6897518e-10, 1.9862688e-10,
+ 2.2232431e-10, 2.4244937e-10, 2.601613e-10, 2.7611988e-10,
+ 2.9073963e-10, 3.042997e-10, 3.1699796e-10, 3.289802e-10,
+ 3.4035738e-10, 3.5121603e-10, 3.616251e-10, 3.7164058e-10,
+ 3.8130857e-10, 3.9066758e-10, 3.9975012e-10, 4.08584e-10,
+ 4.1719309e-10, 4.2559822e-10, 4.338176e-10, 4.418672e-10,
+ 4.497613e-10, 4.5751258e-10, 4.651324e-10, 4.7263105e-10,
+ 4.8001775e-10, 4.87301e-10, 4.944885e-10, 5.015873e-10,
+ 5.0860405e-10, 5.155446e-10, 5.2241467e-10, 5.2921934e-10,
+ 5.359635e-10, 5.426517e-10, 5.4928817e-10, 5.5587696e-10,
+ 5.624219e-10, 5.6892646e-10, 5.753941e-10, 5.818282e-10,
+ 5.882317e-10, 5.946077e-10, 6.00959e-10, 6.072884e-10,
+ 6.135985e-10, 6.19892e-10, 6.2617134e-10, 6.3243905e-10,
+ 6.386974e-10, 6.449488e-10, 6.511956e-10, 6.5744005e-10,
+ 6.6368433e-10, 6.699307e-10, 6.7618144e-10, 6.824387e-10,
+ 6.8870465e-10, 6.949815e-10, 7.012715e-10, 7.075768e-10,
+ 7.1389966e-10, 7.202424e-10, 7.266073e-10, 7.329966e-10,
+ 7.394128e-10, 7.4585826e-10, 7.5233547e-10, 7.58847e-10,
+ 7.653954e-10, 7.719835e-10, 7.7861395e-10, 7.852897e-10,
+ 7.920138e-10, 7.987892e-10, 8.0561924e-10, 8.125073e-10,
+ 8.194569e-10, 8.2647167e-10, 8.3355556e-10, 8.407127e-10,
+ 8.479473e-10, 8.55264e-10, 8.6266755e-10, 8.7016316e-10,
+ 8.777562e-10, 8.8545243e-10, 8.932582e-10, 9.0117996e-10,
+ 9.09225e-10, 9.174008e-10, 9.2571584e-10, 9.341788e-10,
+ 9.427997e-10, 9.515889e-10, 9.605579e-10, 9.697193e-10,
+ 9.790869e-10, 9.88676e-10, 9.985036e-10, 1.0085882e-09,
+ 1.0189509e-09, 1.0296151e-09, 1.0406069e-09, 1.0519566e-09,
+ 1.063698e-09, 1.0758702e-09, 1.0885183e-09, 1.1016947e-09,
+ 1.1154611e-09, 1.1298902e-09, 1.1450696e-09, 1.1611052e-09,
+ 1.1781276e-09, 1.1962995e-09, 1.2158287e-09, 1.2369856e-09,
+ 1.2601323e-09, 1.2857697e-09, 1.3146202e-09, 1.347784e-09,
+ 1.3870636e-09, 1.4357403e-09, 1.5008659e-09, 1.6030948e-09,
+}
+var fn = [128]float32{
+ 1, 0.9635997, 0.9362827, 0.9130436, 0.89228165, 0.87324303,
+ 0.8555006, 0.8387836, 0.8229072, 0.8077383, 0.793177,
+ 0.7791461, 0.7655842, 0.7524416, 0.73967725, 0.7272569,
+ 0.7151515, 0.7033361, 0.69178915, 0.68049186, 0.6694277,
+ 0.658582, 0.6479418, 0.63749546, 0.6272325, 0.6171434,
+ 0.6072195, 0.5974532, 0.58783704, 0.5783647, 0.56903,
+ 0.5598274, 0.5507518, 0.54179835, 0.5329627, 0.52424055,
+ 0.5156282, 0.50712204, 0.49871865, 0.49041483, 0.48220766,
+ 0.4740943, 0.46607214, 0.4581387, 0.45029163, 0.44252872,
+ 0.43484783, 0.427247, 0.41972435, 0.41227803, 0.40490642,
+ 0.39760786, 0.3903808, 0.3832238, 0.37613547, 0.36911446,
+ 0.3621595, 0.35526937, 0.34844297, 0.34167916, 0.33497685,
+ 0.3283351, 0.3217529, 0.3152294, 0.30876362, 0.30235484,
+ 0.29600215, 0.28970486, 0.2834622, 0.2772735, 0.27113807,
+ 0.2650553, 0.25902456, 0.2530453, 0.24711695, 0.241239,
+ 0.23541094, 0.22963232, 0.2239027, 0.21822165, 0.21258877,
+ 0.20700371, 0.20146611, 0.19597565, 0.19053204, 0.18513499,
+ 0.17978427, 0.17447963, 0.1692209, 0.16400786, 0.15884037,
+ 0.15371831, 0.14864157, 0.14361008, 0.13862377, 0.13368265,
+ 0.12878671, 0.12393598, 0.119130544, 0.11437051, 0.10965602,
+ 0.104987256, 0.10036444, 0.095787846, 0.0912578, 0.08677467,
+ 0.0823389, 0.077950984, 0.073611505, 0.06932112, 0.06508058,
+ 0.06089077, 0.056752663, 0.0526674, 0.048636295, 0.044660863,
+ 0.040742867, 0.03688439, 0.033087887, 0.029356318,
+ 0.025693292, 0.022103304, 0.018592102, 0.015167298,
+ 0.011839478, 0.008624485, 0.005548995, 0.0026696292,
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/pcg.go b/platform/dbops/binaries/go/go/src/math/rand/v2/pcg.go
new file mode 100644
index 0000000000000000000000000000000000000000..77708d799e265d0dd7e6eeaf74bc356f9fb6b70c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/pcg.go
@@ -0,0 +1,121 @@
+// 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 rand
+
+import (
+ "errors"
+ "math/bits"
+)
+
+// https://numpy.org/devdocs/reference/random/upgrading-pcg64.html
+// https://github.com/imneme/pcg-cpp/commit/871d0494ee9c9a7b7c43f753e3d8ca47c26f8005
+
+// A PCG is a PCG generator with 128 bits of internal state.
+// A zero PCG is equivalent to NewPCG(0, 0).
+type PCG struct {
+ hi uint64
+ lo uint64
+}
+
+// NewPCG returns a new PCG seeded with the given values.
+func NewPCG(seed1, seed2 uint64) *PCG {
+ return &PCG{seed1, seed2}
+}
+
+// Seed resets the PCG to behave the same way as NewPCG(seed1, seed2).
+func (p *PCG) Seed(seed1, seed2 uint64) {
+ p.hi = seed1
+ p.lo = seed2
+}
+
+// binary.bigEndian.Uint64, copied to avoid dependency
+func beUint64(b []byte) uint64 {
+ _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
+ uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
+}
+
+// binary.bigEndian.PutUint64, copied to avoid dependency
+func bePutUint64(b []byte, v uint64) {
+ _ = b[7] // early bounds check to guarantee safety of writes below
+ b[0] = byte(v >> 56)
+ b[1] = byte(v >> 48)
+ b[2] = byte(v >> 40)
+ b[3] = byte(v >> 32)
+ b[4] = byte(v >> 24)
+ b[5] = byte(v >> 16)
+ b[6] = byte(v >> 8)
+ b[7] = byte(v)
+}
+
+// MarshalBinary implements the encoding.BinaryMarshaler interface.
+func (p *PCG) MarshalBinary() ([]byte, error) {
+ b := make([]byte, 20)
+ copy(b, "pcg:")
+ bePutUint64(b[4:], p.hi)
+ bePutUint64(b[4+8:], p.lo)
+ return b, nil
+}
+
+var errUnmarshalPCG = errors.New("invalid PCG encoding")
+
+// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
+func (p *PCG) UnmarshalBinary(data []byte) error {
+ if len(data) != 20 || string(data[:4]) != "pcg:" {
+ return errUnmarshalPCG
+ }
+ p.hi = beUint64(data[4:])
+ p.lo = beUint64(data[4+8:])
+ return nil
+}
+
+func (p *PCG) next() (hi, lo uint64) {
+ // https://github.com/imneme/pcg-cpp/blob/428802d1a5/include/pcg_random.hpp#L161
+ //
+ // Numpy's PCG multiplies by the 64-bit value cheapMul
+ // instead of the 128-bit value used here and in the official PCG code.
+ // This does not seem worthwhile, at least for Go: not having any high
+ // bits in the multiplier reduces the effect of low bits on the highest bits,
+ // and it only saves 1 multiply out of 3.
+ // (On 32-bit systems, it saves 1 out of 6, since Mul64 is doing 4.)
+ const (
+ mulHi = 2549297995355413924
+ mulLo = 4865540595714422341
+ incHi = 6364136223846793005
+ incLo = 1442695040888963407
+ )
+
+ // state = state * mul + inc
+ hi, lo = bits.Mul64(p.lo, mulLo)
+ hi += p.hi*mulLo + p.lo*mulHi
+ lo, c := bits.Add64(lo, incLo, 0)
+ hi, _ = bits.Add64(hi, incHi, c)
+ p.lo = lo
+ p.hi = hi
+ return hi, lo
+}
+
+// Uint64 return a uniformly-distributed random uint64 value.
+func (p *PCG) Uint64() uint64 {
+ hi, lo := p.next()
+
+ // XSL-RR would be
+ // hi, lo := p.next()
+ // return bits.RotateLeft64(lo^hi, -int(hi>>58))
+ // but Numpy uses DXSM and O'Neill suggests doing the same.
+ // See https://github.com/golang/go/issues/21835#issuecomment-739065688
+ // and following comments.
+
+ // DXSM "double xorshift multiply"
+ // https://github.com/imneme/pcg-cpp/blob/428802d1a5/include/pcg_random.hpp#L1015
+
+ // https://github.com/imneme/pcg-cpp/blob/428802d1a5/include/pcg_random.hpp#L176
+ const cheapMul = 0xda942042e4dd58b5
+ hi ^= hi >> 32
+ hi *= cheapMul
+ hi ^= hi >> 48
+ hi *= (lo | 1)
+ return hi
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/pcg_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/pcg_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..db866c8c856db0fca326652b020f8c4099a46010
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/pcg_test.go
@@ -0,0 +1,79 @@
+// 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 rand_test
+
+import (
+ . "math/rand/v2"
+ "testing"
+)
+
+func BenchmarkPCG_DXSM(b *testing.B) {
+ var p PCG
+ var t uint64
+ for n := b.N; n > 0; n-- {
+ t += p.Uint64()
+ }
+ Sink = t
+}
+
+func TestPCGMarshal(t *testing.T) {
+ var p PCG
+ const (
+ seed1 = 0x123456789abcdef0
+ seed2 = 0xfedcba9876543210
+ want = "pcg:\x12\x34\x56\x78\x9a\xbc\xde\xf0\xfe\xdc\xba\x98\x76\x54\x32\x10"
+ )
+ p.Seed(seed1, seed2)
+ data, err := p.MarshalBinary()
+ if string(data) != want || err != nil {
+ t.Errorf("MarshalBinary() = %q, %v, want %q, nil", data, err, want)
+ }
+
+ q := PCG{}
+ if err := q.UnmarshalBinary([]byte(want)); err != nil {
+ t.Fatalf("UnmarshalBinary(): %v", err)
+ }
+ if q != p {
+ t.Fatalf("after round trip, q = %#x, but p = %#x", q, p)
+ }
+
+ qu := q.Uint64()
+ pu := p.Uint64()
+ if qu != pu {
+ t.Errorf("after round trip, q.Uint64() = %#x, but p.Uint64() = %#x", qu, pu)
+ }
+}
+
+func TestPCG(t *testing.T) {
+ p := NewPCG(1, 2)
+ want := []uint64{
+ 0xc4f5a58656eef510,
+ 0x9dcec3ad077dec6c,
+ 0xc8d04605312f8088,
+ 0xcbedc0dcb63ac19a,
+ 0x3bf98798cae97950,
+ 0xa8c6d7f8d485abc,
+ 0x7ffa3780429cd279,
+ 0x730ad2626b1c2f8e,
+ 0x21ff2330f4a0ad99,
+ 0x2f0901a1947094b0,
+ 0xa9735a3cfbe36cef,
+ 0x71ddb0a01a12c84a,
+ 0xf0e53e77a78453bb,
+ 0x1f173e9663be1e9d,
+ 0x657651da3ac4115e,
+ 0xc8987376b65a157b,
+ 0xbb17008f5fca28e7,
+ 0x8232bd645f29ed22,
+ 0x12be8f07ad14c539,
+ 0x54908a48e8e4736e,
+ }
+
+ for i, x := range want {
+ if u := p.Uint64(); u != x {
+ t.Errorf("PCG #%d = %#x, want %#x", i, u, x)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/race_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/race_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5ab7a21fa5cb8ab1180a33f0b23dfd511a6fead3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/race_test.go
@@ -0,0 +1,44 @@
+// 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 rand_test
+
+import (
+ . "math/rand/v2"
+ "sync"
+ "testing"
+)
+
+// TestConcurrent exercises the rand API concurrently, triggering situations
+// where the race detector is likely to detect issues.
+func TestConcurrent(t *testing.T) {
+ const (
+ numRoutines = 10
+ numCycles = 10
+ )
+ var wg sync.WaitGroup
+ defer wg.Wait()
+ wg.Add(numRoutines)
+ for i := 0; i < numRoutines; i++ {
+ go func(i int) {
+ defer wg.Done()
+ var seed int64
+ for j := 0; j < numCycles; j++ {
+ seed += int64(ExpFloat64())
+ seed += int64(Float32())
+ seed += int64(Float64())
+ seed += int64(IntN(Int()))
+ seed += int64(Int32N(Int32()))
+ seed += int64(Int64N(Int64()))
+ seed += int64(NormFloat64())
+ seed += int64(Uint32())
+ seed += int64(Uint64())
+ for _, p := range Perm(10) {
+ seed += int64(p)
+ }
+ }
+ _ = seed
+ }(i)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/rand.go b/platform/dbops/binaries/go/go/src/math/rand/v2/rand.go
new file mode 100644
index 0000000000000000000000000000000000000000..f490408472bada0efaf14b604ca5bd8b854a87f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/rand.go
@@ -0,0 +1,363 @@
+// 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 rand implements pseudo-random number generators suitable for tasks
+// such as simulation, but it should not be used for security-sensitive work.
+//
+// Random numbers are generated by a [Source], usually wrapped in a [Rand].
+// Both types should be used by a single goroutine at a time: sharing among
+// multiple goroutines requires some kind of synchronization.
+//
+// Top-level functions, such as [Float64] and [Int],
+// are safe for concurrent use by multiple goroutines.
+//
+// This package's outputs might be easily predictable regardless of how it's
+// seeded. For random numbers suitable for security-sensitive work, see the
+// crypto/rand package.
+package rand
+
+import (
+ "math/bits"
+ _ "unsafe" // for go:linkname
+)
+
+// A Source is a source of uniformly-distributed
+// pseudo-random uint64 values in the range [0, 1<<64).
+//
+// A Source is not safe for concurrent use by multiple goroutines.
+type Source interface {
+ Uint64() uint64
+}
+
+// A Rand is a source of random numbers.
+type Rand struct {
+ src Source
+}
+
+// New returns a new Rand that uses random values from src
+// to generate other random values.
+func New(src Source) *Rand {
+ return &Rand{src: src}
+}
+
+// Int64 returns a non-negative pseudo-random 63-bit integer as an int64.
+func (r *Rand) Int64() int64 { return int64(r.src.Uint64() &^ (1 << 63)) }
+
+// Uint32 returns a pseudo-random 32-bit value as a uint32.
+func (r *Rand) Uint32() uint32 { return uint32(r.src.Uint64() >> 32) }
+
+// Uint64 returns a pseudo-random 64-bit value as a uint64.
+func (r *Rand) Uint64() uint64 { return r.src.Uint64() }
+
+// Int32 returns a non-negative pseudo-random 31-bit integer as an int32.
+func (r *Rand) Int32() int32 { return int32(r.src.Uint64() >> 33) }
+
+// Int returns a non-negative pseudo-random int.
+func (r *Rand) Int() int { return int(uint(r.src.Uint64()) << 1 >> 1) }
+
+// Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) Int64N(n int64) int64 {
+ if n <= 0 {
+ panic("invalid argument to Int64N")
+ }
+ return int64(r.uint64n(uint64(n)))
+}
+
+// Uint64N returns, as a uint64, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n == 0.
+func (r *Rand) Uint64N(n uint64) uint64 {
+ if n == 0 {
+ panic("invalid argument to Uint64N")
+ }
+ return r.uint64n(n)
+}
+
+// uint64n is the no-bounds-checks version of Uint64N.
+func (r *Rand) uint64n(n uint64) uint64 {
+ if is32bit && uint64(uint32(n)) == n {
+ return uint64(r.uint32n(uint32(n)))
+ }
+ if n&(n-1) == 0 { // n is power of two, can mask
+ return r.Uint64() & (n - 1)
+ }
+
+ // Suppose we have a uint64 x uniform in the range [0,2⁶⁴)
+ // and want to reduce it to the range [0,n) preserving exact uniformity.
+ // We can simulate a scaling arbitrary precision x * (n/2⁶⁴) by
+ // the high bits of a double-width multiply of x*n, meaning (x*n)/2⁶⁴.
+ // Since there are 2⁶⁴ possible inputs x and only n possible outputs,
+ // the output is necessarily biased if n does not divide 2⁶⁴.
+ // In general (x*n)/2⁶⁴ = k for x*n in [k*2⁶⁴,(k+1)*2⁶⁴).
+ // There are either floor(2⁶⁴/n) or ceil(2⁶⁴/n) possible products
+ // in that range, depending on k.
+ // But suppose we reject the sample and try again when
+ // x*n is in [k*2⁶⁴, k*2⁶⁴+(2⁶⁴%n)), meaning rejecting fewer than n possible
+ // outcomes out of the 2⁶⁴.
+ // Now there are exactly floor(2⁶⁴/n) possible ways to produce
+ // each output value k, so we've restored uniformity.
+ // To get valid uint64 math, 2⁶⁴ % n = (2⁶⁴ - n) % n = -n % n,
+ // so the direct implementation of this algorithm would be:
+ //
+ // hi, lo := bits.Mul64(r.Uint64(), n)
+ // thresh := -n % n
+ // for lo < thresh {
+ // hi, lo = bits.Mul64(r.Uint64(), n)
+ // }
+ //
+ // That still leaves an expensive 64-bit division that we would rather avoid.
+ // We know that thresh < n, and n is usually much less than 2⁶⁴, so we can
+ // avoid the last four lines unless lo < n.
+ //
+ // See also:
+ // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction
+ // https://lemire.me/blog/2016/06/30/fast-random-shuffling
+ hi, lo := bits.Mul64(r.Uint64(), n)
+ if lo < n {
+ thresh := -n % n
+ for lo < thresh {
+ hi, lo = bits.Mul64(r.Uint64(), n)
+ }
+ }
+ return hi
+}
+
+// uint32n is an identical computation to uint64n
+// but optimized for 32-bit systems.
+func (r *Rand) uint32n(n uint32) uint32 {
+ if n&(n-1) == 0 { // n is power of two, can mask
+ return uint32(r.Uint64()) & (n - 1)
+ }
+ // On 64-bit systems we still use the uint64 code below because
+ // the probability of a random uint64 lo being < a uint32 n is near zero,
+ // meaning the unbiasing loop almost never runs.
+ // On 32-bit systems, here we need to implement that same logic in 32-bit math,
+ // both to preserve the exact output sequence observed on 64-bit machines
+ // and to preserve the optimization that the unbiasing loop almost never runs.
+ //
+ // We want to compute
+ // hi, lo := bits.Mul64(r.Uint64(), n)
+ // In terms of 32-bit halves, this is:
+ // x1:x0 := r.Uint64()
+ // 0:hi, lo1:lo0 := bits.Mul64(x1:x0, 0:n)
+ // Writing out the multiplication in terms of bits.Mul32 allows
+ // using direct hardware instructions and avoiding
+ // the computations involving these zeros.
+ x := r.Uint64()
+ lo1a, lo0 := bits.Mul32(uint32(x), n)
+ hi, lo1b := bits.Mul32(uint32(x>>32), n)
+ lo1, c := bits.Add32(lo1a, lo1b, 0)
+ hi += c
+ if lo1 == 0 && lo0 < uint32(n) {
+ n64 := uint64(n)
+ thresh := uint32(-n64 % n64)
+ for lo1 == 0 && lo0 < thresh {
+ x := r.Uint64()
+ lo1a, lo0 = bits.Mul32(uint32(x), n)
+ hi, lo1b = bits.Mul32(uint32(x>>32), n)
+ lo1, c = bits.Add32(lo1a, lo1b, 0)
+ hi += c
+ }
+ }
+ return hi
+}
+
+// Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) Int32N(n int32) int32 {
+ if n <= 0 {
+ panic("invalid argument to Int32N")
+ }
+ return int32(r.uint64n(uint64(n)))
+}
+
+// Uint32N returns, as a uint32, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n == 0.
+func (r *Rand) Uint32N(n uint32) uint32 {
+ if n == 0 {
+ panic("invalid argument to Uint32N")
+ }
+ return uint32(r.uint64n(uint64(n)))
+}
+
+const is32bit = ^uint(0)>>32 == 0
+
+// IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n <= 0.
+func (r *Rand) IntN(n int) int {
+ if n <= 0 {
+ panic("invalid argument to IntN")
+ }
+ return int(r.uint64n(uint64(n)))
+}
+
+// UintN returns, as a uint, a non-negative pseudo-random number in the half-open interval [0,n).
+// It panics if n == 0.
+func (r *Rand) UintN(n uint) uint {
+ if n == 0 {
+ panic("invalid argument to UintN")
+ }
+ return uint(r.uint64n(uint64(n)))
+}
+
+// Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
+func (r *Rand) Float64() float64 {
+ // There are exactly 1<<53 float64s in [0,1). Use Intn(1<<53) / (1<<53).
+ return float64(r.Uint64()<<11>>11) / (1 << 53)
+}
+
+// Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).
+func (r *Rand) Float32() float32 {
+ // There are exactly 1<<24 float32s in [0,1). Use Intn(1<<24) / (1<<24).
+ return float32(r.Uint32()<<8>>8) / (1 << 24)
+}
+
+// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
+// in the half-open interval [0,n).
+func (r *Rand) Perm(n int) []int {
+ p := make([]int, n)
+ for i := range p {
+ p[i] = i
+ }
+ r.Shuffle(len(p), func(i, j int) { p[i], p[j] = p[j], p[i] })
+ return p
+}
+
+// Shuffle pseudo-randomizes the order of elements.
+// n is the number of elements. Shuffle panics if n < 0.
+// swap swaps the elements with indexes i and j.
+func (r *Rand) Shuffle(n int, swap func(i, j int)) {
+ if n < 0 {
+ panic("invalid argument to Shuffle")
+ }
+
+ // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
+ // Shuffle really ought not be called with n that doesn't fit in 32 bits.
+ // Not only will it take a very long time, but with 2³¹! possible permutations,
+ // there's no way that any PRNG can have a big enough internal state to
+ // generate even a minuscule percentage of the possible permutations.
+ // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
+ for i := n - 1; i > 0; i-- {
+ j := int(r.uint64n(uint64(i + 1)))
+ swap(i, j)
+ }
+}
+
+/*
+ * Top-level convenience functions
+ */
+
+// globalRand is the source of random numbers for the top-level
+// convenience functions.
+var globalRand = &Rand{src: &runtimeSource{}}
+
+//go:linkname runtime_rand runtime.rand
+func runtime_rand() uint64
+
+// runtimeSource is a Source that uses the runtime fastrand functions.
+type runtimeSource struct{}
+
+func (*runtimeSource) Uint64() uint64 {
+ return runtime_rand()
+}
+
+// Int64 returns a non-negative pseudo-random 63-bit integer as an int64
+// from the default Source.
+func Int64() int64 { return globalRand.Int64() }
+
+// Uint32 returns a pseudo-random 32-bit value as a uint32
+// from the default Source.
+func Uint32() uint32 { return globalRand.Uint32() }
+
+// Uint64N returns, as a uint64, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func Uint64N(n uint64) uint64 { return globalRand.Uint64N(n) }
+
+// Uint32N returns, as a uint32, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func Uint32N(n uint32) uint32 { return globalRand.Uint32N(n) }
+
+// Uint64 returns a pseudo-random 64-bit value as a uint64
+// from the default Source.
+func Uint64() uint64 { return globalRand.Uint64() }
+
+// Int32 returns a non-negative pseudo-random 31-bit integer as an int32
+// from the default Source.
+func Int32() int32 { return globalRand.Int32() }
+
+// Int returns a non-negative pseudo-random int from the default Source.
+func Int() int { return globalRand.Int() }
+
+// Int64N returns, as an int64, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func Int64N(n int64) int64 { return globalRand.Int64N(n) }
+
+// Int32N returns, as an int32, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func Int32N(n int32) int32 { return globalRand.Int32N(n) }
+
+// IntN returns, as an int, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func IntN(n int) int { return globalRand.IntN(n) }
+
+// UintN returns, as a uint, a pseudo-random number in the half-open interval [0,n)
+// from the default Source.
+// It panics if n <= 0.
+func UintN(n uint) uint { return globalRand.UintN(n) }
+
+// N returns a pseudo-random number in the half-open interval [0,n) from the default Source.
+// The type parameter Int can be any integer type.
+// It panics if n <= 0.
+func N[Int intType](n Int) Int {
+ if n <= 0 {
+ panic("invalid argument to N")
+ }
+ return Int(globalRand.uint64n(uint64(n)))
+}
+
+type intType interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
+}
+
+// Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0)
+// from the default Source.
+func Float64() float64 { return globalRand.Float64() }
+
+// Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0)
+// from the default Source.
+func Float32() float32 { return globalRand.Float32() }
+
+// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
+// in the half-open interval [0,n) from the default Source.
+func Perm(n int) []int { return globalRand.Perm(n) }
+
+// Shuffle pseudo-randomizes the order of elements using the default Source.
+// n is the number of elements. Shuffle panics if n < 0.
+// swap swaps the elements with indexes i and j.
+func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
+
+// NormFloat64 returns a normally distributed float64 in the range
+// [-math.MaxFloat64, +math.MaxFloat64] with
+// standard normal distribution (mean = 0, stddev = 1)
+// from the default Source.
+// To produce a different normal distribution, callers can
+// adjust the output using:
+//
+// sample = NormFloat64() * desiredStdDev + desiredMean
+func NormFloat64() float64 { return globalRand.NormFloat64() }
+
+// ExpFloat64 returns an exponentially distributed float64 in the range
+// (0, +math.MaxFloat64] with an exponential distribution whose rate parameter
+// (lambda) is 1 and whose mean is 1/lambda (1) from the default Source.
+// To produce a distribution with a different rate parameter,
+// callers can adjust the output using:
+//
+// sample = ExpFloat64() / desiredRateParameter
+func ExpFloat64() float64 { return globalRand.ExpFloat64() }
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/rand_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/rand_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c4b53fa93abc84fee14121094f499a20f7c39076
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/rand_test.go
@@ -0,0 +1,787 @@
+// 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 rand_test
+
+import (
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "math"
+ . "math/rand/v2"
+ "os"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+const (
+ numTestSamples = 10000
+)
+
+var rn, kn, wn, fn = GetNormalDistributionParameters()
+var re, ke, we, fe = GetExponentialDistributionParameters()
+
+type statsResults struct {
+ mean float64
+ stddev float64
+ closeEnough float64
+ maxError float64
+}
+
+func max(a, b float64) float64 {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func nearEqual(a, b, closeEnough, maxError float64) bool {
+ absDiff := math.Abs(a - b)
+ if absDiff < closeEnough { // Necessary when one value is zero and one value is close to zero.
+ return true
+ }
+ return absDiff/max(math.Abs(a), math.Abs(b)) < maxError
+}
+
+var testSeeds = []uint64{1, 1754801282, 1698661970, 1550503961}
+
+// checkSimilarDistribution returns success if the mean and stddev of the
+// two statsResults are similar.
+func (this *statsResults) checkSimilarDistribution(expected *statsResults) error {
+ if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
+ s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
+ fmt.Println(s)
+ return errors.New(s)
+ }
+ if !nearEqual(this.stddev, expected.stddev, expected.closeEnough, expected.maxError) {
+ s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
+ fmt.Println(s)
+ return errors.New(s)
+ }
+ return nil
+}
+
+func getStatsResults(samples []float64) *statsResults {
+ res := new(statsResults)
+ var sum, squaresum float64
+ for _, s := range samples {
+ sum += s
+ squaresum += s * s
+ }
+ res.mean = sum / float64(len(samples))
+ res.stddev = math.Sqrt(squaresum/float64(len(samples)) - res.mean*res.mean)
+ return res
+}
+
+func checkSampleDistribution(t *testing.T, samples []float64, expected *statsResults) {
+ t.Helper()
+ actual := getStatsResults(samples)
+ err := actual.checkSimilarDistribution(expected)
+ if err != nil {
+ t.Errorf(err.Error())
+ }
+}
+
+func checkSampleSliceDistributions(t *testing.T, samples []float64, nslices int, expected *statsResults) {
+ t.Helper()
+ chunk := len(samples) / nslices
+ for i := 0; i < nslices; i++ {
+ low := i * chunk
+ var high int
+ if i == nslices-1 {
+ high = len(samples) - 1
+ } else {
+ high = (i + 1) * chunk
+ }
+ checkSampleDistribution(t, samples[low:high], expected)
+ }
+}
+
+//
+// Normal distribution tests
+//
+
+func generateNormalSamples(nsamples int, mean, stddev float64, seed uint64) []float64 {
+ r := New(NewPCG(seed, seed))
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ samples[i] = r.NormFloat64()*stddev + mean
+ }
+ return samples
+}
+
+func testNormalDistribution(t *testing.T, nsamples int, mean, stddev float64, seed uint64) {
+ //fmt.Printf("testing nsamples=%v mean=%v stddev=%v seed=%v\n", nsamples, mean, stddev, seed);
+
+ samples := generateNormalSamples(nsamples, mean, stddev, seed)
+ errorScale := max(1.0, stddev) // Error scales with stddev
+ expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.08 * errorScale}
+
+ // Make sure that the entire set matches the expected distribution.
+ checkSampleDistribution(t, samples, expected)
+
+ // Make sure that each half of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 2, expected)
+
+ // Make sure that each 7th of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 7, expected)
+}
+
+// Actual tests
+
+func TestStandardNormalValues(t *testing.T) {
+ for _, seed := range testSeeds {
+ testNormalDistribution(t, numTestSamples, 0, 1, seed)
+ }
+}
+
+func TestNonStandardNormalValues(t *testing.T) {
+ sdmax := 1000.0
+ mmax := 1000.0
+ if testing.Short() {
+ sdmax = 5
+ mmax = 5
+ }
+ for sd := 0.5; sd < sdmax; sd *= 2 {
+ for m := 0.5; m < mmax; m *= 2 {
+ for _, seed := range testSeeds {
+ testNormalDistribution(t, numTestSamples, m, sd, seed)
+ if testing.Short() {
+ break
+ }
+ }
+ }
+ }
+}
+
+//
+// Exponential distribution tests
+//
+
+func generateExponentialSamples(nsamples int, rate float64, seed uint64) []float64 {
+ r := New(NewPCG(seed, seed))
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ samples[i] = r.ExpFloat64() / rate
+ }
+ return samples
+}
+
+func testExponentialDistribution(t *testing.T, nsamples int, rate float64, seed uint64) {
+ //fmt.Printf("testing nsamples=%v rate=%v seed=%v\n", nsamples, rate, seed);
+
+ mean := 1 / rate
+ stddev := mean
+
+ samples := generateExponentialSamples(nsamples, rate, seed)
+ errorScale := max(1.0, 1/rate) // Error scales with the inverse of the rate
+ expected := &statsResults{mean, stddev, 0.10 * errorScale, 0.20 * errorScale}
+
+ // Make sure that the entire set matches the expected distribution.
+ checkSampleDistribution(t, samples, expected)
+
+ // Make sure that each half of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 2, expected)
+
+ // Make sure that each 7th of the set matches the expected distribution.
+ checkSampleSliceDistributions(t, samples, 7, expected)
+}
+
+// Actual tests
+
+func TestStandardExponentialValues(t *testing.T) {
+ for _, seed := range testSeeds {
+ testExponentialDistribution(t, numTestSamples, 1, seed)
+ }
+}
+
+func TestNonStandardExponentialValues(t *testing.T) {
+ for rate := 0.05; rate < 10; rate *= 2 {
+ for _, seed := range testSeeds {
+ testExponentialDistribution(t, numTestSamples, rate, seed)
+ if testing.Short() {
+ break
+ }
+ }
+ }
+}
+
+//
+// Table generation tests
+//
+
+func initNorm() (testKn []uint32, testWn, testFn []float32) {
+ const m1 = 1 << 31
+ var (
+ dn float64 = rn
+ tn = dn
+ vn float64 = 9.91256303526217e-3
+ )
+
+ testKn = make([]uint32, 128)
+ testWn = make([]float32, 128)
+ testFn = make([]float32, 128)
+
+ q := vn / math.Exp(-0.5*dn*dn)
+ testKn[0] = uint32((dn / q) * m1)
+ testKn[1] = 0
+ testWn[0] = float32(q / m1)
+ testWn[127] = float32(dn / m1)
+ testFn[0] = 1.0
+ testFn[127] = float32(math.Exp(-0.5 * dn * dn))
+ for i := 126; i >= 1; i-- {
+ dn = math.Sqrt(-2.0 * math.Log(vn/dn+math.Exp(-0.5*dn*dn)))
+ testKn[i+1] = uint32((dn / tn) * m1)
+ tn = dn
+ testFn[i] = float32(math.Exp(-0.5 * dn * dn))
+ testWn[i] = float32(dn / m1)
+ }
+ return
+}
+
+func initExp() (testKe []uint32, testWe, testFe []float32) {
+ const m2 = 1 << 32
+ var (
+ de float64 = re
+ te = de
+ ve float64 = 3.9496598225815571993e-3
+ )
+
+ testKe = make([]uint32, 256)
+ testWe = make([]float32, 256)
+ testFe = make([]float32, 256)
+
+ q := ve / math.Exp(-de)
+ testKe[0] = uint32((de / q) * m2)
+ testKe[1] = 0
+ testWe[0] = float32(q / m2)
+ testWe[255] = float32(de / m2)
+ testFe[0] = 1.0
+ testFe[255] = float32(math.Exp(-de))
+ for i := 254; i >= 1; i-- {
+ de = -math.Log(ve/de + math.Exp(-de))
+ testKe[i+1] = uint32((de / te) * m2)
+ te = de
+ testFe[i] = float32(math.Exp(-de))
+ testWe[i] = float32(de / m2)
+ }
+ return
+}
+
+// compareUint32Slices returns the first index where the two slices
+// disagree, or <0 if the lengths are the same and all elements
+// are identical.
+func compareUint32Slices(s1, s2 []uint32) int {
+ if len(s1) != len(s2) {
+ if len(s1) > len(s2) {
+ return len(s2) + 1
+ }
+ return len(s1) + 1
+ }
+ for i := range s1 {
+ if s1[i] != s2[i] {
+ return i
+ }
+ }
+ return -1
+}
+
+// compareFloat32Slices returns the first index where the two slices
+// disagree, or <0 if the lengths are the same and all elements
+// are identical.
+func compareFloat32Slices(s1, s2 []float32) int {
+ if len(s1) != len(s2) {
+ if len(s1) > len(s2) {
+ return len(s2) + 1
+ }
+ return len(s1) + 1
+ }
+ for i := range s1 {
+ if !nearEqual(float64(s1[i]), float64(s2[i]), 0, 1e-7) {
+ return i
+ }
+ }
+ return -1
+}
+
+func TestNormTables(t *testing.T) {
+ testKn, testWn, testFn := initNorm()
+ if i := compareUint32Slices(kn[0:], testKn); i >= 0 {
+ t.Errorf("kn disagrees at index %v; %v != %v", i, kn[i], testKn[i])
+ }
+ if i := compareFloat32Slices(wn[0:], testWn); i >= 0 {
+ t.Errorf("wn disagrees at index %v; %v != %v", i, wn[i], testWn[i])
+ }
+ if i := compareFloat32Slices(fn[0:], testFn); i >= 0 {
+ t.Errorf("fn disagrees at index %v; %v != %v", i, fn[i], testFn[i])
+ }
+}
+
+func TestExpTables(t *testing.T) {
+ testKe, testWe, testFe := initExp()
+ if i := compareUint32Slices(ke[0:], testKe); i >= 0 {
+ t.Errorf("ke disagrees at index %v; %v != %v", i, ke[i], testKe[i])
+ }
+ if i := compareFloat32Slices(we[0:], testWe); i >= 0 {
+ t.Errorf("we disagrees at index %v; %v != %v", i, we[i], testWe[i])
+ }
+ if i := compareFloat32Slices(fe[0:], testFe); i >= 0 {
+ t.Errorf("fe disagrees at index %v; %v != %v", i, fe[i], testFe[i])
+ }
+}
+
+func hasSlowFloatingPoint() bool {
+ switch runtime.GOARCH {
+ case "arm":
+ return os.Getenv("GOARM") == "5"
+ case "mips", "mipsle", "mips64", "mips64le":
+ // Be conservative and assume that all mips boards
+ // have emulated floating point.
+ // TODO: detect what it actually has.
+ return true
+ }
+ return false
+}
+
+func TestFloat32(t *testing.T) {
+ // For issue 6721, the problem came after 7533753 calls, so check 10e6.
+ num := int(10e6)
+ // But do the full amount only on builders (not locally).
+ // But ARM5 floating point emulation is slow (Issue 10749), so
+ // do less for that builder:
+ if testing.Short() && (testenv.Builder() == "" || hasSlowFloatingPoint()) {
+ num /= 100 // 1.72 seconds instead of 172 seconds
+ }
+
+ r := testRand()
+ for ct := 0; ct < num; ct++ {
+ f := r.Float32()
+ if f >= 1 {
+ t.Fatal("Float32() should be in range [0,1). ct:", ct, "f:", f)
+ }
+ }
+}
+
+func TestShuffleSmall(t *testing.T) {
+ // Check that Shuffle allows n=0 and n=1, but that swap is never called for them.
+ r := testRand()
+ for n := 0; n <= 1; n++ {
+ r.Shuffle(n, func(i, j int) { t.Fatalf("swap called, n=%d i=%d j=%d", n, i, j) })
+ }
+}
+
+// encodePerm converts from a permuted slice of length n, such as Perm generates, to an int in [0, n!).
+// See https://en.wikipedia.org/wiki/Lehmer_code.
+// encodePerm modifies the input slice.
+func encodePerm(s []int) int {
+ // Convert to Lehmer code.
+ for i, x := range s {
+ r := s[i+1:]
+ for j, y := range r {
+ if y > x {
+ r[j]--
+ }
+ }
+ }
+ // Convert to int in [0, n!).
+ m := 0
+ fact := 1
+ for i := len(s) - 1; i >= 0; i-- {
+ m += s[i] * fact
+ fact *= len(s) - i
+ }
+ return m
+}
+
+// TestUniformFactorial tests several ways of generating a uniform value in [0, n!).
+func TestUniformFactorial(t *testing.T) {
+ r := New(NewPCG(1, 2))
+ top := 6
+ if testing.Short() {
+ top = 3
+ }
+ for n := 3; n <= top; n++ {
+ t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
+ // Calculate n!.
+ nfact := 1
+ for i := 2; i <= n; i++ {
+ nfact *= i
+ }
+
+ // Test a few different ways to generate a uniform distribution.
+ p := make([]int, n) // re-usable slice for Shuffle generator
+ tests := [...]struct {
+ name string
+ fn func() int
+ }{
+ {name: "Int32N", fn: func() int { return int(r.Int32N(int32(nfact))) }},
+ {name: "Perm", fn: func() int { return encodePerm(r.Perm(n)) }},
+ {name: "Shuffle", fn: func() int {
+ // Generate permutation using Shuffle.
+ for i := range p {
+ p[i] = i
+ }
+ r.Shuffle(n, func(i, j int) { p[i], p[j] = p[j], p[i] })
+ return encodePerm(p)
+ }},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ // Gather chi-squared values and check that they follow
+ // the expected normal distribution given n!-1 degrees of freedom.
+ // See https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test and
+ // https://www.johndcook.com/Beautiful_Testing_ch10.pdf.
+ nsamples := 10 * nfact
+ if nsamples < 1000 {
+ nsamples = 1000
+ }
+ samples := make([]float64, nsamples)
+ for i := range samples {
+ // Generate some uniformly distributed values and count their occurrences.
+ const iters = 1000
+ counts := make([]int, nfact)
+ for i := 0; i < iters; i++ {
+ counts[test.fn()]++
+ }
+ // Calculate chi-squared and add to samples.
+ want := iters / float64(nfact)
+ var χ2 float64
+ for _, have := range counts {
+ err := float64(have) - want
+ χ2 += err * err
+ }
+ χ2 /= want
+ samples[i] = χ2
+ }
+
+ // Check that our samples approximate the appropriate normal distribution.
+ dof := float64(nfact - 1)
+ expected := &statsResults{mean: dof, stddev: math.Sqrt(2 * dof)}
+ errorScale := max(1.0, expected.stddev)
+ expected.closeEnough = 0.10 * errorScale
+ expected.maxError = 0.08 // TODO: What is the right value here? See issue 21211.
+ checkSampleDistribution(t, samples, expected)
+ })
+ }
+ })
+ }
+}
+
+// Benchmarks
+
+var Sink uint64
+
+func testRand() *Rand {
+ return New(NewPCG(1, 2))
+}
+
+func BenchmarkSourceUint64(b *testing.B) {
+ s := NewPCG(1, 2)
+ var t uint64
+ for n := b.N; n > 0; n-- {
+ t += s.Uint64()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkGlobalInt64(b *testing.B) {
+ var t int64
+ for n := b.N; n > 0; n-- {
+ t += Int64()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkGlobalInt64Parallel(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ var t int64
+ for pb.Next() {
+ t += Int64()
+ }
+ atomic.AddUint64(&Sink, uint64(t))
+ })
+}
+
+func BenchmarkGlobalUint64(b *testing.B) {
+ var t uint64
+ for n := b.N; n > 0; n-- {
+ t += Uint64()
+ }
+ Sink = t
+}
+
+func BenchmarkGlobalUint64Parallel(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ var t uint64
+ for pb.Next() {
+ t += Uint64()
+ }
+ atomic.AddUint64(&Sink, t)
+ })
+}
+
+func BenchmarkInt64(b *testing.B) {
+ r := testRand()
+ var t int64
+ for n := b.N; n > 0; n-- {
+ t += r.Int64()
+ }
+ Sink = uint64(t)
+}
+
+var AlwaysFalse = false
+
+func keep[T int | uint | int32 | uint32 | int64 | uint64](x T) T {
+ if AlwaysFalse {
+ return -x
+ }
+ return x
+}
+
+func BenchmarkUint64(b *testing.B) {
+ r := testRand()
+ var t uint64
+ for n := b.N; n > 0; n-- {
+ t += r.Uint64()
+ }
+ Sink = t
+}
+
+func BenchmarkGlobalIntN1000(b *testing.B) {
+ var t int
+ arg := keep(1000)
+ for n := b.N; n > 0; n-- {
+ t += IntN(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkIntN1000(b *testing.B) {
+ r := testRand()
+ var t int
+ arg := keep(1000)
+ for n := b.N; n > 0; n-- {
+ t += r.IntN(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N1000(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(1000))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N1e8(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(1e8))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N1e9(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(1e9))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N2e9(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(2e9))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N1e18(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(1e18))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N2e18(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(2e18))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt64N4e18(b *testing.B) {
+ r := testRand()
+ var t int64
+ arg := keep(int64(4e18))
+ for n := b.N; n > 0; n-- {
+ t += r.Int64N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt32N1000(b *testing.B) {
+ r := testRand()
+ var t int32
+ arg := keep(int32(1000))
+ for n := b.N; n > 0; n-- {
+ t += r.Int32N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt32N1e8(b *testing.B) {
+ r := testRand()
+ var t int32
+ arg := keep(int32(1e8))
+ for n := b.N; n > 0; n-- {
+ t += r.Int32N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt32N1e9(b *testing.B) {
+ r := testRand()
+ var t int32
+ arg := keep(int32(1e9))
+ for n := b.N; n > 0; n-- {
+ t += r.Int32N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkInt32N2e9(b *testing.B) {
+ r := testRand()
+ var t int32
+ arg := keep(int32(2e9))
+ for n := b.N; n > 0; n-- {
+ t += r.Int32N(arg)
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkFloat32(b *testing.B) {
+ r := testRand()
+ var t float32
+ for n := b.N; n > 0; n-- {
+ t += r.Float32()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkFloat64(b *testing.B) {
+ r := testRand()
+ var t float64
+ for n := b.N; n > 0; n-- {
+ t += r.Float64()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkExpFloat64(b *testing.B) {
+ r := testRand()
+ var t float64
+ for n := b.N; n > 0; n-- {
+ t += r.ExpFloat64()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkNormFloat64(b *testing.B) {
+ r := testRand()
+ var t float64
+ for n := b.N; n > 0; n-- {
+ t += r.NormFloat64()
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkPerm3(b *testing.B) {
+ r := testRand()
+ var t int
+ for n := b.N; n > 0; n-- {
+ t += r.Perm(3)[0]
+ }
+ Sink = uint64(t)
+
+}
+
+func BenchmarkPerm30(b *testing.B) {
+ r := testRand()
+ var t int
+ for n := b.N; n > 0; n-- {
+ t += r.Perm(30)[0]
+ }
+ Sink = uint64(t)
+}
+
+func BenchmarkPerm30ViaShuffle(b *testing.B) {
+ r := testRand()
+ var t int
+ for n := b.N; n > 0; n-- {
+ p := make([]int, 30)
+ for i := range p {
+ p[i] = i
+ }
+ r.Shuffle(30, func(i, j int) { p[i], p[j] = p[j], p[i] })
+ t += p[0]
+ }
+ Sink = uint64(t)
+}
+
+// BenchmarkShuffleOverhead uses a minimal swap function
+// to measure just the shuffling overhead.
+func BenchmarkShuffleOverhead(b *testing.B) {
+ r := testRand()
+ for n := b.N; n > 0; n-- {
+ r.Shuffle(30, func(i, j int) {
+ if i < 0 || i >= 30 || j < 0 || j >= 30 {
+ b.Fatalf("bad swap(%d, %d)", i, j)
+ }
+ })
+ }
+}
+
+func BenchmarkConcurrent(b *testing.B) {
+ const goroutines = 4
+ var wg sync.WaitGroup
+ wg.Add(goroutines)
+ for i := 0; i < goroutines; i++ {
+ go func() {
+ defer wg.Done()
+ for n := b.N; n > 0; n-- {
+ Int64()
+ }
+ }()
+ }
+ wg.Wait()
+}
+
+func TestN(t *testing.T) {
+ for i := 0; i < 1000; i++ {
+ v := N(10)
+ if v < 0 || v >= 10 {
+ t.Fatalf("N(10) returned %d", v)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/regress_test.go b/platform/dbops/binaries/go/go/src/math/rand/v2/regress_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c85d58408dde53864482dfa26da5f41a568b4fdf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/regress_test.go
@@ -0,0 +1,563 @@
+// Copyright 2014 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 that random number sequences generated by a specific seed
+// do not change from version to version.
+//
+// Do NOT make changes to the golden outputs. If bugs need to be fixed
+// in the underlying code, find ways to fix them that do not affect the
+// outputs.
+
+package rand_test
+
+import (
+ "bytes"
+ "flag"
+ "fmt"
+ "go/format"
+ "io"
+ . "math/rand/v2"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+var update = flag.Bool("update", false, "update golden results for regression test")
+
+func TestRegress(t *testing.T) {
+ var int32s = []int32{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1}
+ var uint32s = []uint32{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1, 1<<32 - 2, 1<<32 - 1}
+ var int64s = []int64{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1, 1000000000000000000, 1 << 60, 1<<63 - 2, 1<<63 - 1}
+ var uint64s = []uint64{1, 10, 32, 1 << 20, 1<<20 + 1, 1000000000, 1 << 30, 1<<31 - 2, 1<<31 - 1, 1000000000000000000, 1 << 60, 1<<63 - 2, 1<<63 - 1, 1<<64 - 2, 1<<64 - 1}
+ var permSizes = []int{0, 1, 5, 8, 9, 10, 16}
+
+ n := reflect.TypeOf(New(NewPCG(1, 2))).NumMethod()
+ p := 0
+ var buf bytes.Buffer
+ if *update {
+ fmt.Fprintf(&buf, "var regressGolden = []any{\n")
+ }
+ for i := 0; i < n; i++ {
+ if *update && i > 0 {
+ fmt.Fprintf(&buf, "\n")
+ }
+ r := New(NewPCG(1, 2))
+ rv := reflect.ValueOf(r)
+ m := rv.Type().Method(i)
+ mv := rv.Method(i)
+ mt := mv.Type()
+ if mt.NumOut() == 0 {
+ continue
+ }
+ for repeat := 0; repeat < 20; repeat++ {
+ var args []reflect.Value
+ var argstr string
+ if mt.NumIn() == 1 {
+ var x any
+ switch mt.In(0).Kind() {
+ default:
+ t.Fatalf("unexpected argument type for r.%s", m.Name)
+
+ case reflect.Int:
+ if m.Name == "Perm" {
+ x = permSizes[repeat%len(permSizes)]
+ break
+ }
+ big := int64s[repeat%len(int64s)]
+ if int64(int(big)) != big {
+ // On 32-bit machine.
+ // Consume an Int64 like on a 64-bit machine,
+ // to keep the golden data the same on different architectures.
+ r.Int64N(big)
+ if *update {
+ t.Fatalf("must run -update on 64-bit machine")
+ }
+ p++
+ continue
+ }
+ x = int(big)
+
+ case reflect.Uint:
+ big := uint64s[repeat%len(uint64s)]
+ if uint64(uint(big)) != big {
+ r.Uint64N(big) // what would happen on 64-bit machine, to keep stream in sync
+ if *update {
+ t.Fatalf("must run -update on 64-bit machine")
+ }
+ p++
+ continue
+ }
+ x = uint(big)
+
+ case reflect.Int32:
+ x = int32s[repeat%len(int32s)]
+
+ case reflect.Int64:
+ x = int64s[repeat%len(int64s)]
+
+ case reflect.Uint32:
+ x = uint32s[repeat%len(uint32s)]
+
+ case reflect.Uint64:
+ x = uint64s[repeat%len(uint64s)]
+ }
+ argstr = fmt.Sprint(x)
+ args = append(args, reflect.ValueOf(x))
+ }
+
+ var out any
+ out = mv.Call(args)[0].Interface()
+ if m.Name == "Int" || m.Name == "IntN" {
+ out = int64(out.(int))
+ }
+ if m.Name == "Uint" || m.Name == "UintN" {
+ out = uint64(out.(uint))
+ }
+ if *update {
+ var val string
+ big := int64(1 << 60)
+ if int64(int(big)) != big && (m.Name == "Int" || m.Name == "IntN") {
+ // 32-bit machine cannot print 64-bit results
+ val = "truncated"
+ } else if reflect.TypeOf(out).Kind() == reflect.Slice {
+ val = fmt.Sprintf("%#v", out)
+ } else {
+ val = fmt.Sprintf("%T(%v)", out, out)
+ }
+ fmt.Fprintf(&buf, "\t%s, // %s(%s)\n", val, m.Name, argstr)
+ } else if p >= len(regressGolden) {
+ t.Errorf("r.%s(%s) = %v, missing golden value", m.Name, argstr, out)
+ } else {
+ want := regressGolden[p]
+ if m.Name == "Int" {
+ want = int64(int(uint(want.(int64)) << 1 >> 1))
+ }
+ if !reflect.DeepEqual(out, want) {
+ t.Errorf("r.%s(%s) = %v, want %v", m.Name, argstr, out, want)
+ }
+ }
+ p++
+ }
+ }
+ if *update {
+ replace(t, "regress_test.go", buf.Bytes())
+ }
+}
+
+func TestUpdateExample(t *testing.T) {
+ if !*update {
+ t.Skip("-update not given")
+ }
+
+ oldStdout := os.Stdout
+ defer func() {
+ os.Stdout = oldStdout
+ }()
+
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ defer w.Close()
+
+ go func() {
+ os.Stdout = w
+ Example_rand()
+ os.Stdout = oldStdout
+ w.Close()
+ }()
+ out, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var buf bytes.Buffer
+ fmt.Fprintf(&buf, "\t// Output:\n")
+ for _, line := range strings.Split(string(out), "\n") {
+ if line != "" {
+ fmt.Fprintf(&buf, "\t// %s\n", line)
+ }
+ }
+
+ replace(t, "example_test.go", buf.Bytes())
+
+ // Exit so that Example_rand cannot fail.
+ fmt.Printf("UPDATED; ignore non-zero exit status\n")
+ os.Exit(1)
+}
+
+// replace substitutes the definition text from new into the content of file.
+// The text in new is of the form
+//
+// var whatever = T{
+// ...
+// }
+//
+// Replace searches file for an exact match for the text of the first line,
+// finds the closing brace, and then substitutes new for what used to be in the file.
+// This lets us update the regressGolden table during go test -update.
+func replace(t *testing.T, file string, new []byte) {
+ first, _, _ := bytes.Cut(new, []byte("\n"))
+ first = append(append([]byte("\n"), first...), '\n')
+ data, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ i := bytes.Index(data, first)
+ if i < 0 {
+ t.Fatalf("cannot find %q in %s", first, file)
+ }
+ j := bytes.Index(data[i+1:], []byte("\n}\n"))
+ if j < 0 {
+ t.Fatalf("cannot find end in %s", file)
+ }
+ data = append(append(data[:i+1:i+1], new...), data[i+1+j+1:]...)
+ data, err = format.Source(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(file, data, 0666); err != nil {
+ t.Fatal(err)
+ }
+}
+
+var regressGolden = []any{
+ float64(0.5931317151369719), // ExpFloat64()
+ float64(0.0680034588807843), // ExpFloat64()
+ float64(0.036496967459790364), // ExpFloat64()
+ float64(2.460335459645379), // ExpFloat64()
+ float64(1.5792300208419903), // ExpFloat64()
+ float64(0.9149501499404387), // ExpFloat64()
+ float64(0.43463410545541104), // ExpFloat64()
+ float64(0.5513632046504593), // ExpFloat64()
+ float64(0.7426404617374481), // ExpFloat64()
+ float64(1.2334925132631804), // ExpFloat64()
+ float64(0.892529142200442), // ExpFloat64()
+ float64(0.21508763681487764), // ExpFloat64()
+ float64(1.0208588200798545), // ExpFloat64()
+ float64(0.7650739736831382), // ExpFloat64()
+ float64(0.7772788529257701), // ExpFloat64()
+ float64(1.102732861281323), // ExpFloat64()
+ float64(0.6982243043885805), // ExpFloat64()
+ float64(0.4981788638202421), // ExpFloat64()
+ float64(0.15806532306947937), // ExpFloat64()
+ float64(0.9419163802459202), // ExpFloat64()
+
+ float32(0.95955694), // Float32()
+ float32(0.8076733), // Float32()
+ float32(0.8135684), // Float32()
+ float32(0.92872405), // Float32()
+ float32(0.97472525), // Float32()
+ float32(0.5485458), // Float32()
+ float32(0.97740936), // Float32()
+ float32(0.042272687), // Float32()
+ float32(0.99663067), // Float32()
+ float32(0.035181105), // Float32()
+ float32(0.45059562), // Float32()
+ float32(0.86597633), // Float32()
+ float32(0.8954844), // Float32()
+ float32(0.090798736), // Float32()
+ float32(0.46218646), // Float32()
+ float32(0.5955118), // Float32()
+ float32(0.08985227), // Float32()
+ float32(0.19820237), // Float32()
+ float32(0.7443699), // Float32()
+ float32(0.56461), // Float32()
+
+ float64(0.6764556596678251), // Float64()
+ float64(0.4613862177205994), // Float64()
+ float64(0.5085473976760264), // Float64()
+ float64(0.4297927436037299), // Float64()
+ float64(0.797802349388613), // Float64()
+ float64(0.3883664855410056), // Float64()
+ float64(0.8192750264193612), // Float64()
+ float64(0.3381816951746133), // Float64()
+ float64(0.9730458047755973), // Float64()
+ float64(0.281449117585586), // Float64()
+ float64(0.6047654075331631), // Float64()
+ float64(0.9278107175107462), // Float64()
+ float64(0.16387541502137226), // Float64()
+ float64(0.7263900707339023), // Float64()
+ float64(0.6974917552729882), // Float64()
+ float64(0.7640946923790318), // Float64()
+ float64(0.7188183661358182), // Float64()
+ float64(0.5856191500346635), // Float64()
+ float64(0.9549597149363428), // Float64()
+ float64(0.5168804691962643), // Float64()
+
+ int64(4969059760275911952), // Int()
+ int64(2147869220224756844), // Int()
+ int64(5246770554000605320), // Int()
+ int64(5471241176507662746), // Int()
+ int64(4321634407747778896), // Int()
+ int64(760102831717374652), // Int()
+ int64(9221744211007427193), // Int()
+ int64(8289669384274456462), // Int()
+ int64(2449715415482412441), // Int()
+ int64(3389241988064777392), // Int()
+ int64(2986830195847294191), // Int()
+ int64(8204908297817606218), // Int()
+ int64(8134976985547166651), // Int()
+ int64(2240328155279531677), // Int()
+ int64(7311121042813227358), // Int()
+ int64(5231057920893523323), // Int()
+ int64(4257872588489500903), // Int()
+ int64(158397175702351138), // Int()
+ int64(1350674201389090105), // Int()
+ int64(6093522341581845358), // Int()
+
+ int32(1652216515), // Int32()
+ int32(1323786710), // Int32()
+ int32(1684546306), // Int32()
+ int32(1710678126), // Int32()
+ int32(503104460), // Int32()
+ int32(88487615), // Int32()
+ int32(1073552320), // Int32()
+ int32(965044529), // Int32()
+ int32(285184408), // Int32()
+ int32(394559696), // Int32()
+ int32(1421454622), // Int32()
+ int32(955177040), // Int32()
+ int32(2020777787), // Int32()
+ int32(260808523), // Int32()
+ int32(851126509), // Int32()
+ int32(1682717115), // Int32()
+ int32(1569423431), // Int32()
+ int32(1092181682), // Int32()
+ int32(157239171), // Int32()
+ int32(709379364), // Int32()
+
+ int32(0), // Int32N(1)
+ int32(6), // Int32N(10)
+ int32(8), // Int32N(32)
+ int32(704922), // Int32N(1048576)
+ int32(245656), // Int32N(1048577)
+ int32(41205257), // Int32N(1000000000)
+ int32(43831929), // Int32N(1073741824)
+ int32(965044528), // Int32N(2147483646)
+ int32(285184408), // Int32N(2147483647)
+ int32(0), // Int32N(1)
+ int32(6), // Int32N(10)
+ int32(10), // Int32N(32)
+ int32(283579), // Int32N(1048576)
+ int32(127348), // Int32N(1048577)
+ int32(396336665), // Int32N(1000000000)
+ int32(911873403), // Int32N(1073741824)
+ int32(1569423430), // Int32N(2147483646)
+ int32(1092181681), // Int32N(2147483647)
+ int32(0), // Int32N(1)
+ int32(3), // Int32N(10)
+
+ int64(4969059760275911952), // Int64()
+ int64(2147869220224756844), // Int64()
+ int64(5246770554000605320), // Int64()
+ int64(5471241176507662746), // Int64()
+ int64(4321634407747778896), // Int64()
+ int64(760102831717374652), // Int64()
+ int64(9221744211007427193), // Int64()
+ int64(8289669384274456462), // Int64()
+ int64(2449715415482412441), // Int64()
+ int64(3389241988064777392), // Int64()
+ int64(2986830195847294191), // Int64()
+ int64(8204908297817606218), // Int64()
+ int64(8134976985547166651), // Int64()
+ int64(2240328155279531677), // Int64()
+ int64(7311121042813227358), // Int64()
+ int64(5231057920893523323), // Int64()
+ int64(4257872588489500903), // Int64()
+ int64(158397175702351138), // Int64()
+ int64(1350674201389090105), // Int64()
+ int64(6093522341581845358), // Int64()
+
+ int64(0), // Int64N(1)
+ int64(6), // Int64N(10)
+ int64(8), // Int64N(32)
+ int64(704922), // Int64N(1048576)
+ int64(245656), // Int64N(1048577)
+ int64(41205257), // Int64N(1000000000)
+ int64(43831929), // Int64N(1073741824)
+ int64(965044528), // Int64N(2147483646)
+ int64(285184408), // Int64N(2147483647)
+ int64(183731176326946086), // Int64N(1000000000000000000)
+ int64(680987186633600239), // Int64N(1152921504606846976)
+ int64(4102454148908803108), // Int64N(9223372036854775806)
+ int64(8679174511200971228), // Int64N(9223372036854775807)
+ int64(0), // Int64N(1)
+ int64(3), // Int64N(10)
+ int64(27), // Int64N(32)
+ int64(665831), // Int64N(1048576)
+ int64(533292), // Int64N(1048577)
+ int64(73220195), // Int64N(1000000000)
+ int64(686060398), // Int64N(1073741824)
+
+ int64(0), // IntN(1)
+ int64(6), // IntN(10)
+ int64(8), // IntN(32)
+ int64(704922), // IntN(1048576)
+ int64(245656), // IntN(1048577)
+ int64(41205257), // IntN(1000000000)
+ int64(43831929), // IntN(1073741824)
+ int64(965044528), // IntN(2147483646)
+ int64(285184408), // IntN(2147483647)
+ int64(183731176326946086), // IntN(1000000000000000000)
+ int64(680987186633600239), // IntN(1152921504606846976)
+ int64(4102454148908803108), // IntN(9223372036854775806)
+ int64(8679174511200971228), // IntN(9223372036854775807)
+ int64(0), // IntN(1)
+ int64(3), // IntN(10)
+ int64(27), // IntN(32)
+ int64(665831), // IntN(1048576)
+ int64(533292), // IntN(1048577)
+ int64(73220195), // IntN(1000000000)
+ int64(686060398), // IntN(1073741824)
+
+ float64(0.37944549835531083), // NormFloat64()
+ float64(0.07473804659119399), // NormFloat64()
+ float64(0.20006841200604142), // NormFloat64()
+ float64(-1.1253144115495104), // NormFloat64()
+ float64(-0.4005883316435388), // NormFloat64()
+ float64(-3.0853771402394736), // NormFloat64()
+ float64(1.932330243076978), // NormFloat64()
+ float64(1.726131393719264), // NormFloat64()
+ float64(-0.11707238034168332), // NormFloat64()
+ float64(-0.9303318111676635), // NormFloat64()
+ float64(-0.04750789419852852), // NormFloat64()
+ float64(0.22248301107582735), // NormFloat64()
+ float64(-1.83630520614272), // NormFloat64()
+ float64(0.7259521217919809), // NormFloat64()
+ float64(0.8806882871913041), // NormFloat64()
+ float64(-1.5022903484270484), // NormFloat64()
+ float64(0.5972577266810571), // NormFloat64()
+ float64(1.5631937339973658), // NormFloat64()
+ float64(-0.3841235370075905), // NormFloat64()
+ float64(-0.2967295854430667), // NormFloat64()
+
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{1, 4, 2, 0, 3}, // Perm(5)
+ []int{4, 3, 6, 1, 5, 2, 7, 0}, // Perm(8)
+ []int{6, 5, 1, 8, 7, 2, 0, 3, 4}, // Perm(9)
+ []int{9, 4, 2, 5, 6, 8, 1, 7, 0, 3}, // Perm(10)
+ []int{5, 9, 3, 1, 4, 2, 10, 7, 15, 11, 0, 14, 13, 8, 6, 12}, // Perm(16)
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{4, 2, 1, 3, 0}, // Perm(5)
+ []int{0, 2, 3, 1, 5, 4, 6, 7}, // Perm(8)
+ []int{2, 0, 8, 3, 4, 7, 6, 5, 1}, // Perm(9)
+ []int{0, 6, 5, 3, 8, 4, 1, 2, 9, 7}, // Perm(10)
+ []int{9, 14, 4, 11, 13, 8, 0, 6, 2, 12, 3, 7, 1, 10, 5, 15}, // Perm(16)
+ []int{}, // Perm(0)
+ []int{0}, // Perm(1)
+ []int{2, 4, 0, 3, 1}, // Perm(5)
+ []int{3, 2, 1, 0, 7, 5, 4, 6}, // Perm(8)
+ []int{1, 3, 4, 5, 0, 2, 7, 8, 6}, // Perm(9)
+ []int{1, 8, 4, 7, 2, 6, 5, 9, 0, 3}, // Perm(10)
+
+ uint32(3304433030), // Uint32()
+ uint32(2647573421), // Uint32()
+ uint32(3369092613), // Uint32()
+ uint32(3421356252), // Uint32()
+ uint32(1006208920), // Uint32()
+ uint32(176975231), // Uint32()
+ uint32(2147104640), // Uint32()
+ uint32(1930089058), // Uint32()
+ uint32(570368816), // Uint32()
+ uint32(789119393), // Uint32()
+ uint32(2842909244), // Uint32()
+ uint32(1910354080), // Uint32()
+ uint32(4041555575), // Uint32()
+ uint32(521617046), // Uint32()
+ uint32(1702253018), // Uint32()
+ uint32(3365434230), // Uint32()
+ uint32(3138846863), // Uint32()
+ uint32(2184363364), // Uint32()
+ uint32(314478343), // Uint32()
+ uint32(1418758728), // Uint32()
+
+ uint32(0), // Uint32N(1)
+ uint32(6), // Uint32N(10)
+ uint32(8), // Uint32N(32)
+ uint32(704922), // Uint32N(1048576)
+ uint32(245656), // Uint32N(1048577)
+ uint32(41205257), // Uint32N(1000000000)
+ uint32(43831929), // Uint32N(1073741824)
+ uint32(965044528), // Uint32N(2147483646)
+ uint32(285184408), // Uint32N(2147483647)
+ uint32(789119393), // Uint32N(4294967294)
+ uint32(2842909244), // Uint32N(4294967295)
+ uint32(0), // Uint32N(1)
+ uint32(9), // Uint32N(10)
+ uint32(29), // Uint32N(32)
+ uint32(266590), // Uint32N(1048576)
+ uint32(821640), // Uint32N(1048577)
+ uint32(730819735), // Uint32N(1000000000)
+ uint32(522841378), // Uint32N(1073741824)
+ uint32(157239171), // Uint32N(2147483646)
+ uint32(709379364), // Uint32N(2147483647)
+
+ uint64(14192431797130687760), // Uint64()
+ uint64(11371241257079532652), // Uint64()
+ uint64(14470142590855381128), // Uint64()
+ uint64(14694613213362438554), // Uint64()
+ uint64(4321634407747778896), // Uint64()
+ uint64(760102831717374652), // Uint64()
+ uint64(9221744211007427193), // Uint64()
+ uint64(8289669384274456462), // Uint64()
+ uint64(2449715415482412441), // Uint64()
+ uint64(3389241988064777392), // Uint64()
+ uint64(12210202232702069999), // Uint64()
+ uint64(8204908297817606218), // Uint64()
+ uint64(17358349022401942459), // Uint64()
+ uint64(2240328155279531677), // Uint64()
+ uint64(7311121042813227358), // Uint64()
+ uint64(14454429957748299131), // Uint64()
+ uint64(13481244625344276711), // Uint64()
+ uint64(9381769212557126946), // Uint64()
+ uint64(1350674201389090105), // Uint64()
+ uint64(6093522341581845358), // Uint64()
+
+ uint64(0), // Uint64N(1)
+ uint64(6), // Uint64N(10)
+ uint64(8), // Uint64N(32)
+ uint64(704922), // Uint64N(1048576)
+ uint64(245656), // Uint64N(1048577)
+ uint64(41205257), // Uint64N(1000000000)
+ uint64(43831929), // Uint64N(1073741824)
+ uint64(965044528), // Uint64N(2147483646)
+ uint64(285184408), // Uint64N(2147483647)
+ uint64(183731176326946086), // Uint64N(1000000000000000000)
+ uint64(680987186633600239), // Uint64N(1152921504606846976)
+ uint64(4102454148908803108), // Uint64N(9223372036854775806)
+ uint64(8679174511200971228), // Uint64N(9223372036854775807)
+ uint64(2240328155279531676), // Uint64N(18446744073709551614)
+ uint64(7311121042813227357), // Uint64N(18446744073709551615)
+ uint64(0), // Uint64N(1)
+ uint64(7), // Uint64N(10)
+ uint64(2), // Uint64N(32)
+ uint64(312633), // Uint64N(1048576)
+ uint64(346376), // Uint64N(1048577)
+
+ uint64(0), // UintN(1)
+ uint64(6), // UintN(10)
+ uint64(8), // UintN(32)
+ uint64(704922), // UintN(1048576)
+ uint64(245656), // UintN(1048577)
+ uint64(41205257), // UintN(1000000000)
+ uint64(43831929), // UintN(1073741824)
+ uint64(965044528), // UintN(2147483646)
+ uint64(285184408), // UintN(2147483647)
+ uint64(183731176326946086), // UintN(1000000000000000000)
+ uint64(680987186633600239), // UintN(1152921504606846976)
+ uint64(4102454148908803108), // UintN(9223372036854775806)
+ uint64(8679174511200971228), // UintN(9223372036854775807)
+ uint64(2240328155279531676), // UintN(18446744073709551614)
+ uint64(7311121042813227357), // UintN(18446744073709551615)
+ uint64(0), // UintN(1)
+ uint64(7), // UintN(10)
+ uint64(2), // UintN(32)
+ uint64(312633), // UintN(1048576)
+ uint64(346376), // UintN(1048577)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/v2/zipf.go b/platform/dbops/binaries/go/go/src/math/rand/v2/zipf.go
new file mode 100644
index 0000000000000000000000000000000000000000..f04c814eb751ffe36ed259c98cf9e461d8ed7168
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/v2/zipf.go
@@ -0,0 +1,77 @@
+// 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.
+
+// W.Hormann, G.Derflinger:
+// "Rejection-Inversion to Generate Variates
+// from Monotone Discrete Distributions"
+// http://eeyore.wu-wien.ac.at/papers/96-04-04.wh-der.ps.gz
+
+package rand
+
+import "math"
+
+// A Zipf generates Zipf distributed variates.
+type Zipf struct {
+ r *Rand
+ imax float64
+ v float64
+ q float64
+ s float64
+ oneminusQ float64
+ oneminusQinv float64
+ hxm float64
+ hx0minusHxm float64
+}
+
+func (z *Zipf) h(x float64) float64 {
+ return math.Exp(z.oneminusQ*math.Log(z.v+x)) * z.oneminusQinv
+}
+
+func (z *Zipf) hinv(x float64) float64 {
+ return math.Exp(z.oneminusQinv*math.Log(z.oneminusQ*x)) - z.v
+}
+
+// NewZipf returns a Zipf variate generator.
+// The generator generates values k ∈ [0, imax]
+// such that P(k) is proportional to (v + k) ** (-s).
+// Requirements: s > 1 and v >= 1.
+func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf {
+ z := new(Zipf)
+ if s <= 1.0 || v < 1 {
+ return nil
+ }
+ z.r = r
+ z.imax = float64(imax)
+ z.v = v
+ z.q = s
+ z.oneminusQ = 1.0 - z.q
+ z.oneminusQinv = 1.0 / z.oneminusQ
+ z.hxm = z.h(z.imax + 0.5)
+ z.hx0minusHxm = z.h(0.5) - math.Exp(math.Log(z.v)*(-z.q)) - z.hxm
+ z.s = 1 - z.hinv(z.h(1.5)-math.Exp(-z.q*math.Log(z.v+1.0)))
+ return z
+}
+
+// Uint64 returns a value drawn from the Zipf distribution described
+// by the Zipf object.
+func (z *Zipf) Uint64() uint64 {
+ if z == nil {
+ panic("rand: nil Zipf")
+ }
+ k := 0.0
+
+ for {
+ r := z.r.Float64() // r on [0,1]
+ ur := z.hxm + r*z.hx0minusHxm
+ x := z.hinv(ur)
+ k = math.Floor(x + 0.5)
+ if k-x <= z.s {
+ break
+ }
+ if ur >= z.h(k+0.5)-math.Exp(-math.Log(k+z.v)*z.q) {
+ break
+ }
+ }
+ return uint64(k)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/rand/zipf.go b/platform/dbops/binaries/go/go/src/math/rand/zipf.go
new file mode 100644
index 0000000000000000000000000000000000000000..83c8e336491a2e294233735f012348cca349cba4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/rand/zipf.go
@@ -0,0 +1,77 @@
+// 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.
+
+// W.Hormann, G.Derflinger:
+// "Rejection-Inversion to Generate Variates
+// from Monotone Discrete Distributions"
+// http://eeyore.wu-wien.ac.at/papers/96-04-04.wh-der.ps.gz
+
+package rand
+
+import "math"
+
+// A Zipf generates Zipf distributed variates.
+type Zipf struct {
+ r *Rand
+ imax float64
+ v float64
+ q float64
+ s float64
+ oneminusQ float64
+ oneminusQinv float64
+ hxm float64
+ hx0minusHxm float64
+}
+
+func (z *Zipf) h(x float64) float64 {
+ return math.Exp(z.oneminusQ*math.Log(z.v+x)) * z.oneminusQinv
+}
+
+func (z *Zipf) hinv(x float64) float64 {
+ return math.Exp(z.oneminusQinv*math.Log(z.oneminusQ*x)) - z.v
+}
+
+// NewZipf returns a [Zipf] variate generator.
+// The generator generates values k ∈ [0, imax]
+// such that P(k) is proportional to (v + k) ** (-s).
+// Requirements: s > 1 and v >= 1.
+func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf {
+ z := new(Zipf)
+ if s <= 1.0 || v < 1 {
+ return nil
+ }
+ z.r = r
+ z.imax = float64(imax)
+ z.v = v
+ z.q = s
+ z.oneminusQ = 1.0 - z.q
+ z.oneminusQinv = 1.0 / z.oneminusQ
+ z.hxm = z.h(z.imax + 0.5)
+ z.hx0minusHxm = z.h(0.5) - math.Exp(math.Log(z.v)*(-z.q)) - z.hxm
+ z.s = 1 - z.hinv(z.h(1.5)-math.Exp(-z.q*math.Log(z.v+1.0)))
+ return z
+}
+
+// Uint64 returns a value drawn from the [Zipf] distribution described
+// by the [Zipf] object.
+func (z *Zipf) Uint64() uint64 {
+ if z == nil {
+ panic("rand: nil Zipf")
+ }
+ k := 0.0
+
+ for {
+ r := z.r.Float64() // r on [0,1]
+ ur := z.hxm + r*z.hx0minusHxm
+ x := z.hinv(ur)
+ k = math.Floor(x + 0.5)
+ if k-x <= z.s {
+ break
+ }
+ if ur >= z.h(k+0.5)-math.Exp(-math.Log(k+z.v)*z.q) {
+ break
+ }
+ }
+ return uint64(k)
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/example_test.go b/platform/dbops/binaries/go/go/src/mime/multipart/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..fe154ac4f69ae234feb9bc8293e7d7a9f398e107
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/example_test.go
@@ -0,0 +1,52 @@
+// Copyright 2014 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 multipart_test
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "mime"
+ "mime/multipart"
+ "net/mail"
+ "strings"
+)
+
+func ExampleNewReader() {
+ msg := &mail.Message{
+ Header: map[string][]string{
+ "Content-Type": {"multipart/mixed; boundary=foo"},
+ },
+ Body: strings.NewReader(
+ "--foo\r\nFoo: one\r\n\r\nA section\r\n" +
+ "--foo\r\nFoo: two\r\n\r\nAnd another\r\n" +
+ "--foo--\r\n"),
+ }
+ mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
+ if err != nil {
+ log.Fatal(err)
+ }
+ if strings.HasPrefix(mediaType, "multipart/") {
+ mr := multipart.NewReader(msg.Body, params["boundary"])
+ for {
+ p, err := mr.NextPart()
+ if err == io.EOF {
+ return
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+ slurp, err := io.ReadAll(p)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Printf("Part %q: %q\n", p.Header.Get("Foo"), slurp)
+ }
+ }
+
+ // Output:
+ // Part "one": "A section"
+ // Part "two": "And another"
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/formdata.go b/platform/dbops/binaries/go/go/src/mime/multipart/formdata.go
new file mode 100644
index 0000000000000000000000000000000000000000..85bad2a4cb63ba689420103e04bc331eca5a3422
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/formdata.go
@@ -0,0 +1,306 @@
+// 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 multipart
+
+import (
+ "bytes"
+ "errors"
+ "internal/godebug"
+ "io"
+ "math"
+ "net/textproto"
+ "os"
+ "strconv"
+)
+
+// ErrMessageTooLarge is returned by ReadForm if the message form
+// data is too large to be processed.
+var ErrMessageTooLarge = errors.New("multipart: message too large")
+
+// TODO(adg,bradfitz): find a way to unify the DoS-prevention strategy here
+// with that of the http package's ParseForm.
+
+// ReadForm parses an entire multipart message whose parts have
+// a Content-Disposition of "form-data".
+// It stores up to maxMemory bytes + 10MB (reserved for non-file parts)
+// in memory. File parts which can't be stored in memory will be stored on
+// disk in temporary files.
+// It returns ErrMessageTooLarge if all non-file parts can't be stored in
+// memory.
+func (r *Reader) ReadForm(maxMemory int64) (*Form, error) {
+ return r.readForm(maxMemory)
+}
+
+var (
+ multipartFiles = godebug.New("#multipartfiles") // TODO: document and remove #
+ multipartMaxParts = godebug.New("multipartmaxparts")
+)
+
+func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) {
+ form := &Form{make(map[string][]string), make(map[string][]*FileHeader)}
+ var (
+ file *os.File
+ fileOff int64
+ )
+ numDiskFiles := 0
+ combineFiles := true
+ if multipartFiles.Value() == "distinct" {
+ combineFiles = false
+ // multipartFiles.IncNonDefault() // TODO: uncomment after documenting
+ }
+ maxParts := 1000
+ if s := multipartMaxParts.Value(); s != "" {
+ if v, err := strconv.Atoi(s); err == nil && v >= 0 {
+ maxParts = v
+ multipartMaxParts.IncNonDefault()
+ }
+ }
+ maxHeaders := maxMIMEHeaders()
+
+ defer func() {
+ if file != nil {
+ if cerr := file.Close(); err == nil {
+ err = cerr
+ }
+ }
+ if combineFiles && numDiskFiles > 1 {
+ for _, fhs := range form.File {
+ for _, fh := range fhs {
+ fh.tmpshared = true
+ }
+ }
+ }
+ if err != nil {
+ form.RemoveAll()
+ if file != nil {
+ os.Remove(file.Name())
+ }
+ }
+ }()
+
+ // maxFileMemoryBytes is the maximum bytes of file data we will store in memory.
+ // Data past this limit is written to disk.
+ // This limit strictly applies to content, not metadata (filenames, MIME headers, etc.),
+ // since metadata is always stored in memory, not disk.
+ //
+ // maxMemoryBytes is the maximum bytes we will store in memory, including file content,
+ // non-file part values, metadata, and map entry overhead.
+ //
+ // We reserve an additional 10 MB in maxMemoryBytes for non-file data.
+ //
+ // The relationship between these parameters, as well as the overly-large and
+ // unconfigurable 10 MB added on to maxMemory, is unfortunate but difficult to change
+ // within the constraints of the API as documented.
+ maxFileMemoryBytes := maxMemory
+ if maxFileMemoryBytes == math.MaxInt64 {
+ maxFileMemoryBytes--
+ }
+ maxMemoryBytes := maxMemory + int64(10<<20)
+ if maxMemoryBytes <= 0 {
+ if maxMemory < 0 {
+ maxMemoryBytes = 0
+ } else {
+ maxMemoryBytes = math.MaxInt64
+ }
+ }
+ var copyBuf []byte
+ for {
+ p, err := r.nextPart(false, maxMemoryBytes, maxHeaders)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, err
+ }
+ if maxParts <= 0 {
+ return nil, ErrMessageTooLarge
+ }
+ maxParts--
+
+ name := p.FormName()
+ if name == "" {
+ continue
+ }
+ filename := p.FileName()
+
+ // Multiple values for the same key (one map entry, longer slice) are cheaper
+ // than the same number of values for different keys (many map entries), but
+ // using a consistent per-value cost for overhead is simpler.
+ const mapEntryOverhead = 200
+ maxMemoryBytes -= int64(len(name))
+ maxMemoryBytes -= mapEntryOverhead
+ if maxMemoryBytes < 0 {
+ // We can't actually take this path, since nextPart would already have
+ // rejected the MIME headers for being too large. Check anyway.
+ return nil, ErrMessageTooLarge
+ }
+
+ var b bytes.Buffer
+
+ if filename == "" {
+ // value, store as string in memory
+ n, err := io.CopyN(&b, p, maxMemoryBytes+1)
+ if err != nil && err != io.EOF {
+ return nil, err
+ }
+ maxMemoryBytes -= n
+ if maxMemoryBytes < 0 {
+ return nil, ErrMessageTooLarge
+ }
+ form.Value[name] = append(form.Value[name], b.String())
+ continue
+ }
+
+ // file, store in memory or on disk
+ const fileHeaderSize = 100
+ maxMemoryBytes -= mimeHeaderSize(p.Header)
+ maxMemoryBytes -= mapEntryOverhead
+ maxMemoryBytes -= fileHeaderSize
+ if maxMemoryBytes < 0 {
+ return nil, ErrMessageTooLarge
+ }
+ for _, v := range p.Header {
+ maxHeaders -= int64(len(v))
+ }
+ fh := &FileHeader{
+ Filename: filename,
+ Header: p.Header,
+ }
+ n, err := io.CopyN(&b, p, maxFileMemoryBytes+1)
+ if err != nil && err != io.EOF {
+ return nil, err
+ }
+ if n > maxFileMemoryBytes {
+ if file == nil {
+ file, err = os.CreateTemp(r.tempDir, "multipart-")
+ if err != nil {
+ return nil, err
+ }
+ }
+ numDiskFiles++
+ if _, err := file.Write(b.Bytes()); err != nil {
+ return nil, err
+ }
+ if copyBuf == nil {
+ copyBuf = make([]byte, 32*1024) // same buffer size as io.Copy uses
+ }
+ // os.File.ReadFrom will allocate its own copy buffer if we let io.Copy use it.
+ type writerOnly struct{ io.Writer }
+ remainingSize, err := io.CopyBuffer(writerOnly{file}, p, copyBuf)
+ if err != nil {
+ return nil, err
+ }
+ fh.tmpfile = file.Name()
+ fh.Size = int64(b.Len()) + remainingSize
+ fh.tmpoff = fileOff
+ fileOff += fh.Size
+ if !combineFiles {
+ if err := file.Close(); err != nil {
+ return nil, err
+ }
+ file = nil
+ }
+ } else {
+ fh.content = b.Bytes()
+ fh.Size = int64(len(fh.content))
+ maxFileMemoryBytes -= n
+ maxMemoryBytes -= n
+ }
+ form.File[name] = append(form.File[name], fh)
+ }
+
+ return form, nil
+}
+
+func mimeHeaderSize(h textproto.MIMEHeader) (size int64) {
+ size = 400
+ for k, vs := range h {
+ size += int64(len(k))
+ size += 200 // map entry overhead
+ for _, v := range vs {
+ size += int64(len(v))
+ }
+ }
+ return size
+}
+
+// Form is a parsed multipart form.
+// Its File parts are stored either in memory or on disk,
+// and are accessible via the *FileHeader's Open method.
+// Its Value parts are stored as strings.
+// Both are keyed by field name.
+type Form struct {
+ Value map[string][]string
+ File map[string][]*FileHeader
+}
+
+// RemoveAll removes any temporary files associated with a Form.
+func (f *Form) RemoveAll() error {
+ var err error
+ for _, fhs := range f.File {
+ for _, fh := range fhs {
+ if fh.tmpfile != "" {
+ e := os.Remove(fh.tmpfile)
+ if e != nil && !errors.Is(e, os.ErrNotExist) && err == nil {
+ err = e
+ }
+ }
+ }
+ }
+ return err
+}
+
+// A FileHeader describes a file part of a multipart request.
+type FileHeader struct {
+ Filename string
+ Header textproto.MIMEHeader
+ Size int64
+
+ content []byte
+ tmpfile string
+ tmpoff int64
+ tmpshared bool
+}
+
+// Open opens and returns the FileHeader's associated File.
+func (fh *FileHeader) Open() (File, error) {
+ if b := fh.content; b != nil {
+ r := io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b)))
+ return sectionReadCloser{r, nil}, nil
+ }
+ if fh.tmpshared {
+ f, err := os.Open(fh.tmpfile)
+ if err != nil {
+ return nil, err
+ }
+ r := io.NewSectionReader(f, fh.tmpoff, fh.Size)
+ return sectionReadCloser{r, f}, nil
+ }
+ return os.Open(fh.tmpfile)
+}
+
+// File is an interface to access the file part of a multipart message.
+// Its contents may be either stored in memory or on disk.
+// If stored on disk, the File's underlying concrete type will be an *os.File.
+type File interface {
+ io.Reader
+ io.ReaderAt
+ io.Seeker
+ io.Closer
+}
+
+// helper types to turn a []byte into a File
+
+type sectionReadCloser struct {
+ *io.SectionReader
+ io.Closer
+}
+
+func (rc sectionReadCloser) Close() error {
+ if rc.Closer != nil {
+ return rc.Closer.Close()
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/formdata_test.go b/platform/dbops/binaries/go/go/src/mime/multipart/formdata_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfa9f683825855e45548e731e6dfbeb0336241cf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/formdata_test.go
@@ -0,0 +1,544 @@
+// 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 multipart
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "math"
+ "net/textproto"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestReadForm(t *testing.T) {
+ b := strings.NewReader(strings.ReplaceAll(message, "\n", "\r\n"))
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(25)
+ if err != nil {
+ t.Fatal("ReadForm:", err)
+ }
+ defer f.RemoveAll()
+ if g, e := f.Value["texta"][0], textaValue; g != e {
+ t.Errorf("texta value = %q, want %q", g, e)
+ }
+ if g, e := f.Value["textb"][0], textbValue; g != e {
+ t.Errorf("texta value = %q, want %q", g, e)
+ }
+ fd := testFile(t, f.File["filea"][0], "filea.txt", fileaContents)
+ if _, ok := fd.(*os.File); ok {
+ t.Error("file is *os.File, should not be")
+ }
+ fd.Close()
+ fd = testFile(t, f.File["fileb"][0], "fileb.txt", filebContents)
+ if _, ok := fd.(*os.File); !ok {
+ t.Errorf("file has unexpected underlying type %T", fd)
+ }
+ fd.Close()
+}
+
+func TestReadFormWithNamelessFile(t *testing.T) {
+ b := strings.NewReader(strings.ReplaceAll(messageWithFileWithoutName, "\n", "\r\n"))
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(25)
+ if err != nil {
+ t.Fatal("ReadForm:", err)
+ }
+ defer f.RemoveAll()
+
+ if g, e := f.Value["hiddenfile"][0], filebContents; g != e {
+ t.Errorf("hiddenfile value = %q, want %q", g, e)
+ }
+}
+
+// Issue 58384: Handle ReadForm(math.MaxInt64)
+func TestReadFormWitFileNameMaxMemoryOverflow(t *testing.T) {
+ b := strings.NewReader(strings.ReplaceAll(messageWithFileName, "\n", "\r\n"))
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(math.MaxInt64)
+ if err != nil {
+ t.Fatalf("ReadForm(MaxInt64): %v", err)
+ }
+ defer f.RemoveAll()
+
+ fd := testFile(t, f.File["filea"][0], "filea.txt", fileaContents)
+ if _, ok := fd.(*os.File); ok {
+ t.Error("file is *os.File, should not be")
+ }
+ fd.Close()
+}
+
+// Issue 40430: Handle ReadForm(math.MaxInt64)
+func TestReadFormMaxMemoryOverflow(t *testing.T) {
+ b := strings.NewReader(strings.ReplaceAll(messageWithTextContentType, "\n", "\r\n"))
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(math.MaxInt64)
+ if err != nil {
+ t.Fatalf("ReadForm(MaxInt64): %v", err)
+ }
+ if f == nil {
+ t.Fatal("ReadForm(MaxInt64): missing form")
+ }
+ defer f.RemoveAll()
+
+ if g, e := f.Value["texta"][0], textaValue; g != e {
+ t.Errorf("texta value = %q, want %q", g, e)
+ }
+}
+
+func TestReadFormWithTextContentType(t *testing.T) {
+ // From https://github.com/golang/go/issues/24041
+ b := strings.NewReader(strings.ReplaceAll(messageWithTextContentType, "\n", "\r\n"))
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(25)
+ if err != nil {
+ t.Fatal("ReadForm:", err)
+ }
+ defer f.RemoveAll()
+
+ if g, e := f.Value["texta"][0], textaValue; g != e {
+ t.Errorf("texta value = %q, want %q", g, e)
+ }
+}
+
+func testFile(t *testing.T, fh *FileHeader, efn, econtent string) File {
+ if fh.Filename != efn {
+ t.Errorf("filename = %q, want %q", fh.Filename, efn)
+ }
+ if fh.Size != int64(len(econtent)) {
+ t.Errorf("size = %d, want %d", fh.Size, len(econtent))
+ }
+ f, err := fh.Open()
+ if err != nil {
+ t.Fatal("opening file:", err)
+ }
+ b := new(strings.Builder)
+ _, err = io.Copy(b, f)
+ if err != nil {
+ t.Fatal("copying contents:", err)
+ }
+ if g := b.String(); g != econtent {
+ t.Errorf("contents = %q, want %q", g, econtent)
+ }
+ return f
+}
+
+const (
+ fileaContents = "This is a test file."
+ filebContents = "Another test file."
+ textaValue = "foo"
+ textbValue = "bar"
+ boundary = `MyBoundary`
+)
+
+const messageWithFileWithoutName = `
+--MyBoundary
+Content-Disposition: form-data; name="hiddenfile"; filename=""
+Content-Type: text/plain
+
+` + filebContents + `
+--MyBoundary--
+`
+
+const messageWithFileName = `
+--MyBoundary
+Content-Disposition: form-data; name="filea"; filename="filea.txt"
+Content-Type: text/plain
+
+` + fileaContents + `
+--MyBoundary--
+`
+
+const messageWithTextContentType = `
+--MyBoundary
+Content-Disposition: form-data; name="texta"
+Content-Type: text/plain
+
+` + textaValue + `
+--MyBoundary
+`
+
+const message = `
+--MyBoundary
+Content-Disposition: form-data; name="filea"; filename="filea.txt"
+Content-Type: text/plain
+
+` + fileaContents + `
+--MyBoundary
+Content-Disposition: form-data; name="fileb"; filename="fileb.txt"
+Content-Type: text/plain
+
+` + filebContents + `
+--MyBoundary
+Content-Disposition: form-data; name="texta"
+
+` + textaValue + `
+--MyBoundary
+Content-Disposition: form-data; name="textb"
+
+` + textbValue + `
+--MyBoundary--
+`
+
+func TestReadForm_NoReadAfterEOF(t *testing.T) {
+ maxMemory := int64(32) << 20
+ boundary := `---------------------------8d345eef0d38dc9`
+ body := `
+-----------------------------8d345eef0d38dc9
+Content-Disposition: form-data; name="version"
+
+171
+-----------------------------8d345eef0d38dc9--`
+
+ mr := NewReader(&failOnReadAfterErrorReader{t: t, r: strings.NewReader(body)}, boundary)
+
+ f, err := mr.ReadForm(maxMemory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("Got: %#v", f)
+}
+
+// failOnReadAfterErrorReader is an io.Reader wrapping r.
+// It fails t if any Read is called after a failing Read.
+type failOnReadAfterErrorReader struct {
+ t *testing.T
+ r io.Reader
+ sawErr error
+}
+
+func (r *failOnReadAfterErrorReader) Read(p []byte) (n int, err error) {
+ if r.sawErr != nil {
+ r.t.Fatalf("unexpected Read on Reader after previous read saw error %v", r.sawErr)
+ }
+ n, err = r.r.Read(p)
+ r.sawErr = err
+ return
+}
+
+// TestReadForm_NonFileMaxMemory asserts that the ReadForm maxMemory limit is applied
+// while processing non-file form data as well as file form data.
+func TestReadForm_NonFileMaxMemory(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping in -short mode")
+ }
+ n := 10 << 20
+ largeTextValue := strings.Repeat("1", n)
+ message := `--MyBoundary
+Content-Disposition: form-data; name="largetext"
+
+` + largeTextValue + `
+--MyBoundary--
+`
+ testBody := strings.ReplaceAll(message, "\n", "\r\n")
+ // Try parsing the form with increasing maxMemory values.
+ // Changes in how we account for non-file form data may cause the exact point
+ // where we change from rejecting the form as too large to accepting it to vary,
+ // but we should see both successes and failures.
+ const failWhenMaxMemoryLessThan = 128
+ for maxMemory := int64(0); maxMemory < failWhenMaxMemoryLessThan*2; maxMemory += 16 {
+ b := strings.NewReader(testBody)
+ r := NewReader(b, boundary)
+ f, err := r.ReadForm(maxMemory)
+ if err != nil {
+ continue
+ }
+ if g := f.Value["largetext"][0]; g != largeTextValue {
+ t.Errorf("largetext mismatch: got size: %v, expected size: %v", len(g), len(largeTextValue))
+ }
+ f.RemoveAll()
+ if maxMemory < failWhenMaxMemoryLessThan {
+ t.Errorf("ReadForm(%v): no error, expect to hit memory limit when maxMemory < %v", maxMemory, failWhenMaxMemoryLessThan)
+ }
+ return
+ }
+ t.Errorf("ReadForm(x) failed for x < 1024, expect success")
+}
+
+// TestReadForm_MetadataTooLarge verifies that we account for the size of field names,
+// MIME headers, and map entry overhead while limiting the memory consumption of parsed forms.
+func TestReadForm_MetadataTooLarge(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ f func(*Writer)
+ }{{
+ name: "large name",
+ f: func(fw *Writer) {
+ name := strings.Repeat("a", 10<<20)
+ w, _ := fw.CreateFormField(name)
+ w.Write([]byte("value"))
+ },
+ }, {
+ name: "large MIME header",
+ f: func(fw *Writer) {
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition", `form-data; name="a"`)
+ h.Set("X-Foo", strings.Repeat("a", 10<<20))
+ w, _ := fw.CreatePart(h)
+ w.Write([]byte("value"))
+ },
+ }, {
+ name: "many parts",
+ f: func(fw *Writer) {
+ for i := 0; i < 110000; i++ {
+ w, _ := fw.CreateFormField("f")
+ w.Write([]byte("v"))
+ }
+ },
+ }} {
+ t.Run(test.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ fw := NewWriter(&buf)
+ test.f(fw)
+ if err := fw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ fr := NewReader(&buf, fw.Boundary())
+ _, err := fr.ReadForm(0)
+ if err != ErrMessageTooLarge {
+ t.Errorf("fr.ReadForm() = %v, want ErrMessageTooLarge", err)
+ }
+ })
+ }
+}
+
+// TestReadForm_ManyFiles_Combined tests that a multipart form containing many files only
+// results in a single on-disk file.
+func TestReadForm_ManyFiles_Combined(t *testing.T) {
+ const distinct = false
+ testReadFormManyFiles(t, distinct)
+}
+
+// TestReadForm_ManyFiles_Distinct tests that setting GODEBUG=multipartfiles=distinct
+// results in every file in a multipart form being placed in a distinct on-disk file.
+func TestReadForm_ManyFiles_Distinct(t *testing.T) {
+ t.Setenv("GODEBUG", "multipartfiles=distinct")
+ const distinct = true
+ testReadFormManyFiles(t, distinct)
+}
+
+func testReadFormManyFiles(t *testing.T, distinct bool) {
+ var buf bytes.Buffer
+ fw := NewWriter(&buf)
+ const numFiles = 10
+ for i := 0; i < numFiles; i++ {
+ name := fmt.Sprint(i)
+ w, err := fw.CreateFormFile(name, name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.Write([]byte(name))
+ }
+ if err := fw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ fr := NewReader(&buf, fw.Boundary())
+ fr.tempDir = t.TempDir()
+ form, err := fr.ReadForm(0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < numFiles; i++ {
+ name := fmt.Sprint(i)
+ if got := len(form.File[name]); got != 1 {
+ t.Fatalf("form.File[%q] has %v entries, want 1", name, got)
+ }
+ fh := form.File[name][0]
+ file, err := fh.Open()
+ if err != nil {
+ t.Fatalf("form.File[%q].Open() = %v", name, err)
+ }
+ if distinct {
+ if _, ok := file.(*os.File); !ok {
+ t.Fatalf("form.File[%q].Open: %T, want *os.File", name, file)
+ }
+ }
+ got, err := io.ReadAll(file)
+ file.Close()
+ if string(got) != name || err != nil {
+ t.Fatalf("read form.File[%q]: %q, %v; want %q, nil", name, string(got), err, name)
+ }
+ }
+ dir, err := os.Open(fr.tempDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dir.Close()
+ names, err := dir.Readdirnames(0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantNames := 1
+ if distinct {
+ wantNames = numFiles
+ }
+ if len(names) != wantNames {
+ t.Fatalf("temp dir contains %v files; want 1", len(names))
+ }
+ if err := form.RemoveAll(); err != nil {
+ t.Fatalf("form.RemoveAll() = %v", err)
+ }
+ names, err = dir.Readdirnames(0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(names) != 0 {
+ t.Fatalf("temp dir contains %v files; want 0", len(names))
+ }
+}
+
+func TestReadFormLimits(t *testing.T) {
+ for _, test := range []struct {
+ values int
+ files int
+ extraKeysPerFile int
+ wantErr error
+ godebug string
+ }{
+ {values: 1000},
+ {values: 1001, wantErr: ErrMessageTooLarge},
+ {values: 500, files: 500},
+ {values: 501, files: 500, wantErr: ErrMessageTooLarge},
+ {files: 1000},
+ {files: 1001, wantErr: ErrMessageTooLarge},
+ {files: 1, extraKeysPerFile: 9998}, // plus Content-Disposition and Content-Type
+ {files: 1, extraKeysPerFile: 10000, wantErr: ErrMessageTooLarge},
+ {godebug: "multipartmaxparts=100", values: 100},
+ {godebug: "multipartmaxparts=100", values: 101, wantErr: ErrMessageTooLarge},
+ {godebug: "multipartmaxheaders=100", files: 2, extraKeysPerFile: 48},
+ {godebug: "multipartmaxheaders=100", files: 2, extraKeysPerFile: 50, wantErr: ErrMessageTooLarge},
+ } {
+ name := fmt.Sprintf("values=%v/files=%v/extraKeysPerFile=%v", test.values, test.files, test.extraKeysPerFile)
+ if test.godebug != "" {
+ name += fmt.Sprintf("/godebug=%v", test.godebug)
+ }
+ t.Run(name, func(t *testing.T) {
+ if test.godebug != "" {
+ t.Setenv("GODEBUG", test.godebug)
+ }
+ var buf bytes.Buffer
+ fw := NewWriter(&buf)
+ for i := 0; i < test.values; i++ {
+ w, _ := fw.CreateFormField(fmt.Sprintf("field%v", i))
+ fmt.Fprintf(w, "value %v", i)
+ }
+ for i := 0; i < test.files; i++ {
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition",
+ fmt.Sprintf(`form-data; name="file%v"; filename="file%v"`, i, i))
+ h.Set("Content-Type", "application/octet-stream")
+ for j := 0; j < test.extraKeysPerFile; j++ {
+ h.Set(fmt.Sprintf("k%v", j), "v")
+ }
+ w, _ := fw.CreatePart(h)
+ fmt.Fprintf(w, "value %v", i)
+ }
+ if err := fw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ fr := NewReader(bytes.NewReader(buf.Bytes()), fw.Boundary())
+ form, err := fr.ReadForm(1 << 10)
+ if err == nil {
+ defer form.RemoveAll()
+ }
+ if err != test.wantErr {
+ t.Errorf("ReadForm = %v, want %v", err, test.wantErr)
+ }
+ })
+ }
+}
+
+func TestReadFormEndlessHeaderLine(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ prefix string
+ }{{
+ name: "name",
+ prefix: "X-",
+ }, {
+ name: "value",
+ prefix: "X-Header: ",
+ }, {
+ name: "continuation",
+ prefix: "X-Header: foo\r\n ",
+ }} {
+ t.Run(test.name, func(t *testing.T) {
+ const eol = "\r\n"
+ s := `--boundary` + eol
+ s += `Content-Disposition: form-data; name="a"` + eol
+ s += `Content-Type: text/plain` + eol
+ s += test.prefix
+ fr := io.MultiReader(
+ strings.NewReader(s),
+ neverendingReader('X'),
+ )
+ r := NewReader(fr, "boundary")
+ _, err := r.ReadForm(1 << 20)
+ if err != ErrMessageTooLarge {
+ t.Fatalf("ReadForm(1 << 20): %v, want ErrMessageTooLarge", err)
+ }
+ })
+ }
+}
+
+type neverendingReader byte
+
+func (r neverendingReader) Read(p []byte) (n int, err error) {
+ for i := range p {
+ p[i] = byte(r)
+ }
+ return len(p), nil
+}
+
+func BenchmarkReadForm(b *testing.B) {
+ for _, test := range []struct {
+ name string
+ form func(fw *Writer, count int)
+ }{{
+ name: "fields",
+ form: func(fw *Writer, count int) {
+ for i := 0; i < count; i++ {
+ w, _ := fw.CreateFormField(fmt.Sprintf("field%v", i))
+ fmt.Fprintf(w, "value %v", i)
+ }
+ },
+ }, {
+ name: "files",
+ form: func(fw *Writer, count int) {
+ for i := 0; i < count; i++ {
+ w, _ := fw.CreateFormFile(fmt.Sprintf("field%v", i), fmt.Sprintf("file%v", i))
+ fmt.Fprintf(w, "value %v", i)
+ }
+ },
+ }} {
+ b.Run(test.name, func(b *testing.B) {
+ for _, maxMemory := range []int64{
+ 0,
+ 1 << 20,
+ } {
+ var buf bytes.Buffer
+ fw := NewWriter(&buf)
+ test.form(fw, 10)
+ if err := fw.Close(); err != nil {
+ b.Fatal(err)
+ }
+ b.Run(fmt.Sprintf("maxMemory=%v", maxMemory), func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ fr := NewReader(bytes.NewReader(buf.Bytes()), fw.Boundary())
+ form, err := fr.ReadForm(maxMemory)
+ if err != nil {
+ b.Fatal(err)
+ }
+ form.RemoveAll()
+ }
+
+ })
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/multipart.go b/platform/dbops/binaries/go/go/src/mime/multipart/multipart.go
new file mode 100644
index 0000000000000000000000000000000000000000..da1f45810e883aebf868b965245760eaaa1f469d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/multipart.go
@@ -0,0 +1,488 @@
+// 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 multipart implements MIME multipart parsing, as defined in RFC
+2046.
+
+The implementation is sufficient for HTTP (RFC 2388) and the multipart
+bodies generated by popular browsers.
+
+# Limits
+
+To protect against malicious inputs, this package sets limits on the size
+of the MIME data it processes.
+
+Reader.NextPart and Reader.NextRawPart limit the number of headers in a
+part to 10000 and Reader.ReadForm limits the total number of headers in all
+FileHeaders to 10000.
+These limits may be adjusted with the GODEBUG=multipartmaxheaders=
+setting.
+
+Reader.ReadForm further limits the number of parts in a form to 1000.
+This limit may be adjusted with the GODEBUG=multipartmaxparts=
+setting.
+*/
+package multipart
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "internal/godebug"
+ "io"
+ "mime"
+ "mime/quotedprintable"
+ "net/textproto"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+var emptyParams = make(map[string]string)
+
+// This constant needs to be at least 76 for this package to work correctly.
+// This is because \r\n--separator_of_len_70- would fill the buffer and it
+// wouldn't be safe to consume a single byte from it.
+const peekBufferSize = 4096
+
+// A Part represents a single part in a multipart body.
+type Part struct {
+ // The headers of the body, if any, with the keys canonicalized
+ // in the same fashion that the Go http.Request headers are.
+ // For example, "foo-bar" changes case to "Foo-Bar"
+ Header textproto.MIMEHeader
+
+ mr *Reader
+
+ disposition string
+ dispositionParams map[string]string
+
+ // r is either a reader directly reading from mr, or it's a
+ // wrapper around such a reader, decoding the
+ // Content-Transfer-Encoding
+ r io.Reader
+
+ n int // known data bytes waiting in mr.bufReader
+ total int64 // total data bytes read already
+ err error // error to return when n == 0
+ readErr error // read error observed from mr.bufReader
+}
+
+// FormName returns the name parameter if p has a Content-Disposition
+// of type "form-data". Otherwise it returns the empty string.
+func (p *Part) FormName() string {
+ // See https://tools.ietf.org/html/rfc2183 section 2 for EBNF
+ // of Content-Disposition value format.
+ if p.dispositionParams == nil {
+ p.parseContentDisposition()
+ }
+ if p.disposition != "form-data" {
+ return ""
+ }
+ return p.dispositionParams["name"]
+}
+
+// FileName returns the filename parameter of the Part's Content-Disposition
+// header. If not empty, the filename is passed through filepath.Base (which is
+// platform dependent) before being returned.
+func (p *Part) FileName() string {
+ if p.dispositionParams == nil {
+ p.parseContentDisposition()
+ }
+ filename := p.dispositionParams["filename"]
+ if filename == "" {
+ return ""
+ }
+ // RFC 7578, Section 4.2 requires that if a filename is provided, the
+ // directory path information must not be used.
+ return filepath.Base(filename)
+}
+
+func (p *Part) parseContentDisposition() {
+ v := p.Header.Get("Content-Disposition")
+ var err error
+ p.disposition, p.dispositionParams, err = mime.ParseMediaType(v)
+ if err != nil {
+ p.dispositionParams = emptyParams
+ }
+}
+
+// NewReader creates a new multipart Reader reading from r using the
+// given MIME boundary.
+//
+// The boundary is usually obtained from the "boundary" parameter of
+// the message's "Content-Type" header. Use mime.ParseMediaType to
+// parse such headers.
+func NewReader(r io.Reader, boundary string) *Reader {
+ b := []byte("\r\n--" + boundary + "--")
+ return &Reader{
+ bufReader: bufio.NewReaderSize(&stickyErrorReader{r: r}, peekBufferSize),
+ nl: b[:2],
+ nlDashBoundary: b[:len(b)-2],
+ dashBoundaryDash: b[2:],
+ dashBoundary: b[2 : len(b)-2],
+ }
+}
+
+// stickyErrorReader is an io.Reader which never calls Read on its
+// underlying Reader once an error has been seen. (the io.Reader
+// interface's contract promises nothing about the return values of
+// Read calls after an error, yet this package does do multiple Reads
+// after error)
+type stickyErrorReader struct {
+ r io.Reader
+ err error
+}
+
+func (r *stickyErrorReader) Read(p []byte) (n int, _ error) {
+ if r.err != nil {
+ return 0, r.err
+ }
+ n, r.err = r.r.Read(p)
+ return n, r.err
+}
+
+func newPart(mr *Reader, rawPart bool, maxMIMEHeaderSize, maxMIMEHeaders int64) (*Part, error) {
+ bp := &Part{
+ Header: make(map[string][]string),
+ mr: mr,
+ }
+ if err := bp.populateHeaders(maxMIMEHeaderSize, maxMIMEHeaders); err != nil {
+ return nil, err
+ }
+ bp.r = partReader{bp}
+
+ // rawPart is used to switch between Part.NextPart and Part.NextRawPart.
+ if !rawPart {
+ const cte = "Content-Transfer-Encoding"
+ if strings.EqualFold(bp.Header.Get(cte), "quoted-printable") {
+ bp.Header.Del(cte)
+ bp.r = quotedprintable.NewReader(bp.r)
+ }
+ }
+ return bp, nil
+}
+
+func (p *Part) populateHeaders(maxMIMEHeaderSize, maxMIMEHeaders int64) error {
+ r := textproto.NewReader(p.mr.bufReader)
+ header, err := readMIMEHeader(r, maxMIMEHeaderSize, maxMIMEHeaders)
+ if err == nil {
+ p.Header = header
+ }
+ // TODO: Add a distinguishable error to net/textproto.
+ if err != nil && err.Error() == "message too large" {
+ err = ErrMessageTooLarge
+ }
+ return err
+}
+
+// Read reads the body of a part, after its headers and before the
+// next part (if any) begins.
+func (p *Part) Read(d []byte) (n int, err error) {
+ return p.r.Read(d)
+}
+
+// partReader implements io.Reader by reading raw bytes directly from the
+// wrapped *Part, without doing any Transfer-Encoding decoding.
+type partReader struct {
+ p *Part
+}
+
+func (pr partReader) Read(d []byte) (int, error) {
+ p := pr.p
+ br := p.mr.bufReader
+
+ // Read into buffer until we identify some data to return,
+ // or we find a reason to stop (boundary or read error).
+ for p.n == 0 && p.err == nil {
+ peek, _ := br.Peek(br.Buffered())
+ p.n, p.err = scanUntilBoundary(peek, p.mr.dashBoundary, p.mr.nlDashBoundary, p.total, p.readErr)
+ if p.n == 0 && p.err == nil {
+ // Force buffered I/O to read more into buffer.
+ _, p.readErr = br.Peek(len(peek) + 1)
+ if p.readErr == io.EOF {
+ p.readErr = io.ErrUnexpectedEOF
+ }
+ }
+ }
+
+ // Read out from "data to return" part of buffer.
+ if p.n == 0 {
+ return 0, p.err
+ }
+ n := len(d)
+ if n > p.n {
+ n = p.n
+ }
+ n, _ = br.Read(d[:n])
+ p.total += int64(n)
+ p.n -= n
+ if p.n == 0 {
+ return n, p.err
+ }
+ return n, nil
+}
+
+// scanUntilBoundary scans buf to identify how much of it can be safely
+// returned as part of the Part body.
+// dashBoundary is "--boundary".
+// nlDashBoundary is "\r\n--boundary" or "\n--boundary", depending on what mode we are in.
+// The comments below (and the name) assume "\n--boundary", but either is accepted.
+// total is the number of bytes read out so far. If total == 0, then a leading "--boundary" is recognized.
+// readErr is the read error, if any, that followed reading the bytes in buf.
+// scanUntilBoundary returns the number of data bytes from buf that can be
+// returned as part of the Part body and also the error to return (if any)
+// once those data bytes are done.
+func scanUntilBoundary(buf, dashBoundary, nlDashBoundary []byte, total int64, readErr error) (int, error) {
+ if total == 0 {
+ // At beginning of body, allow dashBoundary.
+ if bytes.HasPrefix(buf, dashBoundary) {
+ switch matchAfterPrefix(buf, dashBoundary, readErr) {
+ case -1:
+ return len(dashBoundary), nil
+ case 0:
+ return 0, nil
+ case +1:
+ return 0, io.EOF
+ }
+ }
+ if bytes.HasPrefix(dashBoundary, buf) {
+ return 0, readErr
+ }
+ }
+
+ // Search for "\n--boundary".
+ if i := bytes.Index(buf, nlDashBoundary); i >= 0 {
+ switch matchAfterPrefix(buf[i:], nlDashBoundary, readErr) {
+ case -1:
+ return i + len(nlDashBoundary), nil
+ case 0:
+ return i, nil
+ case +1:
+ return i, io.EOF
+ }
+ }
+ if bytes.HasPrefix(nlDashBoundary, buf) {
+ return 0, readErr
+ }
+
+ // Otherwise, anything up to the final \n is not part of the boundary
+ // and so must be part of the body.
+ // Also if the section from the final \n onward is not a prefix of the boundary,
+ // it too must be part of the body.
+ i := bytes.LastIndexByte(buf, nlDashBoundary[0])
+ if i >= 0 && bytes.HasPrefix(nlDashBoundary, buf[i:]) {
+ return i, nil
+ }
+ return len(buf), readErr
+}
+
+// matchAfterPrefix checks whether buf should be considered to match the boundary.
+// The prefix is "--boundary" or "\r\n--boundary" or "\n--boundary",
+// and the caller has verified already that bytes.HasPrefix(buf, prefix) is true.
+//
+// matchAfterPrefix returns +1 if the buffer does match the boundary,
+// meaning the prefix is followed by a double dash, space, tab, cr, nl,
+// or end of input.
+// It returns -1 if the buffer definitely does NOT match the boundary,
+// meaning the prefix is followed by some other character.
+// For example, "--foobar" does not match "--foo".
+// It returns 0 more input needs to be read to make the decision,
+// meaning that len(buf) == len(prefix) and readErr == nil.
+func matchAfterPrefix(buf, prefix []byte, readErr error) int {
+ if len(buf) == len(prefix) {
+ if readErr != nil {
+ return +1
+ }
+ return 0
+ }
+ c := buf[len(prefix)]
+
+ if c == ' ' || c == '\t' || c == '\r' || c == '\n' {
+ return +1
+ }
+
+ // Try to detect boundaryDash
+ if c == '-' {
+ if len(buf) == len(prefix)+1 {
+ if readErr != nil {
+ // Prefix + "-" does not match
+ return -1
+ }
+ return 0
+ }
+ if buf[len(prefix)+1] == '-' {
+ return +1
+ }
+ }
+
+ return -1
+}
+
+func (p *Part) Close() error {
+ io.Copy(io.Discard, p)
+ return nil
+}
+
+// Reader is an iterator over parts in a MIME multipart body.
+// Reader's underlying parser consumes its input as needed. Seeking
+// isn't supported.
+type Reader struct {
+ bufReader *bufio.Reader
+ tempDir string // used in tests
+
+ currentPart *Part
+ partsRead int
+
+ nl []byte // "\r\n" or "\n" (set after seeing first boundary line)
+ nlDashBoundary []byte // nl + "--boundary"
+ dashBoundaryDash []byte // "--boundary--"
+ dashBoundary []byte // "--boundary"
+}
+
+// maxMIMEHeaderSize is the maximum size of a MIME header we will parse,
+// including header keys, values, and map overhead.
+const maxMIMEHeaderSize = 10 << 20
+
+// multipartMaxHeaders is the maximum number of header entries NextPart will return,
+// as well as the maximum combined total of header entries Reader.ReadForm will return
+// in FileHeaders.
+var multipartMaxHeaders = godebug.New("multipartmaxheaders")
+
+func maxMIMEHeaders() int64 {
+ if s := multipartMaxHeaders.Value(); s != "" {
+ if v, err := strconv.ParseInt(s, 10, 64); err == nil && v >= 0 {
+ multipartMaxHeaders.IncNonDefault()
+ return v
+ }
+ }
+ return 10000
+}
+
+// NextPart returns the next part in the multipart or an error.
+// When there are no more parts, the error io.EOF is returned.
+//
+// As a special case, if the "Content-Transfer-Encoding" header
+// has a value of "quoted-printable", that header is instead
+// hidden and the body is transparently decoded during Read calls.
+func (r *Reader) NextPart() (*Part, error) {
+ return r.nextPart(false, maxMIMEHeaderSize, maxMIMEHeaders())
+}
+
+// NextRawPart returns the next part in the multipart or an error.
+// When there are no more parts, the error io.EOF is returned.
+//
+// Unlike NextPart, it does not have special handling for
+// "Content-Transfer-Encoding: quoted-printable".
+func (r *Reader) NextRawPart() (*Part, error) {
+ return r.nextPart(true, maxMIMEHeaderSize, maxMIMEHeaders())
+}
+
+func (r *Reader) nextPart(rawPart bool, maxMIMEHeaderSize, maxMIMEHeaders int64) (*Part, error) {
+ if r.currentPart != nil {
+ r.currentPart.Close()
+ }
+ if string(r.dashBoundary) == "--" {
+ return nil, fmt.Errorf("multipart: boundary is empty")
+ }
+ expectNewPart := false
+ for {
+ line, err := r.bufReader.ReadSlice('\n')
+
+ if err == io.EOF && r.isFinalBoundary(line) {
+ // If the buffer ends in "--boundary--" without the
+ // trailing "\r\n", ReadSlice will return an error
+ // (since it's missing the '\n'), but this is a valid
+ // multipart EOF so we need to return io.EOF instead of
+ // a fmt-wrapped one.
+ return nil, io.EOF
+ }
+ if err != nil {
+ return nil, fmt.Errorf("multipart: NextPart: %w", err)
+ }
+
+ if r.isBoundaryDelimiterLine(line) {
+ r.partsRead++
+ bp, err := newPart(r, rawPart, maxMIMEHeaderSize, maxMIMEHeaders)
+ if err != nil {
+ return nil, err
+ }
+ r.currentPart = bp
+ return bp, nil
+ }
+
+ if r.isFinalBoundary(line) {
+ // Expected EOF
+ return nil, io.EOF
+ }
+
+ if expectNewPart {
+ return nil, fmt.Errorf("multipart: expecting a new Part; got line %q", string(line))
+ }
+
+ if r.partsRead == 0 {
+ // skip line
+ continue
+ }
+
+ // Consume the "\n" or "\r\n" separator between the
+ // body of the previous part and the boundary line we
+ // now expect will follow. (either a new part or the
+ // end boundary)
+ if bytes.Equal(line, r.nl) {
+ expectNewPart = true
+ continue
+ }
+
+ return nil, fmt.Errorf("multipart: unexpected line in Next(): %q", line)
+ }
+}
+
+// isFinalBoundary reports whether line is the final boundary line
+// indicating that all parts are over.
+// It matches `^--boundary--[ \t]*(\r\n)?$`
+func (r *Reader) isFinalBoundary(line []byte) bool {
+ if !bytes.HasPrefix(line, r.dashBoundaryDash) {
+ return false
+ }
+ rest := line[len(r.dashBoundaryDash):]
+ rest = skipLWSPChar(rest)
+ return len(rest) == 0 || bytes.Equal(rest, r.nl)
+}
+
+func (r *Reader) isBoundaryDelimiterLine(line []byte) (ret bool) {
+ // https://tools.ietf.org/html/rfc2046#section-5.1
+ // The boundary delimiter line is then defined as a line
+ // consisting entirely of two hyphen characters ("-",
+ // decimal value 45) followed by the boundary parameter
+ // value from the Content-Type header field, optional linear
+ // whitespace, and a terminating CRLF.
+ if !bytes.HasPrefix(line, r.dashBoundary) {
+ return false
+ }
+ rest := line[len(r.dashBoundary):]
+ rest = skipLWSPChar(rest)
+
+ // On the first part, see our lines are ending in \n instead of \r\n
+ // and switch into that mode if so. This is a violation of the spec,
+ // but occurs in practice.
+ if r.partsRead == 0 && len(rest) == 1 && rest[0] == '\n' {
+ r.nl = r.nl[1:]
+ r.nlDashBoundary = r.nlDashBoundary[1:]
+ }
+ return bytes.Equal(rest, r.nl)
+}
+
+// skipLWSPChar returns b with leading spaces and tabs removed.
+// RFC 822 defines:
+//
+// LWSP-char = SPACE / HTAB
+func skipLWSPChar(b []byte) []byte {
+ for len(b) > 0 && (b[0] == ' ' || b[0] == '\t') {
+ b = b[1:]
+ }
+ return b
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/multipart_test.go b/platform/dbops/binaries/go/go/src/mime/multipart/multipart_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e0cb768c6967a57c830073c0189b635cd117eceb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/multipart_test.go
@@ -0,0 +1,1020 @@
+// 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 multipart
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/textproto"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestBoundaryLine(t *testing.T) {
+ mr := NewReader(strings.NewReader(""), "myBoundary")
+ if !mr.isBoundaryDelimiterLine([]byte("--myBoundary\r\n")) {
+ t.Error("expected")
+ }
+ if !mr.isBoundaryDelimiterLine([]byte("--myBoundary \r\n")) {
+ t.Error("expected")
+ }
+ if !mr.isBoundaryDelimiterLine([]byte("--myBoundary \n")) {
+ t.Error("expected")
+ }
+ if mr.isBoundaryDelimiterLine([]byte("--myBoundary bogus \n")) {
+ t.Error("expected fail")
+ }
+ if mr.isBoundaryDelimiterLine([]byte("--myBoundary bogus--")) {
+ t.Error("expected fail")
+ }
+}
+
+func escapeString(v string) string {
+ bytes, _ := json.Marshal(v)
+ return string(bytes)
+}
+
+func expectEq(t *testing.T, expected, actual, what string) {
+ if expected == actual {
+ return
+ }
+ t.Errorf("Unexpected value for %s; got %s (len %d) but expected: %s (len %d)",
+ what, escapeString(actual), len(actual), escapeString(expected), len(expected))
+}
+
+func TestNameAccessors(t *testing.T) {
+ tests := [...][3]string{
+ {`form-data; name="foo"`, "foo", ""},
+ {` form-data ; name=foo`, "foo", ""},
+ {`FORM-DATA;name="foo"`, "foo", ""},
+ {` FORM-DATA ; name="foo"`, "foo", ""},
+ {` FORM-DATA ; name="foo"`, "foo", ""},
+ {` FORM-DATA ; name=foo`, "foo", ""},
+ {` FORM-DATA ; filename="foo.txt"; name=foo; baz=quux`, "foo", "foo.txt"},
+ {` not-form-data ; filename="bar.txt"; name=foo; baz=quux`, "", "bar.txt"},
+ }
+ for i, test := range tests {
+ p := &Part{Header: make(map[string][]string)}
+ p.Header.Set("Content-Disposition", test[0])
+ if g, e := p.FormName(), test[1]; g != e {
+ t.Errorf("test %d: FormName() = %q; want %q", i, g, e)
+ }
+ if g, e := p.FileName(), test[2]; g != e {
+ t.Errorf("test %d: FileName() = %q; want %q", i, g, e)
+ }
+ }
+}
+
+var longLine = strings.Repeat("\n\n\r\r\r\n\r\000", (1<<20)/8)
+
+func testMultipartBody(sep string) string {
+ testBody := `
+This is a multi-part message. This line is ignored.
+--MyBoundary
+Header1: value1
+HEADER2: value2
+foo-bar: baz
+
+My value
+The end.
+--MyBoundary
+name: bigsection
+
+[longline]
+--MyBoundary
+Header1: value1b
+HEADER2: value2b
+foo-bar: bazb
+
+Line 1
+Line 2
+Line 3 ends in a newline, but just one.
+
+--MyBoundary
+
+never read data
+--MyBoundary--
+
+
+useless trailer
+`
+ testBody = strings.ReplaceAll(testBody, "\n", sep)
+ return strings.Replace(testBody, "[longline]", longLine, 1)
+}
+
+func TestMultipart(t *testing.T) {
+ bodyReader := strings.NewReader(testMultipartBody("\r\n"))
+ testMultipart(t, bodyReader, false)
+}
+
+func TestMultipartOnlyNewlines(t *testing.T) {
+ bodyReader := strings.NewReader(testMultipartBody("\n"))
+ testMultipart(t, bodyReader, true)
+}
+
+func TestMultipartSlowInput(t *testing.T) {
+ bodyReader := strings.NewReader(testMultipartBody("\r\n"))
+ testMultipart(t, &slowReader{bodyReader}, false)
+}
+
+func testMultipart(t *testing.T, r io.Reader, onlyNewlines bool) {
+ t.Parallel()
+ reader := NewReader(r, "MyBoundary")
+ buf := new(strings.Builder)
+
+ // Part1
+ part, err := reader.NextPart()
+ if part == nil || err != nil {
+ t.Error("Expected part1")
+ return
+ }
+ if x := part.Header.Get("Header1"); x != "value1" {
+ t.Errorf("part.Header.Get(%q) = %q, want %q", "Header1", x, "value1")
+ }
+ if x := part.Header.Get("foo-bar"); x != "baz" {
+ t.Errorf("part.Header.Get(%q) = %q, want %q", "foo-bar", x, "baz")
+ }
+ if x := part.Header.Get("Foo-Bar"); x != "baz" {
+ t.Errorf("part.Header.Get(%q) = %q, want %q", "Foo-Bar", x, "baz")
+ }
+ buf.Reset()
+ if _, err := io.Copy(buf, part); err != nil {
+ t.Errorf("part 1 copy: %v", err)
+ }
+
+ adjustNewlines := func(s string) string {
+ if onlyNewlines {
+ return strings.ReplaceAll(s, "\r\n", "\n")
+ }
+ return s
+ }
+
+ expectEq(t, adjustNewlines("My value\r\nThe end."), buf.String(), "Value of first part")
+
+ // Part2
+ part, err = reader.NextPart()
+ if err != nil {
+ t.Fatalf("Expected part2; got: %v", err)
+ return
+ }
+ if e, g := "bigsection", part.Header.Get("name"); e != g {
+ t.Errorf("part2's name header: expected %q, got %q", e, g)
+ }
+ buf.Reset()
+ if _, err := io.Copy(buf, part); err != nil {
+ t.Errorf("part 2 copy: %v", err)
+ }
+ s := buf.String()
+ if len(s) != len(longLine) {
+ t.Errorf("part2 body expected long line of length %d; got length %d",
+ len(longLine), len(s))
+ }
+ if s != longLine {
+ t.Errorf("part2 long body didn't match")
+ }
+
+ // Part3
+ part, err = reader.NextPart()
+ if part == nil || err != nil {
+ t.Error("Expected part3")
+ return
+ }
+ if part.Header.Get("foo-bar") != "bazb" {
+ t.Error("Expected foo-bar: bazb")
+ }
+ buf.Reset()
+ if _, err := io.Copy(buf, part); err != nil {
+ t.Errorf("part 3 copy: %v", err)
+ }
+ expectEq(t, adjustNewlines("Line 1\r\nLine 2\r\nLine 3 ends in a newline, but just one.\r\n"),
+ buf.String(), "body of part 3")
+
+ // Part4
+ part, err = reader.NextPart()
+ if part == nil || err != nil {
+ t.Error("Expected part 4 without errors")
+ return
+ }
+
+ // Non-existent part5
+ part, err = reader.NextPart()
+ if part != nil {
+ t.Error("Didn't expect a fifth part.")
+ }
+ if err != io.EOF {
+ t.Errorf("On fifth part expected io.EOF; got %v", err)
+ }
+}
+
+func TestVariousTextLineEndings(t *testing.T) {
+ tests := [...]string{
+ "Foo\nBar",
+ "Foo\nBar\n",
+ "Foo\r\nBar",
+ "Foo\r\nBar\r\n",
+ "Foo\rBar",
+ "Foo\rBar\r",
+ "\x00\x01\x02\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10",
+ }
+
+ for testNum, expectedBody := range tests {
+ body := "--BOUNDARY\r\n" +
+ "Content-Disposition: form-data; name=\"value\"\r\n" +
+ "\r\n" +
+ expectedBody +
+ "\r\n--BOUNDARY--\r\n"
+ bodyReader := strings.NewReader(body)
+
+ reader := NewReader(bodyReader, "BOUNDARY")
+ buf := new(bytes.Buffer)
+ part, err := reader.NextPart()
+ if part == nil {
+ t.Errorf("Expected a body part on text %d", testNum)
+ continue
+ }
+ if err != nil {
+ t.Errorf("Unexpected error on text %d: %v", testNum, err)
+ continue
+ }
+ written, err := io.Copy(buf, part)
+ expectEq(t, expectedBody, buf.String(), fmt.Sprintf("test %d", testNum))
+ if err != nil {
+ t.Errorf("Error copying multipart; bytes=%v, error=%v", written, err)
+ }
+
+ part, err = reader.NextPart()
+ if part != nil {
+ t.Errorf("Unexpected part in test %d", testNum)
+ }
+ if err != io.EOF {
+ t.Errorf("On test %d expected io.EOF; got %v", testNum, err)
+ }
+
+ }
+}
+
+type maliciousReader struct {
+ t *testing.T
+ n int
+}
+
+const maxReadThreshold = 1 << 20
+
+func (mr *maliciousReader) Read(b []byte) (n int, err error) {
+ mr.n += len(b)
+ if mr.n >= maxReadThreshold {
+ mr.t.Fatal("too much was read")
+ return 0, io.EOF
+ }
+ return len(b), nil
+}
+
+func TestLineLimit(t *testing.T) {
+ mr := &maliciousReader{t: t}
+ r := NewReader(mr, "fooBoundary")
+ part, err := r.NextPart()
+ if part != nil {
+ t.Errorf("unexpected part read")
+ }
+ if err == nil {
+ t.Errorf("expected an error")
+ }
+ if mr.n >= maxReadThreshold {
+ t.Errorf("expected to read < %d bytes; read %d", maxReadThreshold, mr.n)
+ }
+}
+
+func TestMultipartTruncated(t *testing.T) {
+ for _, body := range []string{
+ `
+This is a multi-part message. This line is ignored.
+--MyBoundary
+foo-bar: baz
+
+Oh no, premature EOF!
+`,
+ `
+This is a multi-part message. This line is ignored.
+--MyBoundary
+foo-bar: baz
+
+Oh no, premature EOF!
+--MyBoundary-`,
+ } {
+ body = strings.ReplaceAll(body, "\n", "\r\n")
+ bodyReader := strings.NewReader(body)
+ r := NewReader(bodyReader, "MyBoundary")
+
+ part, err := r.NextPart()
+ if err != nil {
+ t.Fatalf("didn't get a part")
+ }
+ _, err = io.Copy(io.Discard, part)
+ if err != io.ErrUnexpectedEOF {
+ t.Fatalf("expected error io.ErrUnexpectedEOF; got %v", err)
+ }
+ }
+}
+
+type slowReader struct {
+ r io.Reader
+}
+
+func (s *slowReader) Read(p []byte) (int, error) {
+ if len(p) == 0 {
+ return s.r.Read(p)
+ }
+ return s.r.Read(p[:1])
+}
+
+type sentinelReader struct {
+ // done is closed when this reader is read from.
+ done chan struct{}
+}
+
+func (s *sentinelReader) Read([]byte) (int, error) {
+ if s.done != nil {
+ close(s.done)
+ s.done = nil
+ }
+ return 0, io.EOF
+}
+
+// TestMultipartStreamReadahead tests that PartReader does not block
+// on reading past the end of a part, ensuring that it can be used on
+// a stream like multipart/x-mixed-replace. See golang.org/issue/15431
+func TestMultipartStreamReadahead(t *testing.T) {
+ testBody1 := `
+This is a multi-part message. This line is ignored.
+--MyBoundary
+foo-bar: baz
+
+Body
+--MyBoundary
+`
+ testBody2 := `foo-bar: bop
+
+Body 2
+--MyBoundary--
+`
+ done1 := make(chan struct{})
+ reader := NewReader(
+ io.MultiReader(
+ strings.NewReader(testBody1),
+ &sentinelReader{done1},
+ strings.NewReader(testBody2)),
+ "MyBoundary")
+
+ var i int
+ readPart := func(hdr textproto.MIMEHeader, body string) {
+ part, err := reader.NextPart()
+ if part == nil || err != nil {
+ t.Fatalf("Part %d: NextPart failed: %v", i, err)
+ }
+
+ if !reflect.DeepEqual(part.Header, hdr) {
+ t.Errorf("Part %d: part.Header = %v, want %v", i, part.Header, hdr)
+ }
+ data, err := io.ReadAll(part)
+ expectEq(t, body, string(data), fmt.Sprintf("Part %d body", i))
+ if err != nil {
+ t.Fatalf("Part %d: ReadAll failed: %v", i, err)
+ }
+ i++
+ }
+
+ readPart(textproto.MIMEHeader{"Foo-Bar": {"baz"}}, "Body")
+
+ select {
+ case <-done1:
+ t.Errorf("Reader read past second boundary")
+ default:
+ }
+
+ readPart(textproto.MIMEHeader{"Foo-Bar": {"bop"}}, "Body 2")
+}
+
+func TestLineContinuation(t *testing.T) {
+ // This body, extracted from an email, contains headers that span multiple
+ // lines.
+
+ // TODO: The original mail ended with a double-newline before the
+ // final delimiter; this was manually edited to use a CRLF.
+ testBody :=
+ "\n--Apple-Mail-2-292336769\nContent-Transfer-Encoding: 7bit\nContent-Type: text/plain;\n\tcharset=US-ASCII;\n\tdelsp=yes;\n\tformat=flowed\n\nI'm finding the same thing happening on my system (10.4.1).\n\n\n--Apple-Mail-2-292336769\nContent-Transfer-Encoding: quoted-printable\nContent-Type: text/html;\n\tcharset=ISO-8859-1\n\nI'm finding the same thing =\nhappening on my system (10.4.1).=A0 But I built it with XCode =\n2.0.=\nHTML>=\n\r\n--Apple-Mail-2-292336769--\n"
+
+ r := NewReader(strings.NewReader(testBody), "Apple-Mail-2-292336769")
+
+ for i := 0; i < 2; i++ {
+ part, err := r.NextPart()
+ if err != nil {
+ t.Fatalf("didn't get a part")
+ }
+ var buf strings.Builder
+ n, err := io.Copy(&buf, part)
+ if err != nil {
+ t.Errorf("error reading part: %v\nread so far: %q", err, buf.String())
+ }
+ if n <= 0 {
+ t.Errorf("read %d bytes; expected >0", n)
+ }
+ }
+}
+
+func TestQuotedPrintableEncoding(t *testing.T) {
+ for _, cte := range []string{"quoted-printable", "Quoted-PRINTABLE"} {
+ t.Run(cte, func(t *testing.T) {
+ testQuotedPrintableEncoding(t, cte)
+ })
+ }
+}
+
+func testQuotedPrintableEncoding(t *testing.T, cte string) {
+ // From https://golang.org/issue/4411
+ body := "--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=text\r\nContent-Transfer-Encoding: " + cte + "\r\n\r\nwords words words words words words words words words words words words wor=\r\nds words words words words words words words words words words words words =\r\nwords words words words words words words words words words words words wor=\r\nds words words words words words words words words words words words words =\r\nwords words words words words words words words words\r\n--0016e68ee29c5d515f04cedf6733\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=submit\r\n\r\nSubmit\r\n--0016e68ee29c5d515f04cedf6733--"
+ r := NewReader(strings.NewReader(body), "0016e68ee29c5d515f04cedf6733")
+ part, err := r.NextPart()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if te, ok := part.Header["Content-Transfer-Encoding"]; ok {
+ t.Errorf("unexpected Content-Transfer-Encoding of %q", te)
+ }
+ var buf strings.Builder
+ _, err = io.Copy(&buf, part)
+ if err != nil {
+ t.Error(err)
+ }
+ got := buf.String()
+ want := "words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words"
+ if got != want {
+ t.Errorf("wrong part value:\n got: %q\nwant: %q", got, want)
+ }
+}
+
+func TestRawPart(t *testing.T) {
+ // https://github.com/golang/go/issues/29090
+
+ body := strings.Replace(`--0016e68ee29c5d515f04cedf6733
+Content-Type: text/plain; charset="utf-8"
+Content-Transfer-Encoding: quoted-printable
+
+Hello World.
+--0016e68ee29c5d515f04cedf6733
+Content-Type: text/plain; charset="utf-8"
+Content-Transfer-Encoding: quoted-printable
+
+Hello World.
+--0016e68ee29c5d515f04cedf6733--`, "\n", "\r\n", -1)
+
+ r := NewReader(strings.NewReader(body), "0016e68ee29c5d515f04cedf6733")
+
+ // This part is expected to be raw, bypassing the automatic handling
+ // of quoted-printable.
+ part, err := r.NextRawPart()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := part.Header["Content-Transfer-Encoding"]; !ok {
+ t.Errorf("missing Content-Transfer-Encoding")
+ }
+ var buf strings.Builder
+ _, err = io.Copy(&buf, part)
+ if err != nil {
+ t.Error(err)
+ }
+ got := buf.String()
+ // Data is still quoted-printable.
+ want := `Hello World.
`
+ if got != want {
+ t.Errorf("wrong part value:\n got: %q\nwant: %q", got, want)
+ }
+
+ // This part is expected to have automatic decoding of quoted-printable.
+ part, err = r.NextPart()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if te, ok := part.Header["Content-Transfer-Encoding"]; ok {
+ t.Errorf("unexpected Content-Transfer-Encoding of %q", te)
+ }
+
+ buf.Reset()
+ _, err = io.Copy(&buf, part)
+ if err != nil {
+ t.Error(err)
+ }
+ got = buf.String()
+ // QP data has been decoded.
+ want = `Hello World.
`
+ if got != want {
+ t.Errorf("wrong part value:\n got: %q\nwant: %q", got, want)
+ }
+}
+
+// Test parsing an image attachment from gmail, which previously failed.
+func TestNested(t *testing.T) {
+ // nested-mime is the body part of a multipart/mixed email
+ // with boundary e89a8ff1c1e83553e304be640612
+ f, err := os.Open("testdata/nested-mime")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ mr := NewReader(f, "e89a8ff1c1e83553e304be640612")
+ p, err := mr.NextPart()
+ if err != nil {
+ t.Fatalf("error reading first section (alternative): %v", err)
+ }
+
+ // Read the inner text/plain and text/html sections of the multipart/alternative.
+ mr2 := NewReader(p, "e89a8ff1c1e83553e004be640610")
+ p, err = mr2.NextPart()
+ if err != nil {
+ t.Fatalf("reading text/plain part: %v", err)
+ }
+ if b, err := io.ReadAll(p); string(b) != "*body*\r\n" || err != nil {
+ t.Fatalf("reading text/plain part: got %q, %v", b, err)
+ }
+ p, err = mr2.NextPart()
+ if err != nil {
+ t.Fatalf("reading text/html part: %v", err)
+ }
+ if b, err := io.ReadAll(p); string(b) != "body\r\n" || err != nil {
+ t.Fatalf("reading text/html part: got %q, %v", b, err)
+ }
+
+ p, err = mr2.NextPart()
+ if err != io.EOF {
+ t.Fatalf("final inner NextPart = %v; want io.EOF", err)
+ }
+
+ // Back to the outer multipart/mixed, reading the image attachment.
+ _, err = mr.NextPart()
+ if err != nil {
+ t.Fatalf("error reading the image attachment at the end: %v", err)
+ }
+
+ _, err = mr.NextPart()
+ if err != io.EOF {
+ t.Fatalf("final outer NextPart = %v; want io.EOF", err)
+ }
+}
+
+type headerBody struct {
+ header textproto.MIMEHeader
+ body string
+}
+
+func formData(key, value string) headerBody {
+ return headerBody{
+ textproto.MIMEHeader{
+ "Content-Type": {"text/plain; charset=ISO-8859-1"},
+ "Content-Disposition": {"form-data; name=" + key},
+ },
+ value,
+ }
+}
+
+type parseTest struct {
+ name string
+ in, sep string
+ want []headerBody
+}
+
+var parseTests = []parseTest{
+ // Actual body from App Engine on a blob upload. The final part (the
+ // Content-Type: message/external-body) is what App Engine replaces
+ // the uploaded file with. The other form fields (prefixed with
+ // "other" in their form-data name) are unchanged. A bug was
+ // reported with blob uploads failing when the other fields were
+ // empty. This was the MIME POST body that previously failed.
+ {
+ name: "App Engine post",
+ sep: "00151757727e9583fd04bfbca4c6",
+ in: "--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherEmpty1\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherFoo1\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherFoo2\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherEmpty2\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatFoo\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatFoo\r\n\r\nfoo\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatEmpty\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=otherRepeatEmpty\r\n\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Disposition: form-data; name=submit\r\n\r\nSubmit\r\n--00151757727e9583fd04bfbca4c6\r\nContent-Type: message/external-body; charset=ISO-8859-1; blob-key=AHAZQqG84qllx7HUqO_oou5EvdYQNS3Mbbkb0RjjBoM_Kc1UqEN2ygDxWiyCPulIhpHRPx-VbpB6RX4MrsqhWAi_ZxJ48O9P2cTIACbvATHvg7IgbvZytyGMpL7xO1tlIvgwcM47JNfv_tGhy1XwyEUO8oldjPqg5Q\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\nContent-Type: image/png\r\nContent-Length: 232303\r\nX-AppEngine-Upload-Creation: 2012-05-10 23:14:02.715173\r\nContent-MD5: MzRjODU1ZDZhZGU1NmRlOWEwZmMwMDdlODBmZTA0NzA=\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\n\r\n--00151757727e9583fd04bfbca4c6--",
+ want: []headerBody{
+ formData("otherEmpty1", ""),
+ formData("otherFoo1", "foo"),
+ formData("otherFoo2", "foo"),
+ formData("otherEmpty2", ""),
+ formData("otherRepeatFoo", "foo"),
+ formData("otherRepeatFoo", "foo"),
+ formData("otherRepeatEmpty", ""),
+ formData("otherRepeatEmpty", ""),
+ formData("submit", "Submit"),
+ {textproto.MIMEHeader{
+ "Content-Type": {"message/external-body; charset=ISO-8859-1; blob-key=AHAZQqG84qllx7HUqO_oou5EvdYQNS3Mbbkb0RjjBoM_Kc1UqEN2ygDxWiyCPulIhpHRPx-VbpB6RX4MrsqhWAi_ZxJ48O9P2cTIACbvATHvg7IgbvZytyGMpL7xO1tlIvgwcM47JNfv_tGhy1XwyEUO8oldjPqg5Q"},
+ "Content-Disposition": {"form-data; name=file; filename=\"fall.png\""},
+ }, "Content-Type: image/png\r\nContent-Length: 232303\r\nX-AppEngine-Upload-Creation: 2012-05-10 23:14:02.715173\r\nContent-MD5: MzRjODU1ZDZhZGU1NmRlOWEwZmMwMDdlODBmZTA0NzA=\r\nContent-Disposition: form-data; name=file; filename=\"fall.png\"\r\n\r\n"},
+ },
+ },
+
+ // Single empty part, ended with --boundary immediately after headers.
+ {
+ name: "single empty part, --boundary",
+ sep: "abc",
+ in: "--abc\r\nFoo: bar\r\n\r\n--abc--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ },
+ },
+
+ // Single empty part, ended with \r\n--boundary immediately after headers.
+ {
+ name: "single empty part, \r\n--boundary",
+ sep: "abc",
+ in: "--abc\r\nFoo: bar\r\n\r\n\r\n--abc--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ },
+ },
+
+ // Final part empty.
+ {
+ name: "final part empty",
+ sep: "abc",
+ in: "--abc\r\nFoo: bar\r\n\r\n--abc\r\nFoo2: bar2\r\n\r\n--abc--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ {textproto.MIMEHeader{"Foo2": {"bar2"}}, ""},
+ },
+ },
+
+ // Final part empty with newlines after final separator.
+ {
+ name: "final part empty then crlf",
+ sep: "abc",
+ in: "--abc\r\nFoo: bar\r\n\r\n--abc--\r\n",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ },
+ },
+
+ // Final part empty with lwsp-chars after final separator.
+ {
+ name: "final part empty then lwsp",
+ sep: "abc",
+ in: "--abc\r\nFoo: bar\r\n\r\n--abc-- \t",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ },
+ },
+
+ // No parts (empty form as submitted by Chrome)
+ {
+ name: "no parts",
+ sep: "----WebKitFormBoundaryQfEAfzFOiSemeHfA",
+ in: "------WebKitFormBoundaryQfEAfzFOiSemeHfA--\r\n",
+ want: []headerBody{},
+ },
+
+ // Part containing data starting with the boundary, but with additional suffix.
+ {
+ name: "fake separator as data",
+ sep: "sep",
+ in: "--sep\r\nFoo: bar\r\n\r\n--sepFAKE\r\n--sep--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, "--sepFAKE"},
+ },
+ },
+
+ // Part containing a boundary with whitespace following it.
+ {
+ name: "boundary with whitespace",
+ sep: "sep",
+ in: "--sep \r\nFoo: bar\r\n\r\ntext\r\n--sep--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, "text"},
+ },
+ },
+
+ // With ignored leading line.
+ {
+ name: "leading line",
+ sep: "MyBoundary",
+ in: strings.Replace(`This is a multi-part message. This line is ignored.
+--MyBoundary
+foo: bar
+
+
+--MyBoundary--`, "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, ""},
+ },
+ },
+
+ // Issue 10616; minimal
+ {
+ name: "issue 10616 minimal",
+ sep: "sep",
+ in: "--sep \r\nFoo: bar\r\n\r\n" +
+ "a\r\n" +
+ "--sep_alt\r\n" +
+ "b\r\n" +
+ "\r\n--sep--",
+ want: []headerBody{
+ {textproto.MIMEHeader{"Foo": {"bar"}}, "a\r\n--sep_alt\r\nb\r\n"},
+ },
+ },
+
+ // Issue 10616; full example from bug.
+ {
+ name: "nested separator prefix is outer separator",
+ sep: "----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9",
+ in: strings.Replace(`------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9
+Content-Type: multipart/alternative; boundary="----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt"
+
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
+Content-Type: text/plain; charset="utf-8"
+Content-Transfer-Encoding: 8bit
+
+This is a multi-part message in MIME format.
+
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
+Content-Type: text/html; charset="utf-8"
+Content-Transfer-Encoding: 8bit
+
+html things
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt--
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9--`, "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`multipart/alternative; boundary="----=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt"`}},
+ strings.Replace(`------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
+Content-Type: text/plain; charset="utf-8"
+Content-Transfer-Encoding: 8bit
+
+This is a multi-part message in MIME format.
+
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt
+Content-Type: text/html; charset="utf-8"
+Content-Transfer-Encoding: 8bit
+
+html things
+------=_NextPart_4c2fbafd7ec4c8bf08034fe724b608d9_alt--`, "\n", "\r\n", -1),
+ },
+ },
+ },
+
+ // Issue 12662: Check that we don't consume the leading \r if the peekBuffer
+ // ends in '\r\n--separator-'
+ {
+ name: "peek buffer boundary condition",
+ sep: "00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db",
+ in: strings.Replace(`--00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db
+Content-Disposition: form-data; name="block"; filename="block"
+Content-Type: application/octet-stream
+
+`+strings.Repeat("A", peekBufferSize-65)+"\n--00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db--", "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`application/octet-stream`}, "Content-Disposition": {`form-data; name="block"; filename="block"`}},
+ strings.Repeat("A", peekBufferSize-65),
+ },
+ },
+ },
+
+ // Issue 12662: Same test as above with \r\n at the end
+ {
+ name: "peek buffer boundary condition",
+ sep: "00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db",
+ in: strings.Replace(`--00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db
+Content-Disposition: form-data; name="block"; filename="block"
+Content-Type: application/octet-stream
+
+`+strings.Repeat("A", peekBufferSize-65)+"\n--00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db--\n", "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`application/octet-stream`}, "Content-Disposition": {`form-data; name="block"; filename="block"`}},
+ strings.Repeat("A", peekBufferSize-65),
+ },
+ },
+ },
+
+ // Issue 12662v2: We want to make sure that for short buffers that end with
+ // '\r\n--separator-' we always consume at least one (valid) symbol from the
+ // peekBuffer
+ {
+ name: "peek buffer boundary condition",
+ sep: "aaaaaaaaaa00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db",
+ in: strings.Replace(`--aaaaaaaaaa00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db
+Content-Disposition: form-data; name="block"; filename="block"
+Content-Type: application/octet-stream
+
+`+strings.Repeat("A", peekBufferSize)+"\n--aaaaaaaaaa00ffded004d4dd0fdf945fbdef9d9050cfd6a13a821846299b27fc71b9db--", "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`application/octet-stream`}, "Content-Disposition": {`form-data; name="block"; filename="block"`}},
+ strings.Repeat("A", peekBufferSize),
+ },
+ },
+ },
+
+ // Context: https://github.com/camlistore/camlistore/issues/642
+ // If the file contents in the form happens to have a size such as:
+ // size = peekBufferSize - (len("\n--") + len(boundary) + len("\r") + 1), (modulo peekBufferSize)
+ // then peekBufferSeparatorIndex was wrongly returning (-1, false), which was leading to an nCopy
+ // cut such as:
+ // "somedata\r| |\n--Boundary\r" (instead of "somedata| |\r\n--Boundary\r"), which was making the
+ // subsequent Read miss the boundary.
+ {
+ name: "safeCount off by one",
+ sep: "08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74",
+ in: strings.Replace(`--08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74
+Content-Disposition: form-data; name="myfile"; filename="my-file.txt"
+Content-Type: application/octet-stream
+
+`, "\n", "\r\n", -1) +
+ strings.Repeat("A", peekBufferSize-(len("\n--")+len("08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74")+len("\r")+1)) +
+ strings.Replace(`
+--08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74
+Content-Disposition: form-data; name="key"
+
+val
+--08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74--
+`, "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`application/octet-stream`}, "Content-Disposition": {`form-data; name="myfile"; filename="my-file.txt"`}},
+ strings.Repeat("A", peekBufferSize-(len("\n--")+len("08b84578eabc563dcba967a945cdf0d9f613864a8f4a716f0e81caa71a74")+len("\r")+1)),
+ },
+ {textproto.MIMEHeader{"Content-Disposition": {`form-data; name="key"`}},
+ "val",
+ },
+ },
+ },
+
+ // Issue 46042; a nested multipart uses the outer separator followed by
+ // a dash.
+ {
+ name: "nested separator prefix is outer separator followed by a dash",
+ sep: "foo",
+ in: strings.Replace(`--foo
+Content-Type: multipart/alternative; boundary="foo-bar"
+
+--foo-bar
+
+Body
+--foo-bar
+
+Body2
+--foo-bar--
+--foo--`, "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`multipart/alternative; boundary="foo-bar"`}},
+ strings.Replace(`--foo-bar
+
+Body
+--foo-bar
+
+Body2
+--foo-bar--`, "\n", "\r\n", -1),
+ },
+ },
+ },
+
+ // A nested boundary cannot be the outer separator followed by double dash.
+ {
+ name: "nested separator prefix is outer separator followed by double dash",
+ sep: "foo",
+ in: strings.Replace(`--foo
+Content-Type: multipart/alternative; boundary="foo--"
+
+--foo--
+
+Body
+
+--foo--`, "\n", "\r\n", -1),
+ want: []headerBody{
+ {textproto.MIMEHeader{"Content-Type": {`multipart/alternative; boundary="foo--"`}}, ""},
+ },
+ },
+
+ roundTripParseTest(),
+}
+
+func TestParse(t *testing.T) {
+Cases:
+ for _, tt := range parseTests {
+ r := NewReader(strings.NewReader(tt.in), tt.sep)
+ got := []headerBody{}
+ for {
+ p, err := r.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Errorf("in test %q, NextPart: %v", tt.name, err)
+ continue Cases
+ }
+ pbody, err := io.ReadAll(p)
+ if err != nil {
+ t.Errorf("in test %q, error reading part: %v", tt.name, err)
+ continue Cases
+ }
+ got = append(got, headerBody{p.Header, string(pbody)})
+ }
+ if !reflect.DeepEqual(tt.want, got) {
+ t.Errorf("test %q:\n got: %v\nwant: %v", tt.name, got, tt.want)
+ if len(tt.want) != len(got) {
+ t.Errorf("test %q: got %d parts, want %d", tt.name, len(got), len(tt.want))
+ } else if len(got) > 1 {
+ for pi, wantPart := range tt.want {
+ if !reflect.DeepEqual(wantPart, got[pi]) {
+ t.Errorf("test %q, part %d:\n got: %v\nwant: %v", tt.name, pi, got[pi], wantPart)
+ }
+ }
+ }
+ }
+ }
+}
+
+func partsFromReader(r *Reader) ([]headerBody, error) {
+ got := []headerBody{}
+ for {
+ p, err := r.NextPart()
+ if err == io.EOF {
+ return got, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("NextPart: %v", err)
+ }
+ pbody, err := io.ReadAll(p)
+ if err != nil {
+ return nil, fmt.Errorf("error reading part: %v", err)
+ }
+ got = append(got, headerBody{p.Header, string(pbody)})
+ }
+}
+
+func TestParseAllSizes(t *testing.T) {
+ t.Parallel()
+ maxSize := 5 << 10
+ if testing.Short() {
+ maxSize = 512
+ }
+ var buf bytes.Buffer
+ body := strings.Repeat("a", maxSize)
+ bodyb := []byte(body)
+ for size := 0; size < maxSize; size++ {
+ buf.Reset()
+ w := NewWriter(&buf)
+ part, _ := w.CreateFormField("f")
+ part.Write(bodyb[:size])
+ part, _ = w.CreateFormField("key")
+ part.Write([]byte("val"))
+ w.Close()
+ r := NewReader(&buf, w.Boundary())
+ got, err := partsFromReader(r)
+ if err != nil {
+ t.Errorf("For size %d: %v", size, err)
+ continue
+ }
+ if len(got) != 2 {
+ t.Errorf("For size %d, num parts = %d; want 2", size, len(got))
+ continue
+ }
+ if got[0].body != body[:size] {
+ t.Errorf("For size %d, got unexpected len %d: %q", size, len(got[0].body), got[0].body)
+ }
+ }
+}
+
+func roundTripParseTest() parseTest {
+ t := parseTest{
+ name: "round trip",
+ want: []headerBody{
+ formData("empty", ""),
+ formData("lf", "\n"),
+ formData("cr", "\r"),
+ formData("crlf", "\r\n"),
+ formData("foo", "bar"),
+ },
+ }
+ var buf strings.Builder
+ w := NewWriter(&buf)
+ for _, p := range t.want {
+ pw, err := w.CreatePart(p.header)
+ if err != nil {
+ panic(err)
+ }
+ _, err = pw.Write([]byte(p.body))
+ if err != nil {
+ panic(err)
+ }
+ }
+ w.Close()
+ t.in = buf.String()
+ t.sep = w.Boundary()
+ return t
+}
+
+func TestNoBoundary(t *testing.T) {
+ mr := NewReader(strings.NewReader(""), "")
+ _, err := mr.NextPart()
+ if got, want := fmt.Sprint(err), "multipart: boundary is empty"; got != want {
+ t.Errorf("NextPart error = %v; want %v", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/readmimeheader.go b/platform/dbops/binaries/go/go/src/mime/multipart/readmimeheader.go
new file mode 100644
index 0000000000000000000000000000000000000000..25aa6e2092861b0952b7ea17ae64c9eb3c61ba0c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/readmimeheader.go
@@ -0,0 +1,14 @@
+// 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 multipart
+
+import (
+ "net/textproto"
+ _ "unsafe" // for go:linkname
+)
+
+// readMIMEHeader is defined in package net/textproto.
+//
+//go:linkname readMIMEHeader net/textproto.readMIMEHeader
+func readMIMEHeader(r *textproto.Reader, maxMemory, maxHeaders int64) (textproto.MIMEHeader, error)
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/testdata/nested-mime b/platform/dbops/binaries/go/go/src/mime/multipart/testdata/nested-mime
new file mode 100644
index 0000000000000000000000000000000000000000..71c238e38902fef782169ac6114f9e7428bd0113
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/testdata/nested-mime
@@ -0,0 +1,29 @@
+--e89a8ff1c1e83553e304be640612
+Content-Type: multipart/alternative; boundary=e89a8ff1c1e83553e004be640610
+
+--e89a8ff1c1e83553e004be640610
+Content-Type: text/plain; charset=UTF-8
+
+*body*
+
+--e89a8ff1c1e83553e004be640610
+Content-Type: text/html; charset=UTF-8
+
+body
+
+--e89a8ff1c1e83553e004be640610--
+--e89a8ff1c1e83553e304be640612
+Content-Type: image/png; name="x.png"
+Content-Disposition: attachment;
+ filename="x.png"
+Content-Transfer-Encoding: base64
+X-Attachment-Id: f_h1edgigu0
+
+iVBORw0KGgoAAAANSUhEUgAAAagAAADrCAIAAACza5XhAAAKMWlDQ1BJQ0MgUHJvZmlsZQAASImd
+lndUU9kWh8+9N71QkhCKlNBraFICSA29SJEuKjEJEErAkAAiNkRUcERRkaYIMijggKNDkbEiioUB
+8b2kqeGaj4aTNftesu5mob4pr07ecMywRwLBvDCJOksqlUyldAZD7g9fxIZRWWPMvXRNJROJRBIG
+Y7Vx0mva1HAwYqibdKONXye3dW4iUonhWFJnqK7OaanU1gGkErFYEgaj0cg8wK+zVPh2ziwnHy07
+U8lYTNapezSzOuevRwLB7CFkqQQCwaJDiBQIBIJFhwh8AoFg0SHUqQUCASRJKkwkhMy/JfODWPEJ
+BIJFhwh8AoFg0TFnQqQ55GtPFopcJsN97e1nYtNuIBYeGBgYCmYrmE3jZ05iaGAoMX0xzxkWz6Hv
+yO7WvrlwzA0uLzrD+VkKqViwl9IfTBVNFMyc/x9alloiPPlqhQAAAABJRU5ErkJggg==
+--e89a8ff1c1e83553e304be640612--
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/writer.go b/platform/dbops/binaries/go/go/src/mime/multipart/writer.go
new file mode 100644
index 0000000000000000000000000000000000000000..d1ff151a7d1d6441bf8a9209bdd0529a6d29066d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/writer.go
@@ -0,0 +1,201 @@
+// 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 multipart
+
+import (
+ "bytes"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "io"
+ "net/textproto"
+ "sort"
+ "strings"
+)
+
+// A Writer generates multipart messages.
+type Writer struct {
+ w io.Writer
+ boundary string
+ lastpart *part
+}
+
+// NewWriter returns a new multipart Writer with a random boundary,
+// writing to w.
+func NewWriter(w io.Writer) *Writer {
+ return &Writer{
+ w: w,
+ boundary: randomBoundary(),
+ }
+}
+
+// Boundary returns the Writer's boundary.
+func (w *Writer) Boundary() string {
+ return w.boundary
+}
+
+// SetBoundary overrides the Writer's default randomly-generated
+// boundary separator with an explicit value.
+//
+// SetBoundary must be called before any parts are created, may only
+// contain certain ASCII characters, and must be non-empty and
+// at most 70 bytes long.
+func (w *Writer) SetBoundary(boundary string) error {
+ if w.lastpart != nil {
+ return errors.New("mime: SetBoundary called after write")
+ }
+ // rfc2046#section-5.1.1
+ if len(boundary) < 1 || len(boundary) > 70 {
+ return errors.New("mime: invalid boundary length")
+ }
+ end := len(boundary) - 1
+ for i, b := range boundary {
+ if 'A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' || '0' <= b && b <= '9' {
+ continue
+ }
+ switch b {
+ case '\'', '(', ')', '+', '_', ',', '-', '.', '/', ':', '=', '?':
+ continue
+ case ' ':
+ if i != end {
+ continue
+ }
+ }
+ return errors.New("mime: invalid boundary character")
+ }
+ w.boundary = boundary
+ return nil
+}
+
+// FormDataContentType returns the Content-Type for an HTTP
+// multipart/form-data with this Writer's Boundary.
+func (w *Writer) FormDataContentType() string {
+ b := w.boundary
+ // We must quote the boundary if it contains any of the
+ // tspecials characters defined by RFC 2045, or space.
+ if strings.ContainsAny(b, `()<>@,;:\"/[]?= `) {
+ b = `"` + b + `"`
+ }
+ return "multipart/form-data; boundary=" + b
+}
+
+func randomBoundary() string {
+ var buf [30]byte
+ _, err := io.ReadFull(rand.Reader, buf[:])
+ if err != nil {
+ panic(err)
+ }
+ return fmt.Sprintf("%x", buf[:])
+}
+
+// CreatePart creates a new multipart section with the provided
+// header. The body of the part should be written to the returned
+// Writer. After calling CreatePart, any previous part may no longer
+// be written to.
+func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, error) {
+ if w.lastpart != nil {
+ if err := w.lastpart.close(); err != nil {
+ return nil, err
+ }
+ }
+ var b bytes.Buffer
+ if w.lastpart != nil {
+ fmt.Fprintf(&b, "\r\n--%s\r\n", w.boundary)
+ } else {
+ fmt.Fprintf(&b, "--%s\r\n", w.boundary)
+ }
+
+ keys := make([]string, 0, len(header))
+ for k := range header {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ for _, v := range header[k] {
+ fmt.Fprintf(&b, "%s: %s\r\n", k, v)
+ }
+ }
+ fmt.Fprintf(&b, "\r\n")
+ _, err := io.Copy(w.w, &b)
+ if err != nil {
+ return nil, err
+ }
+ p := &part{
+ mw: w,
+ }
+ w.lastpart = p
+ return p, nil
+}
+
+var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
+
+func escapeQuotes(s string) string {
+ return quoteEscaper.Replace(s)
+}
+
+// CreateFormFile is a convenience wrapper around CreatePart. It creates
+// a new form-data header with the provided field name and file name.
+func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error) {
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition",
+ fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
+ escapeQuotes(fieldname), escapeQuotes(filename)))
+ h.Set("Content-Type", "application/octet-stream")
+ return w.CreatePart(h)
+}
+
+// CreateFormField calls CreatePart with a header using the
+// given field name.
+func (w *Writer) CreateFormField(fieldname string) (io.Writer, error) {
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition",
+ fmt.Sprintf(`form-data; name="%s"`, escapeQuotes(fieldname)))
+ return w.CreatePart(h)
+}
+
+// WriteField calls CreateFormField and then writes the given value.
+func (w *Writer) WriteField(fieldname, value string) error {
+ p, err := w.CreateFormField(fieldname)
+ if err != nil {
+ return err
+ }
+ _, err = p.Write([]byte(value))
+ return err
+}
+
+// Close finishes the multipart message and writes the trailing
+// boundary end line to the output.
+func (w *Writer) Close() error {
+ if w.lastpart != nil {
+ if err := w.lastpart.close(); err != nil {
+ return err
+ }
+ w.lastpart = nil
+ }
+ _, err := fmt.Fprintf(w.w, "\r\n--%s--\r\n", w.boundary)
+ return err
+}
+
+type part struct {
+ mw *Writer
+ closed bool
+ we error // last error that occurred writing
+}
+
+func (p *part) close() error {
+ p.closed = true
+ return p.we
+}
+
+func (p *part) Write(d []byte) (n int, err error) {
+ if p.closed {
+ return 0, errors.New("multipart: can't write to finished part")
+ }
+ n, err = p.mw.w.Write(d)
+ if err != nil {
+ p.we = err
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/multipart/writer_test.go b/platform/dbops/binaries/go/go/src/mime/multipart/writer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e0f1314c98350d3d106df99594bda6675ca01f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/multipart/writer_test.go
@@ -0,0 +1,174 @@
+// 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 multipart
+
+import (
+ "bytes"
+ "io"
+ "mime"
+ "net/textproto"
+ "strings"
+ "testing"
+)
+
+func TestWriter(t *testing.T) {
+ fileContents := []byte("my file contents")
+
+ var b bytes.Buffer
+ w := NewWriter(&b)
+ {
+ part, err := w.CreateFormFile("myfile", "my-file.txt")
+ if err != nil {
+ t.Fatalf("CreateFormFile: %v", err)
+ }
+ part.Write(fileContents)
+ err = w.WriteField("key", "val")
+ if err != nil {
+ t.Fatalf("WriteField: %v", err)
+ }
+ part.Write([]byte("val"))
+ err = w.Close()
+ if err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+ s := b.String()
+ if len(s) == 0 {
+ t.Fatal("String: unexpected empty result")
+ }
+ if s[0] == '\r' || s[0] == '\n' {
+ t.Fatal("String: unexpected newline")
+ }
+ }
+
+ r := NewReader(&b, w.Boundary())
+
+ part, err := r.NextPart()
+ if err != nil {
+ t.Fatalf("part 1: %v", err)
+ }
+ if g, e := part.FormName(), "myfile"; g != e {
+ t.Errorf("part 1: want form name %q, got %q", e, g)
+ }
+ slurp, err := io.ReadAll(part)
+ if err != nil {
+ t.Fatalf("part 1: ReadAll: %v", err)
+ }
+ if e, g := string(fileContents), string(slurp); e != g {
+ t.Errorf("part 1: want contents %q, got %q", e, g)
+ }
+
+ part, err = r.NextPart()
+ if err != nil {
+ t.Fatalf("part 2: %v", err)
+ }
+ if g, e := part.FormName(), "key"; g != e {
+ t.Errorf("part 2: want form name %q, got %q", e, g)
+ }
+ slurp, err = io.ReadAll(part)
+ if err != nil {
+ t.Fatalf("part 2: ReadAll: %v", err)
+ }
+ if e, g := "val", string(slurp); e != g {
+ t.Errorf("part 2: want contents %q, got %q", e, g)
+ }
+
+ part, err = r.NextPart()
+ if part != nil || err == nil {
+ t.Fatalf("expected end of parts; got %v, %v", part, err)
+ }
+}
+
+func TestWriterSetBoundary(t *testing.T) {
+ tests := []struct {
+ b string
+ ok bool
+ }{
+ {"abc", true},
+ {"", false},
+ {"ungültig", false},
+ {"!", false},
+ {strings.Repeat("x", 70), true},
+ {strings.Repeat("x", 71), false},
+ {"bad!ascii!", false},
+ {"my-separator", true},
+ {"with space", true},
+ {"badspace ", false},
+ {"(boundary)", true},
+ }
+ for i, tt := range tests {
+ var b strings.Builder
+ w := NewWriter(&b)
+ err := w.SetBoundary(tt.b)
+ got := err == nil
+ if got != tt.ok {
+ t.Errorf("%d. boundary %q = %v (%v); want %v", i, tt.b, got, err, tt.ok)
+ } else if tt.ok {
+ got := w.Boundary()
+ if got != tt.b {
+ t.Errorf("boundary = %q; want %q", got, tt.b)
+ }
+
+ ct := w.FormDataContentType()
+ mt, params, err := mime.ParseMediaType(ct)
+ if err != nil {
+ t.Errorf("could not parse Content-Type %q: %v", ct, err)
+ } else if mt != "multipart/form-data" {
+ t.Errorf("unexpected media type %q; want %q", mt, "multipart/form-data")
+ } else if b := params["boundary"]; b != tt.b {
+ t.Errorf("unexpected boundary parameter %q; want %q", b, tt.b)
+ }
+
+ w.Close()
+ wantSub := "\r\n--" + tt.b + "--\r\n"
+ if got := b.String(); !strings.Contains(got, wantSub) {
+ t.Errorf("expected %q in output. got: %q", wantSub, got)
+ }
+ }
+ }
+}
+
+func TestWriterBoundaryGoroutines(t *testing.T) {
+ // Verify there's no data race accessing any lazy boundary if it's used by
+ // different goroutines. This was previously broken by
+ // https://codereview.appspot.com/95760043/ and reverted in
+ // https://codereview.appspot.com/117600043/
+ w := NewWriter(io.Discard)
+ done := make(chan int)
+ go func() {
+ w.CreateFormField("foo")
+ done <- 1
+ }()
+ w.Boundary()
+ <-done
+}
+
+func TestSortedHeader(t *testing.T) {
+ var buf strings.Builder
+ w := NewWriter(&buf)
+ if err := w.SetBoundary("MIMEBOUNDARY"); err != nil {
+ t.Fatalf("Error setting mime boundary: %v", err)
+ }
+
+ header := textproto.MIMEHeader{
+ "A": {"2"},
+ "B": {"5", "7", "6"},
+ "C": {"4"},
+ "M": {"3"},
+ "Z": {"1"},
+ }
+
+ part, err := w.CreatePart(header)
+ if err != nil {
+ t.Fatalf("Unable to create part: %v", err)
+ }
+ part.Write([]byte("foo"))
+
+ w.Close()
+
+ want := "--MIMEBOUNDARY\r\nA: 2\r\nB: 5\r\nB: 7\r\nB: 6\r\nC: 4\r\nM: 3\r\nZ: 1\r\n\r\nfoo\r\n--MIMEBOUNDARY--\r\n"
+ if want != buf.String() {
+ t.Fatalf("\n got: %q\nwant: %q\n", buf.String(), want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/quotedprintable/example_test.go b/platform/dbops/binaries/go/go/src/mime/quotedprintable/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e5a479a3a7f07bb567eadddd5c92f30009f235eb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/quotedprintable/example_test.go
@@ -0,0 +1,37 @@
+// 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 quotedprintable_test
+
+import (
+ "fmt"
+ "io"
+ "mime/quotedprintable"
+ "os"
+ "strings"
+)
+
+func ExampleNewReader() {
+ for _, s := range []string{
+ `=48=65=6C=6C=6F=2C=20=47=6F=70=68=65=72=73=21`,
+ `invalid escape: hello`,
+ "Hello, Gophers! This symbol will be unescaped: =3D and this will be written in =\r\none line.",
+ } {
+ b, err := io.ReadAll(quotedprintable.NewReader(strings.NewReader(s)))
+ fmt.Printf("%s %v\n", b, err)
+ }
+ // Output:
+ // Hello, Gophers!
+ // invalid escape: hello
+ // Hello, Gophers! This symbol will be unescaped: = and this will be written in one line.
+}
+
+func ExampleNewWriter() {
+ w := quotedprintable.NewWriter(os.Stdout)
+ w.Write([]byte("These symbols will be escaped: = \t"))
+ w.Close()
+
+ // Output:
+ // These symbols will be escaped: =3D =09
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader.go b/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader.go
new file mode 100644
index 0000000000000000000000000000000000000000..4239625402a2f79fcbaafcadae7d7ba2ade1db0c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader.go
@@ -0,0 +1,139 @@
+// 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 quotedprintable implements quoted-printable encoding as specified by
+// RFC 2045.
+package quotedprintable
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+)
+
+// Reader is a quoted-printable decoder.
+type Reader struct {
+ br *bufio.Reader
+ rerr error // last read error
+ line []byte // to be consumed before more of br
+}
+
+// NewReader returns a quoted-printable reader, decoding from r.
+func NewReader(r io.Reader) *Reader {
+ return &Reader{
+ br: bufio.NewReader(r),
+ }
+}
+
+func fromHex(b byte) (byte, error) {
+ switch {
+ case b >= '0' && b <= '9':
+ return b - '0', nil
+ case b >= 'A' && b <= 'F':
+ return b - 'A' + 10, nil
+ // Accept badly encoded bytes.
+ case b >= 'a' && b <= 'f':
+ return b - 'a' + 10, nil
+ }
+ return 0, fmt.Errorf("quotedprintable: invalid hex byte 0x%02x", b)
+}
+
+func readHexByte(v []byte) (b byte, err error) {
+ if len(v) < 2 {
+ return 0, io.ErrUnexpectedEOF
+ }
+ var hb, lb byte
+ if hb, err = fromHex(v[0]); err != nil {
+ return 0, err
+ }
+ if lb, err = fromHex(v[1]); err != nil {
+ return 0, err
+ }
+ return hb<<4 | lb, nil
+}
+
+func isQPDiscardWhitespace(r rune) bool {
+ switch r {
+ case '\n', '\r', ' ', '\t':
+ return true
+ }
+ return false
+}
+
+var (
+ crlf = []byte("\r\n")
+ lf = []byte("\n")
+ softSuffix = []byte("=")
+)
+
+// Read reads and decodes quoted-printable data from the underlying reader.
+func (r *Reader) Read(p []byte) (n int, err error) {
+ // Deviations from RFC 2045:
+ // 1. in addition to "=\r\n", "=\n" is also treated as soft line break.
+ // 2. it will pass through a '\r' or '\n' not preceded by '=', consistent
+ // with other broken QP encoders & decoders.
+ // 3. it accepts soft line-break (=) at end of message (issue 15486); i.e.
+ // the final byte read from the underlying reader is allowed to be '=',
+ // and it will be silently ignored.
+ // 4. it takes = as literal = if not followed by two hex digits
+ // but not at end of line (issue 13219).
+ for len(p) > 0 {
+ if len(r.line) == 0 {
+ if r.rerr != nil {
+ return n, r.rerr
+ }
+ r.line, r.rerr = r.br.ReadSlice('\n')
+
+ // Does the line end in CRLF instead of just LF?
+ hasLF := bytes.HasSuffix(r.line, lf)
+ hasCR := bytes.HasSuffix(r.line, crlf)
+ wholeLine := r.line
+ r.line = bytes.TrimRightFunc(wholeLine, isQPDiscardWhitespace)
+ if bytes.HasSuffix(r.line, softSuffix) {
+ rightStripped := wholeLine[len(r.line):]
+ r.line = r.line[:len(r.line)-1]
+ if !bytes.HasPrefix(rightStripped, lf) && !bytes.HasPrefix(rightStripped, crlf) &&
+ !(len(rightStripped) == 0 && len(r.line) > 0 && r.rerr == io.EOF) {
+ r.rerr = fmt.Errorf("quotedprintable: invalid bytes after =: %q", rightStripped)
+ }
+ } else if hasLF {
+ if hasCR {
+ r.line = append(r.line, '\r', '\n')
+ } else {
+ r.line = append(r.line, '\n')
+ }
+ }
+ continue
+ }
+ b := r.line[0]
+
+ switch {
+ case b == '=':
+ b, err = readHexByte(r.line[1:])
+ if err != nil {
+ if len(r.line) >= 2 && r.line[1] != '\r' && r.line[1] != '\n' {
+ // Take the = as a literal =.
+ b = '='
+ break
+ }
+ return n, err
+ }
+ r.line = r.line[2:] // 2 of the 3; other 1 is done below
+ case b == '\t' || b == '\r' || b == '\n':
+ break
+ case b >= 0x80:
+ // As an extension to RFC 2045, we accept
+ // values >= 0x80 without complaint. Issue 22597.
+ break
+ case b < ' ' || b > '~':
+ return n, fmt.Errorf("quotedprintable: invalid unescaped byte 0x%02x in body", b)
+ }
+ p[0] = b
+ p = p[1:]
+ r.line = r.line[1:]
+ n++
+ }
+ return n, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader_test.go b/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0af1e5f0f7545525d2ea4229adb2d7db5d3c37d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/quotedprintable/reader_test.go
@@ -0,0 +1,216 @@
+// 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 quotedprintable
+
+import (
+ "bufio"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "os/exec"
+ "regexp"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestReader(t *testing.T) {
+ tests := []struct {
+ in, want string
+ err any
+ }{
+ {in: "", want: ""},
+ {in: "foo bar", want: "foo bar"},
+ {in: "foo bar=3D", want: "foo bar="},
+ {in: "foo bar=3d", want: "foo bar="}, // lax.
+ {in: "foo bar=\n", want: "foo bar"},
+ {in: "foo bar\n", want: "foo bar\n"}, // somewhat lax.
+ {in: "foo bar=0", want: "foo bar=0"}, // lax
+ {in: "foo bar=0D=0A", want: "foo bar\r\n"},
+ {in: " A B \r\n C ", want: " A B\r\n C"},
+ {in: " A B =\r\n C ", want: " A B C"},
+ {in: " A B =\n C ", want: " A B C"}, // lax. treating LF as CRLF
+ {in: "foo=\nbar", want: "foobar"},
+ {in: "foo\x00bar", want: "foo", err: "quotedprintable: invalid unescaped byte 0x00 in body"},
+ {in: "foo bar\xff", want: "foo bar\xff"},
+
+ // Equal sign.
+ {in: "=3D30\n", want: "=30\n"},
+ {in: "=00=FF0=\n", want: "\x00\xff0"},
+
+ // Trailing whitespace
+ {in: "foo \n", want: "foo\n"},
+ {in: "foo \n\nfoo =\n\nfoo=20\n\n", want: "foo\n\nfoo \nfoo \n\n"},
+
+ // Tests that we allow bare \n and \r through, despite it being strictly
+ // not permitted per RFC 2045, Section 6.7 Page 22 bullet (4).
+ {in: "foo\nbar", want: "foo\nbar"},
+ {in: "foo\rbar", want: "foo\rbar"},
+ {in: "foo\r\nbar", want: "foo\r\nbar"},
+
+ // Different types of soft line-breaks.
+ {in: "foo=\r\nbar", want: "foobar"},
+ {in: "foo=\nbar", want: "foobar"},
+ {in: "foo=\rbar", want: "foo", err: "quotedprintable: invalid hex byte 0x0d"},
+ {in: "foo=\r\r\r \nbar", want: "foo", err: `quotedprintable: invalid bytes after =: "\r\r\r \n"`},
+ // Issue 15486, accept trailing soft line-break at end of input.
+ {in: "foo=", want: "foo"},
+ {in: "=", want: "", err: `quotedprintable: invalid bytes after =: ""`},
+
+ // Example from RFC 2045:
+ {in: "Now's the time =\n" + "for all folk to come=\n" + " to the aid of their country.",
+ want: "Now's the time for all folk to come to the aid of their country."},
+ {in: "accept UTF-8 right quotation mark: ’",
+ want: "accept UTF-8 right quotation mark: ’"},
+ }
+ for _, tt := range tests {
+ var buf strings.Builder
+ _, err := io.Copy(&buf, NewReader(strings.NewReader(tt.in)))
+ if got := buf.String(); got != tt.want {
+ t.Errorf("for %q, got %q; want %q", tt.in, got, tt.want)
+ }
+ switch verr := tt.err.(type) {
+ case nil:
+ if err != nil {
+ t.Errorf("for %q, got unexpected error: %v", tt.in, err)
+ }
+ case string:
+ if got := fmt.Sprint(err); got != verr {
+ t.Errorf("for %q, got error %q; want %q", tt.in, got, verr)
+ }
+ case error:
+ if err != verr {
+ t.Errorf("for %q, got error %q; want %q", tt.in, err, verr)
+ }
+ }
+ }
+
+}
+
+func everySequence(base, alpha string, length int, fn func(string)) {
+ if len(base) == length {
+ fn(base)
+ return
+ }
+ for i := 0; i < len(alpha); i++ {
+ everySequence(base+alpha[i:i+1], alpha, length, fn)
+ }
+}
+
+var useQprint = flag.Bool("qprint", false, "Compare against the 'qprint' program.")
+
+var badSoftRx = regexp.MustCompile(`=([^\r\n]+?\n)|([^\r\n]+$)|(\r$)|(\r[^\n]+\n)|( \r\n)`)
+
+func TestExhaustive(t *testing.T) {
+ if *useQprint {
+ _, err := exec.LookPath("qprint")
+ if err != nil {
+ t.Fatalf("Error looking for qprint: %v", err)
+ }
+ }
+
+ var buf strings.Builder
+ res := make(map[string]int)
+ n := 6
+ if testing.Short() {
+ n = 4
+ }
+ everySequence("", "0A \r\n=", n, func(s string) {
+ if strings.HasSuffix(s, "=") || strings.Contains(s, "==") {
+ return
+ }
+ buf.Reset()
+ _, err := io.Copy(&buf, NewReader(strings.NewReader(s)))
+ if err != nil {
+ errStr := err.Error()
+ if strings.Contains(errStr, "invalid bytes after =:") {
+ errStr = "invalid bytes after ="
+ }
+ res[errStr]++
+ if strings.Contains(errStr, "invalid hex byte ") {
+ if strings.HasSuffix(errStr, "0x20") && (strings.Contains(s, "=0 ") || strings.Contains(s, "=A ") || strings.Contains(s, "= ")) {
+ return
+ }
+ if strings.HasSuffix(errStr, "0x3d") && (strings.Contains(s, "=0=") || strings.Contains(s, "=A=")) {
+ return
+ }
+ if strings.HasSuffix(errStr, "0x0a") || strings.HasSuffix(errStr, "0x0d") {
+ // bunch of cases; since whitespace at the end of a line before \n is removed.
+ return
+ }
+ }
+ if strings.Contains(errStr, "unexpected EOF") {
+ return
+ }
+ if errStr == "invalid bytes after =" && badSoftRx.MatchString(s) {
+ return
+ }
+ t.Errorf("decode(%q) = %v", s, err)
+ return
+ }
+ if *useQprint {
+ cmd := exec.Command("qprint", "-d")
+ cmd.Stdin = strings.NewReader(s)
+ stderr, err := cmd.StderrPipe()
+ if err != nil {
+ panic(err)
+ }
+ qpres := make(chan any, 2)
+ go func() {
+ br := bufio.NewReader(stderr)
+ s, _ := br.ReadString('\n')
+ if s != "" {
+ qpres <- errors.New(s)
+ if cmd.Process != nil {
+ // It can get stuck on invalid input, like:
+ // echo -n "0000= " | qprint -d
+ cmd.Process.Kill()
+ }
+ }
+ }()
+ go func() {
+ want, err := cmd.Output()
+ if err == nil {
+ qpres <- want
+ }
+ }()
+ select {
+ case got := <-qpres:
+ if want, ok := got.([]byte); ok {
+ if string(want) != buf.String() {
+ t.Errorf("go decode(%q) = %q; qprint = %q", s, want, buf.String())
+ }
+ } else {
+ t.Logf("qprint -d(%q) = %v", s, got)
+ }
+ case <-time.After(5 * time.Second):
+ t.Logf("qprint timeout on %q", s)
+ }
+ }
+ res["OK"]++
+ })
+ var outcomes []string
+ for k, v := range res {
+ outcomes = append(outcomes, fmt.Sprintf("%v: %d", k, v))
+ }
+ sort.Strings(outcomes)
+ got := strings.Join(outcomes, "\n")
+ want := `OK: 28934
+invalid bytes after =: 3949
+quotedprintable: invalid hex byte 0x0d: 2048
+unexpected EOF: 194`
+ if testing.Short() {
+ want = `OK: 896
+invalid bytes after =: 100
+quotedprintable: invalid hex byte 0x0d: 26
+unexpected EOF: 3`
+ }
+
+ if got != want {
+ t.Errorf("Got:\n%s\nWant:\n%s", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer.go b/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer.go
new file mode 100644
index 0000000000000000000000000000000000000000..16ea0bf7d622806f7829259251778c5a48834677
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer.go
@@ -0,0 +1,172 @@
+// 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.
+
+package quotedprintable
+
+import "io"
+
+const lineMaxLen = 76
+
+// A Writer is a quoted-printable writer that implements io.WriteCloser.
+type Writer struct {
+ // Binary mode treats the writer's input as pure binary and processes end of
+ // line bytes as binary data.
+ Binary bool
+
+ w io.Writer
+ i int
+ line [78]byte
+ cr bool
+}
+
+// NewWriter returns a new Writer that writes to w.
+func NewWriter(w io.Writer) *Writer {
+ return &Writer{w: w}
+}
+
+// Write encodes p using quoted-printable encoding and writes it to the
+// underlying io.Writer. It limits line length to 76 characters. The encoded
+// bytes are not necessarily flushed until the Writer is closed.
+func (w *Writer) Write(p []byte) (n int, err error) {
+ for i, b := range p {
+ switch {
+ // Simple writes are done in batch.
+ case b >= '!' && b <= '~' && b != '=':
+ continue
+ case isWhitespace(b) || !w.Binary && (b == '\n' || b == '\r'):
+ continue
+ }
+
+ if i > n {
+ if err := w.write(p[n:i]); err != nil {
+ return n, err
+ }
+ n = i
+ }
+
+ if err := w.encode(b); err != nil {
+ return n, err
+ }
+ n++
+ }
+
+ if n == len(p) {
+ return n, nil
+ }
+
+ if err := w.write(p[n:]); err != nil {
+ return n, err
+ }
+
+ return len(p), nil
+}
+
+// Close closes the Writer, flushing any unwritten data to the underlying
+// io.Writer, but does not close the underlying io.Writer.
+func (w *Writer) Close() error {
+ if err := w.checkLastByte(); err != nil {
+ return err
+ }
+
+ return w.flush()
+}
+
+// write limits text encoded in quoted-printable to 76 characters per line.
+func (w *Writer) write(p []byte) error {
+ for _, b := range p {
+ if b == '\n' || b == '\r' {
+ // If the previous byte was \r, the CRLF has already been inserted.
+ if w.cr && b == '\n' {
+ w.cr = false
+ continue
+ }
+
+ if b == '\r' {
+ w.cr = true
+ }
+
+ if err := w.checkLastByte(); err != nil {
+ return err
+ }
+ if err := w.insertCRLF(); err != nil {
+ return err
+ }
+ continue
+ }
+
+ if w.i == lineMaxLen-1 {
+ if err := w.insertSoftLineBreak(); err != nil {
+ return err
+ }
+ }
+
+ w.line[w.i] = b
+ w.i++
+ w.cr = false
+ }
+
+ return nil
+}
+
+func (w *Writer) encode(b byte) error {
+ if lineMaxLen-1-w.i < 3 {
+ if err := w.insertSoftLineBreak(); err != nil {
+ return err
+ }
+ }
+
+ w.line[w.i] = '='
+ w.line[w.i+1] = upperhex[b>>4]
+ w.line[w.i+2] = upperhex[b&0x0f]
+ w.i += 3
+
+ return nil
+}
+
+const upperhex = "0123456789ABCDEF"
+
+// checkLastByte encodes the last buffered byte if it is a space or a tab.
+func (w *Writer) checkLastByte() error {
+ if w.i == 0 {
+ return nil
+ }
+
+ b := w.line[w.i-1]
+ if isWhitespace(b) {
+ w.i--
+ if err := w.encode(b); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (w *Writer) insertSoftLineBreak() error {
+ w.line[w.i] = '='
+ w.i++
+
+ return w.insertCRLF()
+}
+
+func (w *Writer) insertCRLF() error {
+ w.line[w.i] = '\r'
+ w.line[w.i+1] = '\n'
+ w.i += 2
+
+ return w.flush()
+}
+
+func (w *Writer) flush() error {
+ if _, err := w.w.Write(w.line[:w.i]); err != nil {
+ return err
+ }
+
+ w.i = 0
+ return nil
+}
+
+func isWhitespace(b byte) bool {
+ return b == ' ' || b == '\t'
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer_test.go b/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..07411fe269eba2b83bda4800942cfbf93cb99a51
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/quotedprintable/writer_test.go
@@ -0,0 +1,158 @@
+// 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.
+
+package quotedprintable
+
+import (
+ "bytes"
+ "io"
+ "strings"
+ "testing"
+)
+
+func TestWriter(t *testing.T) {
+ testWriter(t, false)
+}
+
+func TestWriterBinary(t *testing.T) {
+ testWriter(t, true)
+}
+
+func testWriter(t *testing.T, binary bool) {
+ tests := []struct {
+ in, want, wantB string
+ }{
+ {in: "", want: ""},
+ {in: "foo bar", want: "foo bar"},
+ {in: "foo bar=", want: "foo bar=3D"},
+ {in: "foo bar\r", want: "foo bar\r\n", wantB: "foo bar=0D"},
+ {in: "foo bar\r\r", want: "foo bar\r\n\r\n", wantB: "foo bar=0D=0D"},
+ {in: "foo bar\n", want: "foo bar\r\n", wantB: "foo bar=0A"},
+ {in: "foo bar\r\n", want: "foo bar\r\n", wantB: "foo bar=0D=0A"},
+ {in: "foo bar\r\r\n", want: "foo bar\r\n\r\n", wantB: "foo bar=0D=0D=0A"},
+ {in: "foo bar ", want: "foo bar=20"},
+ {in: "foo bar\t", want: "foo bar=09"},
+ {in: "foo bar ", want: "foo bar =20"},
+ {in: "foo bar \n", want: "foo bar=20\r\n", wantB: "foo bar =0A"},
+ {in: "foo bar \r", want: "foo bar=20\r\n", wantB: "foo bar =0D"},
+ {in: "foo bar \r\n", want: "foo bar=20\r\n", wantB: "foo bar =0D=0A"},
+ {in: "foo bar \n", want: "foo bar =20\r\n", wantB: "foo bar =0A"},
+ {in: "foo bar \n ", want: "foo bar =20\r\n=20", wantB: "foo bar =0A=20"},
+ {in: "¡Hola Señor!", want: "=C2=A1Hola Se=C3=B1or!"},
+ {
+ in: "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~",
+ want: "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~",
+ },
+ {
+ in: strings.Repeat("a", 75),
+ want: strings.Repeat("a", 75),
+ },
+ {
+ in: strings.Repeat("a", 76),
+ want: strings.Repeat("a", 75) + "=\r\na",
+ },
+ {
+ in: strings.Repeat("a", 72) + "=",
+ want: strings.Repeat("a", 72) + "=3D",
+ },
+ {
+ in: strings.Repeat("a", 73) + "=",
+ want: strings.Repeat("a", 73) + "=\r\n=3D",
+ },
+ {
+ in: strings.Repeat("a", 74) + "=",
+ want: strings.Repeat("a", 74) + "=\r\n=3D",
+ },
+ {
+ in: strings.Repeat("a", 75) + "=",
+ want: strings.Repeat("a", 75) + "=\r\n=3D",
+ },
+ {
+ in: strings.Repeat(" ", 73),
+ want: strings.Repeat(" ", 72) + "=20",
+ },
+ {
+ in: strings.Repeat(" ", 74),
+ want: strings.Repeat(" ", 73) + "=\r\n=20",
+ },
+ {
+ in: strings.Repeat(" ", 75),
+ want: strings.Repeat(" ", 74) + "=\r\n=20",
+ },
+ {
+ in: strings.Repeat(" ", 76),
+ want: strings.Repeat(" ", 75) + "=\r\n=20",
+ },
+ {
+ in: strings.Repeat(" ", 77),
+ want: strings.Repeat(" ", 75) + "=\r\n =20",
+ },
+ }
+
+ for _, tt := range tests {
+ buf := new(strings.Builder)
+ w := NewWriter(buf)
+
+ want := tt.want
+ if binary {
+ w.Binary = true
+ if tt.wantB != "" {
+ want = tt.wantB
+ }
+ }
+
+ if _, err := w.Write([]byte(tt.in)); err != nil {
+ t.Errorf("Write(%q): %v", tt.in, err)
+ continue
+ }
+ if err := w.Close(); err != nil {
+ t.Errorf("Close(): %v", err)
+ continue
+ }
+ got := buf.String()
+ if got != want {
+ t.Errorf("Write(%q), got:\n%q\nwant:\n%q", tt.in, got, want)
+ }
+ }
+}
+
+func TestRoundTrip(t *testing.T) {
+ buf := new(bytes.Buffer)
+ w := NewWriter(buf)
+ if _, err := w.Write(testMsg); err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+ if err := w.Close(); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+
+ r := NewReader(buf)
+ gotBytes, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatalf("Error while reading from Reader: %v", err)
+ }
+ got := string(gotBytes)
+ if got != string(testMsg) {
+ t.Errorf("Encoding and decoding changed the message, got:\n%s", got)
+ }
+}
+
+// From https://fr.wikipedia.org/wiki/Quoted-Printable
+var testMsg = []byte("Quoted-Printable (QP) est un format d'encodage de données codées sur 8 bits, qui utilise exclusivement les caractères alphanumériques imprimables du code ASCII (7 bits).\r\n" +
+ "\r\n" +
+ "En effet, les différents codages comprennent de nombreux caractères qui ne sont pas représentables en ASCII (par exemple les caractères accentués), ainsi que des caractères dits « non-imprimables ».\r\n" +
+ "\r\n" +
+ "L'encodage Quoted-Printable permet de remédier à ce problème, en procédant de la manière suivante :\r\n" +
+ "\r\n" +
+ "Un octet correspondant à un caractère imprimable de l'ASCII sauf le signe égal (donc un caractère de code ASCII entre 33 et 60 ou entre 62 et 126) ou aux caractères de saut de ligne (codes ASCII 13 et 10) ou une suite de tabulations et espaces non situées en fin de ligne (de codes ASCII respectifs 9 et 32) est représenté tel quel.\r\n" +
+ "Un octet qui ne correspond pas à la définition ci-dessus (caractère non imprimable de l'ASCII, tabulation ou espaces non suivies d'un caractère imprimable avant la fin de la ligne ou signe égal) est représenté par un signe égal, suivi de son numéro, exprimé en hexadécimal.\r\n" +
+ "Enfin, un signe égal suivi par un saut de ligne (donc la suite des trois caractères de codes ASCII 61, 13 et 10) peut être inséré n'importe où, afin de limiter la taille des lignes produites si nécessaire. Une limite de 76 caractères par ligne est généralement respectée.\r\n")
+
+func BenchmarkWriter(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ w := NewWriter(io.Discard)
+ w.Write(testMsg)
+ w.Close()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/testdata/test.types b/platform/dbops/binaries/go/go/src/mime/testdata/test.types
new file mode 100644
index 0000000000000000000000000000000000000000..9b040edd7ba921aa6945cc68cae67f4b5c7c52e9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/testdata/test.types
@@ -0,0 +1,8 @@
+# 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.
+
+
+ # mime package test
+application/test t1 # Simple test
+text/test t2 # Text test
diff --git a/platform/dbops/binaries/go/go/src/mime/testdata/test.types.globs2 b/platform/dbops/binaries/go/go/src/mime/testdata/test.types.globs2
new file mode 100644
index 0000000000000000000000000000000000000000..4606d98f13a53a242160dadea442793c7baa196c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/testdata/test.types.globs2
@@ -0,0 +1,14 @@
+# 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.
+
+
+# mime package test for globs2
+50:document/test:*.t3
+50:example/test:*.t4
+50:text/plain:*,v
+50:application/x-trash:*~
+30:example/do-not-use:*.t4
+10:example/glob-question-mark:*.foo?ar
+10:example/glob-asterisk:*.foo*r
+10:example/glob-range:*.foo[1-3]
diff --git a/platform/dbops/binaries/go/go/src/mime/testdata/test.types.plan9 b/platform/dbops/binaries/go/go/src/mime/testdata/test.types.plan9
new file mode 100644
index 0000000000000000000000000000000000000000..19dbf41cce1bb2f84f7dc709686b1ca9005a2709
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/testdata/test.types.plan9
@@ -0,0 +1,8 @@
+# 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.
+
+
+ # mime package test
+.t1 application test - y # Simple test
+.t2 text test - y # Text test
diff --git a/platform/dbops/binaries/go/go/src/net/http/alpn_test.go b/platform/dbops/binaries/go/go/src/net/http/alpn_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a51038c355a23abb70537d646482ce56b5d47f9b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/alpn_test.go
@@ -0,0 +1,132 @@
+// 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 http_test
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "io"
+ . "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestNextProtoUpgrade(t *testing.T) {
+ setParallel(t)
+ defer afterTest(t)
+ ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+ fmt.Fprintf(w, "path=%s,proto=", r.URL.Path)
+ if r.TLS != nil {
+ w.Write([]byte(r.TLS.NegotiatedProtocol))
+ }
+ if r.RemoteAddr == "" {
+ t.Error("request with no RemoteAddr")
+ }
+ if r.Body == nil {
+ t.Errorf("request with nil Body")
+ }
+ }))
+ ts.TLS = &tls.Config{
+ NextProtos: []string{"unhandled-proto", "tls-0.9"},
+ }
+ ts.Config.TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){
+ "tls-0.9": handleTLSProtocol09,
+ }
+ ts.StartTLS()
+ defer ts.Close()
+
+ // Normal request, without NPN.
+ {
+ c := ts.Client()
+ res, err := c.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := "path=/,proto="; string(body) != want {
+ t.Errorf("plain request = %q; want %q", body, want)
+ }
+ }
+
+ // Request to an advertised but unhandled NPN protocol.
+ // Server will hang up.
+ {
+ certPool := x509.NewCertPool()
+ certPool.AddCert(ts.Certificate())
+ tr := &Transport{
+ TLSClientConfig: &tls.Config{
+ RootCAs: certPool,
+ NextProtos: []string{"unhandled-proto"},
+ },
+ }
+ defer tr.CloseIdleConnections()
+ c := &Client{
+ Transport: tr,
+ }
+ res, err := c.Get(ts.URL)
+ if err == nil {
+ defer res.Body.Close()
+ var buf bytes.Buffer
+ res.Write(&buf)
+ t.Errorf("expected error on unhandled-proto request; got: %s", buf.Bytes())
+ }
+ }
+
+ // Request using the "tls-0.9" protocol, which we register here.
+ // It is HTTP/0.9 over TLS.
+ {
+ c := ts.Client()
+ tlsConfig := c.Transport.(*Transport).TLSClientConfig
+ tlsConfig.NextProtos = []string{"tls-0.9"}
+ conn, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn.Write([]byte("GET /foo\n"))
+ body, err := io.ReadAll(conn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := "path=/foo,proto=tls-0.9"; string(body) != want {
+ t.Errorf("plain request = %q; want %q", body, want)
+ }
+ }
+}
+
+// handleTLSProtocol09 implements the HTTP/0.9 protocol over TLS, for the
+// TestNextProtoUpgrade test.
+func handleTLSProtocol09(srv *Server, conn *tls.Conn, h Handler) {
+ br := bufio.NewReader(conn)
+ line, err := br.ReadString('\n')
+ if err != nil {
+ return
+ }
+ line = strings.TrimSpace(line)
+ path := strings.TrimPrefix(line, "GET ")
+ if path == line {
+ return
+ }
+ req, _ := NewRequest("GET", path, nil)
+ req.Proto = "HTTP/0.9"
+ req.ProtoMajor = 0
+ req.ProtoMinor = 9
+ rw := &http09Writer{conn, make(Header)}
+ h.ServeHTTP(rw, req)
+}
+
+type http09Writer struct {
+ io.Writer
+ h Header
+}
+
+func (w http09Writer) Header() Header { return w.h }
+func (w http09Writer) WriteHeader(int) {} // no headers
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/cgi_main.go b/platform/dbops/binaries/go/go/src/net/http/cgi/cgi_main.go
new file mode 100644
index 0000000000000000000000000000000000000000..8997d66a117dd54a67c7c32a182a6853ba0c5e8e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/cgi_main.go
@@ -0,0 +1,145 @@
+// 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 cgi
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path"
+ "sort"
+ "strings"
+ "time"
+)
+
+func cgiMain() {
+ switch path.Join(os.Getenv("SCRIPT_NAME"), os.Getenv("PATH_INFO")) {
+ case "/bar", "/test.cgi", "/myscript/bar", "/test.cgi/extrapath":
+ testCGI()
+ return
+ }
+ childCGIProcess()
+}
+
+// testCGI is a CGI program translated from a Perl program to complete host_test.
+// test cases in host_test should be provided by testCGI.
+func testCGI() {
+ req, err := Request()
+ if err != nil {
+ panic(err)
+ }
+
+ err = req.ParseForm()
+ if err != nil {
+ panic(err)
+ }
+
+ params := req.Form
+ if params.Get("loc") != "" {
+ fmt.Printf("Location: %s\r\n\r\n", params.Get("loc"))
+ return
+ }
+
+ fmt.Printf("Content-Type: text/html\r\n")
+ fmt.Printf("X-CGI-Pid: %d\r\n", os.Getpid())
+ fmt.Printf("X-Test-Header: X-Test-Value\r\n")
+ fmt.Printf("\r\n")
+
+ if params.Get("writestderr") != "" {
+ fmt.Fprintf(os.Stderr, "Hello, stderr!\n")
+ }
+
+ if params.Get("bigresponse") != "" {
+ // 17 MB, for OS X: golang.org/issue/4958
+ line := strings.Repeat("A", 1024)
+ for i := 0; i < 17*1024; i++ {
+ fmt.Printf("%s\r\n", line)
+ }
+ return
+ }
+
+ fmt.Printf("test=Hello CGI\r\n")
+
+ keys := make([]string, 0, len(params))
+ for k := range params {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ fmt.Printf("param-%s=%s\r\n", key, params.Get(key))
+ }
+
+ envs := envMap(os.Environ())
+ keys = make([]string, 0, len(envs))
+ for k := range envs {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ fmt.Printf("env-%s=%s\r\n", key, envs[key])
+ }
+
+ cwd, _ := os.Getwd()
+ fmt.Printf("cwd=%s\r\n", cwd)
+}
+
+type neverEnding byte
+
+func (b neverEnding) Read(p []byte) (n int, err error) {
+ for i := range p {
+ p[i] = byte(b)
+ }
+ return len(p), nil
+}
+
+// childCGIProcess is used by integration_test to complete unit tests.
+func childCGIProcess() {
+ if os.Getenv("REQUEST_METHOD") == "" {
+ // Not in a CGI environment; skipping test.
+ return
+ }
+ switch os.Getenv("REQUEST_URI") {
+ case "/immediate-disconnect":
+ os.Exit(0)
+ case "/no-content-type":
+ fmt.Printf("Content-Length: 6\n\nHello\n")
+ os.Exit(0)
+ case "/empty-headers":
+ fmt.Printf("\nHello")
+ os.Exit(0)
+ }
+ Serve(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+ if req.FormValue("nil-request-body") == "1" {
+ fmt.Fprintf(rw, "nil-request-body=%v\n", req.Body == nil)
+ return
+ }
+ rw.Header().Set("X-Test-Header", "X-Test-Value")
+ req.ParseForm()
+ if req.FormValue("no-body") == "1" {
+ return
+ }
+ if eb, ok := req.Form["exact-body"]; ok {
+ io.WriteString(rw, eb[0])
+ return
+ }
+ if req.FormValue("write-forever") == "1" {
+ io.Copy(rw, neverEnding('a'))
+ for {
+ time.Sleep(5 * time.Second) // hang forever, until killed
+ }
+ }
+ fmt.Fprintf(rw, "test=Hello CGI-in-CGI\n")
+ for k, vv := range req.Form {
+ for _, v := range vv {
+ fmt.Fprintf(rw, "param-%s=%s\n", k, v)
+ }
+ }
+ for _, kv := range os.Environ() {
+ fmt.Fprintf(rw, "env-%s\n", kv)
+ }
+ }))
+ os.Exit(0)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/child.go b/platform/dbops/binaries/go/go/src/net/http/cgi/child.go
new file mode 100644
index 0000000000000000000000000000000000000000..e29fe20d7d5e31d206818b297d8c51f37ff050a2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/child.go
@@ -0,0 +1,222 @@
+// 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 CGI from the perspective of a child
+// process.
+
+package cgi
+
+import (
+ "bufio"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// Request returns the HTTP request as represented in the current
+// environment. This assumes the current program is being run
+// by a web server in a CGI environment.
+// The returned Request's Body is populated, if applicable.
+func Request() (*http.Request, error) {
+ r, err := RequestFromMap(envMap(os.Environ()))
+ if err != nil {
+ return nil, err
+ }
+ if r.ContentLength > 0 {
+ r.Body = io.NopCloser(io.LimitReader(os.Stdin, r.ContentLength))
+ }
+ return r, nil
+}
+
+func envMap(env []string) map[string]string {
+ m := make(map[string]string)
+ for _, kv := range env {
+ if k, v, ok := strings.Cut(kv, "="); ok {
+ m[k] = v
+ }
+ }
+ return m
+}
+
+// RequestFromMap creates an [http.Request] from CGI variables.
+// The returned Request's Body field is not populated.
+func RequestFromMap(params map[string]string) (*http.Request, error) {
+ r := new(http.Request)
+ r.Method = params["REQUEST_METHOD"]
+ if r.Method == "" {
+ return nil, errors.New("cgi: no REQUEST_METHOD in environment")
+ }
+
+ r.Proto = params["SERVER_PROTOCOL"]
+ var ok bool
+ r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
+ if !ok {
+ return nil, errors.New("cgi: invalid SERVER_PROTOCOL version")
+ }
+
+ r.Close = true
+ r.Trailer = http.Header{}
+ r.Header = http.Header{}
+
+ r.Host = params["HTTP_HOST"]
+
+ if lenstr := params["CONTENT_LENGTH"]; lenstr != "" {
+ clen, err := strconv.ParseInt(lenstr, 10, 64)
+ if err != nil {
+ return nil, errors.New("cgi: bad CONTENT_LENGTH in environment: " + lenstr)
+ }
+ r.ContentLength = clen
+ }
+
+ if ct := params["CONTENT_TYPE"]; ct != "" {
+ r.Header.Set("Content-Type", ct)
+ }
+
+ // Copy "HTTP_FOO_BAR" variables to "Foo-Bar" Headers
+ for k, v := range params {
+ if k == "HTTP_HOST" {
+ continue
+ }
+ if after, found := strings.CutPrefix(k, "HTTP_"); found {
+ r.Header.Add(strings.ReplaceAll(after, "_", "-"), v)
+ }
+ }
+
+ uriStr := params["REQUEST_URI"]
+ if uriStr == "" {
+ // Fallback to SCRIPT_NAME, PATH_INFO and QUERY_STRING.
+ uriStr = params["SCRIPT_NAME"] + params["PATH_INFO"]
+ s := params["QUERY_STRING"]
+ if s != "" {
+ uriStr += "?" + s
+ }
+ }
+
+ // There's apparently a de-facto standard for this.
+ // https://web.archive.org/web/20170105004655/http://docstore.mik.ua/orelly/linux/cgi/ch03_02.htm#ch03-35636
+ if s := params["HTTPS"]; s == "on" || s == "ON" || s == "1" {
+ r.TLS = &tls.ConnectionState{HandshakeComplete: true}
+ }
+
+ if r.Host != "" {
+ // Hostname is provided, so we can reasonably construct a URL.
+ rawurl := r.Host + uriStr
+ if r.TLS == nil {
+ rawurl = "http://" + rawurl
+ } else {
+ rawurl = "https://" + rawurl
+ }
+ url, err := url.Parse(rawurl)
+ if err != nil {
+ return nil, errors.New("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl)
+ }
+ r.URL = url
+ }
+ // Fallback logic if we don't have a Host header or the URL
+ // failed to parse
+ if r.URL == nil {
+ url, err := url.Parse(uriStr)
+ if err != nil {
+ return nil, errors.New("cgi: failed to parse REQUEST_URI into a URL: " + uriStr)
+ }
+ r.URL = url
+ }
+
+ // Request.RemoteAddr has its port set by Go's standard http
+ // server, so we do here too.
+ remotePort, _ := strconv.Atoi(params["REMOTE_PORT"]) // zero if unset or invalid
+ r.RemoteAddr = net.JoinHostPort(params["REMOTE_ADDR"], strconv.Itoa(remotePort))
+
+ return r, nil
+}
+
+// Serve executes the provided [Handler] on the currently active CGI
+// request, if any. If there's no current CGI environment
+// an error is returned. The provided handler may be nil to use
+// [http.DefaultServeMux].
+func Serve(handler http.Handler) error {
+ req, err := Request()
+ if err != nil {
+ return err
+ }
+ if req.Body == nil {
+ req.Body = http.NoBody
+ }
+ if handler == nil {
+ handler = http.DefaultServeMux
+ }
+ rw := &response{
+ req: req,
+ header: make(http.Header),
+ bufw: bufio.NewWriter(os.Stdout),
+ }
+ handler.ServeHTTP(rw, req)
+ rw.Write(nil) // make sure a response is sent
+ if err = rw.bufw.Flush(); err != nil {
+ return err
+ }
+ return nil
+}
+
+type response struct {
+ req *http.Request
+ header http.Header
+ code int
+ wroteHeader bool
+ wroteCGIHeader bool
+ bufw *bufio.Writer
+}
+
+func (r *response) Flush() {
+ r.bufw.Flush()
+}
+
+func (r *response) Header() http.Header {
+ return r.header
+}
+
+func (r *response) Write(p []byte) (n int, err error) {
+ if !r.wroteHeader {
+ r.WriteHeader(http.StatusOK)
+ }
+ if !r.wroteCGIHeader {
+ r.writeCGIHeader(p)
+ }
+ return r.bufw.Write(p)
+}
+
+func (r *response) WriteHeader(code int) {
+ if r.wroteHeader {
+ // Note: explicitly using Stderr, as Stdout is our HTTP output.
+ fmt.Fprintf(os.Stderr, "CGI attempted to write header twice on request for %s", r.req.URL)
+ return
+ }
+ r.wroteHeader = true
+ r.code = code
+}
+
+// writeCGIHeader finalizes the header sent to the client and writes it to the output.
+// p is not written by writeHeader, but is the first chunk of the body
+// that will be written. It is sniffed for a Content-Type if none is
+// set explicitly.
+func (r *response) writeCGIHeader(p []byte) {
+ if r.wroteCGIHeader {
+ return
+ }
+ r.wroteCGIHeader = true
+ fmt.Fprintf(r.bufw, "Status: %d %s\r\n", r.code, http.StatusText(r.code))
+ if _, hasType := r.header["Content-Type"]; !hasType {
+ r.header.Set("Content-Type", http.DetectContentType(p))
+ }
+ r.header.Write(r.bufw)
+ r.bufw.WriteString("\r\n")
+ r.bufw.Flush()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/child_test.go b/platform/dbops/binaries/go/go/src/net/http/cgi/child_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..18cf789bd59decfd85ac7c9f9707fe2b1a209b96
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/child_test.go
@@ -0,0 +1,208 @@
+// 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.
+
+// Tests for CGI (the child process perspective)
+
+package cgi
+
+import (
+ "bufio"
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestRequest(t *testing.T) {
+ env := map[string]string{
+ "SERVER_PROTOCOL": "HTTP/1.1",
+ "REQUEST_METHOD": "GET",
+ "HTTP_HOST": "example.com",
+ "HTTP_REFERER": "elsewhere",
+ "HTTP_USER_AGENT": "goclient",
+ "HTTP_FOO_BAR": "baz",
+ "REQUEST_URI": "/path?a=b",
+ "CONTENT_LENGTH": "123",
+ "CONTENT_TYPE": "text/xml",
+ "REMOTE_ADDR": "5.6.7.8",
+ "REMOTE_PORT": "54321",
+ }
+ req, err := RequestFromMap(env)
+ if err != nil {
+ t.Fatalf("RequestFromMap: %v", err)
+ }
+ if g, e := req.UserAgent(), "goclient"; e != g {
+ t.Errorf("expected UserAgent %q; got %q", e, g)
+ }
+ if g, e := req.Method, "GET"; e != g {
+ t.Errorf("expected Method %q; got %q", e, g)
+ }
+ if g, e := req.Header.Get("Content-Type"), "text/xml"; e != g {
+ t.Errorf("expected Content-Type %q; got %q", e, g)
+ }
+ if g, e := req.ContentLength, int64(123); e != g {
+ t.Errorf("expected ContentLength %d; got %d", e, g)
+ }
+ if g, e := req.Referer(), "elsewhere"; e != g {
+ t.Errorf("expected Referer %q; got %q", e, g)
+ }
+ if req.Header == nil {
+ t.Fatalf("unexpected nil Header")
+ }
+ if g, e := req.Header.Get("Foo-Bar"), "baz"; e != g {
+ t.Errorf("expected Foo-Bar %q; got %q", e, g)
+ }
+ if g, e := req.URL.String(), "http://example.com/path?a=b"; e != g {
+ t.Errorf("expected URL %q; got %q", e, g)
+ }
+ if g, e := req.FormValue("a"), "b"; e != g {
+ t.Errorf("expected FormValue(a) %q; got %q", e, g)
+ }
+ if req.Trailer == nil {
+ t.Errorf("unexpected nil Trailer")
+ }
+ if req.TLS != nil {
+ t.Errorf("expected nil TLS")
+ }
+ if e, g := "5.6.7.8:54321", req.RemoteAddr; e != g {
+ t.Errorf("RemoteAddr: got %q; want %q", g, e)
+ }
+}
+
+func TestRequestWithTLS(t *testing.T) {
+ env := map[string]string{
+ "SERVER_PROTOCOL": "HTTP/1.1",
+ "REQUEST_METHOD": "GET",
+ "HTTP_HOST": "example.com",
+ "HTTP_REFERER": "elsewhere",
+ "REQUEST_URI": "/path?a=b",
+ "CONTENT_TYPE": "text/xml",
+ "HTTPS": "1",
+ "REMOTE_ADDR": "5.6.7.8",
+ }
+ req, err := RequestFromMap(env)
+ if err != nil {
+ t.Fatalf("RequestFromMap: %v", err)
+ }
+ if g, e := req.URL.String(), "https://example.com/path?a=b"; e != g {
+ t.Errorf("expected URL %q; got %q", e, g)
+ }
+ if req.TLS == nil {
+ t.Errorf("expected non-nil TLS")
+ }
+}
+
+func TestRequestWithoutHost(t *testing.T) {
+ env := map[string]string{
+ "SERVER_PROTOCOL": "HTTP/1.1",
+ "HTTP_HOST": "",
+ "REQUEST_METHOD": "GET",
+ "REQUEST_URI": "/path?a=b",
+ "CONTENT_LENGTH": "123",
+ }
+ req, err := RequestFromMap(env)
+ if err != nil {
+ t.Fatalf("RequestFromMap: %v", err)
+ }
+ if req.URL == nil {
+ t.Fatalf("unexpected nil URL")
+ }
+ if g, e := req.URL.String(), "/path?a=b"; e != g {
+ t.Errorf("URL = %q; want %q", g, e)
+ }
+}
+
+func TestRequestWithoutRequestURI(t *testing.T) {
+ env := map[string]string{
+ "SERVER_PROTOCOL": "HTTP/1.1",
+ "HTTP_HOST": "example.com",
+ "REQUEST_METHOD": "GET",
+ "SCRIPT_NAME": "/dir/scriptname",
+ "PATH_INFO": "/p1/p2",
+ "QUERY_STRING": "a=1&b=2",
+ "CONTENT_LENGTH": "123",
+ }
+ req, err := RequestFromMap(env)
+ if err != nil {
+ t.Fatalf("RequestFromMap: %v", err)
+ }
+ if req.URL == nil {
+ t.Fatalf("unexpected nil URL")
+ }
+ if g, e := req.URL.String(), "http://example.com/dir/scriptname/p1/p2?a=1&b=2"; e != g {
+ t.Errorf("URL = %q; want %q", g, e)
+ }
+}
+
+func TestRequestWithoutRemotePort(t *testing.T) {
+ env := map[string]string{
+ "SERVER_PROTOCOL": "HTTP/1.1",
+ "HTTP_HOST": "example.com",
+ "REQUEST_METHOD": "GET",
+ "REQUEST_URI": "/path?a=b",
+ "CONTENT_LENGTH": "123",
+ "REMOTE_ADDR": "5.6.7.8",
+ }
+ req, err := RequestFromMap(env)
+ if err != nil {
+ t.Fatalf("RequestFromMap: %v", err)
+ }
+ if e, g := "5.6.7.8:0", req.RemoteAddr; e != g {
+ t.Errorf("RemoteAddr: got %q; want %q", g, e)
+ }
+}
+
+func TestResponse(t *testing.T) {
+ var tests = []struct {
+ name string
+ body string
+ wantCT string
+ }{
+ {
+ name: "no body",
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "html",
+ body: "test pageThis is a body",
+ wantCT: "text/html; charset=utf-8",
+ },
+ {
+ name: "text",
+ body: strings.Repeat("gopher", 86),
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "jpg",
+ body: "\xFF\xD8\xFF" + strings.Repeat("B", 1024),
+ wantCT: "image/jpeg",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ resp := response{
+ req: httptest.NewRequest("GET", "/", nil),
+ header: http.Header{},
+ bufw: bufio.NewWriter(&buf),
+ }
+ n, err := resp.Write([]byte(tt.body))
+ if err != nil {
+ t.Errorf("Write: unexpected %v", err)
+ }
+ if want := len(tt.body); n != want {
+ t.Errorf("reported short Write: got %v want %v", n, want)
+ }
+ resp.writeCGIHeader(nil)
+ resp.Flush()
+ if got := resp.Header().Get("Content-Type"); got != tt.wantCT {
+ t.Errorf("wrong content-type: got %q, want %q", got, tt.wantCT)
+ }
+ if !bytes.HasSuffix(buf.Bytes(), []byte(tt.body)) {
+ t.Errorf("body was not correctly written")
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/host.go b/platform/dbops/binaries/go/go/src/net/http/cgi/host.go
new file mode 100644
index 0000000000000000000000000000000000000000..ef222ab73a75c0ce2c6d897bd635470f503ca071
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/host.go
@@ -0,0 +1,409 @@
+// 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 host side of CGI (being the webserver
+// parent process).
+
+// Package cgi implements CGI (Common Gateway Interface) as specified
+// in RFC 3875.
+//
+// Note that using CGI means starting a new process to handle each
+// request, which is typically less efficient than using a
+// long-running server. This package is intended primarily for
+// compatibility with existing systems.
+package cgi
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/textproto"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
+
+var osDefaultInheritEnv = func() []string {
+ switch runtime.GOOS {
+ case "darwin", "ios":
+ return []string{"DYLD_LIBRARY_PATH"}
+ case "android", "linux", "freebsd", "netbsd", "openbsd":
+ return []string{"LD_LIBRARY_PATH"}
+ case "hpux":
+ return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
+ case "irix":
+ return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
+ case "illumos", "solaris":
+ return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
+ case "windows":
+ return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
+ }
+ return nil
+}()
+
+// Handler runs an executable in a subprocess with a CGI environment.
+type Handler struct {
+ Path string // path to the CGI executable
+ Root string // root URI prefix of handler or empty for "/"
+
+ // Dir specifies the CGI executable's working directory.
+ // If Dir is empty, the base directory of Path is used.
+ // If Path has no base directory, the current working
+ // directory is used.
+ Dir string
+
+ Env []string // extra environment variables to set, if any, as "key=value"
+ InheritEnv []string // environment variables to inherit from host, as "key"
+ Logger *log.Logger // optional log for errors or nil to use log.Print
+ Args []string // optional arguments to pass to child process
+ Stderr io.Writer // optional stderr for the child process; nil means os.Stderr
+
+ // PathLocationHandler specifies the root http Handler that
+ // should handle internal redirects when the CGI process
+ // returns a Location header value starting with a "/", as
+ // specified in RFC 3875 § 6.3.2. This will likely be
+ // http.DefaultServeMux.
+ //
+ // If nil, a CGI response with a local URI path is instead sent
+ // back to the client and not redirected internally.
+ PathLocationHandler http.Handler
+}
+
+func (h *Handler) stderr() io.Writer {
+ if h.Stderr != nil {
+ return h.Stderr
+ }
+ return os.Stderr
+}
+
+// removeLeadingDuplicates remove leading duplicate in environments.
+// It's possible to override environment like following.
+//
+// cgi.Handler{
+// ...
+// Env: []string{"SCRIPT_FILENAME=foo.php"},
+// }
+func removeLeadingDuplicates(env []string) (ret []string) {
+ for i, e := range env {
+ found := false
+ if eq := strings.IndexByte(e, '='); eq != -1 {
+ keq := e[:eq+1] // "key="
+ for _, e2 := range env[i+1:] {
+ if strings.HasPrefix(e2, keq) {
+ found = true
+ break
+ }
+ }
+ }
+ if !found {
+ ret = append(ret, e)
+ }
+ }
+ return
+}
+
+func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
+ if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" {
+ rw.WriteHeader(http.StatusBadRequest)
+ rw.Write([]byte("Chunked request bodies are not supported by CGI."))
+ return
+ }
+
+ root := strings.TrimRight(h.Root, "/")
+ pathInfo := strings.TrimPrefix(req.URL.Path, root)
+
+ port := "80"
+ if req.TLS != nil {
+ port = "443"
+ }
+ if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
+ port = matches[1]
+ }
+
+ env := []string{
+ "SERVER_SOFTWARE=go",
+ "SERVER_PROTOCOL=HTTP/1.1",
+ "HTTP_HOST=" + req.Host,
+ "GATEWAY_INTERFACE=CGI/1.1",
+ "REQUEST_METHOD=" + req.Method,
+ "QUERY_STRING=" + req.URL.RawQuery,
+ "REQUEST_URI=" + req.URL.RequestURI(),
+ "PATH_INFO=" + pathInfo,
+ "SCRIPT_NAME=" + root,
+ "SCRIPT_FILENAME=" + h.Path,
+ "SERVER_PORT=" + port,
+ }
+
+ if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil {
+ env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort)
+ } else {
+ // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined
+ env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr)
+ }
+
+ if hostDomain, _, err := net.SplitHostPort(req.Host); err == nil {
+ env = append(env, "SERVER_NAME="+hostDomain)
+ } else {
+ env = append(env, "SERVER_NAME="+req.Host)
+ }
+
+ if req.TLS != nil {
+ env = append(env, "HTTPS=on")
+ }
+
+ for k, v := range req.Header {
+ k = strings.Map(upperCaseAndUnderscore, k)
+ if k == "PROXY" {
+ // See Issue 16405
+ continue
+ }
+ joinStr := ", "
+ if k == "COOKIE" {
+ joinStr = "; "
+ }
+ env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr))
+ }
+
+ if req.ContentLength > 0 {
+ env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength))
+ }
+ if ctype := req.Header.Get("Content-Type"); ctype != "" {
+ env = append(env, "CONTENT_TYPE="+ctype)
+ }
+
+ envPath := os.Getenv("PATH")
+ if envPath == "" {
+ envPath = "/bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin"
+ }
+ env = append(env, "PATH="+envPath)
+
+ for _, e := range h.InheritEnv {
+ if v := os.Getenv(e); v != "" {
+ env = append(env, e+"="+v)
+ }
+ }
+
+ for _, e := range osDefaultInheritEnv {
+ if v := os.Getenv(e); v != "" {
+ env = append(env, e+"="+v)
+ }
+ }
+
+ if h.Env != nil {
+ env = append(env, h.Env...)
+ }
+
+ env = removeLeadingDuplicates(env)
+
+ var cwd, path string
+ if h.Dir != "" {
+ path = h.Path
+ cwd = h.Dir
+ } else {
+ cwd, path = filepath.Split(h.Path)
+ }
+ if cwd == "" {
+ cwd = "."
+ }
+
+ internalError := func(err error) {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("CGI error: %v", err)
+ }
+
+ cmd := &exec.Cmd{
+ Path: path,
+ Args: append([]string{h.Path}, h.Args...),
+ Dir: cwd,
+ Env: env,
+ Stderr: h.stderr(),
+ }
+ if req.ContentLength != 0 {
+ cmd.Stdin = req.Body
+ }
+ stdoutRead, err := cmd.StdoutPipe()
+ if err != nil {
+ internalError(err)
+ return
+ }
+
+ err = cmd.Start()
+ if err != nil {
+ internalError(err)
+ return
+ }
+ if hook := testHookStartProcess; hook != nil {
+ hook(cmd.Process)
+ }
+ defer cmd.Wait()
+ defer stdoutRead.Close()
+
+ linebody := bufio.NewReaderSize(stdoutRead, 1024)
+ headers := make(http.Header)
+ statusCode := 0
+ headerLines := 0
+ sawBlankLine := false
+ for {
+ line, isPrefix, err := linebody.ReadLine()
+ if isPrefix {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("cgi: long header line from subprocess.")
+ return
+ }
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("cgi: error reading headers: %v", err)
+ return
+ }
+ if len(line) == 0 {
+ sawBlankLine = true
+ break
+ }
+ headerLines++
+ header, val, ok := strings.Cut(string(line), ":")
+ if !ok {
+ h.printf("cgi: bogus header line: %s", string(line))
+ continue
+ }
+ if !httpguts.ValidHeaderFieldName(header) {
+ h.printf("cgi: invalid header name: %q", header)
+ continue
+ }
+ val = textproto.TrimString(val)
+ switch {
+ case header == "Status":
+ if len(val) < 3 {
+ h.printf("cgi: bogus status (short): %q", val)
+ return
+ }
+ code, err := strconv.Atoi(val[0:3])
+ if err != nil {
+ h.printf("cgi: bogus status: %q", val)
+ h.printf("cgi: line was %q", line)
+ return
+ }
+ statusCode = code
+ default:
+ headers.Add(header, val)
+ }
+ }
+ if headerLines == 0 || !sawBlankLine {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("cgi: no headers")
+ return
+ }
+
+ if loc := headers.Get("Location"); loc != "" {
+ if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil {
+ h.handleInternalRedirect(rw, req, loc)
+ return
+ }
+ if statusCode == 0 {
+ statusCode = http.StatusFound
+ }
+ }
+
+ if statusCode == 0 && headers.Get("Content-Type") == "" {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("cgi: missing required Content-Type in headers")
+ return
+ }
+
+ if statusCode == 0 {
+ statusCode = http.StatusOK
+ }
+
+ // Copy headers to rw's headers, after we've decided not to
+ // go into handleInternalRedirect, which won't want its rw
+ // headers to have been touched.
+ for k, vv := range headers {
+ for _, v := range vv {
+ rw.Header().Add(k, v)
+ }
+ }
+
+ rw.WriteHeader(statusCode)
+
+ _, err = io.Copy(rw, linebody)
+ if err != nil {
+ h.printf("cgi: copy error: %v", err)
+ // And kill the child CGI process so we don't hang on
+ // the deferred cmd.Wait above if the error was just
+ // the client (rw) going away. If it was a read error
+ // (because the child died itself), then the extra
+ // kill of an already-dead process is harmless (the PID
+ // won't be reused until the Wait above).
+ cmd.Process.Kill()
+ }
+}
+
+func (h *Handler) printf(format string, v ...any) {
+ if h.Logger != nil {
+ h.Logger.Printf(format, v...)
+ } else {
+ log.Printf(format, v...)
+ }
+}
+
+func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) {
+ url, err := req.URL.Parse(path)
+ if err != nil {
+ rw.WriteHeader(http.StatusInternalServerError)
+ h.printf("cgi: error resolving local URI path %q: %v", path, err)
+ return
+ }
+ // TODO: RFC 3875 isn't clear if only GET is supported, but it
+ // suggests so: "Note that any message-body attached to the
+ // request (such as for a POST request) may not be available
+ // to the resource that is the target of the redirect." We
+ // should do some tests against Apache to see how it handles
+ // POST, HEAD, etc. Does the internal redirect get the same
+ // method or just GET? What about incoming headers?
+ // (e.g. Cookies) Which headers, if any, are copied into the
+ // second request?
+ newReq := &http.Request{
+ Method: "GET",
+ URL: url,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: make(http.Header),
+ Host: url.Host,
+ RemoteAddr: req.RemoteAddr,
+ TLS: req.TLS,
+ }
+ h.PathLocationHandler.ServeHTTP(rw, newReq)
+}
+
+func upperCaseAndUnderscore(r rune) rune {
+ switch {
+ case r >= 'a' && r <= 'z':
+ return r - ('a' - 'A')
+ case r == '-':
+ return '_'
+ case r == '=':
+ // Maybe not part of the CGI 'spec' but would mess up
+ // the environment in any case, as Go represents the
+ // environment as a slice of "key=value" strings.
+ return '_'
+ }
+ // TODO: other transformations in spec or practice?
+ return r
+}
+
+var testHookStartProcess func(*os.Process) // nil except for some tests
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/host_test.go b/platform/dbops/binaries/go/go/src/net/http/cgi/host_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f29395fe8493f02a85308db46ab847d253539a5c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/host_test.go
@@ -0,0 +1,518 @@
+// 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.
+
+// Tests for package cgi
+
+package cgi
+
+import (
+ "bufio"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestMain executes the test binary as the cgi server if
+// SERVER_SOFTWARE is set, and runs the tests otherwise.
+func TestMain(m *testing.M) {
+ // SERVER_SOFTWARE swap variable is set when starting the cgi server.
+ if os.Getenv("SERVER_SOFTWARE") != "" {
+ cgiMain()
+ os.Exit(0)
+ }
+
+ os.Exit(m.Run())
+}
+
+func newRequest(httpreq string) *http.Request {
+ buf := bufio.NewReader(strings.NewReader(httpreq))
+ req, err := http.ReadRequest(buf)
+ if err != nil {
+ panic("cgi: bogus http request in test: " + httpreq)
+ }
+ req.RemoteAddr = "1.2.3.4:1234"
+ return req
+}
+
+func runCgiTest(t *testing.T, h *Handler,
+ httpreq string,
+ expectedMap map[string]string, checks ...func(reqInfo map[string]string)) *httptest.ResponseRecorder {
+ rw := httptest.NewRecorder()
+ req := newRequest(httpreq)
+ h.ServeHTTP(rw, req)
+ runResponseChecks(t, rw, expectedMap, checks...)
+ return rw
+}
+
+func runResponseChecks(t *testing.T, rw *httptest.ResponseRecorder,
+ expectedMap map[string]string, checks ...func(reqInfo map[string]string)) {
+ // Make a map to hold the test map that the CGI returns.
+ m := make(map[string]string)
+ m["_body"] = rw.Body.String()
+ linesRead := 0
+readlines:
+ for {
+ line, err := rw.Body.ReadString('\n')
+ switch {
+ case err == io.EOF:
+ break readlines
+ case err != nil:
+ t.Fatalf("unexpected error reading from CGI: %v", err)
+ }
+ linesRead++
+ trimmedLine := strings.TrimRight(line, "\r\n")
+ k, v, ok := strings.Cut(trimmedLine, "=")
+ if !ok {
+ t.Fatalf("Unexpected response from invalid line number %v: %q; existing map=%v",
+ linesRead, line, m)
+ }
+ m[k] = v
+ }
+
+ for key, expected := range expectedMap {
+ got := m[key]
+ if key == "cwd" {
+ // For Windows. golang.org/issue/4645.
+ fi1, _ := os.Stat(got)
+ fi2, _ := os.Stat(expected)
+ if os.SameFile(fi1, fi2) {
+ got = expected
+ }
+ }
+ if got != expected {
+ t.Errorf("for key %q got %q; expected %q", key, got, expected)
+ }
+ }
+ for _, check := range checks {
+ check(m)
+ }
+}
+
+func TestCGIBasicGet(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{
+ "test": "Hello CGI",
+ "param-a": "b",
+ "param-foo": "bar",
+ "env-GATEWAY_INTERFACE": "CGI/1.1",
+ "env-HTTP_HOST": "example.com:80",
+ "env-PATH_INFO": "",
+ "env-QUERY_STRING": "foo=bar&a=b",
+ "env-REMOTE_ADDR": "1.2.3.4",
+ "env-REMOTE_HOST": "1.2.3.4",
+ "env-REMOTE_PORT": "1234",
+ "env-REQUEST_METHOD": "GET",
+ "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "/test.cgi",
+ "env-SERVER_NAME": "example.com",
+ "env-SERVER_PORT": "80",
+ "env-SERVER_SOFTWARE": "go",
+ }
+ replay := runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com:80\n\n", expectedMap)
+
+ if expected, got := "text/html", replay.Header().Get("Content-Type"); got != expected {
+ t.Errorf("got a Content-Type of %q; expected %q", got, expected)
+ }
+ if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
+ t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
+ }
+}
+
+func TestCGIEnvIPv6(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{
+ "test": "Hello CGI",
+ "param-a": "b",
+ "param-foo": "bar",
+ "env-GATEWAY_INTERFACE": "CGI/1.1",
+ "env-HTTP_HOST": "example.com",
+ "env-PATH_INFO": "",
+ "env-QUERY_STRING": "foo=bar&a=b",
+ "env-REMOTE_ADDR": "2000::3000",
+ "env-REMOTE_HOST": "2000::3000",
+ "env-REMOTE_PORT": "12345",
+ "env-REQUEST_METHOD": "GET",
+ "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "/test.cgi",
+ "env-SERVER_NAME": "example.com",
+ "env-SERVER_PORT": "80",
+ "env-SERVER_SOFTWARE": "go",
+ }
+
+ rw := httptest.NewRecorder()
+ req := newRequest("GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n")
+ req.RemoteAddr = "[2000::3000]:12345"
+ h.ServeHTTP(rw, req)
+ runResponseChecks(t, rw, expectedMap)
+}
+
+func TestCGIBasicGetAbsPath(t *testing.T) {
+ absPath, err := filepath.Abs(os.Args[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: absPath,
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{
+ "env-REQUEST_URI": "/test.cgi?foo=bar&a=b",
+ "env-SCRIPT_FILENAME": absPath,
+ "env-SCRIPT_NAME": "/test.cgi",
+ }
+ runCgiTest(t, h, "GET /test.cgi?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestPathInfo(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{
+ "param-a": "b",
+ "env-PATH_INFO": "/extrapath",
+ "env-QUERY_STRING": "a=b",
+ "env-REQUEST_URI": "/test.cgi/extrapath?a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "/test.cgi",
+ }
+ runCgiTest(t, h, "GET /test.cgi/extrapath?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestPathInfoDirRoot(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/myscript//",
+ }
+ expectedMap := map[string]string{
+ "env-PATH_INFO": "/bar",
+ "env-QUERY_STRING": "a=b",
+ "env-REQUEST_URI": "/myscript/bar?a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "/myscript",
+ }
+ runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestDupHeaders(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ }
+ expectedMap := map[string]string{
+ "env-REQUEST_URI": "/myscript/bar?a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-HTTP_COOKIE": "nom=NOM; yum=YUM",
+ "env-HTTP_X_FOO": "val1, val2",
+ }
+ runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\n"+
+ "Cookie: nom=NOM\n"+
+ "Cookie: yum=YUM\n"+
+ "X-Foo: val1\n"+
+ "X-Foo: val2\n"+
+ "Host: example.com\n\n",
+ expectedMap)
+}
+
+// Issue 16405: CGI+http.Transport differing uses of HTTP_PROXY.
+// Verify we don't set the HTTP_PROXY environment variable.
+// Hope nobody was depending on it. It's not a known header, though.
+func TestDropProxyHeader(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ }
+ expectedMap := map[string]string{
+ "env-REQUEST_URI": "/myscript/bar?a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-HTTP_X_FOO": "a",
+ }
+ runCgiTest(t, h, "GET /myscript/bar?a=b HTTP/1.0\n"+
+ "X-Foo: a\n"+
+ "Proxy: should_be_stripped\n"+
+ "Host: example.com\n\n",
+ expectedMap,
+ func(reqInfo map[string]string) {
+ if v, ok := reqInfo["env-HTTP_PROXY"]; ok {
+ t.Errorf("HTTP_PROXY = %q; should be absent", v)
+ }
+ })
+}
+
+func TestPathInfoNoRoot(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "",
+ }
+ expectedMap := map[string]string{
+ "env-PATH_INFO": "/bar",
+ "env-QUERY_STRING": "a=b",
+ "env-REQUEST_URI": "/bar?a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "",
+ }
+ runCgiTest(t, h, "GET /bar?a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestCGIBasicPost(t *testing.T) {
+ testenv.MustHaveExec(t)
+ postReq := `POST /test.cgi?a=b HTTP/1.0
+Host: example.com
+Content-Type: application/x-www-form-urlencoded
+Content-Length: 15
+
+postfoo=postbar`
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{
+ "test": "Hello CGI",
+ "param-postfoo": "postbar",
+ "env-REQUEST_METHOD": "POST",
+ "env-CONTENT_LENGTH": "15",
+ "env-REQUEST_URI": "/test.cgi?a=b",
+ }
+ runCgiTest(t, h, postReq, expectedMap)
+}
+
+func chunk(s string) string {
+ return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
+}
+
+// The CGI spec doesn't allow chunked requests.
+func TestCGIPostChunked(t *testing.T) {
+ testenv.MustHaveExec(t)
+ postReq := `POST /test.cgi?a=b HTTP/1.1
+Host: example.com
+Content-Type: application/x-www-form-urlencoded
+Transfer-Encoding: chunked
+
+` + chunk("postfoo") + chunk("=") + chunk("postbar") + chunk("")
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap := map[string]string{}
+ resp := runCgiTest(t, h, postReq, expectedMap)
+ if got, expected := resp.Code, http.StatusBadRequest; got != expected {
+ t.Fatalf("Expected %v response code from chunked request body; got %d",
+ expected, got)
+ }
+}
+
+func TestRedirect(t *testing.T) {
+ testenv.MustHaveExec(t)
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ rec := runCgiTest(t, h, "GET /test.cgi?loc=http://foo.com/ HTTP/1.0\nHost: example.com\n\n", nil)
+ if e, g := 302, rec.Code; e != g {
+ t.Errorf("expected status code %d; got %d", e, g)
+ }
+ if e, g := "http://foo.com/", rec.Header().Get("Location"); e != g {
+ t.Errorf("expected Location header of %q; got %q", e, g)
+ }
+}
+
+func TestInternalRedirect(t *testing.T) {
+ testenv.MustHaveExec(t)
+ baseHandler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+ fmt.Fprintf(rw, "basepath=%s\n", req.URL.Path)
+ fmt.Fprintf(rw, "remoteaddr=%s\n", req.RemoteAddr)
+ })
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ PathLocationHandler: baseHandler,
+ }
+ expectedMap := map[string]string{
+ "basepath": "/foo",
+ "remoteaddr": "1.2.3.4:1234",
+ }
+ runCgiTest(t, h, "GET /test.cgi?loc=/foo HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+// TestCopyError tests that we kill the process if there's an error copying
+// its output. (for example, from the client having gone away)
+//
+// If we fail to do so, the test will time out (and dump its goroutines) with a
+// call to [Handler.ServeHTTP] blocked on a deferred call to [exec.Cmd.Wait].
+func TestCopyError(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ ts := httptest.NewServer(h)
+ defer ts.Close()
+
+ conn, err := net.Dial("tcp", ts.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, _ := http.NewRequest("GET", "http://example.com/test.cgi?bigresponse=1", nil)
+ err = req.Write(conn)
+ if err != nil {
+ t.Fatalf("Write: %v", err)
+ }
+
+ res, err := http.ReadResponse(bufio.NewReader(conn), req)
+ if err != nil {
+ t.Fatalf("ReadResponse: %v", err)
+ }
+
+ var buf [5000]byte
+ n, err := io.ReadFull(res.Body, buf[:])
+ if err != nil {
+ t.Fatalf("ReadFull: %d bytes, %v", n, err)
+ }
+
+ if !handlerRunning() {
+ t.Fatalf("pre-conn.Close, expected handler to still be running")
+ }
+ conn.Close()
+ closed := time.Now()
+
+ nextSleep := 1 * time.Millisecond
+ for {
+ time.Sleep(nextSleep)
+ nextSleep *= 2
+ if !handlerRunning() {
+ break
+ }
+ t.Logf("handler still running %v after conn.Close", time.Since(closed))
+ }
+}
+
+// handlerRunning reports whether any goroutine is currently running
+// [Handler.ServeHTTP].
+func handlerRunning() bool {
+ r := regexp.MustCompile(`net/http/cgi\.\(\*Handler\)\.ServeHTTP`)
+ buf := make([]byte, 64<<10)
+ for {
+ n := runtime.Stack(buf, true)
+ if n < len(buf) {
+ return r.Match(buf[:n])
+ }
+ // Buffer wasn't large enough for a full goroutine dump.
+ // Resize it and try again.
+ buf = make([]byte, 2*len(buf))
+ }
+}
+
+func TestDir(t *testing.T) {
+ testenv.MustHaveExec(t)
+ cwd, _ := os.Getwd()
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ Dir: cwd,
+ }
+ expectedMap := map[string]string{
+ "cwd": cwd,
+ }
+ runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
+
+ cwd, _ = os.Getwd()
+ cwd, _ = filepath.Split(os.Args[0])
+ h = &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ }
+ expectedMap = map[string]string{
+ "cwd": cwd,
+ }
+ runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestEnvOverride(t *testing.T) {
+ testenv.MustHaveExec(t)
+ cgifile, _ := filepath.Abs("testdata/test.cgi")
+
+ cwd, _ := os.Getwd()
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ Dir: cwd,
+ Env: []string{
+ "SCRIPT_FILENAME=" + cgifile,
+ "REQUEST_URI=/foo/bar",
+ "PATH=/wibble"},
+ }
+ expectedMap := map[string]string{
+ "cwd": cwd,
+ "env-SCRIPT_FILENAME": cgifile,
+ "env-REQUEST_URI": "/foo/bar",
+ "env-PATH": "/wibble",
+ }
+ runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
+}
+
+func TestHandlerStderr(t *testing.T) {
+ testenv.MustHaveExec(t)
+ var stderr strings.Builder
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.cgi",
+ Stderr: &stderr,
+ }
+
+ rw := httptest.NewRecorder()
+ req := newRequest("GET /test.cgi?writestderr=1 HTTP/1.0\nHost: example.com\n\n")
+ h.ServeHTTP(rw, req)
+ if got, want := stderr.String(), "Hello, stderr!\n"; got != want {
+ t.Errorf("Stderr = %q; want %q", got, want)
+ }
+}
+
+func TestRemoveLeadingDuplicates(t *testing.T) {
+ tests := []struct {
+ env []string
+ want []string
+ }{
+ {
+ env: []string{"a=b", "b=c", "a=b2"},
+ want: []string{"b=c", "a=b2"},
+ },
+ {
+ env: []string{"a=b", "b=c", "d", "e=f"},
+ want: []string{"a=b", "b=c", "d", "e=f"},
+ },
+ }
+ for _, tt := range tests {
+ got := removeLeadingDuplicates(tt.env)
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("removeLeadingDuplicates(%q) = %q; want %q", tt.env, got, tt.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cgi/integration_test.go b/platform/dbops/binaries/go/go/src/net/http/cgi/integration_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..68f908e2b26d8d8da7f2a7b3fa0da70ff70f8457
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cgi/integration_test.go
@@ -0,0 +1,207 @@
+// 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.
+
+// Tests a Go CGI program running under a Go CGI host process.
+// Further, the two programs are the same binary, just checking
+// their environment to figure out what mode to run in.
+
+package cgi
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+)
+
+// This test is a CGI host (testing host.go) that runs its own binary
+// as a child process testing the other half of CGI (child.go).
+func TestHostingOurselves(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ expectedMap := map[string]string{
+ "test": "Hello CGI-in-CGI",
+ "param-a": "b",
+ "param-foo": "bar",
+ "env-GATEWAY_INTERFACE": "CGI/1.1",
+ "env-HTTP_HOST": "example.com",
+ "env-PATH_INFO": "",
+ "env-QUERY_STRING": "foo=bar&a=b",
+ "env-REMOTE_ADDR": "1.2.3.4",
+ "env-REMOTE_HOST": "1.2.3.4",
+ "env-REMOTE_PORT": "1234",
+ "env-REQUEST_METHOD": "GET",
+ "env-REQUEST_URI": "/test.go?foo=bar&a=b",
+ "env-SCRIPT_FILENAME": os.Args[0],
+ "env-SCRIPT_NAME": "/test.go",
+ "env-SERVER_NAME": "example.com",
+ "env-SERVER_PORT": "80",
+ "env-SERVER_SOFTWARE": "go",
+ }
+ replay := runCgiTest(t, h, "GET /test.go?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
+
+ if expected, got := "text/plain; charset=utf-8", replay.Header().Get("Content-Type"); got != expected {
+ t.Errorf("got a Content-Type of %q; expected %q", got, expected)
+ }
+ if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
+ t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
+ }
+}
+
+type customWriterRecorder struct {
+ w io.Writer
+ *httptest.ResponseRecorder
+}
+
+func (r *customWriterRecorder) Write(p []byte) (n int, err error) {
+ return r.w.Write(p)
+}
+
+type limitWriter struct {
+ w io.Writer
+ n int
+}
+
+func (w *limitWriter) Write(p []byte) (n int, err error) {
+ if len(p) > w.n {
+ p = p[:w.n]
+ }
+ if len(p) > 0 {
+ n, err = w.w.Write(p)
+ w.n -= n
+ }
+ if w.n == 0 {
+ err = errors.New("past write limit")
+ }
+ return
+}
+
+// If there's an error copying the child's output to the parent, test
+// that we kill the child.
+func TestKillChildAfterCopyError(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ req, _ := http.NewRequest("GET", "http://example.com/test.go?write-forever=1", nil)
+ rec := httptest.NewRecorder()
+ var out bytes.Buffer
+ const writeLen = 50 << 10
+ rw := &customWriterRecorder{&limitWriter{&out, writeLen}, rec}
+
+ h.ServeHTTP(rw, req)
+ if out.Len() != writeLen || out.Bytes()[0] != 'a' {
+ t.Errorf("unexpected output: %q", out.Bytes())
+ }
+}
+
+// Test that a child handler writing only headers works.
+// golang.org/issue/7196
+func TestChildOnlyHeaders(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ expectedMap := map[string]string{
+ "_body": "",
+ }
+ replay := runCgiTest(t, h, "GET /test.go?no-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
+ if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
+ t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
+ }
+}
+
+// Test that a child handler does not receive a nil Request Body.
+// golang.org/issue/39190
+func TestNilRequestBody(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ expectedMap := map[string]string{
+ "nil-request-body": "false",
+ }
+ _ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
+ _ = runCgiTest(t, h, "POST /test.go?nil-request-body=1 HTTP/1.0\nHost: example.com\nContent-Length: 0\n\n", expectedMap)
+}
+
+func TestChildContentType(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ var tests = []struct {
+ name string
+ body string
+ wantCT string
+ }{
+ {
+ name: "no body",
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "html",
+ body: "test pageThis is a body",
+ wantCT: "text/html; charset=utf-8",
+ },
+ {
+ name: "text",
+ body: strings.Repeat("gopher", 86),
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "jpg",
+ body: "\xFF\xD8\xFF" + strings.Repeat("B", 1024),
+ wantCT: "image/jpeg",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ expectedMap := map[string]string{"_body": tt.body}
+ req := fmt.Sprintf("GET /test.go?exact-body=%s HTTP/1.0\nHost: example.com\n\n", url.QueryEscape(tt.body))
+ replay := runCgiTest(t, h, req, expectedMap)
+ if got := replay.Header().Get("Content-Type"); got != tt.wantCT {
+ t.Errorf("got a Content-Type of %q; expected it to start with %q", got, tt.wantCT)
+ }
+ })
+ }
+}
+
+// golang.org/issue/7198
+func Test500WithNoHeaders(t *testing.T) { want500Test(t, "/immediate-disconnect") }
+func Test500WithNoContentType(t *testing.T) { want500Test(t, "/no-content-type") }
+func Test500WithEmptyHeaders(t *testing.T) { want500Test(t, "/empty-headers") }
+
+func want500Test(t *testing.T, path string) {
+ h := &Handler{
+ Path: os.Args[0],
+ Root: "/test.go",
+ }
+ expectedMap := map[string]string{
+ "_body": "",
+ }
+ replay := runCgiTest(t, h, "GET "+path+" HTTP/1.0\nHost: example.com\n\n", expectedMap)
+ if replay.Code != 500 {
+ t.Errorf("Got code %d; want 500", replay.Code)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/client.go b/platform/dbops/binaries/go/go/src/net/http/client.go
new file mode 100644
index 0000000000000000000000000000000000000000..8fc348fe5d36e65404ac2ec873baa11d786b63b7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/client.go
@@ -0,0 +1,1038 @@
+// 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.
+
+// HTTP client. See RFC 7230 through 7235.
+//
+// This is the high-level Client interface.
+// The low-level implementation is in transport.go.
+
+package http
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http/internal/ascii"
+ "net/url"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// A Client is an HTTP client. Its zero value ([DefaultClient]) is a
+// usable client that uses [DefaultTransport].
+//
+// The [Client.Transport] typically has internal state (cached TCP
+// connections), so Clients should be reused instead of created as
+// needed. Clients are safe for concurrent use by multiple goroutines.
+//
+// A Client is higher-level than a [RoundTripper] (such as [Transport])
+// and additionally handles HTTP details such as cookies and
+// redirects.
+//
+// When following redirects, the Client will forward all headers set on the
+// initial [Request] except:
+//
+// - when forwarding sensitive headers like "Authorization",
+// "WWW-Authenticate", and "Cookie" to untrusted targets.
+// These headers will be ignored when following a redirect to a domain
+// that is not a subdomain match or exact match of the initial domain.
+// For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
+// will forward the sensitive headers, but a redirect to "bar.com" will not.
+// - when forwarding the "Cookie" header with a non-nil cookie Jar.
+// Since each redirect may mutate the state of the cookie jar,
+// a redirect may possibly alter a cookie set in the initial request.
+// When forwarding the "Cookie" header, any mutated cookies will be omitted,
+// with the expectation that the Jar will insert those mutated cookies
+// with the updated values (assuming the origin matches).
+// If Jar is nil, the initial cookies are forwarded without change.
+type Client struct {
+ // Transport specifies the mechanism by which individual
+ // HTTP requests are made.
+ // If nil, DefaultTransport is used.
+ Transport RoundTripper
+
+ // CheckRedirect specifies the policy for handling redirects.
+ // If CheckRedirect is not nil, the client calls it before
+ // following an HTTP redirect. The arguments req and via are
+ // the upcoming request and the requests made already, oldest
+ // first. If CheckRedirect returns an error, the Client's Get
+ // method returns both the previous Response (with its Body
+ // closed) and CheckRedirect's error (wrapped in a url.Error)
+ // instead of issuing the Request req.
+ // As a special case, if CheckRedirect returns ErrUseLastResponse,
+ // then the most recent response is returned with its body
+ // unclosed, along with a nil error.
+ //
+ // If CheckRedirect is nil, the Client uses its default policy,
+ // which is to stop after 10 consecutive requests.
+ CheckRedirect func(req *Request, via []*Request) error
+
+ // Jar specifies the cookie jar.
+ //
+ // The Jar is used to insert relevant cookies into every
+ // outbound Request and is updated with the cookie values
+ // of every inbound Response. The Jar is consulted for every
+ // redirect that the Client follows.
+ //
+ // If Jar is nil, cookies are only sent if they are explicitly
+ // set on the Request.
+ Jar CookieJar
+
+ // Timeout specifies a time limit for requests made by this
+ // Client. The timeout includes connection time, any
+ // redirects, and reading the response body. The timer remains
+ // running after Get, Head, Post, or Do return and will
+ // interrupt reading of the Response.Body.
+ //
+ // A Timeout of zero means no timeout.
+ //
+ // The Client cancels requests to the underlying Transport
+ // as if the Request's Context ended.
+ //
+ // For compatibility, the Client will also use the deprecated
+ // CancelRequest method on Transport if found. New
+ // RoundTripper implementations should use the Request's Context
+ // for cancellation instead of implementing CancelRequest.
+ Timeout time.Duration
+}
+
+// DefaultClient is the default [Client] and is used by [Get], [Head], and [Post].
+var DefaultClient = &Client{}
+
+// RoundTripper is an interface representing the ability to execute a
+// single HTTP transaction, obtaining the [Response] for a given [Request].
+//
+// A RoundTripper must be safe for concurrent use by multiple
+// goroutines.
+type RoundTripper interface {
+ // RoundTrip executes a single HTTP transaction, returning
+ // a Response for the provided Request.
+ //
+ // RoundTrip should not attempt to interpret the response. In
+ // particular, RoundTrip must return err == nil if it obtained
+ // a response, regardless of the response's HTTP status code.
+ // A non-nil err should be reserved for failure to obtain a
+ // response. Similarly, RoundTrip should not attempt to
+ // handle higher-level protocol details such as redirects,
+ // authentication, or cookies.
+ //
+ // RoundTrip should not modify the request, except for
+ // consuming and closing the Request's Body. RoundTrip may
+ // read fields of the request in a separate goroutine. Callers
+ // should not mutate or reuse the request until the Response's
+ // Body has been closed.
+ //
+ // RoundTrip must always close the body, including on errors,
+ // but depending on the implementation may do so in a separate
+ // goroutine even after RoundTrip returns. This means that
+ // callers wanting to reuse the body for subsequent requests
+ // must arrange to wait for the Close call before doing so.
+ //
+ // The Request's URL and Header fields must be initialized.
+ RoundTrip(*Request) (*Response, error)
+}
+
+// refererForURL returns a referer without any authentication info or
+// an empty string if lastReq scheme is https and newReq scheme is http.
+// If the referer was explicitly set, then it will continue to be used.
+func refererForURL(lastReq, newReq *url.URL, explicitRef string) string {
+ // https://tools.ietf.org/html/rfc7231#section-5.5.2
+ // "Clients SHOULD NOT include a Referer header field in a
+ // (non-secure) HTTP request if the referring page was
+ // transferred with a secure protocol."
+ if lastReq.Scheme == "https" && newReq.Scheme == "http" {
+ return ""
+ }
+ if explicitRef != "" {
+ return explicitRef
+ }
+
+ referer := lastReq.String()
+ if lastReq.User != nil {
+ // This is not very efficient, but is the best we can
+ // do without:
+ // - introducing a new method on URL
+ // - creating a race condition
+ // - copying the URL struct manually, which would cause
+ // maintenance problems down the line
+ auth := lastReq.User.String() + "@"
+ referer = strings.Replace(referer, auth, "", 1)
+ }
+ return referer
+}
+
+// didTimeout is non-nil only if err != nil.
+func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
+ if c.Jar != nil {
+ for _, cookie := range c.Jar.Cookies(req.URL) {
+ req.AddCookie(cookie)
+ }
+ }
+ resp, didTimeout, err = send(req, c.transport(), deadline)
+ if err != nil {
+ return nil, didTimeout, err
+ }
+ if c.Jar != nil {
+ if rc := resp.Cookies(); len(rc) > 0 {
+ c.Jar.SetCookies(req.URL, rc)
+ }
+ }
+ return resp, nil, nil
+}
+
+func (c *Client) deadline() time.Time {
+ if c.Timeout > 0 {
+ return time.Now().Add(c.Timeout)
+ }
+ return time.Time{}
+}
+
+func (c *Client) transport() RoundTripper {
+ if c.Transport != nil {
+ return c.Transport
+ }
+ return DefaultTransport
+}
+
+// ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.
+var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client")
+
+// send issues an HTTP request.
+// Caller should close resp.Body when done reading from it.
+func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
+ req := ireq // req is either the original request, or a modified fork
+
+ if rt == nil {
+ req.closeBody()
+ return nil, alwaysFalse, errors.New("http: no Client.Transport or DefaultTransport")
+ }
+
+ if req.URL == nil {
+ req.closeBody()
+ return nil, alwaysFalse, errors.New("http: nil Request.URL")
+ }
+
+ if req.RequestURI != "" {
+ req.closeBody()
+ return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests")
+ }
+
+ // forkReq forks req into a shallow clone of ireq the first
+ // time it's called.
+ forkReq := func() {
+ if ireq == req {
+ req = new(Request)
+ *req = *ireq // shallow clone
+ }
+ }
+
+ // Most the callers of send (Get, Post, et al) don't need
+ // Headers, leaving it uninitialized. We guarantee to the
+ // Transport that this has been initialized, though.
+ if req.Header == nil {
+ forkReq()
+ req.Header = make(Header)
+ }
+
+ if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
+ username := u.Username()
+ password, _ := u.Password()
+ forkReq()
+ req.Header = cloneOrMakeHeader(ireq.Header)
+ req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
+ }
+
+ if !deadline.IsZero() {
+ forkReq()
+ }
+ stopTimer, didTimeout := setRequestCancel(req, rt, deadline)
+
+ resp, err = rt.RoundTrip(req)
+ if err != nil {
+ stopTimer()
+ if resp != nil {
+ log.Printf("RoundTripper returned a response & error; ignoring response")
+ }
+ if tlsErr, ok := err.(tls.RecordHeaderError); ok {
+ // If we get a bad TLS record header, check to see if the
+ // response looks like HTTP and give a more helpful error.
+ // See golang.org/issue/11111.
+ if string(tlsErr.RecordHeader[:]) == "HTTP/" {
+ err = ErrSchemeMismatch
+ }
+ }
+ return nil, didTimeout, err
+ }
+ if resp == nil {
+ return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a nil *Response with a nil error", rt)
+ }
+ if resp.Body == nil {
+ // The documentation on the Body field says “The http Client and Transport
+ // guarantee that Body is always non-nil, even on responses without a body
+ // or responses with a zero-length body.” Unfortunately, we didn't document
+ // that same constraint for arbitrary RoundTripper implementations, and
+ // RoundTripper implementations in the wild (mostly in tests) assume that
+ // they can use a nil Body to mean an empty one (similar to Request.Body).
+ // (See https://golang.org/issue/38095.)
+ //
+ // If the ContentLength allows the Body to be empty, fill in an empty one
+ // here to ensure that it is non-nil.
+ if resp.ContentLength > 0 && req.Method != "HEAD" {
+ return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a *Response with content length %d but a nil Body", rt, resp.ContentLength)
+ }
+ resp.Body = io.NopCloser(strings.NewReader(""))
+ }
+ if !deadline.IsZero() {
+ resp.Body = &cancelTimerBody{
+ stop: stopTimer,
+ rc: resp.Body,
+ reqDidTimeout: didTimeout,
+ }
+ }
+ return resp, nil, nil
+}
+
+// timeBeforeContextDeadline reports whether the non-zero Time t is
+// before ctx's deadline, if any. If ctx does not have a deadline, it
+// always reports true (the deadline is considered infinite).
+func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool {
+ d, ok := ctx.Deadline()
+ if !ok {
+ return true
+ }
+ return t.Before(d)
+}
+
+// knownRoundTripperImpl reports whether rt is a RoundTripper that's
+// maintained by the Go team and known to implement the latest
+// optional semantics (notably contexts). The Request is used
+// to check whether this particular request is using an alternate protocol,
+// in which case we need to check the RoundTripper for that protocol.
+func knownRoundTripperImpl(rt RoundTripper, req *Request) bool {
+ switch t := rt.(type) {
+ case *Transport:
+ if altRT := t.alternateRoundTripper(req); altRT != nil {
+ return knownRoundTripperImpl(altRT, req)
+ }
+ return true
+ case *http2Transport, http2noDialH2RoundTripper:
+ return true
+ }
+ // There's a very minor chance of a false positive with this.
+ // Instead of detecting our golang.org/x/net/http2.Transport,
+ // it might detect a Transport type in a different http2
+ // package. But I know of none, and the only problem would be
+ // some temporarily leaked goroutines if the transport didn't
+ // support contexts. So this is a good enough heuristic:
+ if reflect.TypeOf(rt).String() == "*http2.Transport" {
+ return true
+ }
+ return false
+}
+
+// setRequestCancel sets req.Cancel and adds a deadline context to req
+// if deadline is non-zero. The RoundTripper's type is used to
+// determine whether the legacy CancelRequest behavior should be used.
+//
+// As background, there are three ways to cancel a request:
+// First was Transport.CancelRequest. (deprecated)
+// Second was Request.Cancel.
+// Third was Request.Context.
+// This function populates the second and third, and uses the first if it really needs to.
+func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool) {
+ if deadline.IsZero() {
+ return nop, alwaysFalse
+ }
+ knownTransport := knownRoundTripperImpl(rt, req)
+ oldCtx := req.Context()
+
+ if req.Cancel == nil && knownTransport {
+ // If they already had a Request.Context that's
+ // expiring sooner, do nothing:
+ if !timeBeforeContextDeadline(deadline, oldCtx) {
+ return nop, alwaysFalse
+ }
+
+ var cancelCtx func()
+ req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
+ return cancelCtx, func() bool { return time.Now().After(deadline) }
+ }
+ initialReqCancel := req.Cancel // the user's original Request.Cancel, if any
+
+ var cancelCtx func()
+ if timeBeforeContextDeadline(deadline, oldCtx) {
+ req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
+ }
+
+ cancel := make(chan struct{})
+ req.Cancel = cancel
+
+ doCancel := func() {
+ // The second way in the func comment above:
+ close(cancel)
+ // The first way, used only for RoundTripper
+ // implementations written before Go 1.5 or Go 1.6.
+ type canceler interface{ CancelRequest(*Request) }
+ if v, ok := rt.(canceler); ok {
+ v.CancelRequest(req)
+ }
+ }
+
+ stopTimerCh := make(chan struct{})
+ var once sync.Once
+ stopTimer = func() {
+ once.Do(func() {
+ close(stopTimerCh)
+ if cancelCtx != nil {
+ cancelCtx()
+ }
+ })
+ }
+
+ timer := time.NewTimer(time.Until(deadline))
+ var timedOut atomic.Bool
+
+ go func() {
+ select {
+ case <-initialReqCancel:
+ doCancel()
+ timer.Stop()
+ case <-timer.C:
+ timedOut.Store(true)
+ doCancel()
+ case <-stopTimerCh:
+ timer.Stop()
+ }
+ }()
+
+ return stopTimer, timedOut.Load
+}
+
+// See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
+// "To receive authorization, the client sends the userid and password,
+// separated by a single colon (":") character, within a base64
+// encoded string in the credentials."
+// It is not meant to be urlencoded.
+func basicAuth(username, password string) string {
+ auth := username + ":" + password
+ return base64.StdEncoding.EncodeToString([]byte(auth))
+}
+
+// Get issues a GET to the specified URL. If the response is one of
+// the following redirect codes, Get follows the redirect, up to a
+// maximum of 10 redirects:
+//
+// 301 (Moved Permanently)
+// 302 (Found)
+// 303 (See Other)
+// 307 (Temporary Redirect)
+// 308 (Permanent Redirect)
+//
+// An error is returned if there were too many redirects or if there
+// was an HTTP protocol error. A non-2xx response doesn't cause an
+// error. Any returned error will be of type [*url.Error]. The url.Error
+// value's Timeout method will report true if the request timed out.
+//
+// When err is nil, resp always contains a non-nil resp.Body.
+// Caller should close resp.Body when done reading from it.
+//
+// Get is a wrapper around DefaultClient.Get.
+//
+// To make a request with custom headers, use [NewRequest] and
+// DefaultClient.Do.
+//
+// To make a request with a specified context.Context, use [NewRequestWithContext]
+// and DefaultClient.Do.
+func Get(url string) (resp *Response, err error) {
+ return DefaultClient.Get(url)
+}
+
+// Get issues a GET to the specified URL. If the response is one of the
+// following redirect codes, Get follows the redirect after calling the
+// [Client.CheckRedirect] function:
+//
+// 301 (Moved Permanently)
+// 302 (Found)
+// 303 (See Other)
+// 307 (Temporary Redirect)
+// 308 (Permanent Redirect)
+//
+// An error is returned if the [Client.CheckRedirect] function fails
+// or if there was an HTTP protocol error. A non-2xx response doesn't
+// cause an error. Any returned error will be of type [*url.Error]. The
+// url.Error value's Timeout method will report true if the request
+// timed out.
+//
+// When err is nil, resp always contains a non-nil resp.Body.
+// Caller should close resp.Body when done reading from it.
+//
+// To make a request with custom headers, use [NewRequest] and [Client.Do].
+//
+// To make a request with a specified context.Context, use [NewRequestWithContext]
+// and Client.Do.
+func (c *Client) Get(url string) (resp *Response, err error) {
+ req, err := NewRequest("GET", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return c.Do(req)
+}
+
+func alwaysFalse() bool { return false }
+
+// ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
+// control how redirects are processed. If returned, the next request
+// is not sent and the most recent response is returned with its body
+// unclosed.
+var ErrUseLastResponse = errors.New("net/http: use last response")
+
+// checkRedirect calls either the user's configured CheckRedirect
+// function, or the default.
+func (c *Client) checkRedirect(req *Request, via []*Request) error {
+ fn := c.CheckRedirect
+ if fn == nil {
+ fn = defaultCheckRedirect
+ }
+ return fn(req, via)
+}
+
+// redirectBehavior describes what should happen when the
+// client encounters a 3xx status code from the server.
+func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool) {
+ switch resp.StatusCode {
+ case 301, 302, 303:
+ redirectMethod = reqMethod
+ shouldRedirect = true
+ includeBody = false
+
+ // RFC 2616 allowed automatic redirection only with GET and
+ // HEAD requests. RFC 7231 lifts this restriction, but we still
+ // restrict other methods to GET to maintain compatibility.
+ // See Issue 18570.
+ if reqMethod != "GET" && reqMethod != "HEAD" {
+ redirectMethod = "GET"
+ }
+ case 307, 308:
+ redirectMethod = reqMethod
+ shouldRedirect = true
+ includeBody = true
+
+ if ireq.GetBody == nil && ireq.outgoingLength() != 0 {
+ // We had a request body, and 307/308 require
+ // re-sending it, but GetBody is not defined. So just
+ // return this response to the user instead of an
+ // error, like we did in Go 1.7 and earlier.
+ shouldRedirect = false
+ }
+ }
+ return redirectMethod, shouldRedirect, includeBody
+}
+
+// urlErrorOp returns the (*url.Error).Op value to use for the
+// provided (*Request).Method value.
+func urlErrorOp(method string) string {
+ if method == "" {
+ return "Get"
+ }
+ if lowerMethod, ok := ascii.ToLower(method); ok {
+ return method[:1] + lowerMethod[1:]
+ }
+ return method
+}
+
+// Do sends an HTTP request and returns an HTTP response, following
+// policy (such as redirects, cookies, auth) as configured on the
+// client.
+//
+// An error is returned if caused by client policy (such as
+// CheckRedirect), or failure to speak HTTP (such as a network
+// connectivity problem). A non-2xx status code doesn't cause an
+// error.
+//
+// If the returned error is nil, the [Response] will contain a non-nil
+// Body which the user is expected to close. If the Body is not both
+// read to EOF and closed, the [Client]'s underlying [RoundTripper]
+// (typically [Transport]) may not be able to re-use a persistent TCP
+// connection to the server for a subsequent "keep-alive" request.
+//
+// The request Body, if non-nil, will be closed by the underlying
+// Transport, even on errors. The Body may be closed asynchronously after
+// Do returns.
+//
+// On error, any Response can be ignored. A non-nil Response with a
+// non-nil error only occurs when CheckRedirect fails, and even then
+// the returned [Response.Body] is already closed.
+//
+// Generally [Get], [Post], or [PostForm] will be used instead of Do.
+//
+// If the server replies with a redirect, the Client first uses the
+// CheckRedirect function to determine whether the redirect should be
+// followed. If permitted, a 301, 302, or 303 redirect causes
+// subsequent requests to use HTTP method GET
+// (or HEAD if the original request was HEAD), with no body.
+// A 307 or 308 redirect preserves the original HTTP method and body,
+// provided that the [Request.GetBody] function is defined.
+// The [NewRequest] function automatically sets GetBody for common
+// standard library body types.
+//
+// Any returned error will be of type [*url.Error]. The url.Error
+// value's Timeout method will report true if the request timed out.
+func (c *Client) Do(req *Request) (*Response, error) {
+ return c.do(req)
+}
+
+var testHookClientDoResult func(retres *Response, reterr error)
+
+func (c *Client) do(req *Request) (retres *Response, reterr error) {
+ if testHookClientDoResult != nil {
+ defer func() { testHookClientDoResult(retres, reterr) }()
+ }
+ if req.URL == nil {
+ req.closeBody()
+ return nil, &url.Error{
+ Op: urlErrorOp(req.Method),
+ Err: errors.New("http: nil Request.URL"),
+ }
+ }
+
+ var (
+ deadline = c.deadline()
+ reqs []*Request
+ resp *Response
+ copyHeaders = c.makeHeadersCopier(req)
+ reqBodyClosed = false // have we closed the current req.Body?
+
+ // Redirect behavior:
+ redirectMethod string
+ includeBody bool
+ )
+ uerr := func(err error) error {
+ // the body may have been closed already by c.send()
+ if !reqBodyClosed {
+ req.closeBody()
+ }
+ var urlStr string
+ if resp != nil && resp.Request != nil {
+ urlStr = stripPassword(resp.Request.URL)
+ } else {
+ urlStr = stripPassword(req.URL)
+ }
+ return &url.Error{
+ Op: urlErrorOp(reqs[0].Method),
+ URL: urlStr,
+ Err: err,
+ }
+ }
+ for {
+ // For all but the first request, create the next
+ // request hop and replace req.
+ if len(reqs) > 0 {
+ loc := resp.Header.Get("Location")
+ if loc == "" {
+ // While most 3xx responses include a Location, it is not
+ // required and 3xx responses without a Location have been
+ // observed in the wild. See issues #17773 and #49281.
+ return resp, nil
+ }
+ u, err := req.URL.Parse(loc)
+ if err != nil {
+ resp.closeBody()
+ return nil, uerr(fmt.Errorf("failed to parse Location header %q: %v", loc, err))
+ }
+ host := ""
+ if req.Host != "" && req.Host != req.URL.Host {
+ // If the caller specified a custom Host header and the
+ // redirect location is relative, preserve the Host header
+ // through the redirect. See issue #22233.
+ if u, _ := url.Parse(loc); u != nil && !u.IsAbs() {
+ host = req.Host
+ }
+ }
+ ireq := reqs[0]
+ req = &Request{
+ Method: redirectMethod,
+ Response: resp,
+ URL: u,
+ Header: make(Header),
+ Host: host,
+ Cancel: ireq.Cancel,
+ ctx: ireq.ctx,
+ }
+ if includeBody && ireq.GetBody != nil {
+ req.Body, err = ireq.GetBody()
+ if err != nil {
+ resp.closeBody()
+ return nil, uerr(err)
+ }
+ req.ContentLength = ireq.ContentLength
+ }
+
+ // Copy original headers before setting the Referer,
+ // in case the user set Referer on their first request.
+ // If they really want to override, they can do it in
+ // their CheckRedirect func.
+ copyHeaders(req)
+
+ // Add the Referer header from the most recent
+ // request URL to the new one, if it's not https->http:
+ if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL, req.Header.Get("Referer")); ref != "" {
+ req.Header.Set("Referer", ref)
+ }
+ err = c.checkRedirect(req, reqs)
+
+ // Sentinel error to let users select the
+ // previous response, without closing its
+ // body. See Issue 10069.
+ if err == ErrUseLastResponse {
+ return resp, nil
+ }
+
+ // Close the previous response's body. But
+ // read at least some of the body so if it's
+ // small the underlying TCP connection will be
+ // re-used. No need to check for errors: if it
+ // fails, the Transport won't reuse it anyway.
+ const maxBodySlurpSize = 2 << 10
+ if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
+ io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
+ }
+ resp.Body.Close()
+
+ if err != nil {
+ // Special case for Go 1 compatibility: return both the response
+ // and an error if the CheckRedirect function failed.
+ // See https://golang.org/issue/3795
+ // The resp.Body has already been closed.
+ ue := uerr(err)
+ ue.(*url.Error).URL = loc
+ return resp, ue
+ }
+ }
+
+ reqs = append(reqs, req)
+ var err error
+ var didTimeout func() bool
+ if resp, didTimeout, err = c.send(req, deadline); err != nil {
+ // c.send() always closes req.Body
+ reqBodyClosed = true
+ if !deadline.IsZero() && didTimeout() {
+ err = &httpError{
+ err: err.Error() + " (Client.Timeout exceeded while awaiting headers)",
+ timeout: true,
+ }
+ }
+ return nil, uerr(err)
+ }
+
+ var shouldRedirect bool
+ redirectMethod, shouldRedirect, includeBody = redirectBehavior(req.Method, resp, reqs[0])
+ if !shouldRedirect {
+ return resp, nil
+ }
+
+ req.closeBody()
+ }
+}
+
+// makeHeadersCopier makes a function that copies headers from the
+// initial Request, ireq. For every redirect, this function must be called
+// so that it can copy headers into the upcoming Request.
+func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
+ // The headers to copy are from the very initial request.
+ // We use a closured callback to keep a reference to these original headers.
+ var (
+ ireqhdr = cloneOrMakeHeader(ireq.Header)
+ icookies map[string][]*Cookie
+ )
+ if c.Jar != nil && ireq.Header.Get("Cookie") != "" {
+ icookies = make(map[string][]*Cookie)
+ for _, c := range ireq.Cookies() {
+ icookies[c.Name] = append(icookies[c.Name], c)
+ }
+ }
+
+ preq := ireq // The previous request
+ return func(req *Request) {
+ // If Jar is present and there was some initial cookies provided
+ // via the request header, then we may need to alter the initial
+ // cookies as we follow redirects since each redirect may end up
+ // modifying a pre-existing cookie.
+ //
+ // Since cookies already set in the request header do not contain
+ // information about the original domain and path, the logic below
+ // assumes any new set cookies override the original cookie
+ // regardless of domain or path.
+ //
+ // See https://golang.org/issue/17494
+ if c.Jar != nil && icookies != nil {
+ var changed bool
+ resp := req.Response // The response that caused the upcoming redirect
+ for _, c := range resp.Cookies() {
+ if _, ok := icookies[c.Name]; ok {
+ delete(icookies, c.Name)
+ changed = true
+ }
+ }
+ if changed {
+ ireqhdr.Del("Cookie")
+ var ss []string
+ for _, cs := range icookies {
+ for _, c := range cs {
+ ss = append(ss, c.Name+"="+c.Value)
+ }
+ }
+ sort.Strings(ss) // Ensure deterministic headers
+ ireqhdr.Set("Cookie", strings.Join(ss, "; "))
+ }
+ }
+
+ // Copy the initial request's Header values
+ // (at least the safe ones).
+ for k, vv := range ireqhdr {
+ if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
+ req.Header[k] = vv
+ }
+ }
+
+ preq = req // Update previous Request with the current request
+ }
+}
+
+func defaultCheckRedirect(req *Request, via []*Request) error {
+ if len(via) >= 10 {
+ return errors.New("stopped after 10 redirects")
+ }
+ return nil
+}
+
+// Post issues a POST to the specified URL.
+//
+// Caller should close resp.Body when done reading from it.
+//
+// If the provided body is an [io.Closer], it is closed after the
+// request.
+//
+// Post is a wrapper around DefaultClient.Post.
+//
+// To set custom headers, use [NewRequest] and DefaultClient.Do.
+//
+// See the [Client.Do] method documentation for details on how redirects
+// are handled.
+//
+// To make a request with a specified context.Context, use [NewRequestWithContext]
+// and DefaultClient.Do.
+func Post(url, contentType string, body io.Reader) (resp *Response, err error) {
+ return DefaultClient.Post(url, contentType, body)
+}
+
+// Post issues a POST to the specified URL.
+//
+// Caller should close resp.Body when done reading from it.
+//
+// If the provided body is an [io.Closer], it is closed after the
+// request.
+//
+// To set custom headers, use [NewRequest] and [Client.Do].
+//
+// To make a request with a specified context.Context, use [NewRequestWithContext]
+// and [Client.Do].
+//
+// See the Client.Do method documentation for details on how redirects
+// are handled.
+func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error) {
+ req, err := NewRequest("POST", url, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", contentType)
+ return c.Do(req)
+}
+
+// PostForm issues a POST to the specified URL, with data's keys and
+// values URL-encoded as the request body.
+//
+// The Content-Type header is set to application/x-www-form-urlencoded.
+// To set other headers, use [NewRequest] and DefaultClient.Do.
+//
+// When err is nil, resp always contains a non-nil resp.Body.
+// Caller should close resp.Body when done reading from it.
+//
+// PostForm is a wrapper around DefaultClient.PostForm.
+//
+// See the [Client.Do] method documentation for details on how redirects
+// are handled.
+//
+// To make a request with a specified [context.Context], use [NewRequestWithContext]
+// and DefaultClient.Do.
+func PostForm(url string, data url.Values) (resp *Response, err error) {
+ return DefaultClient.PostForm(url, data)
+}
+
+// PostForm issues a POST to the specified URL,
+// with data's keys and values URL-encoded as the request body.
+//
+// The Content-Type header is set to application/x-www-form-urlencoded.
+// To set other headers, use [NewRequest] and [Client.Do].
+//
+// When err is nil, resp always contains a non-nil resp.Body.
+// Caller should close resp.Body when done reading from it.
+//
+// See the Client.Do method documentation for details on how redirects
+// are handled.
+//
+// To make a request with a specified context.Context, use [NewRequestWithContext]
+// and Client.Do.
+func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
+ return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
+}
+
+// Head issues a HEAD to the specified URL. If the response is one of
+// the following redirect codes, Head follows the redirect, up to a
+// maximum of 10 redirects:
+//
+// 301 (Moved Permanently)
+// 302 (Found)
+// 303 (See Other)
+// 307 (Temporary Redirect)
+// 308 (Permanent Redirect)
+//
+// Head is a wrapper around DefaultClient.Head.
+//
+// To make a request with a specified [context.Context], use [NewRequestWithContext]
+// and DefaultClient.Do.
+func Head(url string) (resp *Response, err error) {
+ return DefaultClient.Head(url)
+}
+
+// Head issues a HEAD to the specified URL. If the response is one of the
+// following redirect codes, Head follows the redirect after calling the
+// [Client.CheckRedirect] function:
+//
+// 301 (Moved Permanently)
+// 302 (Found)
+// 303 (See Other)
+// 307 (Temporary Redirect)
+// 308 (Permanent Redirect)
+//
+// To make a request with a specified [context.Context], use [NewRequestWithContext]
+// and [Client.Do].
+func (c *Client) Head(url string) (resp *Response, err error) {
+ req, err := NewRequest("HEAD", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return c.Do(req)
+}
+
+// CloseIdleConnections closes any connections on its [Transport] which
+// were previously connected from previous requests but are now
+// sitting idle in a "keep-alive" state. It does not interrupt any
+// connections currently in use.
+//
+// If [Client.Transport] does not have a [Client.CloseIdleConnections] method
+// then this method does nothing.
+func (c *Client) CloseIdleConnections() {
+ type closeIdler interface {
+ CloseIdleConnections()
+ }
+ if tr, ok := c.transport().(closeIdler); ok {
+ tr.CloseIdleConnections()
+ }
+}
+
+// cancelTimerBody is an io.ReadCloser that wraps rc with two features:
+// 1. On Read error or close, the stop func is called.
+// 2. On Read failure, if reqDidTimeout is true, the error is wrapped and
+// marked as net.Error that hit its timeout.
+type cancelTimerBody struct {
+ stop func() // stops the time.Timer waiting to cancel the request
+ rc io.ReadCloser
+ reqDidTimeout func() bool
+}
+
+func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
+ n, err = b.rc.Read(p)
+ if err == nil {
+ return n, nil
+ }
+ if err == io.EOF {
+ return n, err
+ }
+ if b.reqDidTimeout() {
+ err = &httpError{
+ err: err.Error() + " (Client.Timeout or context cancellation while reading body)",
+ timeout: true,
+ }
+ }
+ return n, err
+}
+
+func (b *cancelTimerBody) Close() error {
+ err := b.rc.Close()
+ b.stop()
+ return err
+}
+
+func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool {
+ switch CanonicalHeaderKey(headerKey) {
+ case "Authorization", "Www-Authenticate", "Cookie", "Cookie2":
+ // Permit sending auth/cookie headers from "foo.com"
+ // to "sub.foo.com".
+
+ // Note that we don't send all cookies to subdomains
+ // automatically. This function is only used for
+ // Cookies set explicitly on the initial outgoing
+ // client request. Cookies automatically added via the
+ // CookieJar mechanism continue to follow each
+ // cookie's scope as set by Set-Cookie. But for
+ // outgoing requests with the Cookie header set
+ // directly, we don't know their scope, so we assume
+ // it's for *.domain.com.
+
+ ihost := idnaASCIIFromURL(initial)
+ dhost := idnaASCIIFromURL(dest)
+ return isDomainOrSubdomain(dhost, ihost)
+ }
+ // All other headers are copied:
+ return true
+}
+
+// isDomainOrSubdomain reports whether sub is a subdomain (or exact
+// match) of the parent domain.
+//
+// Both domains must already be in canonical form.
+func isDomainOrSubdomain(sub, parent string) bool {
+ if sub == parent {
+ return true
+ }
+ // If sub contains a :, it's probably an IPv6 address (and is definitely not a hostname).
+ // Don't check the suffix in this case, to avoid matching the contents of a IPv6 zone.
+ // For example, "::1%.www.example.com" is not a subdomain of "www.example.com".
+ if strings.ContainsAny(sub, ":%") {
+ return false
+ }
+ // If sub is "foo.example.com" and parent is "example.com",
+ // that means sub must end in "."+parent.
+ // Do it without allocating.
+ if !strings.HasSuffix(sub, parent) {
+ return false
+ }
+ return sub[len(sub)-len(parent)-1] == '.'
+}
+
+func stripPassword(u *url.URL) string {
+ _, passSet := u.User.Password()
+ if passSet {
+ return strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
+ }
+ return u.String()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/client_test.go b/platform/dbops/binaries/go/go/src/net/http/client_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e2a1cbbdea10daae766576ba2492d9a35a6590ac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/client_test.go
@@ -0,0 +1,2130 @@
+// 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.
+
+// Tests for client.go
+
+package http_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "log"
+ "net"
+ . "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Last-Modified", "sometime")
+ fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
+})
+
+// pedanticReadAll works like io.ReadAll but additionally
+// verifies that r obeys the documented io.Reader contract.
+func pedanticReadAll(r io.Reader) (b []byte, err error) {
+ var bufa [64]byte
+ buf := bufa[:]
+ for {
+ n, err := r.Read(buf)
+ if n == 0 && err == nil {
+ return nil, fmt.Errorf("Read: n=0 with err=nil")
+ }
+ b = append(b, buf[:n]...)
+ if err == io.EOF {
+ n, err := r.Read(buf)
+ if n != 0 || err != io.EOF {
+ return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
+ }
+ return b, nil
+ }
+ if err != nil {
+ return b, err
+ }
+ }
+}
+
+func TestClient(t *testing.T) { run(t, testClient) }
+func testClient(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, robotsTxtHandler).ts
+
+ c := ts.Client()
+ r, err := c.Get(ts.URL)
+ var b []byte
+ if err == nil {
+ b, err = pedanticReadAll(r.Body)
+ r.Body.Close()
+ }
+ if err != nil {
+ t.Error(err)
+ } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
+ t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
+ }
+}
+
+func TestClientHead(t *testing.T) { run(t, testClientHead) }
+func testClientHead(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, robotsTxtHandler)
+ r, err := cst.c.Head(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := r.Header["Last-Modified"]; !ok {
+ t.Error("Last-Modified header not found.")
+ }
+}
+
+type recordingTransport struct {
+ req *Request
+}
+
+func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
+ t.req = req
+ return nil, errors.New("dummy impl")
+}
+
+func TestGetRequestFormat(t *testing.T) {
+ setParallel(t)
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+ url := "http://dummy.faketld/"
+ client.Get(url) // Note: doesn't hit network
+ if tr.req.Method != "GET" {
+ t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
+ }
+ if tr.req.URL.String() != url {
+ t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
+ }
+ if tr.req.Header == nil {
+ t.Errorf("expected non-nil request Header")
+ }
+}
+
+func TestPostRequestFormat(t *testing.T) {
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+
+ url := "http://dummy.faketld/"
+ json := `{"key":"value"}`
+ b := strings.NewReader(json)
+ client.Post(url, "application/json", b) // Note: doesn't hit network
+
+ if tr.req.Method != "POST" {
+ t.Errorf("got method %q, want %q", tr.req.Method, "POST")
+ }
+ if tr.req.URL.String() != url {
+ t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
+ }
+ if tr.req.Header == nil {
+ t.Fatalf("expected non-nil request Header")
+ }
+ if tr.req.Close {
+ t.Error("got Close true, want false")
+ }
+ if g, e := tr.req.ContentLength, int64(len(json)); g != e {
+ t.Errorf("got ContentLength %d, want %d", g, e)
+ }
+}
+
+func TestPostFormRequestFormat(t *testing.T) {
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+
+ urlStr := "http://dummy.faketld/"
+ form := make(url.Values)
+ form.Set("foo", "bar")
+ form.Add("foo", "bar2")
+ form.Set("bar", "baz")
+ client.PostForm(urlStr, form) // Note: doesn't hit network
+
+ if tr.req.Method != "POST" {
+ t.Errorf("got method %q, want %q", tr.req.Method, "POST")
+ }
+ if tr.req.URL.String() != urlStr {
+ t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
+ }
+ if tr.req.Header == nil {
+ t.Fatalf("expected non-nil request Header")
+ }
+ if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
+ t.Errorf("got Content-Type %q, want %q", g, e)
+ }
+ if tr.req.Close {
+ t.Error("got Close true, want false")
+ }
+ // Depending on map iteration, body can be either of these.
+ expectedBody := "foo=bar&foo=bar2&bar=baz"
+ expectedBody1 := "bar=baz&foo=bar&foo=bar2"
+ if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
+ t.Errorf("got ContentLength %d, want %d", g, e)
+ }
+ bodyb, err := io.ReadAll(tr.req.Body)
+ if err != nil {
+ t.Fatalf("ReadAll on req.Body: %v", err)
+ }
+ if g := string(bodyb); g != expectedBody && g != expectedBody1 {
+ t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
+ }
+}
+
+func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
+func testClientRedirects(t *testing.T, mode testMode) {
+ var ts *httptest.Server
+ ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ n, _ := strconv.Atoi(r.FormValue("n"))
+ // Test Referer header. (7 is arbitrary position to test at)
+ if n == 7 {
+ if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
+ t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
+ }
+ }
+ if n < 15 {
+ Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
+ return
+ }
+ fmt.Fprintf(w, "n=%d", n)
+ })).ts
+
+ c := ts.Client()
+ _, err := c.Get(ts.URL)
+ if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
+ t.Errorf("with default client Get, expected error %q, got %q", e, g)
+ }
+
+ // HEAD request should also have the ability to follow redirects.
+ _, err = c.Head(ts.URL)
+ if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
+ t.Errorf("with default client Head, expected error %q, got %q", e, g)
+ }
+
+ // Do should also follow redirects.
+ greq, _ := NewRequest("GET", ts.URL, nil)
+ _, err = c.Do(greq)
+ if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
+ t.Errorf("with default client Do, expected error %q, got %q", e, g)
+ }
+
+ // Requests with an empty Method should also redirect (Issue 12705)
+ greq.Method = ""
+ _, err = c.Do(greq)
+ if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
+ t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
+ }
+
+ var checkErr error
+ var lastVia []*Request
+ var lastReq *Request
+ c.CheckRedirect = func(req *Request, via []*Request) error {
+ lastReq = req
+ lastVia = via
+ return checkErr
+ }
+ res, err := c.Get(ts.URL)
+ if err != nil {
+ t.Fatalf("Get error: %v", err)
+ }
+ res.Body.Close()
+ finalURL := res.Request.URL.String()
+ if e, g := "", fmt.Sprintf("%v", err); e != g {
+ t.Errorf("with custom client, expected error %q, got %q", e, g)
+ }
+ if !strings.HasSuffix(finalURL, "/?n=15") {
+ t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
+ }
+ if e, g := 15, len(lastVia); e != g {
+ t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
+ }
+
+ // Test that Request.Cancel is propagated between requests (Issue 14053)
+ creq, _ := NewRequest("HEAD", ts.URL, nil)
+ cancel := make(chan struct{})
+ creq.Cancel = cancel
+ if _, err := c.Do(creq); err != nil {
+ t.Fatal(err)
+ }
+ if lastReq == nil {
+ t.Fatal("didn't see redirect")
+ }
+ if lastReq.Cancel != cancel {
+ t.Errorf("expected lastReq to have the cancel channel set on the initial req")
+ }
+
+ checkErr = errors.New("no redirects allowed")
+ res, err = c.Get(ts.URL)
+ if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
+ t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
+ }
+ if res == nil {
+ t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
+ }
+ res.Body.Close()
+ if res.Header.Get("Location") == "" {
+ t.Errorf("no Location header in Response")
+ }
+}
+
+// Tests that Client redirects' contexts are derived from the original request's context.
+func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
+func testClientRedirectsContext(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ Redirect(w, r, "/", StatusTemporaryRedirect)
+ })).ts
+
+ ctx, cancel := context.WithCancel(context.Background())
+ c := ts.Client()
+ c.CheckRedirect = func(req *Request, via []*Request) error {
+ cancel()
+ select {
+ case <-req.Context().Done():
+ return nil
+ case <-time.After(5 * time.Second):
+ return errors.New("redirected request's context never expired after root request canceled")
+ }
+ }
+ req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
+ _, err := c.Do(req)
+ ue, ok := err.(*url.Error)
+ if !ok {
+ t.Fatalf("got error %T; want *url.Error", err)
+ }
+ if ue.Err != context.Canceled {
+ t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
+ }
+}
+
+type redirectTest struct {
+ suffix string
+ want int // response code
+ redirectBody string
+}
+
+func TestPostRedirects(t *testing.T) {
+ postRedirectTests := []redirectTest{
+ {"/", 200, "first"},
+ {"/?code=301&next=302", 200, "c301"},
+ {"/?code=302&next=302", 200, "c302"},
+ {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
+ {"/?code=304", 304, "c304"},
+ {"/?code=305", 305, "c305"},
+ {"/?code=307&next=303,308,302", 200, "c307"},
+ {"/?code=308&next=302,301", 200, "c308"},
+ {"/?code=404", 404, "c404"},
+ }
+
+ wantSegments := []string{
+ `POST / "first"`,
+ `POST /?code=301&next=302 "c301"`,
+ `GET /?code=302 ""`,
+ `GET / ""`,
+ `POST /?code=302&next=302 "c302"`,
+ `GET /?code=302 ""`,
+ `GET / ""`,
+ `POST /?code=303&next=301 "c303wc301"`,
+ `GET /?code=301 ""`,
+ `GET / ""`,
+ `POST /?code=304 "c304"`,
+ `POST /?code=305 "c305"`,
+ `POST /?code=307&next=303,308,302 "c307"`,
+ `POST /?code=303&next=308,302 "c307"`,
+ `GET /?code=308&next=302 ""`,
+ `GET /?code=302 "c307"`,
+ `GET / ""`,
+ `POST /?code=308&next=302,301 "c308"`,
+ `POST /?code=302&next=301 "c308"`,
+ `GET /?code=301 ""`,
+ `GET / ""`,
+ `POST /?code=404 "c404"`,
+ }
+ want := strings.Join(wantSegments, "\n")
+ run(t, func(t *testing.T, mode testMode) {
+ testRedirectsByMethod(t, mode, "POST", postRedirectTests, want)
+ })
+}
+
+func TestDeleteRedirects(t *testing.T) {
+ deleteRedirectTests := []redirectTest{
+ {"/", 200, "first"},
+ {"/?code=301&next=302,308", 200, "c301"},
+ {"/?code=302&next=302", 200, "c302"},
+ {"/?code=303", 200, "c303"},
+ {"/?code=307&next=301,308,303,302,304", 304, "c307"},
+ {"/?code=308&next=307", 200, "c308"},
+ {"/?code=404", 404, "c404"},
+ }
+
+ wantSegments := []string{
+ `DELETE / "first"`,
+ `DELETE /?code=301&next=302,308 "c301"`,
+ `GET /?code=302&next=308 ""`,
+ `GET /?code=308 ""`,
+ `GET / "c301"`,
+ `DELETE /?code=302&next=302 "c302"`,
+ `GET /?code=302 ""`,
+ `GET / ""`,
+ `DELETE /?code=303 "c303"`,
+ `GET / ""`,
+ `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
+ `DELETE /?code=301&next=308,303,302,304 "c307"`,
+ `GET /?code=308&next=303,302,304 ""`,
+ `GET /?code=303&next=302,304 "c307"`,
+ `GET /?code=302&next=304 ""`,
+ `GET /?code=304 ""`,
+ `DELETE /?code=308&next=307 "c308"`,
+ `DELETE /?code=307 "c308"`,
+ `DELETE / "c308"`,
+ `DELETE /?code=404 "c404"`,
+ }
+ want := strings.Join(wantSegments, "\n")
+ run(t, func(t *testing.T, mode testMode) {
+ testRedirectsByMethod(t, mode, "DELETE", deleteRedirectTests, want)
+ })
+}
+
+func testRedirectsByMethod(t *testing.T, mode testMode, method string, table []redirectTest, want string) {
+ var log struct {
+ sync.Mutex
+ bytes.Buffer
+ }
+ var ts *httptest.Server
+ ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ log.Lock()
+ slurp, _ := io.ReadAll(r.Body)
+ fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
+ if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
+ fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
+ }
+ log.WriteByte('\n')
+ log.Unlock()
+ urlQuery := r.URL.Query()
+ if v := urlQuery.Get("code"); v != "" {
+ location := ts.URL
+ if final := urlQuery.Get("next"); final != "" {
+ first, rest, _ := strings.Cut(final, ",")
+ location = fmt.Sprintf("%s?code=%s", location, first)
+ if rest != "" {
+ location = fmt.Sprintf("%s&next=%s", location, rest)
+ }
+ }
+ code, _ := strconv.Atoi(v)
+ if code/100 == 3 {
+ w.Header().Set("Location", location)
+ }
+ w.WriteHeader(code)
+ }
+ })).ts
+
+ c := ts.Client()
+ for _, tt := range table {
+ content := tt.redirectBody
+ req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
+ req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
+ res, err := c.Do(req)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != tt.want {
+ t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
+ }
+ }
+ log.Lock()
+ got := log.String()
+ log.Unlock()
+
+ got = strings.TrimSpace(got)
+ want = strings.TrimSpace(want)
+
+ if got != want {
+ got, want, lines := removeCommonLines(got, want)
+ t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
+ }
+}
+
+func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
+ for {
+ nl := strings.IndexByte(a, '\n')
+ if nl < 0 {
+ return a, b, commonLines
+ }
+ line := a[:nl+1]
+ if !strings.HasPrefix(b, line) {
+ return a, b, commonLines
+ }
+ commonLines++
+ a = a[len(line):]
+ b = b[len(line):]
+ }
+}
+
+func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
+func testClientRedirectUseResponse(t *testing.T, mode testMode) {
+ const body = "Hello, world."
+ var ts *httptest.Server
+ ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if strings.Contains(r.URL.Path, "/other") {
+ io.WriteString(w, "wrong body")
+ } else {
+ w.Header().Set("Location", ts.URL+"/other")
+ w.WriteHeader(StatusFound)
+ io.WriteString(w, body)
+ }
+ })).ts
+
+ c := ts.Client()
+ c.CheckRedirect = func(req *Request, via []*Request) error {
+ if req.Response == nil {
+ t.Error("expected non-nil Request.Response")
+ }
+ return ErrUseLastResponse
+ }
+ res, err := c.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != StatusFound {
+ t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
+ }
+ defer res.Body.Close()
+ slurp, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(slurp) != body {
+ t.Errorf("body = %q; want %q", slurp, body)
+ }
+}
+
+// Issues 17773 and 49281: don't follow a 3xx if the response doesn't
+// have a Location header.
+func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
+func testClientRedirectNoLocation(t *testing.T, mode testMode) {
+ for _, code := range []int{301, 308} {
+ t.Run(fmt.Sprint(code), func(t *testing.T) {
+ setParallel(t)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Foo", "Bar")
+ w.WriteHeader(code)
+ }))
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != code {
+ t.Errorf("status = %d; want %d", res.StatusCode, code)
+ }
+ if got := res.Header.Get("Foo"); got != "Bar" {
+ t.Errorf("Foo header = %q; want Bar", got)
+ }
+ })
+ }
+}
+
+// Don't follow a 307/308 if we can't resent the request body.
+func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
+func testClientRedirect308NoGetBody(t *testing.T, mode testMode) {
+ const fakeURL = "https://localhost:1234/" // won't be hit
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Location", fakeURL)
+ w.WriteHeader(308)
+ })).ts
+ req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := ts.Client()
+ req.GetBody = nil // so it can't rewind.
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != 308 {
+ t.Errorf("status = %d; want %d", res.StatusCode, 308)
+ }
+ if got := res.Header.Get("Location"); got != fakeURL {
+ t.Errorf("Location header = %q; want %q", got, fakeURL)
+ }
+}
+
+var expectedCookies = []*Cookie{
+ {Name: "ChocolateChip", Value: "tasty"},
+ {Name: "First", Value: "Hit"},
+ {Name: "Second", Value: "Hit"},
+}
+
+var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
+ for _, cookie := range r.Cookies() {
+ SetCookie(w, cookie)
+ }
+ if r.URL.Path == "/" {
+ SetCookie(w, expectedCookies[1])
+ Redirect(w, r, "/second", StatusMovedPermanently)
+ } else {
+ SetCookie(w, expectedCookies[2])
+ w.Write([]byte("hello"))
+ }
+})
+
+func TestClientSendsCookieFromJar(t *testing.T) {
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+ client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
+ us := "http://dummy.faketld/"
+ u, _ := url.Parse(us)
+ client.Jar.SetCookies(u, expectedCookies)
+
+ client.Get(us) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+
+ client.Head(us) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+
+ client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+
+ client.PostForm(us, url.Values{}) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+
+ req, _ := NewRequest("GET", us, nil)
+ client.Do(req) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+
+ req, _ = NewRequest("POST", us, nil)
+ client.Do(req) // Note: doesn't hit network
+ matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
+}
+
+// Just enough correctness for our redirect tests. Uses the URL.Host as the
+// scope of all cookies.
+type TestJar struct {
+ m sync.Mutex
+ perURL map[string][]*Cookie
+}
+
+func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
+ j.m.Lock()
+ defer j.m.Unlock()
+ if j.perURL == nil {
+ j.perURL = make(map[string][]*Cookie)
+ }
+ j.perURL[u.Host] = cookies
+}
+
+func (j *TestJar) Cookies(u *url.URL) []*Cookie {
+ j.m.Lock()
+ defer j.m.Unlock()
+ return j.perURL[u.Host]
+}
+
+func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
+func testRedirectCookiesJar(t *testing.T, mode testMode) {
+ var ts *httptest.Server
+ ts = newClientServerTest(t, mode, echoCookiesRedirectHandler).ts
+ c := ts.Client()
+ c.Jar = new(TestJar)
+ u, _ := url.Parse(ts.URL)
+ c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
+ resp, err := c.Get(ts.URL)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ resp.Body.Close()
+ matchReturnedCookies(t, expectedCookies, resp.Cookies())
+}
+
+func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
+ if len(given) != len(expected) {
+ t.Logf("Received cookies: %v", given)
+ t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
+ }
+ for _, ec := range expected {
+ foundC := false
+ for _, c := range given {
+ if ec.Name == c.Name && ec.Value == c.Value {
+ foundC = true
+ break
+ }
+ }
+ if !foundC {
+ t.Errorf("Missing cookie %v", ec)
+ }
+ }
+}
+
+func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
+func testJarCalls(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ pathSuffix := r.RequestURI[1:]
+ if r.RequestURI == "/nosetcookie" {
+ return // don't set cookies for this path
+ }
+ SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
+ if r.RequestURI == "/" {
+ Redirect(w, r, "http://secondhost.fake/secondpath", 302)
+ }
+ })).ts
+ jar := new(RecordingJar)
+ c := ts.Client()
+ c.Jar = jar
+ c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
+ return net.Dial("tcp", ts.Listener.Addr().String())
+ }
+ _, err := c.Get("http://firsthost.fake/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = c.Get("http://firsthost.fake/nosetcookie")
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := jar.log.String()
+ want := `Cookies("http://firsthost.fake/")
+SetCookie("http://firsthost.fake/", [name=val])
+Cookies("http://secondhost.fake/secondpath")
+SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
+Cookies("http://firsthost.fake/nosetcookie")
+`
+ if got != want {
+ t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
+ }
+}
+
+// RecordingJar keeps a log of calls made to it, without
+// tracking any cookies.
+type RecordingJar struct {
+ mu sync.Mutex
+ log bytes.Buffer
+}
+
+func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
+ j.logf("SetCookie(%q, %v)\n", u, cookies)
+}
+
+func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
+ j.logf("Cookies(%q)\n", u)
+ return nil
+}
+
+func (j *RecordingJar) logf(format string, args ...any) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ fmt.Fprintf(&j.log, format, args...)
+}
+
+func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
+func testStreamingGet(t *testing.T, mode testMode) {
+ say := make(chan string)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.(Flusher).Flush()
+ for str := range say {
+ w.Write([]byte(str))
+ w.(Flusher).Flush()
+ }
+ }))
+
+ c := cst.c
+ res, err := c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var buf [10]byte
+ for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
+ say <- str
+ n, err := io.ReadFull(res.Body, buf[0:len(str)])
+ if err != nil {
+ t.Fatalf("ReadFull on %q: %v", str, err)
+ }
+ if n != len(str) {
+ t.Fatalf("Receiving %q, only read %d bytes", str, n)
+ }
+ got := string(buf[0:n])
+ if got != str {
+ t.Fatalf("Expected %q, got %q", str, got)
+ }
+ }
+ close(say)
+ _, err = io.ReadFull(res.Body, buf[0:1])
+ if err != io.EOF {
+ t.Fatalf("at end expected EOF, got %v", err)
+ }
+}
+
+type writeCountingConn struct {
+ net.Conn
+ count *int
+}
+
+func (c *writeCountingConn) Write(p []byte) (int, error) {
+ *c.count++
+ return c.Conn.Write(p)
+}
+
+// TestClientWrites verifies that client requests are buffered and we
+// don't send a TCP packet per line of the http request + body.
+func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
+func testClientWrites(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ })).ts
+
+ writes := 0
+ dialer := func(netz string, addr string) (net.Conn, error) {
+ c, err := net.Dial(netz, addr)
+ if err == nil {
+ c = &writeCountingConn{c, &writes}
+ }
+ return c, err
+ }
+ c := ts.Client()
+ c.Transport.(*Transport).Dial = dialer
+
+ _, err := c.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if writes != 1 {
+ t.Errorf("Get request did %d Write calls, want 1", writes)
+ }
+
+ writes = 0
+ _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if writes != 1 {
+ t.Errorf("Post request did %d Write calls, want 1", writes)
+ }
+}
+
+func TestClientInsecureTransport(t *testing.T) {
+ run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
+}
+func testClientInsecureTransport(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Write([]byte("Hello"))
+ }))
+ ts := cst.ts
+ errLog := new(strings.Builder)
+ ts.Config.ErrorLog = log.New(errLog, "", 0)
+
+ // TODO(bradfitz): add tests for skipping hostname checks too?
+ // would require a new cert for testing, and probably
+ // redundant with these tests.
+ c := ts.Client()
+ for _, insecure := range []bool{true, false} {
+ c.Transport.(*Transport).TLSClientConfig = &tls.Config{
+ InsecureSkipVerify: insecure,
+ }
+ res, err := c.Get(ts.URL)
+ if (err == nil) != insecure {
+ t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
+ }
+ if res != nil {
+ res.Body.Close()
+ }
+ }
+
+ cst.close()
+ if !strings.Contains(errLog.String(), "TLS handshake error") {
+ t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
+ }
+}
+
+func TestClientErrorWithRequestURI(t *testing.T) {
+ defer afterTest(t)
+ req, _ := NewRequest("GET", "http://localhost:1234/", nil)
+ req.RequestURI = "/this/field/is/illegal/and/should/error/"
+ _, err := DefaultClient.Do(req)
+ if err == nil {
+ t.Fatalf("expected an error")
+ }
+ if !strings.Contains(err.Error(), "RequestURI") {
+ t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
+ }
+}
+
+func TestClientWithCorrectTLSServerName(t *testing.T) {
+ run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
+}
+func testClientWithCorrectTLSServerName(t *testing.T, mode testMode) {
+ const serverName = "example.com"
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if r.TLS.ServerName != serverName {
+ t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
+ }
+ })).ts
+
+ c := ts.Client()
+ c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
+ if _, err := c.Get(ts.URL); err != nil {
+ t.Fatalf("expected successful TLS connection, got error: %v", err)
+ }
+}
+
+func TestClientWithIncorrectTLSServerName(t *testing.T) {
+ run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
+}
+func testClientWithIncorrectTLSServerName(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {}))
+ ts := cst.ts
+ errLog := new(strings.Builder)
+ ts.Config.ErrorLog = log.New(errLog, "", 0)
+
+ c := ts.Client()
+ c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
+ _, err := c.Get(ts.URL)
+ if err == nil {
+ t.Fatalf("expected an error")
+ }
+ if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
+ t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
+ }
+
+ cst.close()
+ if !strings.Contains(errLog.String(), "TLS handshake error") {
+ t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
+ }
+}
+
+// Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
+// when not empty.
+//
+// tls.Config.ServerName (non-empty, set to "example.com") takes
+// precedence over "some-other-host.tld" which previously incorrectly
+// took precedence. We don't actually connect to (or even resolve)
+// "some-other-host.tld", though, because of the Transport.Dial hook.
+//
+// The httptest.Server has a cert with "example.com" as its name.
+func TestTransportUsesTLSConfigServerName(t *testing.T) {
+ run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
+}
+func testTransportUsesTLSConfigServerName(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Write([]byte("Hello"))
+ })).ts
+
+ c := ts.Client()
+ tr := c.Transport.(*Transport)
+ tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
+ tr.Dial = func(netw, addr string) (net.Conn, error) {
+ return net.Dial(netw, ts.Listener.Addr().String())
+ }
+ res, err := c.Get("https://some-other-host.tld/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+}
+
+func TestResponseSetsTLSConnectionState(t *testing.T) {
+ run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
+}
+func testResponseSetsTLSConnectionState(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Write([]byte("Hello"))
+ })).ts
+
+ c := ts.Client()
+ tr := c.Transport.(*Transport)
+ tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA}
+ tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
+ tr.Dial = func(netw, addr string) (net.Conn, error) {
+ return net.Dial(netw, ts.Listener.Addr().String())
+ }
+ res, err := c.Get("https://example.com/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.TLS == nil {
+ t.Fatal("Response didn't set TLS Connection State.")
+ }
+ if got, want := res.TLS.CipherSuite, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
+ t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
+ }
+}
+
+// Check that an HTTPS client can interpret a particular TLS error
+// to determine that the server is speaking HTTP.
+// See golang.org/issue/11111.
+func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
+ run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
+}
+func testHTTPSClientDetectsHTTPServer(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
+ ts.Config.ErrorLog = quietLog
+
+ _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
+ if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
+ t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
+ }
+}
+
+// Verify Response.ContentLength is populated. https://golang.org/issue/4126
+func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
+func testClientHeadContentLength(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if v := r.FormValue("cl"); v != "" {
+ w.Header().Set("Content-Length", v)
+ }
+ }))
+ tests := []struct {
+ suffix string
+ want int64
+ }{
+ {"/?cl=1234", 1234},
+ {"/?cl=0", 0},
+ {"", -1},
+ }
+ for _, tt := range tests {
+ req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.ContentLength != tt.want {
+ t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
+ }
+ bs, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(bs) != 0 {
+ t.Errorf("Unexpected content: %q", bs)
+ }
+ }
+}
+
+func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
+func testEmptyPasswordAuth(t *testing.T, mode testMode) {
+ gopher := "gopher"
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ auth := r.Header.Get("Authorization")
+ if strings.HasPrefix(auth, "Basic ") {
+ encoded := auth[6:]
+ decoded, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := gopher + ":"
+ s := string(decoded)
+ if expected != s {
+ t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
+ }
+ } else {
+ t.Errorf("Invalid auth %q", auth)
+ }
+ })).ts
+ defer ts.Close()
+ req, err := NewRequest("GET", ts.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.URL.User = url.User(gopher)
+ c := ts.Client()
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+}
+
+func TestBasicAuth(t *testing.T) {
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+
+ url := "http://My%20User:My%20Pass@dummy.faketld/"
+ expected := "My User:My Pass"
+ client.Get(url)
+
+ if tr.req.Method != "GET" {
+ t.Errorf("got method %q, want %q", tr.req.Method, "GET")
+ }
+ if tr.req.URL.String() != url {
+ t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
+ }
+ if tr.req.Header == nil {
+ t.Fatalf("expected non-nil request Header")
+ }
+ auth := tr.req.Header.Get("Authorization")
+ if strings.HasPrefix(auth, "Basic ") {
+ encoded := auth[6:]
+ decoded, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(decoded)
+ if expected != s {
+ t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
+ }
+ } else {
+ t.Errorf("Invalid auth %q", auth)
+ }
+}
+
+func TestBasicAuthHeadersPreserved(t *testing.T) {
+ defer afterTest(t)
+ tr := &recordingTransport{}
+ client := &Client{Transport: tr}
+
+ // If Authorization header is provided, username in URL should not override it
+ url := "http://My%20User@dummy.faketld/"
+ req, err := NewRequest("GET", url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.SetBasicAuth("My User", "My Pass")
+ expected := "My User:My Pass"
+ client.Do(req)
+
+ if tr.req.Method != "GET" {
+ t.Errorf("got method %q, want %q", tr.req.Method, "GET")
+ }
+ if tr.req.URL.String() != url {
+ t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
+ }
+ if tr.req.Header == nil {
+ t.Fatalf("expected non-nil request Header")
+ }
+ auth := tr.req.Header.Get("Authorization")
+ if strings.HasPrefix(auth, "Basic ") {
+ encoded := auth[6:]
+ decoded, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(decoded)
+ if expected != s {
+ t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
+ }
+ } else {
+ t.Errorf("Invalid auth %q", auth)
+ }
+
+}
+
+func TestStripPasswordFromError(t *testing.T) {
+ client := &Client{Transport: &recordingTransport{}}
+ testCases := []struct {
+ desc string
+ in string
+ out string
+ }{
+ {
+ desc: "Strip password from error message",
+ in: "http://user:password@dummy.faketld/",
+ out: `Get "http://user:***@dummy.faketld/": dummy impl`,
+ },
+ {
+ desc: "Don't Strip password from domain name",
+ in: "http://user:password@password.faketld/",
+ out: `Get "http://user:***@password.faketld/": dummy impl`,
+ },
+ {
+ desc: "Don't Strip password from path",
+ in: "http://user:password@dummy.faketld/password",
+ out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
+ },
+ {
+ desc: "Strip escaped password",
+ in: "http://user:pa%2Fssword@dummy.faketld/",
+ out: `Get "http://user:***@dummy.faketld/": dummy impl`,
+ },
+ }
+ for _, tC := range testCases {
+ t.Run(tC.desc, func(t *testing.T) {
+ _, err := client.Get(tC.in)
+ if err.Error() != tC.out {
+ t.Errorf("Unexpected output for %q: expected %q, actual %q",
+ tC.in, tC.out, err.Error())
+ }
+ })
+ }
+}
+
+func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
+func testClientTimeout(t *testing.T, mode testMode) {
+ var (
+ mu sync.Mutex
+ nonce string // a unique per-request string
+ sawSlowNonce bool // true if the handler saw /slow?nonce=
+ )
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ _ = r.ParseForm()
+ if r.URL.Path == "/" {
+ Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
+ return
+ }
+ if r.URL.Path == "/slow" {
+ mu.Lock()
+ if r.Form.Get("nonce") == nonce {
+ sawSlowNonce = true
+ } else {
+ t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
+ }
+ mu.Unlock()
+
+ w.Write([]byte("Hello"))
+ w.(Flusher).Flush()
+ <-r.Context().Done()
+ return
+ }
+ }))
+
+ // Try to trigger a timeout after reading part of the response body.
+ // The initial timeout is empirically usually long enough on a decently fast
+ // machine, but if we undershoot we'll retry with exponentially longer
+ // timeouts until the test either passes or times out completely.
+ // This keeps the test reasonably fast in the typical case but allows it to
+ // also eventually succeed on arbitrarily slow machines.
+ timeout := 10 * time.Millisecond
+ nextNonce := 0
+ for ; ; timeout *= 2 {
+ if timeout <= 0 {
+ // The only way we can feasibly hit this while the test is running is if
+ // the request fails without actually waiting for the timeout to occur.
+ t.Fatalf("timeout overflow")
+ }
+ if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
+ t.Fatalf("failed to produce expected timeout before test deadline")
+ }
+ t.Logf("attempting test with timeout %v", timeout)
+ cst.c.Timeout = timeout
+
+ mu.Lock()
+ nonce = fmt.Sprint(nextNonce)
+ nextNonce++
+ sawSlowNonce = false
+ mu.Unlock()
+ res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
+ if err != nil {
+ if strings.Contains(err.Error(), "Client.Timeout") {
+ // Timed out before handler could respond.
+ t.Logf("timeout before response received")
+ continue
+ }
+ if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+ testenv.SkipFlaky(t, 43120)
+ }
+ t.Fatal(err)
+ }
+
+ mu.Lock()
+ ok := sawSlowNonce
+ mu.Unlock()
+ if !ok {
+ t.Fatal("handler never got /slow request, but client returned response")
+ }
+
+ _, err = io.ReadAll(res.Body)
+ res.Body.Close()
+
+ if err == nil {
+ t.Fatal("expected error from ReadAll")
+ }
+ ne, ok := err.(net.Error)
+ if !ok {
+ t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
+ } else if !ne.Timeout() {
+ t.Errorf("net.Error.Timeout = false; want true")
+ }
+ if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
+ if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+ testenv.SkipFlaky(t, 43120)
+ }
+ t.Errorf("error string = %q; missing timeout substring", got)
+ }
+
+ break
+ }
+}
+
+// Client.Timeout firing before getting to the body
+func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
+func testClientTimeout_Headers(t *testing.T, mode testMode) {
+ donec := make(chan bool, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ <-donec
+ }), optQuietLog)
+ // Note that we use a channel send here and not a close.
+ // The race detector doesn't know that we're waiting for a timeout
+ // and thinks that the waitgroup inside httptest.Server is added to concurrently
+ // with us closing it. If we timed out immediately, we could close the testserver
+ // before we entered the handler. We're not timing out immediately and there's
+ // no way we would be done before we entered the handler, but the race detector
+ // doesn't know this, so synchronize explicitly.
+ defer func() { donec <- true }()
+
+ cst.c.Timeout = 5 * time.Millisecond
+ res, err := cst.c.Get(cst.ts.URL)
+ if err == nil {
+ res.Body.Close()
+ t.Fatal("got response from Get; expected error")
+ }
+ if _, ok := err.(*url.Error); !ok {
+ t.Fatalf("Got error of type %T; want *url.Error", err)
+ }
+ ne, ok := err.(net.Error)
+ if !ok {
+ t.Fatalf("Got error of type %T; want some net.Error", err)
+ }
+ if !ne.Timeout() {
+ t.Error("net.Error.Timeout = false; want true")
+ }
+ if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
+ if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+ testenv.SkipFlaky(t, 43120)
+ }
+ t.Errorf("error string = %q; missing timeout substring", got)
+ }
+}
+
+// Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
+// returned.
+func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
+func testClientTimeoutCancel(t *testing.T, mode testMode) {
+ testDone := make(chan struct{})
+ ctx, cancel := context.WithCancel(context.Background())
+
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.(Flusher).Flush()
+ <-testDone
+ }))
+ defer close(testDone)
+
+ cst.c.Timeout = 1 * time.Hour
+ req, _ := NewRequest("GET", cst.ts.URL, nil)
+ req.Cancel = ctx.Done()
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cancel()
+ _, err = io.Copy(io.Discard, res.Body)
+ if err != ExportErrRequestCanceled {
+ t.Fatalf("error = %v; want errRequestCanceled", err)
+ }
+}
+
+// Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
+func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
+func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Write([]byte("body"))
+ }))
+
+ cst.c.Timeout = 1 * time.Hour
+ req, _ := NewRequest("GET", cst.ts.URL, nil)
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = io.Copy(io.Discard, res.Body); err != nil {
+ t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
+ }
+ if err = res.Body.Close(); err != nil {
+ t.Fatalf("res.Body.Close() = %v, want nil", err)
+ }
+}
+
+func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
+func testClientRedirectEatsBody(t *testing.T, mode testMode) {
+ saw := make(chan string, 2)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ saw <- r.RemoteAddr
+ if r.URL.Path == "/" {
+ Redirect(w, r, "/foo", StatusFound) // which includes a body
+ }
+ }))
+
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var first string
+ select {
+ case first = <-saw:
+ default:
+ t.Fatal("server didn't see a request")
+ }
+
+ var second string
+ select {
+ case second = <-saw:
+ default:
+ t.Fatal("server didn't see a second request")
+ }
+
+ if first != second {
+ t.Fatal("server saw different client ports before & after the redirect")
+ }
+}
+
+// eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
+type eofReaderFunc func()
+
+func (f eofReaderFunc) Read(p []byte) (n int, err error) {
+ f()
+ return 0, io.EOF
+}
+
+func TestReferer(t *testing.T) {
+ tests := []struct {
+ lastReq, newReq, explicitRef string // from -> to URLs, explicitly set Referer value
+ want string
+ }{
+ // don't send user:
+ {lastReq: "http://gopher@test.com", newReq: "http://link.com", want: "http://test.com"},
+ {lastReq: "https://gopher@test.com", newReq: "https://link.com", want: "https://test.com"},
+
+ // don't send a user and password:
+ {lastReq: "http://gopher:go@test.com", newReq: "http://link.com", want: "http://test.com"},
+ {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", want: "https://test.com"},
+
+ // nothing to do:
+ {lastReq: "http://test.com", newReq: "http://link.com", want: "http://test.com"},
+ {lastReq: "https://test.com", newReq: "https://link.com", want: "https://test.com"},
+
+ // https to http doesn't send a referer:
+ {lastReq: "https://test.com", newReq: "http://link.com", want: ""},
+ {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", want: ""},
+
+ // https to http should remove an existing referer:
+ {lastReq: "https://test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
+ {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
+
+ // don't override an existing referer:
+ {lastReq: "https://test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
+ {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
+ }
+ for _, tt := range tests {
+ l, err := url.Parse(tt.lastReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n, err := url.Parse(tt.newReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := ExportRefererForURL(l, n, tt.explicitRef)
+ if r != tt.want {
+ t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
+ }
+ }
+}
+
+// issue15577Tripper returns a Response with a redirect response
+// header and doesn't populate its Response.Request field.
+type issue15577Tripper struct{}
+
+func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
+ resp := &Response{
+ StatusCode: 303,
+ Header: map[string][]string{"Location": {"http://www.example.com/"}},
+ Body: io.NopCloser(strings.NewReader("")),
+ }
+ return resp, nil
+}
+
+// Issue 15577: don't assume the roundtripper's response populates its Request field.
+func TestClientRedirectResponseWithoutRequest(t *testing.T) {
+ c := &Client{
+ CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
+ Transport: issue15577Tripper{},
+ }
+ // Check that this doesn't crash:
+ c.Get("http://dummy.tld")
+}
+
+// Issue 4800: copy (some) headers when Client follows a redirect.
+// Issue 35104: Since both URLs have the same host (localhost)
+// but different ports, sensitive headers like Cookie and Authorization
+// are preserved.
+func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
+func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
+ const (
+ ua = "some-agent/1.2"
+ xfoo = "foo-val"
+ )
+ var ts2URL string
+ ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ want := Header{
+ "User-Agent": []string{ua},
+ "X-Foo": []string{xfoo},
+ "Referer": []string{ts2URL},
+ "Accept-Encoding": []string{"gzip"},
+ "Cookie": []string{"foo=bar"},
+ "Authorization": []string{"secretpassword"},
+ }
+ if !reflect.DeepEqual(r.Header, want) {
+ t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
+ }
+ if t.Failed() {
+ w.Header().Set("Result", "got errors")
+ } else {
+ w.Header().Set("Result", "ok")
+ }
+ })).ts
+ ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ Redirect(w, r, ts1.URL, StatusFound)
+ })).ts
+ ts2URL = ts2.URL
+
+ c := ts1.Client()
+ c.CheckRedirect = func(r *Request, via []*Request) error {
+ want := Header{
+ "User-Agent": []string{ua},
+ "X-Foo": []string{xfoo},
+ "Referer": []string{ts2URL},
+ "Cookie": []string{"foo=bar"},
+ "Authorization": []string{"secretpassword"},
+ }
+ if !reflect.DeepEqual(r.Header, want) {
+ t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
+ }
+ return nil
+ }
+
+ req, _ := NewRequest("GET", ts2.URL, nil)
+ req.Header.Add("User-Agent", ua)
+ req.Header.Add("X-Foo", xfoo)
+ req.Header.Add("Cookie", "foo=bar")
+ req.Header.Add("Authorization", "secretpassword")
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 200 {
+ t.Fatal(res.Status)
+ }
+ if got := res.Header.Get("Result"); got != "ok" {
+ t.Errorf("result = %q; want ok", got)
+ }
+}
+
+// Issue 22233: copy host when Client follows a relative redirect.
+func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
+func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
+ // Virtual hostname: should not receive any request.
+ virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ t.Errorf("Virtual host received request %v", r.URL)
+ w.WriteHeader(403)
+ io.WriteString(w, "should not see this response")
+ })).ts
+ defer virtual.Close()
+ virtualHost := strings.TrimPrefix(virtual.URL, "http://")
+ virtualHost = strings.TrimPrefix(virtualHost, "https://")
+ t.Logf("Virtual host is %v", virtualHost)
+
+ // Actual hostname: should not receive any request.
+ const wantBody = "response body"
+ var tsURL string
+ var tsHost string
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ switch r.URL.Path {
+ case "/":
+ // Relative redirect.
+ if r.Host != virtualHost {
+ t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
+ w.WriteHeader(404)
+ return
+ }
+ w.Header().Set("Location", "/hop")
+ w.WriteHeader(302)
+ case "/hop":
+ // Absolute redirect.
+ if r.Host != virtualHost {
+ t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
+ w.WriteHeader(404)
+ return
+ }
+ w.Header().Set("Location", tsURL+"/final")
+ w.WriteHeader(302)
+ case "/final":
+ if r.Host != tsHost {
+ t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
+ w.WriteHeader(404)
+ return
+ }
+ w.WriteHeader(200)
+ io.WriteString(w, wantBody)
+ default:
+ t.Errorf("Serving unexpected path %q", r.URL.Path)
+ w.WriteHeader(404)
+ }
+ })).ts
+ tsURL = ts.URL
+ tsHost = strings.TrimPrefix(ts.URL, "http://")
+ tsHost = strings.TrimPrefix(tsHost, "https://")
+ t.Logf("Server host is %v", tsHost)
+
+ c := ts.Client()
+ req, _ := NewRequest("GET", ts.URL, nil)
+ req.Host = virtualHost
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 200 {
+ t.Fatal(resp.Status)
+ }
+ if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
+ t.Errorf("body = %q; want %q", got, wantBody)
+ }
+}
+
+// Issue 17494: cookies should be altered when Client follows redirects.
+func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
+func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
+ cookieMap := func(cs []*Cookie) map[string][]string {
+ m := make(map[string][]string)
+ for _, c := range cs {
+ m[c.Name] = append(m[c.Name], c.Value)
+ }
+ return m
+ }
+
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ var want map[string][]string
+ got := cookieMap(r.Cookies())
+
+ c, _ := r.Cookie("Cycle")
+ switch c.Value {
+ case "0":
+ want = map[string][]string{
+ "Cookie1": {"OldValue1a", "OldValue1b"},
+ "Cookie2": {"OldValue2"},
+ "Cookie3": {"OldValue3a", "OldValue3b"},
+ "Cookie4": {"OldValue4"},
+ "Cycle": {"0"},
+ }
+ SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
+ SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
+ Redirect(w, r, "/", StatusFound)
+ case "1":
+ want = map[string][]string{
+ "Cookie1": {"OldValue1a", "OldValue1b"},
+ "Cookie3": {"OldValue3a", "OldValue3b"},
+ "Cookie4": {"OldValue4"},
+ "Cycle": {"1"},
+ }
+ SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
+ SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
+ SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
+ Redirect(w, r, "/", StatusFound)
+ case "2":
+ want = map[string][]string{
+ "Cookie1": {"OldValue1a", "OldValue1b"},
+ "Cookie3": {"NewValue3"},
+ "Cookie4": {"NewValue4"},
+ "Cycle": {"2"},
+ }
+ SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
+ SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
+ Redirect(w, r, "/", StatusFound)
+ case "3":
+ want = map[string][]string{
+ "Cookie1": {"OldValue1a", "OldValue1b"},
+ "Cookie3": {"NewValue3"},
+ "Cookie4": {"NewValue4"},
+ "Cookie5": {"NewValue5"},
+ "Cycle": {"3"},
+ }
+ // Don't redirect to ensure the loop ends.
+ default:
+ t.Errorf("unexpected redirect cycle")
+ return
+ }
+
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
+ }
+ })).ts
+
+ jar, _ := cookiejar.New(nil)
+ c := ts.Client()
+ c.Jar = jar
+
+ u, _ := url.Parse(ts.URL)
+ req, _ := NewRequest("GET", ts.URL, nil)
+ req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
+ req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
+ req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
+ req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
+ req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
+ jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
+ jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 200 {
+ t.Fatal(res.Status)
+ }
+}
+
+// Part of Issue 4800
+func TestShouldCopyHeaderOnRedirect(t *testing.T) {
+ tests := []struct {
+ header string
+ initialURL string
+ destURL string
+ want bool
+ }{
+ {"User-Agent", "http://foo.com/", "http://bar.com/", true},
+ {"X-Foo", "http://foo.com/", "http://bar.com/", true},
+
+ // Sensitive headers:
+ {"cookie", "http://foo.com/", "http://bar.com/", false},
+ {"cookie2", "http://foo.com/", "http://bar.com/", false},
+ {"authorization", "http://foo.com/", "http://bar.com/", false},
+ {"authorization", "http://foo.com/", "https://foo.com/", true},
+ {"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
+ {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
+ {"authorization", "http://foo.com/", "http://[::1%25.foo.com]/", false},
+
+ // But subdomains should work:
+ {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
+ {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
+ {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
+ {"www-authenticate", "http://foo.com/", "https://foo.com/", true},
+ {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
+ {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
+ {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
+ {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
+ {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
+
+ {"authorization", "http://foo.com/", "http://foo.com/", true},
+ {"authorization", "http://foo.com/", "http://sub.foo.com/", true},
+ {"authorization", "http://foo.com/", "http://notfoo.com/", false},
+ {"authorization", "http://foo.com/", "https://foo.com/", true},
+ {"authorization", "http://foo.com:80/", "http://foo.com/", true},
+ {"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
+ {"authorization", "http://foo.com:443/", "https://foo.com/", true},
+ {"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
+ {"authorization", "http://foo.com:1234/", "http://foo.com/", true},
+ }
+ for i, tt := range tests {
+ u0, err := url.Parse(tt.initialURL)
+ if err != nil {
+ t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
+ continue
+ }
+ u1, err := url.Parse(tt.destURL)
+ if err != nil {
+ t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
+ continue
+ }
+ got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
+ if got != tt.want {
+ t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
+ i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
+ }
+ }
+}
+
+func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
+func testClientRedirectTypes(t *testing.T, mode testMode) {
+ tests := [...]struct {
+ method string
+ serverStatus int
+ wantMethod string // desired subsequent client method
+ }{
+ 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
+ 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
+ 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
+ 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
+ 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
+
+ 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
+ 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
+ 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
+ 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
+ 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
+
+ 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
+ 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
+ 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
+ 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
+ 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
+
+ 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
+ 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
+ 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
+ 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
+ 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
+
+ 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
+ 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
+ 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
+ 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
+ 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
+
+ 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
+ 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
+ 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
+ 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
+ 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
+ }
+
+ handlerc := make(chan HandlerFunc, 1)
+
+ ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
+ h := <-handlerc
+ h(rw, req)
+ })).ts
+
+ c := ts.Client()
+ for i, tt := range tests {
+ handlerc <- func(w ResponseWriter, r *Request) {
+ w.Header().Set("Location", ts.URL)
+ w.WriteHeader(tt.serverStatus)
+ }
+
+ req, err := NewRequest(tt.method, ts.URL, nil)
+ if err != nil {
+ t.Errorf("#%d: NewRequest: %v", i, err)
+ continue
+ }
+
+ c.CheckRedirect = func(req *Request, via []*Request) error {
+ if got, want := req.Method, tt.wantMethod; got != want {
+ return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
+ }
+ handlerc <- func(rw ResponseWriter, req *Request) {
+ // TODO: Check that the body is valid when we do 307 and 308 support
+ }
+ return nil
+ }
+
+ res, err := c.Do(req)
+ if err != nil {
+ t.Errorf("#%d: Response: %v", i, err)
+ continue
+ }
+
+ res.Body.Close()
+ }
+}
+
+// issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
+// Its Read returns readErr and increments *readCalls atomically.
+// Its Close returns nil and increments *closeCalls atomically.
+type issue18239Body struct {
+ readCalls *int32
+ closeCalls *int32
+ readErr error
+}
+
+func (b issue18239Body) Read([]byte) (int, error) {
+ atomic.AddInt32(b.readCalls, 1)
+ return 0, b.readErr
+}
+
+func (b issue18239Body) Close() error {
+ atomic.AddInt32(b.closeCalls, 1)
+ return nil
+}
+
+// Issue 18239: make sure the Transport doesn't retry requests with bodies
+// if Request.GetBody is not defined.
+func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
+func testTransportBodyReadError(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if r.URL.Path == "/ping" {
+ return
+ }
+ buf := make([]byte, 1)
+ n, err := r.Body.Read(buf)
+ w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
+ })).ts
+ c := ts.Client()
+ tr := c.Transport.(*Transport)
+
+ // Do one initial successful request to create an idle TCP connection
+ // for the subsequent request to reuse. (The Transport only retries
+ // requests on reused connections.)
+ res, err := c.Get(ts.URL + "/ping")
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+
+ var readCallsAtomic int32
+ var closeCallsAtomic int32 // atomic
+ someErr := errors.New("some body read error")
+ body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
+
+ req, err := NewRequest("POST", ts.URL, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req = req.WithT(t)
+ _, err = tr.RoundTrip(req)
+ if err != someErr {
+ t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
+ }
+
+ // And verify that our Body wasn't used multiple times, which
+ // would indicate retries. (as it buggily was during part of
+ // Go 1.8's dev cycle)
+ readCalls := atomic.LoadInt32(&readCallsAtomic)
+ closeCalls := atomic.LoadInt32(&closeCallsAtomic)
+ if readCalls != 1 {
+ t.Errorf("read calls = %d; want 1", readCalls)
+ }
+ if closeCalls != 1 {
+ t.Errorf("close calls = %d; want 1", closeCalls)
+ }
+}
+
+type roundTripperWithoutCloseIdle struct{}
+
+func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
+
+type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
+
+func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
+func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
+
+func TestClientCloseIdleConnections(t *testing.T) {
+ c := &Client{Transport: roundTripperWithoutCloseIdle{}}
+ c.CloseIdleConnections() // verify we don't crash at least
+
+ closed := false
+ var tr RoundTripper = roundTripperWithCloseIdle(func() {
+ closed = true
+ })
+ c = &Client{Transport: tr}
+ c.CloseIdleConnections()
+ if !closed {
+ t.Error("not closed")
+ }
+}
+
+func TestClientPropagatesTimeoutToContext(t *testing.T) {
+ errDial := errors.New("not actually dialing")
+ c := &Client{
+ Timeout: 5 * time.Second,
+ Transport: &Transport{
+ DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ t.Error("no deadline")
+ } else {
+ t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
+ }
+ return nil, errDial
+ },
+ },
+ }
+ c.Get("https://example.tld/")
+}
+
+// Issue 33545: lock-in the behavior promised by Client.Do's
+// docs about request cancellation vs timing out.
+func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
+func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Write([]byte("Hello, World!"))
+ }))
+
+ cases := []string{"timeout", "canceled"}
+
+ for _, name := range cases {
+ t.Run(name, func(t *testing.T) {
+ var ctx context.Context
+ var cancel func()
+ if name == "timeout" {
+ ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
+ } else {
+ ctx, cancel = context.WithCancel(context.Background())
+ cancel()
+ }
+ defer cancel()
+
+ req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
+ _, err := cst.c.Do(req)
+ if err == nil {
+ t.Fatal("Unexpectedly got a nil error")
+ }
+
+ ue := err.(*url.Error)
+
+ var wantIsTimeout bool
+ var wantErr error = context.Canceled
+ if name == "timeout" {
+ wantErr = context.DeadlineExceeded
+ wantIsTimeout = true
+ }
+ if g, w := ue.Timeout(), wantIsTimeout; g != w {
+ t.Fatalf("url.Timeout() = %t, want %t", g, w)
+ }
+ if g, w := ue.Err, wantErr; g != w {
+ t.Errorf("url.Error.Err = %v; want %v", g, w)
+ }
+ })
+ }
+}
+
+type nilBodyRoundTripper struct{}
+
+func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
+ return &Response{
+ StatusCode: StatusOK,
+ Status: StatusText(StatusOK),
+ Body: nil,
+ Request: req,
+ }, nil
+}
+
+func TestClientPopulatesNilResponseBody(t *testing.T) {
+ c := &Client{Transport: nilBodyRoundTripper{}}
+
+ resp, err := c.Get("http://localhost/anything")
+ if err != nil {
+ t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
+ }
+
+ if resp.Body == nil {
+ t.Fatalf("Client failed to provide a non-nil Body as documented")
+ }
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ t.Fatalf("error from Close on substitute Response.Body: %v", err)
+ }
+ }()
+
+ if b, err := io.ReadAll(resp.Body); err != nil {
+ t.Errorf("read error from substitute Response.Body: %v", err)
+ } else if len(b) != 0 {
+ t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
+ }
+}
+
+// Issue 40382: Client calls Close multiple times on Request.Body.
+func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
+func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.WriteHeader(StatusNoContent)
+ }))
+
+ // Issue occurred non-deterministically: needed to occur after a successful
+ // write (into TCP buffer) but before end of body.
+ for i := 0; i < 50 && !t.Failed(); i++ {
+ body := &issue40382Body{t: t, n: 300000}
+ req, err := NewRequest(MethodPost, cst.ts.URL, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := cst.tr.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ }
+}
+
+// issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
+// Its Read reads n bytes before returning io.EOF.
+// Its Close returns nil but fails the test if called more than once.
+type issue40382Body struct {
+ t *testing.T
+ n int
+ closeCallsAtomic int32
+}
+
+func (b *issue40382Body) Read(p []byte) (int, error) {
+ switch {
+ case b.n == 0:
+ return 0, io.EOF
+ case b.n < len(p):
+ p = p[:b.n]
+ fallthrough
+ default:
+ for i := range p {
+ p[i] = 'x'
+ }
+ b.n -= len(p)
+ return len(p), nil
+ }
+}
+
+func (b *issue40382Body) Close() error {
+ if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
+ b.t.Error("Body closed more than once")
+ }
+ return nil
+}
+
+func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
+func testProbeZeroLengthBody(t *testing.T, mode testMode) {
+ reqc := make(chan struct{})
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ close(reqc)
+ if _, err := io.Copy(w, r.Body); err != nil {
+ t.Errorf("error copying request body: %v", err)
+ }
+ }))
+
+ bodyr, bodyw := io.Pipe()
+ var gotBody string
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ req, _ := NewRequest("GET", cst.ts.URL, bodyr)
+ res, err := cst.c.Do(req)
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Error(err)
+ }
+ gotBody = string(b)
+ }()
+
+ select {
+ case <-reqc:
+ // Request should be sent after trying to probe the request body for 200ms.
+ case <-time.After(60 * time.Second):
+ t.Errorf("request not sent after 60s")
+ }
+
+ // Write the request body and wait for the request to complete.
+ const content = "body"
+ bodyw.Write([]byte(content))
+ bodyw.Close()
+ wg.Wait()
+ if gotBody != content {
+ t.Fatalf("server got body %q, want %q", gotBody, content)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/clientserver_test.go b/platform/dbops/binaries/go/go/src/net/http/clientserver_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..32948f3aed4abe0dc5739d13f3ca43f611eacecb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/clientserver_test.go
@@ -0,0 +1,1756 @@
+// 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.
+
+// Tests that use both the client & server, in both HTTP/1 and HTTP/2 mode.
+
+package http_test
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/rand"
+ "crypto/sha1"
+ "crypto/tls"
+ "fmt"
+ "hash"
+ "io"
+ "log"
+ "net"
+ . "net/http"
+ "net/http/httptest"
+ "net/http/httptrace"
+ "net/http/httputil"
+ "net/textproto"
+ "net/url"
+ "os"
+ "reflect"
+ "runtime"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type testMode string
+
+const (
+ http1Mode = testMode("h1") // HTTP/1.1
+ https1Mode = testMode("https1") // HTTPS/1.1
+ http2Mode = testMode("h2") // HTTP/2
+)
+
+type testNotParallelOpt struct{}
+
+var (
+ testNotParallel = testNotParallelOpt{}
+)
+
+type TBRun[T any] interface {
+ testing.TB
+ Run(string, func(T)) bool
+}
+
+// run runs a client/server test in a variety of test configurations.
+//
+// Tests execute in HTTP/1.1 and HTTP/2 modes by default.
+// To run in a different set of configurations, pass a []testMode option.
+//
+// Tests call t.Parallel() by default.
+// To disable parallel execution, pass the testNotParallel option.
+func run[T TBRun[T]](t T, f func(t T, mode testMode), opts ...any) {
+ t.Helper()
+ modes := []testMode{http1Mode, http2Mode}
+ parallel := true
+ for _, opt := range opts {
+ switch opt := opt.(type) {
+ case []testMode:
+ modes = opt
+ case testNotParallelOpt:
+ parallel = false
+ default:
+ t.Fatalf("unknown option type %T", opt)
+ }
+ }
+ if t, ok := any(t).(*testing.T); ok && parallel {
+ setParallel(t)
+ }
+ for _, mode := range modes {
+ t.Run(string(mode), func(t T) {
+ t.Helper()
+ if t, ok := any(t).(*testing.T); ok && parallel {
+ setParallel(t)
+ }
+ t.Cleanup(func() {
+ afterTest(t)
+ })
+ f(t, mode)
+ })
+ }
+}
+
+type clientServerTest struct {
+ t testing.TB
+ h2 bool
+ h Handler
+ ts *httptest.Server
+ tr *Transport
+ c *Client
+}
+
+func (t *clientServerTest) close() {
+ t.tr.CloseIdleConnections()
+ t.ts.Close()
+}
+
+func (t *clientServerTest) getURL(u string) string {
+ res, err := t.c.Get(u)
+ if err != nil {
+ t.t.Fatal(err)
+ }
+ defer res.Body.Close()
+ slurp, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.t.Fatal(err)
+ }
+ return string(slurp)
+}
+
+func (t *clientServerTest) scheme() string {
+ if t.h2 {
+ return "https"
+ }
+ return "http"
+}
+
+var optQuietLog = func(ts *httptest.Server) {
+ ts.Config.ErrorLog = quietLog
+}
+
+func optWithServerLog(lg *log.Logger) func(*httptest.Server) {
+ return func(ts *httptest.Server) {
+ ts.Config.ErrorLog = lg
+ }
+}
+
+// newClientServerTest creates and starts an httptest.Server.
+//
+// The mode parameter selects the implementation to test:
+// HTTP/1, HTTP/2, etc. Tests using newClientServerTest should use
+// the 'run' function, which will start a subtests for each tested mode.
+//
+// The vararg opts parameter can include functions to configure the
+// test server or transport.
+//
+// func(*httptest.Server) // run before starting the server
+// func(*http.Transport)
+func newClientServerTest(t testing.TB, mode testMode, h Handler, opts ...any) *clientServerTest {
+ if mode == http2Mode {
+ CondSkipHTTP2(t)
+ }
+ cst := &clientServerTest{
+ t: t,
+ h2: mode == http2Mode,
+ h: h,
+ }
+ cst.ts = httptest.NewUnstartedServer(h)
+
+ var transportFuncs []func(*Transport)
+ for _, opt := range opts {
+ switch opt := opt.(type) {
+ case func(*Transport):
+ transportFuncs = append(transportFuncs, opt)
+ case func(*httptest.Server):
+ opt(cst.ts)
+ default:
+ t.Fatalf("unhandled option type %T", opt)
+ }
+ }
+
+ if cst.ts.Config.ErrorLog == nil {
+ cst.ts.Config.ErrorLog = log.New(testLogWriter{t}, "", 0)
+ }
+
+ switch mode {
+ case http1Mode:
+ cst.ts.Start()
+ case https1Mode:
+ cst.ts.StartTLS()
+ case http2Mode:
+ ExportHttp2ConfigureServer(cst.ts.Config, nil)
+ cst.ts.TLS = cst.ts.Config.TLSConfig
+ cst.ts.StartTLS()
+ default:
+ t.Fatalf("unknown test mode %v", mode)
+ }
+ cst.c = cst.ts.Client()
+ cst.tr = cst.c.Transport.(*Transport)
+ if mode == http2Mode {
+ if err := ExportHttp2ConfigureTransport(cst.tr); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, f := range transportFuncs {
+ f(cst.tr)
+ }
+ t.Cleanup(func() {
+ cst.close()
+ })
+ return cst
+}
+
+type testLogWriter struct {
+ t testing.TB
+}
+
+func (w testLogWriter) Write(b []byte) (int, error) {
+ w.t.Logf("server log: %v", strings.TrimSpace(string(b)))
+ return len(b), nil
+}
+
+// Testing the newClientServerTest helper itself.
+func TestNewClientServerTest(t *testing.T) {
+ run(t, testNewClientServerTest, []testMode{http1Mode, https1Mode, http2Mode})
+}
+func testNewClientServerTest(t *testing.T, mode testMode) {
+ var got struct {
+ sync.Mutex
+ proto string
+ hasTLS bool
+ }
+ h := HandlerFunc(func(w ResponseWriter, r *Request) {
+ got.Lock()
+ defer got.Unlock()
+ got.proto = r.Proto
+ got.hasTLS = r.TLS != nil
+ })
+ cst := newClientServerTest(t, mode, h)
+ if _, err := cst.c.Head(cst.ts.URL); err != nil {
+ t.Fatal(err)
+ }
+ var wantProto string
+ var wantTLS bool
+ switch mode {
+ case http1Mode:
+ wantProto = "HTTP/1.1"
+ wantTLS = false
+ case https1Mode:
+ wantProto = "HTTP/1.1"
+ wantTLS = true
+ case http2Mode:
+ wantProto = "HTTP/2.0"
+ wantTLS = true
+ }
+ if got.proto != wantProto {
+ t.Errorf("req.Proto = %q, want %q", got.proto, wantProto)
+ }
+ if got.hasTLS != wantTLS {
+ t.Errorf("req.TLS set: %v, want %v", got.hasTLS, wantTLS)
+ }
+}
+
+func TestChunkedResponseHeaders(t *testing.T) { run(t, testChunkedResponseHeaders) }
+func testChunkedResponseHeaders(t *testing.T, mode testMode) {
+ log.SetOutput(io.Discard) // is noisy otherwise
+ defer log.SetOutput(os.Stderr)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted
+ w.(Flusher).Flush()
+ fmt.Fprintf(w, "I am a chunked response.")
+ }))
+
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatalf("Get error: %v", err)
+ }
+ defer res.Body.Close()
+ if g, e := res.ContentLength, int64(-1); g != e {
+ t.Errorf("expected ContentLength of %d; got %d", e, g)
+ }
+ wantTE := []string{"chunked"}
+ if mode == http2Mode {
+ wantTE = nil
+ }
+ if !reflect.DeepEqual(res.TransferEncoding, wantTE) {
+ t.Errorf("TransferEncoding = %v; want %v", res.TransferEncoding, wantTE)
+ }
+ if got, haveCL := res.Header["Content-Length"]; haveCL {
+ t.Errorf("Unexpected Content-Length: %q", got)
+ }
+}
+
+type reqFunc func(c *Client, url string) (*Response, error)
+
+// h12Compare is a test that compares HTTP/1 and HTTP/2 behavior
+// against each other.
+type h12Compare struct {
+ Handler func(ResponseWriter, *Request) // required
+ ReqFunc reqFunc // optional
+ CheckResponse func(proto string, res *Response) // optional
+ EarlyCheckResponse func(proto string, res *Response) // optional; pre-normalize
+ Opts []any
+}
+
+func (tt h12Compare) reqFunc() reqFunc {
+ if tt.ReqFunc == nil {
+ return (*Client).Get
+ }
+ return tt.ReqFunc
+}
+
+func (tt h12Compare) run(t *testing.T) {
+ setParallel(t)
+ cst1 := newClientServerTest(t, http1Mode, HandlerFunc(tt.Handler), tt.Opts...)
+ defer cst1.close()
+ cst2 := newClientServerTest(t, http2Mode, HandlerFunc(tt.Handler), tt.Opts...)
+ defer cst2.close()
+
+ res1, err := tt.reqFunc()(cst1.c, cst1.ts.URL)
+ if err != nil {
+ t.Errorf("HTTP/1 request: %v", err)
+ return
+ }
+ res2, err := tt.reqFunc()(cst2.c, cst2.ts.URL)
+ if err != nil {
+ t.Errorf("HTTP/2 request: %v", err)
+ return
+ }
+
+ if fn := tt.EarlyCheckResponse; fn != nil {
+ fn("HTTP/1.1", res1)
+ fn("HTTP/2.0", res2)
+ }
+
+ tt.normalizeRes(t, res1, "HTTP/1.1")
+ tt.normalizeRes(t, res2, "HTTP/2.0")
+ res1body, res2body := res1.Body, res2.Body
+
+ eres1 := mostlyCopy(res1)
+ eres2 := mostlyCopy(res2)
+ if !reflect.DeepEqual(eres1, eres2) {
+ t.Errorf("Response headers to handler differed:\nhttp/1 (%v):\n\t%#v\nhttp/2 (%v):\n\t%#v",
+ cst1.ts.URL, eres1, cst2.ts.URL, eres2)
+ }
+ if !reflect.DeepEqual(res1body, res2body) {
+ t.Errorf("Response bodies to handler differed.\nhttp1: %v\nhttp2: %v\n", res1body, res2body)
+ }
+ if fn := tt.CheckResponse; fn != nil {
+ res1.Body, res2.Body = res1body, res2body
+ fn("HTTP/1.1", res1)
+ fn("HTTP/2.0", res2)
+ }
+}
+
+func mostlyCopy(r *Response) *Response {
+ c := *r
+ c.Body = nil
+ c.TransferEncoding = nil
+ c.TLS = nil
+ c.Request = nil
+ return &c
+}
+
+type slurpResult struct {
+ io.ReadCloser
+ body []byte
+ err error
+}
+
+func (sr slurpResult) String() string { return fmt.Sprintf("body %q; err %v", sr.body, sr.err) }
+
+func (tt h12Compare) normalizeRes(t *testing.T, res *Response, wantProto string) {
+ if res.Proto == wantProto || res.Proto == "HTTP/IGNORE" {
+ res.Proto, res.ProtoMajor, res.ProtoMinor = "", 0, 0
+ } else {
+ t.Errorf("got %q response; want %q", res.Proto, wantProto)
+ }
+ slurp, err := io.ReadAll(res.Body)
+
+ res.Body.Close()
+ res.Body = slurpResult{
+ ReadCloser: io.NopCloser(bytes.NewReader(slurp)),
+ body: slurp,
+ err: err,
+ }
+ for i, v := range res.Header["Date"] {
+ res.Header["Date"][i] = strings.Repeat("x", len(v))
+ }
+ if res.Request == nil {
+ t.Errorf("for %s, no request", wantProto)
+ }
+ if (res.TLS != nil) != (wantProto == "HTTP/2.0") {
+ t.Errorf("TLS set = %v; want %v", res.TLS != nil, res.TLS == nil)
+ }
+}
+
+// Issue 13532
+func TestH12_HeadContentLengthNoBody(t *testing.T) {
+ h12Compare{
+ ReqFunc: (*Client).Head,
+ Handler: func(w ResponseWriter, r *Request) {
+ },
+ }.run(t)
+}
+
+func TestH12_HeadContentLengthSmallBody(t *testing.T) {
+ h12Compare{
+ ReqFunc: (*Client).Head,
+ Handler: func(w ResponseWriter, r *Request) {
+ io.WriteString(w, "small")
+ },
+ }.run(t)
+}
+
+func TestH12_HeadContentLengthLargeBody(t *testing.T) {
+ h12Compare{
+ ReqFunc: (*Client).Head,
+ Handler: func(w ResponseWriter, r *Request) {
+ chunk := strings.Repeat("x", 512<<10)
+ for i := 0; i < 10; i++ {
+ io.WriteString(w, chunk)
+ }
+ },
+ }.run(t)
+}
+
+func TestH12_200NoBody(t *testing.T) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {}}.run(t)
+}
+
+func TestH2_204NoBody(t *testing.T) { testH12_noBody(t, 204) }
+func TestH2_304NoBody(t *testing.T) { testH12_noBody(t, 304) }
+func TestH2_404NoBody(t *testing.T) { testH12_noBody(t, 404) }
+
+func testH12_noBody(t *testing.T, status int) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {
+ w.WriteHeader(status)
+ }}.run(t)
+}
+
+func TestH12_SmallBody(t *testing.T) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {
+ io.WriteString(w, "small body")
+ }}.run(t)
+}
+
+func TestH12_ExplicitContentLength(t *testing.T) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Length", "3")
+ io.WriteString(w, "foo")
+ }}.run(t)
+}
+
+func TestH12_FlushBeforeBody(t *testing.T) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {
+ w.(Flusher).Flush()
+ io.WriteString(w, "foo")
+ }}.run(t)
+}
+
+func TestH12_FlushMidBody(t *testing.T) {
+ h12Compare{Handler: func(w ResponseWriter, r *Request) {
+ io.WriteString(w, "foo")
+ w.(Flusher).Flush()
+ io.WriteString(w, "bar")
+ }}.run(t)
+}
+
+func TestH12_Head_ExplicitLen(t *testing.T) {
+ h12Compare{
+ ReqFunc: (*Client).Head,
+ Handler: func(w ResponseWriter, r *Request) {
+ if r.Method != "HEAD" {
+ t.Errorf("unexpected method %q", r.Method)
+ }
+ w.Header().Set("Content-Length", "1235")
+ },
+ }.run(t)
+}
+
+func TestH12_Head_ImplicitLen(t *testing.T) {
+ h12Compare{
+ ReqFunc: (*Client).Head,
+ Handler: func(w ResponseWriter, r *Request) {
+ if r.Method != "HEAD" {
+ t.Errorf("unexpected method %q", r.Method)
+ }
+ io.WriteString(w, "foo")
+ },
+ }.run(t)
+}
+
+func TestH12_HandlerWritesTooLittle(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Length", "3")
+ io.WriteString(w, "12") // one byte short
+ },
+ CheckResponse: func(proto string, res *Response) {
+ sr, ok := res.Body.(slurpResult)
+ if !ok {
+ t.Errorf("%s body is %T; want slurpResult", proto, res.Body)
+ return
+ }
+ if sr.err != io.ErrUnexpectedEOF {
+ t.Errorf("%s read error = %v; want io.ErrUnexpectedEOF", proto, sr.err)
+ }
+ if string(sr.body) != "12" {
+ t.Errorf("%s body = %q; want %q", proto, sr.body, "12")
+ }
+ },
+ }.run(t)
+}
+
+// Tests that the HTTP/1 and HTTP/2 servers prevent handlers from
+// writing more than they declared. This test does not test whether
+// the transport deals with too much data, though, since the server
+// doesn't make it possible to send bogus data. For those tests, see
+// transport_test.go (for HTTP/1) or x/net/http2/transport_test.go
+// (for HTTP/2).
+func TestH12_HandlerWritesTooMuch(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Length", "3")
+ w.(Flusher).Flush()
+ io.WriteString(w, "123")
+ w.(Flusher).Flush()
+ n, err := io.WriteString(w, "x") // too many
+ if n > 0 || err == nil {
+ t.Errorf("for proto %q, final write = %v, %v; want 0, some error", r.Proto, n, err)
+ }
+ },
+ }.run(t)
+}
+
+// Verify that both our HTTP/1 and HTTP/2 request and auto-decompress gzip.
+// Some hosts send gzip even if you don't ask for it; see golang.org/issue/13298
+func TestH12_AutoGzip(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ if ae := r.Header.Get("Accept-Encoding"); ae != "gzip" {
+ t.Errorf("%s Accept-Encoding = %q; want gzip", r.Proto, ae)
+ }
+ w.Header().Set("Content-Encoding", "gzip")
+ gz := gzip.NewWriter(w)
+ io.WriteString(gz, "I am some gzipped content. Go go go go go go go go go go go go should compress well.")
+ gz.Close()
+ },
+ }.run(t)
+}
+
+func TestH12_AutoGzip_Disabled(t *testing.T) {
+ h12Compare{
+ Opts: []any{
+ func(tr *Transport) { tr.DisableCompression = true },
+ },
+ Handler: func(w ResponseWriter, r *Request) {
+ fmt.Fprintf(w, "%q", r.Header["Accept-Encoding"])
+ if ae := r.Header.Get("Accept-Encoding"); ae != "" {
+ t.Errorf("%s Accept-Encoding = %q; want empty", r.Proto, ae)
+ }
+ },
+ }.run(t)
+}
+
+// Test304Responses verifies that 304s don't declare that they're
+// chunking in their response headers and aren't allowed to produce
+// output.
+func Test304Responses(t *testing.T) { run(t, test304Responses) }
+func test304Responses(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.WriteHeader(StatusNotModified)
+ _, err := w.Write([]byte("illegal body"))
+ if err != ErrBodyNotAllowed {
+ t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err)
+ }
+ }))
+ defer cst.close()
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.TransferEncoding) > 0 {
+ t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
+ }
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Error(err)
+ }
+ if len(body) > 0 {
+ t.Errorf("got unexpected body %q", string(body))
+ }
+}
+
+func TestH12_ServerEmptyContentLength(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ w.Header()["Content-Type"] = []string{""}
+ io.WriteString(w, "hi")
+ },
+ }.run(t)
+}
+
+func TestH12_RequestContentLength_Known_NonZero(t *testing.T) {
+ h12requestContentLength(t, func() io.Reader { return strings.NewReader("FOUR") }, 4)
+}
+
+func TestH12_RequestContentLength_Known_Zero(t *testing.T) {
+ h12requestContentLength(t, func() io.Reader { return nil }, 0)
+}
+
+func TestH12_RequestContentLength_Unknown(t *testing.T) {
+ h12requestContentLength(t, func() io.Reader { return struct{ io.Reader }{strings.NewReader("Stuff")} }, -1)
+}
+
+func h12requestContentLength(t *testing.T, bodyfn func() io.Reader, wantLen int64) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ w.Header().Set("Got-Length", fmt.Sprint(r.ContentLength))
+ fmt.Fprintf(w, "Req.ContentLength=%v", r.ContentLength)
+ },
+ ReqFunc: func(c *Client, url string) (*Response, error) {
+ return c.Post(url, "text/plain", bodyfn())
+ },
+ CheckResponse: func(proto string, res *Response) {
+ if got, want := res.Header.Get("Got-Length"), fmt.Sprint(wantLen); got != want {
+ t.Errorf("Proto %q got length %q; want %q", proto, got, want)
+ }
+ },
+ }.run(t)
+}
+
+// Tests that closing the Request.Cancel channel also while still
+// reading the response body. Issue 13159.
+func TestCancelRequestMidBody(t *testing.T) { run(t, testCancelRequestMidBody) }
+func testCancelRequestMidBody(t *testing.T, mode testMode) {
+ unblock := make(chan bool)
+ didFlush := make(chan bool, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ io.WriteString(w, "Hello")
+ w.(Flusher).Flush()
+ didFlush <- true
+ <-unblock
+ io.WriteString(w, ", world.")
+ }))
+ defer close(unblock)
+
+ req, _ := NewRequest("GET", cst.ts.URL, nil)
+ cancel := make(chan struct{})
+ req.Cancel = cancel
+
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ <-didFlush
+
+ // Read a bit before we cancel. (Issue 13626)
+ // We should have "Hello" at least sitting there.
+ firstRead := make([]byte, 10)
+ n, err := res.Body.Read(firstRead)
+ if err != nil {
+ t.Fatal(err)
+ }
+ firstRead = firstRead[:n]
+
+ close(cancel)
+
+ rest, err := io.ReadAll(res.Body)
+ all := string(firstRead) + string(rest)
+ if all != "Hello" {
+ t.Errorf("Read %q (%q + %q); want Hello", all, firstRead, rest)
+ }
+ if err != ExportErrRequestCanceled {
+ t.Errorf("ReadAll error = %v; want %v", err, ExportErrRequestCanceled)
+ }
+}
+
+// Tests that clients can send trailers to a server and that the server can read them.
+func TestTrailersClientToServer(t *testing.T) { run(t, testTrailersClientToServer) }
+func testTrailersClientToServer(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ var decl []string
+ for k := range r.Trailer {
+ decl = append(decl, k)
+ }
+ sort.Strings(decl)
+
+ slurp, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("Server reading request body: %v", err)
+ }
+ if string(slurp) != "foo" {
+ t.Errorf("Server read request body %q; want foo", slurp)
+ }
+ if r.Trailer == nil {
+ io.WriteString(w, "nil Trailer")
+ } else {
+ fmt.Fprintf(w, "decl: %v, vals: %s, %s",
+ decl,
+ r.Trailer.Get("Client-Trailer-A"),
+ r.Trailer.Get("Client-Trailer-B"))
+ }
+ }))
+
+ var req *Request
+ req, _ = NewRequest("POST", cst.ts.URL, io.MultiReader(
+ eofReaderFunc(func() {
+ req.Trailer["Client-Trailer-A"] = []string{"valuea"}
+ }),
+ strings.NewReader("foo"),
+ eofReaderFunc(func() {
+ req.Trailer["Client-Trailer-B"] = []string{"valueb"}
+ }),
+ ))
+ req.Trailer = Header{
+ "Client-Trailer-A": nil, // to be set later
+ "Client-Trailer-B": nil, // to be set later
+ }
+ req.ContentLength = -1
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := wantBody(res, err, "decl: [Client-Trailer-A Client-Trailer-B], vals: valuea, valueb"); err != nil {
+ t.Error(err)
+ }
+}
+
+// Tests that servers send trailers to a client and that the client can read them.
+func TestTrailersServerToClient(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ testTrailersServerToClient(t, mode, false)
+ })
+}
+func TestTrailersServerToClientFlush(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ testTrailersServerToClient(t, mode, true)
+ })
+}
+
+func testTrailersServerToClient(t *testing.T, mode testMode, flush bool) {
+ const body = "Some body"
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
+ w.Header().Add("Trailer", "Server-Trailer-C")
+
+ io.WriteString(w, body)
+ if flush {
+ w.(Flusher).Flush()
+ }
+
+ // How handlers set Trailers: declare it ahead of time
+ // with the Trailer header, and then mutate the
+ // Header() of those values later, after the response
+ // has been written (we wrote to w above).
+ w.Header().Set("Server-Trailer-A", "valuea")
+ w.Header().Set("Server-Trailer-C", "valuec") // skipping B
+ w.Header().Set("Server-Trailer-NotDeclared", "should be omitted")
+ }))
+
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ wantHeader := Header{
+ "Content-Type": {"text/plain; charset=utf-8"},
+ }
+ wantLen := -1
+ if mode == http2Mode && !flush {
+ // In HTTP/1.1, any use of trailers forces HTTP/1.1
+ // chunking and a flush at the first write. That's
+ // unnecessary with HTTP/2's framing, so the server
+ // is able to calculate the length while still sending
+ // trailers afterwards.
+ wantLen = len(body)
+ wantHeader["Content-Length"] = []string{fmt.Sprint(wantLen)}
+ }
+ if res.ContentLength != int64(wantLen) {
+ t.Errorf("ContentLength = %v; want %v", res.ContentLength, wantLen)
+ }
+
+ delete(res.Header, "Date") // irrelevant for test
+ if !reflect.DeepEqual(res.Header, wantHeader) {
+ t.Errorf("Header = %v; want %v", res.Header, wantHeader)
+ }
+
+ if got, want := res.Trailer, (Header{
+ "Server-Trailer-A": nil,
+ "Server-Trailer-B": nil,
+ "Server-Trailer-C": nil,
+ }); !reflect.DeepEqual(got, want) {
+ t.Errorf("Trailer before body read = %v; want %v", got, want)
+ }
+
+ if err := wantBody(res, nil, body); err != nil {
+ t.Fatal(err)
+ }
+
+ if got, want := res.Trailer, (Header{
+ "Server-Trailer-A": {"valuea"},
+ "Server-Trailer-B": nil,
+ "Server-Trailer-C": {"valuec"},
+ }); !reflect.DeepEqual(got, want) {
+ t.Errorf("Trailer after body read = %v; want %v", got, want)
+ }
+}
+
+// Don't allow a Body.Read after Body.Close. Issue 13648.
+func TestResponseBodyReadAfterClose(t *testing.T) { run(t, testResponseBodyReadAfterClose) }
+func testResponseBodyReadAfterClose(t *testing.T, mode testMode) {
+ const body = "Some body"
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ io.WriteString(w, body)
+ }))
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ data, err := io.ReadAll(res.Body)
+ if len(data) != 0 || err == nil {
+ t.Fatalf("ReadAll returned %q, %v; want error", data, err)
+ }
+}
+
+func TestConcurrentReadWriteReqBody(t *testing.T) { run(t, testConcurrentReadWriteReqBody) }
+func testConcurrentReadWriteReqBody(t *testing.T, mode testMode) {
+ const reqBody = "some request body"
+ const resBody = "some response body"
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ var wg sync.WaitGroup
+ wg.Add(2)
+ didRead := make(chan bool, 1)
+ // Read in one goroutine.
+ go func() {
+ defer wg.Done()
+ data, err := io.ReadAll(r.Body)
+ if string(data) != reqBody {
+ t.Errorf("Handler read %q; want %q", data, reqBody)
+ }
+ if err != nil {
+ t.Errorf("Handler Read: %v", err)
+ }
+ didRead <- true
+ }()
+ // Write in another goroutine.
+ go func() {
+ defer wg.Done()
+ if mode != http2Mode {
+ // our HTTP/1 implementation intentionally
+ // doesn't permit writes during read (mostly
+ // due to it being undefined); if that is ever
+ // relaxed, change this.
+ <-didRead
+ }
+ io.WriteString(w, resBody)
+ }()
+ wg.Wait()
+ }))
+ req, _ := NewRequest("POST", cst.ts.URL, strings.NewReader(reqBody))
+ req.Header.Add("Expect", "100-continue") // just to complicate things
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := io.ReadAll(res.Body)
+ defer res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != resBody {
+ t.Errorf("read %q; want %q", data, resBody)
+ }
+}
+
+func TestConnectRequest(t *testing.T) { run(t, testConnectRequest) }
+func testConnectRequest(t *testing.T, mode testMode) {
+ gotc := make(chan *Request, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ gotc <- r
+ }))
+
+ u, err := url.Parse(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tests := []struct {
+ req *Request
+ want string
+ }{
+ {
+ req: &Request{
+ Method: "CONNECT",
+ Header: Header{},
+ URL: u,
+ },
+ want: u.Host,
+ },
+ {
+ req: &Request{
+ Method: "CONNECT",
+ Header: Header{},
+ URL: u,
+ Host: "example.com:123",
+ },
+ want: "example.com:123",
+ },
+ }
+
+ for i, tt := range tests {
+ res, err := cst.c.Do(tt.req)
+ if err != nil {
+ t.Errorf("%d. RoundTrip = %v", i, err)
+ continue
+ }
+ res.Body.Close()
+ req := <-gotc
+ if req.Method != "CONNECT" {
+ t.Errorf("method = %q; want CONNECT", req.Method)
+ }
+ if req.Host != tt.want {
+ t.Errorf("Host = %q; want %q", req.Host, tt.want)
+ }
+ if req.URL.Host != tt.want {
+ t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want)
+ }
+ }
+}
+
+func TestTransportUserAgent(t *testing.T) { run(t, testTransportUserAgent) }
+func testTransportUserAgent(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ fmt.Fprintf(w, "%q", r.Header["User-Agent"])
+ }))
+
+ either := func(a, b string) string {
+ if mode == http2Mode {
+ return b
+ }
+ return a
+ }
+
+ tests := []struct {
+ setup func(*Request)
+ want string
+ }{
+ {
+ func(r *Request) {},
+ either(`["Go-http-client/1.1"]`, `["Go-http-client/2.0"]`),
+ },
+ {
+ func(r *Request) { r.Header.Set("User-Agent", "foo/1.2.3") },
+ `["foo/1.2.3"]`,
+ },
+ {
+ func(r *Request) { r.Header["User-Agent"] = []string{"single", "or", "multiple"} },
+ `["single"]`,
+ },
+ {
+ func(r *Request) { r.Header.Set("User-Agent", "") },
+ `[]`,
+ },
+ {
+ func(r *Request) { r.Header["User-Agent"] = nil },
+ `[]`,
+ },
+ }
+ for i, tt := range tests {
+ req, _ := NewRequest("GET", cst.ts.URL, nil)
+ tt.setup(req)
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Errorf("%d. RoundTrip = %v", i, err)
+ continue
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Errorf("%d. read body = %v", i, err)
+ continue
+ }
+ if string(slurp) != tt.want {
+ t.Errorf("%d. body mismatch.\n got: %s\nwant: %s\n", i, slurp, tt.want)
+ }
+ }
+}
+
+func TestStarRequestMethod(t *testing.T) {
+ for _, method := range []string{"FOO", "OPTIONS"} {
+ t.Run(method, func(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ testStarRequest(t, method, mode)
+ })
+ })
+ }
+}
+func testStarRequest(t *testing.T, method string, mode testMode) {
+ gotc := make(chan *Request, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("foo", "bar")
+ gotc <- r
+ w.(Flusher).Flush()
+ }))
+
+ u, err := url.Parse(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ u.Path = "*"
+
+ req := &Request{
+ Method: method,
+ Header: Header{},
+ URL: u,
+ }
+
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatalf("RoundTrip = %v", err)
+ }
+ res.Body.Close()
+
+ wantFoo := "bar"
+ wantLen := int64(-1)
+ if method == "OPTIONS" {
+ wantFoo = ""
+ wantLen = 0
+ }
+ if res.StatusCode != 200 {
+ t.Errorf("status code = %v; want %d", res.Status, 200)
+ }
+ if res.ContentLength != wantLen {
+ t.Errorf("content length = %v; want %d", res.ContentLength, wantLen)
+ }
+ if got := res.Header.Get("foo"); got != wantFoo {
+ t.Errorf("response \"foo\" header = %q; want %q", got, wantFoo)
+ }
+ select {
+ case req = <-gotc:
+ default:
+ req = nil
+ }
+ if req == nil {
+ if method != "OPTIONS" {
+ t.Fatalf("handler never got request")
+ }
+ return
+ }
+ if req.Method != method {
+ t.Errorf("method = %q; want %q", req.Method, method)
+ }
+ if req.URL.Path != "*" {
+ t.Errorf("URL.Path = %q; want *", req.URL.Path)
+ }
+ if req.RequestURI != "*" {
+ t.Errorf("RequestURI = %q; want *", req.RequestURI)
+ }
+}
+
+// Issue 13957
+func TestTransportDiscardsUnneededConns(t *testing.T) {
+ run(t, testTransportDiscardsUnneededConns, []testMode{http2Mode})
+}
+func testTransportDiscardsUnneededConns(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ fmt.Fprintf(w, "Hello, %v", r.RemoteAddr)
+ }))
+ defer cst.close()
+
+ var numOpen, numClose int32 // atomic
+
+ tlsConfig := &tls.Config{InsecureSkipVerify: true}
+ tr := &Transport{
+ TLSClientConfig: tlsConfig,
+ DialTLS: func(_, addr string) (net.Conn, error) {
+ time.Sleep(10 * time.Millisecond)
+ rc, err := net.Dial("tcp", addr)
+ if err != nil {
+ return nil, err
+ }
+ atomic.AddInt32(&numOpen, 1)
+ c := noteCloseConn{rc, func() { atomic.AddInt32(&numClose, 1) }}
+ return tls.Client(c, tlsConfig), nil
+ },
+ }
+ if err := ExportHttp2ConfigureTransport(tr); err != nil {
+ t.Fatal(err)
+ }
+ defer tr.CloseIdleConnections()
+
+ c := &Client{Transport: tr}
+
+ const N = 10
+ gotBody := make(chan string, N)
+ var wg sync.WaitGroup
+ for i := 0; i < N; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ resp, err := c.Get(cst.ts.URL)
+ if err != nil {
+ // Try to work around spurious connection reset on loaded system.
+ // See golang.org/issue/33585 and golang.org/issue/36797.
+ time.Sleep(10 * time.Millisecond)
+ resp, err = c.Get(cst.ts.URL)
+ if err != nil {
+ t.Errorf("Get: %v", err)
+ return
+ }
+ }
+ defer resp.Body.Close()
+ slurp, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Error(err)
+ }
+ gotBody <- string(slurp)
+ }()
+ }
+ wg.Wait()
+ close(gotBody)
+
+ var last string
+ for got := range gotBody {
+ if last == "" {
+ last = got
+ continue
+ }
+ if got != last {
+ t.Errorf("Response body changed: %q -> %q", last, got)
+ }
+ }
+
+ var open, close int32
+ for i := 0; i < 150; i++ {
+ open, close = atomic.LoadInt32(&numOpen), atomic.LoadInt32(&numClose)
+ if open < 1 {
+ t.Fatalf("open = %d; want at least", open)
+ }
+ if close == open-1 {
+ // Success
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Errorf("%d connections opened, %d closed; want %d to close", open, close, open-1)
+}
+
+// tests that Transport doesn't retain a pointer to the provided request.
+func TestTransportGCRequest(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ t.Run("Body", func(t *testing.T) { testTransportGCRequest(t, mode, true) })
+ t.Run("NoBody", func(t *testing.T) { testTransportGCRequest(t, mode, false) })
+ })
+}
+func testTransportGCRequest(t *testing.T, mode testMode, body bool) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ io.ReadAll(r.Body)
+ if body {
+ io.WriteString(w, "Hello.")
+ }
+ }))
+
+ didGC := make(chan struct{})
+ (func() {
+ body := strings.NewReader("some body")
+ req, _ := NewRequest("POST", cst.ts.URL, body)
+ runtime.SetFinalizer(req, func(*Request) { close(didGC) })
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.ReadAll(res.Body); err != nil {
+ t.Fatal(err)
+ }
+ if err := res.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+ })()
+ for {
+ select {
+ case <-didGC:
+ return
+ case <-time.After(1 * time.Millisecond):
+ runtime.GC()
+ }
+ }
+}
+
+func TestTransportRejectsInvalidHeaders(t *testing.T) { run(t, testTransportRejectsInvalidHeaders) }
+func testTransportRejectsInvalidHeaders(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ fmt.Fprintf(w, "Handler saw headers: %q", r.Header)
+ }), optQuietLog)
+ cst.tr.DisableKeepAlives = true
+
+ tests := []struct {
+ key, val string
+ ok bool
+ }{
+ {"Foo", "capital-key", true}, // verify h2 allows capital keys
+ {"Foo", "foo\x00bar", false}, // \x00 byte in value not allowed
+ {"Foo", "two\nlines", false}, // \n byte in value not allowed
+ {"bogus\nkey", "v", false}, // \n byte also not allowed in key
+ {"A space", "v", false}, // spaces in keys not allowed
+ {"имя", "v", false}, // key must be ascii
+ {"name", "валю", true}, // value may be non-ascii
+ {"", "v", false}, // key must be non-empty
+ {"k", "", true}, // value may be empty
+ }
+ for _, tt := range tests {
+ dialedc := make(chan bool, 1)
+ cst.tr.Dial = func(netw, addr string) (net.Conn, error) {
+ dialedc <- true
+ return net.Dial(netw, addr)
+ }
+ req, _ := NewRequest("GET", cst.ts.URL, nil)
+ req.Header[tt.key] = []string{tt.val}
+ res, err := cst.c.Do(req)
+ var body []byte
+ if err == nil {
+ body, _ = io.ReadAll(res.Body)
+ res.Body.Close()
+ }
+ var dialed bool
+ select {
+ case <-dialedc:
+ dialed = true
+ default:
+ }
+
+ if !tt.ok && dialed {
+ t.Errorf("For key %q, value %q, transport dialed. Expected local failure. Response was: (%v, %v)\nServer replied with: %s", tt.key, tt.val, res, err, body)
+ } else if (err == nil) != tt.ok {
+ t.Errorf("For key %q, value %q; got err = %v; want ok=%v", tt.key, tt.val, err, tt.ok)
+ }
+ }
+}
+
+func TestInterruptWithPanic(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ t.Run("boom", func(t *testing.T) { testInterruptWithPanic(t, mode, "boom") })
+ t.Run("nil", func(t *testing.T) { t.Setenv("GODEBUG", "panicnil=1"); testInterruptWithPanic(t, mode, nil) })
+ t.Run("ErrAbortHandler", func(t *testing.T) { testInterruptWithPanic(t, mode, ErrAbortHandler) })
+ }, testNotParallel)
+}
+func testInterruptWithPanic(t *testing.T, mode testMode, panicValue any) {
+ const msg = "hello"
+
+ testDone := make(chan struct{})
+ defer close(testDone)
+
+ var errorLog lockedBytesBuffer
+ gotHeaders := make(chan bool, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ io.WriteString(w, msg)
+ w.(Flusher).Flush()
+
+ select {
+ case <-gotHeaders:
+ case <-testDone:
+ }
+ panic(panicValue)
+ }), func(ts *httptest.Server) {
+ ts.Config.ErrorLog = log.New(&errorLog, "", 0)
+ })
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gotHeaders <- true
+ defer res.Body.Close()
+ slurp, err := io.ReadAll(res.Body)
+ if string(slurp) != msg {
+ t.Errorf("client read %q; want %q", slurp, msg)
+ }
+ if err == nil {
+ t.Errorf("client read all successfully; want some error")
+ }
+ logOutput := func() string {
+ errorLog.Lock()
+ defer errorLog.Unlock()
+ return errorLog.String()
+ }
+ wantStackLogged := panicValue != nil && panicValue != ErrAbortHandler
+
+ waitCondition(t, 10*time.Millisecond, func(d time.Duration) bool {
+ gotLog := logOutput()
+ if !wantStackLogged {
+ if gotLog == "" {
+ return true
+ }
+ t.Fatalf("want no log output; got: %s", gotLog)
+ }
+ if gotLog == "" {
+ if d > 0 {
+ t.Logf("wanted a stack trace logged; got nothing after %v", d)
+ }
+ return false
+ }
+ if !strings.Contains(gotLog, "created by ") && strings.Count(gotLog, "\n") < 6 {
+ if d > 0 {
+ t.Logf("output doesn't look like a panic stack trace after %v. Got: %s", d, gotLog)
+ }
+ return false
+ }
+ return true
+ })
+}
+
+type lockedBytesBuffer struct {
+ sync.Mutex
+ bytes.Buffer
+}
+
+func (b *lockedBytesBuffer) Write(p []byte) (int, error) {
+ b.Lock()
+ defer b.Unlock()
+ return b.Buffer.Write(p)
+}
+
+// Issue 15366
+func TestH12_AutoGzipWithDumpResponse(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ h := w.Header()
+ h.Set("Content-Encoding", "gzip")
+ h.Set("Content-Length", "23")
+ io.WriteString(w, "\x1f\x8b\b\x00\x00\x00\x00\x00\x00\x00s\xf3\xf7\a\x00\xab'\xd4\x1a\x03\x00\x00\x00")
+ },
+ EarlyCheckResponse: func(proto string, res *Response) {
+ if !res.Uncompressed {
+ t.Errorf("%s: expected Uncompressed to be set", proto)
+ }
+ dump, err := httputil.DumpResponse(res, true)
+ if err != nil {
+ t.Errorf("%s: DumpResponse: %v", proto, err)
+ return
+ }
+ if strings.Contains(string(dump), "Connection: close") {
+ t.Errorf("%s: should not see \"Connection: close\" in dump; got:\n%s", proto, dump)
+ }
+ if !strings.Contains(string(dump), "FOO") {
+ t.Errorf("%s: should see \"FOO\" in response; got:\n%s", proto, dump)
+ }
+ },
+ }.run(t)
+}
+
+// Issue 14607
+func TestCloseIdleConnections(t *testing.T) { run(t, testCloseIdleConnections) }
+func testCloseIdleConnections(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("X-Addr", r.RemoteAddr)
+ }))
+ get := func() string {
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ v := res.Header.Get("X-Addr")
+ if v == "" {
+ t.Fatal("didn't get X-Addr")
+ }
+ return v
+ }
+ a1 := get()
+ cst.tr.CloseIdleConnections()
+ a2 := get()
+ if a1 == a2 {
+ t.Errorf("didn't close connection")
+ }
+}
+
+type noteCloseConn struct {
+ net.Conn
+ closeFunc func()
+}
+
+func (x noteCloseConn) Close() error {
+ x.closeFunc()
+ return x.Conn.Close()
+}
+
+type testErrorReader struct{ t *testing.T }
+
+func (r testErrorReader) Read(p []byte) (n int, err error) {
+ r.t.Error("unexpected Read call")
+ return 0, io.EOF
+}
+
+func TestNoSniffExpectRequestBody(t *testing.T) { run(t, testNoSniffExpectRequestBody) }
+func testNoSniffExpectRequestBody(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.WriteHeader(StatusUnauthorized)
+ }))
+
+ // Set ExpectContinueTimeout non-zero so RoundTrip won't try to write it.
+ cst.tr.ExpectContinueTimeout = 10 * time.Second
+
+ req, err := NewRequest("POST", cst.ts.URL, testErrorReader{t})
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.ContentLength = 0 // so transport is tempted to sniff it
+ req.Header.Set("Expect", "100-continue")
+ res, err := cst.tr.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != StatusUnauthorized {
+ t.Errorf("status code = %v; want %v", res.StatusCode, StatusUnauthorized)
+ }
+}
+
+func TestServerUndeclaredTrailers(t *testing.T) { run(t, testServerUndeclaredTrailers) }
+func testServerUndeclaredTrailers(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Foo", "Bar")
+ w.Header().Set("Trailer:Foo", "Baz")
+ w.(Flusher).Flush()
+ w.Header().Add("Trailer:Foo", "Baz2")
+ w.Header().Set("Trailer:Bar", "Quux")
+ }))
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.Copy(io.Discard, res.Body); err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ delete(res.Header, "Date")
+ delete(res.Header, "Content-Type")
+
+ if want := (Header{"Foo": {"Bar"}}); !reflect.DeepEqual(res.Header, want) {
+ t.Errorf("Header = %#v; want %#v", res.Header, want)
+ }
+ if want := (Header{"Foo": {"Baz", "Baz2"}, "Bar": {"Quux"}}); !reflect.DeepEqual(res.Trailer, want) {
+ t.Errorf("Trailer = %#v; want %#v", res.Trailer, want)
+ }
+}
+
+func TestBadResponseAfterReadingBody(t *testing.T) {
+ run(t, testBadResponseAfterReadingBody, []testMode{http1Mode})
+}
+func testBadResponseAfterReadingBody(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ _, err := io.Copy(io.Discard, r.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, _, err := w.(Hijacker).Hijack()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ fmt.Fprintln(c, "some bogus crap")
+ }))
+
+ closes := 0
+ res, err := cst.c.Post(cst.ts.URL, "text/plain", countCloseReader{&closes, strings.NewReader("hello")})
+ if err == nil {
+ res.Body.Close()
+ t.Fatal("expected an error to be returned from Post")
+ }
+ if closes != 1 {
+ t.Errorf("closes = %d; want 1", closes)
+ }
+}
+
+func TestWriteHeader0(t *testing.T) { run(t, testWriteHeader0) }
+func testWriteHeader0(t *testing.T, mode testMode) {
+ gotpanic := make(chan bool, 1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ defer close(gotpanic)
+ defer func() {
+ if e := recover(); e != nil {
+ got := fmt.Sprintf("%T, %v", e, e)
+ want := "string, invalid WriteHeader code 0"
+ if got != want {
+ t.Errorf("unexpected panic value:\n got: %v\nwant: %v\n", got, want)
+ }
+ gotpanic <- true
+
+ // Set an explicit 503. This also tests that the WriteHeader call panics
+ // before it recorded that an explicit value was set and that bogus
+ // value wasn't stuck.
+ w.WriteHeader(503)
+ }
+ }()
+ w.WriteHeader(0)
+ }))
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != 503 {
+ t.Errorf("Response: %v %q; want 503", res.StatusCode, res.Status)
+ }
+ if !<-gotpanic {
+ t.Error("expected panic in handler")
+ }
+}
+
+// Issue 23010: don't be super strict checking WriteHeader's code if
+// it's not even valid to call WriteHeader then anyway.
+func TestWriteHeaderNoCodeCheck(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ testWriteHeaderAfterWrite(t, mode, false)
+ })
+}
+func TestWriteHeaderNoCodeCheck_h1hijack(t *testing.T) {
+ testWriteHeaderAfterWrite(t, http1Mode, true)
+}
+func testWriteHeaderAfterWrite(t *testing.T, mode testMode, hijack bool) {
+ var errorLog lockedBytesBuffer
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if hijack {
+ conn, _, _ := w.(Hijacker).Hijack()
+ defer conn.Close()
+ conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nfoo"))
+ w.WriteHeader(0) // verify this doesn't panic if there's already output; Issue 23010
+ conn.Write([]byte("bar"))
+ return
+ }
+ io.WriteString(w, "foo")
+ w.(Flusher).Flush()
+ w.WriteHeader(0) // verify this doesn't panic if there's already output; Issue 23010
+ io.WriteString(w, "bar")
+ }), func(ts *httptest.Server) {
+ ts.Config.ErrorLog = log.New(&errorLog, "", 0)
+ })
+ res, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(body), "foobar"; got != want {
+ t.Errorf("got = %q; want %q", got, want)
+ }
+
+ // Also check the stderr output:
+ if mode == http2Mode {
+ // TODO: also emit this log message for HTTP/2?
+ // We historically haven't, so don't check.
+ return
+ }
+ gotLog := strings.TrimSpace(errorLog.String())
+ wantLog := "http: superfluous response.WriteHeader call from net/http_test.testWriteHeaderAfterWrite.func1 (clientserver_test.go:"
+ if hijack {
+ wantLog = "http: response.WriteHeader on hijacked connection from net/http_test.testWriteHeaderAfterWrite.func1 (clientserver_test.go:"
+ }
+ if !strings.HasPrefix(gotLog, wantLog) {
+ t.Errorf("stderr output = %q; want %q", gotLog, wantLog)
+ }
+}
+
+func TestBidiStreamReverseProxy(t *testing.T) {
+ run(t, testBidiStreamReverseProxy, []testMode{http2Mode})
+}
+func testBidiStreamReverseProxy(t *testing.T, mode testMode) {
+ backend := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ if _, err := io.Copy(w, r.Body); err != nil {
+ log.Printf("bidi backend copy: %v", err)
+ }
+ }))
+
+ backURL, err := url.Parse(backend.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rp := httputil.NewSingleHostReverseProxy(backURL)
+ rp.Transport = backend.tr
+ proxy := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ rp.ServeHTTP(w, r)
+ }))
+
+ bodyRes := make(chan any, 1) // error or hash.Hash
+ pr, pw := io.Pipe()
+ req, _ := NewRequest("PUT", proxy.ts.URL, pr)
+ const size = 4 << 20
+ go func() {
+ h := sha1.New()
+ _, err := io.CopyN(io.MultiWriter(h, pw), rand.Reader, size)
+ go pw.Close()
+ if err != nil {
+ bodyRes <- err
+ } else {
+ bodyRes <- h
+ }
+ }()
+ res, err := backend.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ hgot := sha1.New()
+ n, err := io.Copy(hgot, res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != size {
+ t.Fatalf("got %d bytes; want %d", n, size)
+ }
+ select {
+ case v := <-bodyRes:
+ switch v := v.(type) {
+ default:
+ t.Fatalf("body copy: %v", err)
+ case hash.Hash:
+ if !bytes.Equal(v.Sum(nil), hgot.Sum(nil)) {
+ t.Errorf("written bytes didn't match received bytes")
+ }
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout")
+ }
+
+}
+
+// Always use HTTP/1.1 for WebSocket upgrades.
+func TestH12_WebSocketUpgrade(t *testing.T) {
+ h12Compare{
+ Handler: func(w ResponseWriter, r *Request) {
+ h := w.Header()
+ h.Set("Foo", "bar")
+ },
+ ReqFunc: func(c *Client, url string) (*Response, error) {
+ req, _ := NewRequest("GET", url, nil)
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "WebSocket")
+ return c.Do(req)
+ },
+ EarlyCheckResponse: func(proto string, res *Response) {
+ if res.Proto != "HTTP/1.1" {
+ t.Errorf("%s: expected HTTP/1.1, got %q", proto, res.Proto)
+ }
+ res.Proto = "HTTP/IGNORE" // skip later checks that Proto must be 1.1 vs 2.0
+ },
+ }.run(t)
+}
+
+func TestIdentityTransferEncoding(t *testing.T) { run(t, testIdentityTransferEncoding) }
+func testIdentityTransferEncoding(t *testing.T, mode testMode) {
+ const body = "body"
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ gotBody, _ := io.ReadAll(r.Body)
+ if got, want := string(gotBody), body; got != want {
+ t.Errorf("got request body = %q; want %q", got, want)
+ }
+ w.Header().Set("Transfer-Encoding", "identity")
+ w.WriteHeader(StatusOK)
+ w.(Flusher).Flush()
+ io.WriteString(w, body)
+ }))
+ req, _ := NewRequest("GET", cst.ts.URL, strings.NewReader(body))
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ gotBody, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(gotBody), body; got != want {
+ t.Errorf("got response body = %q; want %q", got, want)
+ }
+}
+
+func TestEarlyHintsRequest(t *testing.T) { run(t, testEarlyHintsRequest) }
+func testEarlyHintsRequest(t *testing.T, mode testMode) {
+ var wg sync.WaitGroup
+ wg.Add(1)
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ h := w.Header()
+
+ h.Add("Content-Length", "123") // must be ignored
+ h.Add("Link", "; rel=preload; as=style")
+ h.Add("Link", "; rel=preload; as=script")
+ w.WriteHeader(StatusEarlyHints)
+
+ wg.Wait()
+
+ h.Add("Link", "; rel=preload; as=script")
+ w.WriteHeader(StatusEarlyHints)
+
+ w.Write([]byte("Hello"))
+ }))
+
+ checkLinkHeaders := func(t *testing.T, expected, got []string) {
+ t.Helper()
+
+ if len(expected) != len(got) {
+ t.Errorf("got %d expected %d", len(got), len(expected))
+ }
+
+ for i := range expected {
+ if expected[i] != got[i] {
+ t.Errorf("got %q expected %q", got[i], expected[i])
+ }
+ }
+ }
+
+ checkExcludedHeaders := func(t *testing.T, header textproto.MIMEHeader) {
+ t.Helper()
+
+ for _, h := range []string{"Content-Length", "Transfer-Encoding"} {
+ if v, ok := header[h]; ok {
+ t.Errorf("%s is %q; must not be sent", h, v)
+ }
+ }
+ }
+
+ var respCounter uint8
+ trace := &httptrace.ClientTrace{
+ Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
+ switch respCounter {
+ case 0:
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script"}, header["Link"])
+ checkExcludedHeaders(t, header)
+
+ wg.Done()
+ case 1:
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script", "; rel=preload; as=script"}, header["Link"])
+ checkExcludedHeaders(t, header)
+
+ default:
+ t.Error("Unexpected 1xx response")
+ }
+
+ respCounter++
+
+ return nil
+ },
+ }
+ req, _ := NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), "GET", cst.ts.URL, nil)
+
+ res, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script", "; rel=preload; as=script"}, res.Header["Link"])
+ if cl := res.Header.Get("Content-Length"); cl != "123" {
+ t.Errorf("Content-Length is %q; want 123", cl)
+ }
+
+ body, _ := io.ReadAll(res.Body)
+ if string(body) != "Hello" {
+ t.Errorf("Read body %q; want Hello", body)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/clone.go b/platform/dbops/binaries/go/go/src/net/http/clone.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a3375bff7164163d39753f4bbf1edb9e87f87cd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/clone.go
@@ -0,0 +1,74 @@
+// 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 http
+
+import (
+ "mime/multipart"
+ "net/textproto"
+ "net/url"
+)
+
+func cloneURLValues(v url.Values) url.Values {
+ if v == nil {
+ return nil
+ }
+ // http.Header and url.Values have the same representation, so temporarily
+ // treat it like http.Header, which does have a clone:
+ return url.Values(Header(v).Clone())
+}
+
+func cloneURL(u *url.URL) *url.URL {
+ if u == nil {
+ return nil
+ }
+ u2 := new(url.URL)
+ *u2 = *u
+ if u.User != nil {
+ u2.User = new(url.Userinfo)
+ *u2.User = *u.User
+ }
+ return u2
+}
+
+func cloneMultipartForm(f *multipart.Form) *multipart.Form {
+ if f == nil {
+ return nil
+ }
+ f2 := &multipart.Form{
+ Value: (map[string][]string)(Header(f.Value).Clone()),
+ }
+ if f.File != nil {
+ m := make(map[string][]*multipart.FileHeader)
+ for k, vv := range f.File {
+ vv2 := make([]*multipart.FileHeader, len(vv))
+ for i, v := range vv {
+ vv2[i] = cloneMultipartFileHeader(v)
+ }
+ m[k] = vv2
+ }
+ f2.File = m
+ }
+ return f2
+}
+
+func cloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader {
+ if fh == nil {
+ return nil
+ }
+ fh2 := new(multipart.FileHeader)
+ *fh2 = *fh
+ fh2.Header = textproto.MIMEHeader(Header(fh.Header).Clone())
+ return fh2
+}
+
+// cloneOrMakeHeader invokes Header.Clone but if the
+// result is nil, it'll instead make and return a non-nil Header.
+func cloneOrMakeHeader(hdr Header) Header {
+ clone := hdr.Clone()
+ if clone == nil {
+ clone = make(Header)
+ }
+ return clone
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookie.go b/platform/dbops/binaries/go/go/src/net/http/cookie.go
new file mode 100644
index 0000000000000000000000000000000000000000..c22897f3f99e4d238f5ca74ee00e8c5ddd95985d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookie.go
@@ -0,0 +1,468 @@
+// 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 http
+
+import (
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "net/http/internal/ascii"
+ "net/textproto"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an
+// HTTP response or the Cookie header of an HTTP request.
+//
+// See https://tools.ietf.org/html/rfc6265 for details.
+type Cookie struct {
+ Name string
+ Value string
+
+ Path string // optional
+ Domain string // optional
+ Expires time.Time // optional
+ RawExpires string // for reading cookies only
+
+ // MaxAge=0 means no 'Max-Age' attribute specified.
+ // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
+ // MaxAge>0 means Max-Age attribute present and given in seconds
+ MaxAge int
+ Secure bool
+ HttpOnly bool
+ SameSite SameSite
+ Raw string
+ Unparsed []string // Raw text of unparsed attribute-value pairs
+}
+
+// SameSite allows a server to define a cookie attribute making it impossible for
+// the browser to send this cookie along with cross-site requests. The main
+// goal is to mitigate the risk of cross-origin information leakage, and provide
+// some protection against cross-site request forgery attacks.
+//
+// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
+type SameSite int
+
+const (
+ SameSiteDefaultMode SameSite = iota + 1
+ SameSiteLaxMode
+ SameSiteStrictMode
+ SameSiteNoneMode
+)
+
+// readSetCookies parses all "Set-Cookie" values from
+// the header h and returns the successfully parsed Cookies.
+func readSetCookies(h Header) []*Cookie {
+ cookieCount := len(h["Set-Cookie"])
+ if cookieCount == 0 {
+ return []*Cookie{}
+ }
+ cookies := make([]*Cookie, 0, cookieCount)
+ for _, line := range h["Set-Cookie"] {
+ parts := strings.Split(textproto.TrimString(line), ";")
+ if len(parts) == 1 && parts[0] == "" {
+ continue
+ }
+ parts[0] = textproto.TrimString(parts[0])
+ name, value, ok := strings.Cut(parts[0], "=")
+ if !ok {
+ continue
+ }
+ name = textproto.TrimString(name)
+ if !isCookieNameValid(name) {
+ continue
+ }
+ value, ok = parseCookieValue(value, true)
+ if !ok {
+ continue
+ }
+ c := &Cookie{
+ Name: name,
+ Value: value,
+ Raw: line,
+ }
+ for i := 1; i < len(parts); i++ {
+ parts[i] = textproto.TrimString(parts[i])
+ if len(parts[i]) == 0 {
+ continue
+ }
+
+ attr, val, _ := strings.Cut(parts[i], "=")
+ lowerAttr, isASCII := ascii.ToLower(attr)
+ if !isASCII {
+ continue
+ }
+ val, ok = parseCookieValue(val, false)
+ if !ok {
+ c.Unparsed = append(c.Unparsed, parts[i])
+ continue
+ }
+
+ switch lowerAttr {
+ case "samesite":
+ lowerVal, ascii := ascii.ToLower(val)
+ if !ascii {
+ c.SameSite = SameSiteDefaultMode
+ continue
+ }
+ switch lowerVal {
+ case "lax":
+ c.SameSite = SameSiteLaxMode
+ case "strict":
+ c.SameSite = SameSiteStrictMode
+ case "none":
+ c.SameSite = SameSiteNoneMode
+ default:
+ c.SameSite = SameSiteDefaultMode
+ }
+ continue
+ case "secure":
+ c.Secure = true
+ continue
+ case "httponly":
+ c.HttpOnly = true
+ continue
+ case "domain":
+ c.Domain = val
+ continue
+ case "max-age":
+ secs, err := strconv.Atoi(val)
+ if err != nil || secs != 0 && val[0] == '0' {
+ break
+ }
+ if secs <= 0 {
+ secs = -1
+ }
+ c.MaxAge = secs
+ continue
+ case "expires":
+ c.RawExpires = val
+ exptime, err := time.Parse(time.RFC1123, val)
+ if err != nil {
+ exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", val)
+ if err != nil {
+ c.Expires = time.Time{}
+ break
+ }
+ }
+ c.Expires = exptime.UTC()
+ continue
+ case "path":
+ c.Path = val
+ continue
+ }
+ c.Unparsed = append(c.Unparsed, parts[i])
+ }
+ cookies = append(cookies, c)
+ }
+ return cookies
+}
+
+// SetCookie adds a Set-Cookie header to the provided [ResponseWriter]'s headers.
+// The provided cookie must have a valid Name. Invalid cookies may be
+// silently dropped.
+func SetCookie(w ResponseWriter, cookie *Cookie) {
+ if v := cookie.String(); v != "" {
+ w.Header().Add("Set-Cookie", v)
+ }
+}
+
+// String returns the serialization of the cookie for use in a [Cookie]
+// header (if only Name and Value are set) or a Set-Cookie response
+// header (if other fields are set).
+// If c is nil or c.Name is invalid, the empty string is returned.
+func (c *Cookie) String() string {
+ if c == nil || !isCookieNameValid(c.Name) {
+ return ""
+ }
+ // extraCookieLength derived from typical length of cookie attributes
+ // see RFC 6265 Sec 4.1.
+ const extraCookieLength = 110
+ var b strings.Builder
+ b.Grow(len(c.Name) + len(c.Value) + len(c.Domain) + len(c.Path) + extraCookieLength)
+ b.WriteString(c.Name)
+ b.WriteRune('=')
+ b.WriteString(sanitizeCookieValue(c.Value))
+
+ if len(c.Path) > 0 {
+ b.WriteString("; Path=")
+ b.WriteString(sanitizeCookiePath(c.Path))
+ }
+ if len(c.Domain) > 0 {
+ if validCookieDomain(c.Domain) {
+ // A c.Domain containing illegal characters is not
+ // sanitized but simply dropped which turns the cookie
+ // into a host-only cookie. A leading dot is okay
+ // but won't be sent.
+ d := c.Domain
+ if d[0] == '.' {
+ d = d[1:]
+ }
+ b.WriteString("; Domain=")
+ b.WriteString(d)
+ } else {
+ log.Printf("net/http: invalid Cookie.Domain %q; dropping domain attribute", c.Domain)
+ }
+ }
+ var buf [len(TimeFormat)]byte
+ if validCookieExpires(c.Expires) {
+ b.WriteString("; Expires=")
+ b.Write(c.Expires.UTC().AppendFormat(buf[:0], TimeFormat))
+ }
+ if c.MaxAge > 0 {
+ b.WriteString("; Max-Age=")
+ b.Write(strconv.AppendInt(buf[:0], int64(c.MaxAge), 10))
+ } else if c.MaxAge < 0 {
+ b.WriteString("; Max-Age=0")
+ }
+ if c.HttpOnly {
+ b.WriteString("; HttpOnly")
+ }
+ if c.Secure {
+ b.WriteString("; Secure")
+ }
+ switch c.SameSite {
+ case SameSiteDefaultMode:
+ // Skip, default mode is obtained by not emitting the attribute.
+ case SameSiteNoneMode:
+ b.WriteString("; SameSite=None")
+ case SameSiteLaxMode:
+ b.WriteString("; SameSite=Lax")
+ case SameSiteStrictMode:
+ b.WriteString("; SameSite=Strict")
+ }
+ return b.String()
+}
+
+// Valid reports whether the cookie is valid.
+func (c *Cookie) Valid() error {
+ if c == nil {
+ return errors.New("http: nil Cookie")
+ }
+ if !isCookieNameValid(c.Name) {
+ return errors.New("http: invalid Cookie.Name")
+ }
+ if !c.Expires.IsZero() && !validCookieExpires(c.Expires) {
+ return errors.New("http: invalid Cookie.Expires")
+ }
+ for i := 0; i < len(c.Value); i++ {
+ if !validCookieValueByte(c.Value[i]) {
+ return fmt.Errorf("http: invalid byte %q in Cookie.Value", c.Value[i])
+ }
+ }
+ if len(c.Path) > 0 {
+ for i := 0; i < len(c.Path); i++ {
+ if !validCookiePathByte(c.Path[i]) {
+ return fmt.Errorf("http: invalid byte %q in Cookie.Path", c.Path[i])
+ }
+ }
+ }
+ if len(c.Domain) > 0 {
+ if !validCookieDomain(c.Domain) {
+ return errors.New("http: invalid Cookie.Domain")
+ }
+ }
+ return nil
+}
+
+// readCookies parses all "Cookie" values from the header h and
+// returns the successfully parsed Cookies.
+//
+// if filter isn't empty, only cookies of that name are returned.
+func readCookies(h Header, filter string) []*Cookie {
+ lines := h["Cookie"]
+ if len(lines) == 0 {
+ return []*Cookie{}
+ }
+
+ cookies := make([]*Cookie, 0, len(lines)+strings.Count(lines[0], ";"))
+ for _, line := range lines {
+ line = textproto.TrimString(line)
+
+ var part string
+ for len(line) > 0 { // continue since we have rest
+ part, line, _ = strings.Cut(line, ";")
+ part = textproto.TrimString(part)
+ if part == "" {
+ continue
+ }
+ name, val, _ := strings.Cut(part, "=")
+ name = textproto.TrimString(name)
+ if !isCookieNameValid(name) {
+ continue
+ }
+ if filter != "" && filter != name {
+ continue
+ }
+ val, ok := parseCookieValue(val, true)
+ if !ok {
+ continue
+ }
+ cookies = append(cookies, &Cookie{Name: name, Value: val})
+ }
+ }
+ return cookies
+}
+
+// validCookieDomain reports whether v is a valid cookie domain-value.
+func validCookieDomain(v string) bool {
+ if isCookieDomainName(v) {
+ return true
+ }
+ if net.ParseIP(v) != nil && !strings.Contains(v, ":") {
+ return true
+ }
+ return false
+}
+
+// validCookieExpires reports whether v is a valid cookie expires-value.
+func validCookieExpires(t time.Time) bool {
+ // IETF RFC 6265 Section 5.1.1.5, the year must not be less than 1601
+ return t.Year() >= 1601
+}
+
+// isCookieDomainName reports whether s is a valid domain name or a valid
+// domain name with a leading dot '.'. It is almost a direct copy of
+// package net's isDomainName.
+func isCookieDomainName(s string) bool {
+ if len(s) == 0 {
+ return false
+ }
+ if len(s) > 255 {
+ return false
+ }
+
+ if s[0] == '.' {
+ // A cookie a domain attribute may start with a leading dot.
+ s = s[1:]
+ }
+ last := byte('.')
+ ok := false // Ok once we've seen a letter.
+ partlen := 0
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ switch {
+ default:
+ return false
+ case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
+ // No '_' allowed here (in contrast to package net).
+ ok = true
+ partlen++
+ case '0' <= c && c <= '9':
+ // fine
+ partlen++
+ case c == '-':
+ // Byte before dash cannot be dot.
+ if last == '.' {
+ return false
+ }
+ partlen++
+ case c == '.':
+ // Byte before dot cannot be dot, dash.
+ if last == '.' || last == '-' {
+ return false
+ }
+ if partlen > 63 || partlen == 0 {
+ return false
+ }
+ partlen = 0
+ }
+ last = c
+ }
+ if last == '-' || partlen > 63 {
+ return false
+ }
+
+ return ok
+}
+
+var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
+
+func sanitizeCookieName(n string) string {
+ return cookieNameSanitizer.Replace(n)
+}
+
+// sanitizeCookieValue produces a suitable cookie-value from v.
+// https://tools.ietf.org/html/rfc6265#section-4.1.1
+//
+// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
+// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+// ; US-ASCII characters excluding CTLs,
+// ; whitespace DQUOTE, comma, semicolon,
+// ; and backslash
+//
+// We loosen this as spaces and commas are common in cookie values
+// but we produce a quoted cookie-value if and only if v contains
+// commas or spaces.
+// See https://golang.org/issue/7243 for the discussion.
+func sanitizeCookieValue(v string) string {
+ v = sanitizeOrWarn("Cookie.Value", validCookieValueByte, v)
+ if len(v) == 0 {
+ return v
+ }
+ if strings.ContainsAny(v, " ,") {
+ return `"` + v + `"`
+ }
+ return v
+}
+
+func validCookieValueByte(b byte) bool {
+ return 0x20 <= b && b < 0x7f && b != '"' && b != ';' && b != '\\'
+}
+
+// path-av = "Path=" path-value
+// path-value =
+func sanitizeCookiePath(v string) string {
+ return sanitizeOrWarn("Cookie.Path", validCookiePathByte, v)
+}
+
+func validCookiePathByte(b byte) bool {
+ return 0x20 <= b && b < 0x7f && b != ';'
+}
+
+func sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string {
+ ok := true
+ for i := 0; i < len(v); i++ {
+ if valid(v[i]) {
+ continue
+ }
+ log.Printf("net/http: invalid byte %q in %s; dropping invalid bytes", v[i], fieldName)
+ ok = false
+ break
+ }
+ if ok {
+ return v
+ }
+ buf := make([]byte, 0, len(v))
+ for i := 0; i < len(v); i++ {
+ if b := v[i]; valid(b) {
+ buf = append(buf, b)
+ }
+ }
+ return string(buf)
+}
+
+func parseCookieValue(raw string, allowDoubleQuote bool) (string, bool) {
+ // Strip the quotes, if present.
+ if allowDoubleQuote && len(raw) > 1 && raw[0] == '"' && raw[len(raw)-1] == '"' {
+ raw = raw[1 : len(raw)-1]
+ }
+ for i := 0; i < len(raw); i++ {
+ if !validCookieValueByte(raw[i]) {
+ return "", false
+ }
+ }
+ return raw, true
+}
+
+func isCookieNameValid(raw string) bool {
+ if raw == "" {
+ return false
+ }
+ return strings.IndexFunc(raw, isNotToken) < 0
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookie_test.go b/platform/dbops/binaries/go/go/src/net/http/cookie_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e5bd46a744fba57e9ddce0e637d34cfc33f2f9a1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookie_test.go
@@ -0,0 +1,652 @@
+// 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 http
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+var writeSetCookiesTests = []struct {
+ Cookie *Cookie
+ Raw string
+}{
+ {
+ &Cookie{Name: "cookie-1", Value: "v$1"},
+ "cookie-1=v$1",
+ },
+ {
+ &Cookie{Name: "cookie-2", Value: "two", MaxAge: 3600},
+ "cookie-2=two; Max-Age=3600",
+ },
+ {
+ &Cookie{Name: "cookie-3", Value: "three", Domain: ".example.com"},
+ "cookie-3=three; Domain=example.com",
+ },
+ {
+ &Cookie{Name: "cookie-4", Value: "four", Path: "/restricted/"},
+ "cookie-4=four; Path=/restricted/",
+ },
+ {
+ &Cookie{Name: "cookie-5", Value: "five", Domain: "wrong;bad.abc"},
+ "cookie-5=five",
+ },
+ {
+ &Cookie{Name: "cookie-6", Value: "six", Domain: "bad-.abc"},
+ "cookie-6=six",
+ },
+ {
+ &Cookie{Name: "cookie-7", Value: "seven", Domain: "127.0.0.1"},
+ "cookie-7=seven; Domain=127.0.0.1",
+ },
+ {
+ &Cookie{Name: "cookie-8", Value: "eight", Domain: "::1"},
+ "cookie-8=eight",
+ },
+ {
+ &Cookie{Name: "cookie-9", Value: "expiring", Expires: time.Unix(1257894000, 0)},
+ "cookie-9=expiring; Expires=Tue, 10 Nov 2009 23:00:00 GMT",
+ },
+ // According to IETF 6265 Section 5.1.1.5, the year cannot be less than 1601
+ {
+ &Cookie{Name: "cookie-10", Value: "expiring-1601", Expires: time.Date(1601, 1, 1, 1, 1, 1, 1, time.UTC)},
+ "cookie-10=expiring-1601; Expires=Mon, 01 Jan 1601 01:01:01 GMT",
+ },
+ {
+ &Cookie{Name: "cookie-11", Value: "invalid-expiry", Expires: time.Date(1600, 1, 1, 1, 1, 1, 1, time.UTC)},
+ "cookie-11=invalid-expiry",
+ },
+ {
+ &Cookie{Name: "cookie-12", Value: "samesite-default", SameSite: SameSiteDefaultMode},
+ "cookie-12=samesite-default",
+ },
+ {
+ &Cookie{Name: "cookie-13", Value: "samesite-lax", SameSite: SameSiteLaxMode},
+ "cookie-13=samesite-lax; SameSite=Lax",
+ },
+ {
+ &Cookie{Name: "cookie-14", Value: "samesite-strict", SameSite: SameSiteStrictMode},
+ "cookie-14=samesite-strict; SameSite=Strict",
+ },
+ {
+ &Cookie{Name: "cookie-15", Value: "samesite-none", SameSite: SameSiteNoneMode},
+ "cookie-15=samesite-none; SameSite=None",
+ },
+ // The "special" cookies have values containing commas or spaces which
+ // are disallowed by RFC 6265 but are common in the wild.
+ {
+ &Cookie{Name: "special-1", Value: "a z"},
+ `special-1="a z"`,
+ },
+ {
+ &Cookie{Name: "special-2", Value: " z"},
+ `special-2=" z"`,
+ },
+ {
+ &Cookie{Name: "special-3", Value: "a "},
+ `special-3="a "`,
+ },
+ {
+ &Cookie{Name: "special-4", Value: " "},
+ `special-4=" "`,
+ },
+ {
+ &Cookie{Name: "special-5", Value: "a,z"},
+ `special-5="a,z"`,
+ },
+ {
+ &Cookie{Name: "special-6", Value: ",z"},
+ `special-6=",z"`,
+ },
+ {
+ &Cookie{Name: "special-7", Value: "a,"},
+ `special-7="a,"`,
+ },
+ {
+ &Cookie{Name: "special-8", Value: ","},
+ `special-8=","`,
+ },
+ {
+ &Cookie{Name: "empty-value", Value: ""},
+ `empty-value=`,
+ },
+ {
+ nil,
+ ``,
+ },
+ {
+ &Cookie{Name: ""},
+ ``,
+ },
+ {
+ &Cookie{Name: "\t"},
+ ``,
+ },
+ {
+ &Cookie{Name: "\r"},
+ ``,
+ },
+ {
+ &Cookie{Name: "a\nb", Value: "v"},
+ ``,
+ },
+ {
+ &Cookie{Name: "a\nb", Value: "v"},
+ ``,
+ },
+ {
+ &Cookie{Name: "a\rb", Value: "v"},
+ ``,
+ },
+}
+
+func TestWriteSetCookies(t *testing.T) {
+ defer log.SetOutput(os.Stderr)
+ var logbuf strings.Builder
+ log.SetOutput(&logbuf)
+
+ for i, tt := range writeSetCookiesTests {
+ if g, e := tt.Cookie.String(), tt.Raw; g != e {
+ t.Errorf("Test %d, expecting:\n%s\nGot:\n%s\n", i, e, g)
+ continue
+ }
+ }
+
+ if got, sub := logbuf.String(), "dropping domain attribute"; !strings.Contains(got, sub) {
+ t.Errorf("Expected substring %q in log output. Got:\n%s", sub, got)
+ }
+}
+
+type headerOnlyResponseWriter Header
+
+func (ho headerOnlyResponseWriter) Header() Header {
+ return Header(ho)
+}
+
+func (ho headerOnlyResponseWriter) Write([]byte) (int, error) {
+ panic("NOIMPL")
+}
+
+func (ho headerOnlyResponseWriter) WriteHeader(int) {
+ panic("NOIMPL")
+}
+
+func TestSetCookie(t *testing.T) {
+ m := make(Header)
+ SetCookie(headerOnlyResponseWriter(m), &Cookie{Name: "cookie-1", Value: "one", Path: "/restricted/"})
+ SetCookie(headerOnlyResponseWriter(m), &Cookie{Name: "cookie-2", Value: "two", MaxAge: 3600})
+ if l := len(m["Set-Cookie"]); l != 2 {
+ t.Fatalf("expected %d cookies, got %d", 2, l)
+ }
+ if g, e := m["Set-Cookie"][0], "cookie-1=one; Path=/restricted/"; g != e {
+ t.Errorf("cookie #1: want %q, got %q", e, g)
+ }
+ if g, e := m["Set-Cookie"][1], "cookie-2=two; Max-Age=3600"; g != e {
+ t.Errorf("cookie #2: want %q, got %q", e, g)
+ }
+}
+
+var addCookieTests = []struct {
+ Cookies []*Cookie
+ Raw string
+}{
+ {
+ []*Cookie{},
+ "",
+ },
+ {
+ []*Cookie{{Name: "cookie-1", Value: "v$1"}},
+ "cookie-1=v$1",
+ },
+ {
+ []*Cookie{
+ {Name: "cookie-1", Value: "v$1"},
+ {Name: "cookie-2", Value: "v$2"},
+ {Name: "cookie-3", Value: "v$3"},
+ },
+ "cookie-1=v$1; cookie-2=v$2; cookie-3=v$3",
+ },
+}
+
+func TestAddCookie(t *testing.T) {
+ for i, tt := range addCookieTests {
+ req, _ := NewRequest("GET", "http://example.com/", nil)
+ for _, c := range tt.Cookies {
+ req.AddCookie(c)
+ }
+ if g := req.Header.Get("Cookie"); g != tt.Raw {
+ t.Errorf("Test %d:\nwant: %s\n got: %s\n", i, tt.Raw, g)
+ continue
+ }
+ }
+}
+
+var readSetCookiesTests = []struct {
+ Header Header
+ Cookies []*Cookie
+}{
+ {
+ Header{"Set-Cookie": {"Cookie-1=v$1"}},
+ []*Cookie{{Name: "Cookie-1", Value: "v$1", Raw: "Cookie-1=v$1"}},
+ },
+ {
+ Header{"Set-Cookie": {"NID=99=YsDT5i3E-CXax-; expires=Wed, 23-Nov-2011 01:05:03 GMT; path=/; domain=.google.ch; HttpOnly"}},
+ []*Cookie{{
+ Name: "NID",
+ Value: "99=YsDT5i3E-CXax-",
+ Path: "/",
+ Domain: ".google.ch",
+ HttpOnly: true,
+ Expires: time.Date(2011, 11, 23, 1, 5, 3, 0, time.UTC),
+ RawExpires: "Wed, 23-Nov-2011 01:05:03 GMT",
+ Raw: "NID=99=YsDT5i3E-CXax-; expires=Wed, 23-Nov-2011 01:05:03 GMT; path=/; domain=.google.ch; HttpOnly",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {".ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly"}},
+ []*Cookie{{
+ Name: ".ASPXAUTH",
+ Value: "7E3AA",
+ Path: "/",
+ Expires: time.Date(2012, 3, 7, 14, 25, 6, 0, time.UTC),
+ RawExpires: "Wed, 07-Mar-2012 14:25:06 GMT",
+ HttpOnly: true,
+ Raw: ".ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"ASP.NET_SessionId=foo; path=/; HttpOnly"}},
+ []*Cookie{{
+ Name: "ASP.NET_SessionId",
+ Value: "foo",
+ Path: "/",
+ HttpOnly: true,
+ Raw: "ASP.NET_SessionId=foo; path=/; HttpOnly",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"samesitedefault=foo; SameSite"}},
+ []*Cookie{{
+ Name: "samesitedefault",
+ Value: "foo",
+ SameSite: SameSiteDefaultMode,
+ Raw: "samesitedefault=foo; SameSite",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"samesiteinvalidisdefault=foo; SameSite=invalid"}},
+ []*Cookie{{
+ Name: "samesiteinvalidisdefault",
+ Value: "foo",
+ SameSite: SameSiteDefaultMode,
+ Raw: "samesiteinvalidisdefault=foo; SameSite=invalid",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"samesitelax=foo; SameSite=Lax"}},
+ []*Cookie{{
+ Name: "samesitelax",
+ Value: "foo",
+ SameSite: SameSiteLaxMode,
+ Raw: "samesitelax=foo; SameSite=Lax",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"samesitestrict=foo; SameSite=Strict"}},
+ []*Cookie{{
+ Name: "samesitestrict",
+ Value: "foo",
+ SameSite: SameSiteStrictMode,
+ Raw: "samesitestrict=foo; SameSite=Strict",
+ }},
+ },
+ {
+ Header{"Set-Cookie": {"samesitenone=foo; SameSite=None"}},
+ []*Cookie{{
+ Name: "samesitenone",
+ Value: "foo",
+ SameSite: SameSiteNoneMode,
+ Raw: "samesitenone=foo; SameSite=None",
+ }},
+ },
+ // Make sure we can properly read back the Set-Cookie headers we create
+ // for values containing spaces or commas:
+ {
+ Header{"Set-Cookie": {`special-1=a z`}},
+ []*Cookie{{Name: "special-1", Value: "a z", Raw: `special-1=a z`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-2=" z"`}},
+ []*Cookie{{Name: "special-2", Value: " z", Raw: `special-2=" z"`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-3="a "`}},
+ []*Cookie{{Name: "special-3", Value: "a ", Raw: `special-3="a "`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-4=" "`}},
+ []*Cookie{{Name: "special-4", Value: " ", Raw: `special-4=" "`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-5=a,z`}},
+ []*Cookie{{Name: "special-5", Value: "a,z", Raw: `special-5=a,z`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-6=",z"`}},
+ []*Cookie{{Name: "special-6", Value: ",z", Raw: `special-6=",z"`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-7=a,`}},
+ []*Cookie{{Name: "special-7", Value: "a,", Raw: `special-7=a,`}},
+ },
+ {
+ Header{"Set-Cookie": {`special-8=","`}},
+ []*Cookie{{Name: "special-8", Value: ",", Raw: `special-8=","`}},
+ },
+ // Make sure we can properly read back the Set-Cookie headers
+ // for names containing spaces:
+ {
+ Header{"Set-Cookie": {`special-9 =","`}},
+ []*Cookie{{Name: "special-9", Value: ",", Raw: `special-9 =","`}},
+ },
+
+ // TODO(bradfitz): users have reported seeing this in the
+ // wild, but do browsers handle it? RFC 6265 just says "don't
+ // do that" (section 3) and then never mentions header folding
+ // again.
+ // Header{"Set-Cookie": {"ASP.NET_SessionId=foo; path=/; HttpOnly, .ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly"}},
+}
+
+func toJSON(v any) string {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return fmt.Sprintf("%#v", v)
+ }
+ return string(b)
+}
+
+func TestReadSetCookies(t *testing.T) {
+ for i, tt := range readSetCookiesTests {
+ for n := 0; n < 2; n++ { // to verify readSetCookies doesn't mutate its input
+ c := readSetCookies(tt.Header)
+ if !reflect.DeepEqual(c, tt.Cookies) {
+ t.Errorf("#%d readSetCookies: have\n%s\nwant\n%s\n", i, toJSON(c), toJSON(tt.Cookies))
+ continue
+ }
+ }
+ }
+}
+
+var readCookiesTests = []struct {
+ Header Header
+ Filter string
+ Cookies []*Cookie
+}{
+ {
+ Header{"Cookie": {"Cookie-1=v$1", "c2=v2"}},
+ "",
+ []*Cookie{
+ {Name: "Cookie-1", Value: "v$1"},
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {"Cookie-1=v$1", "c2=v2"}},
+ "c2",
+ []*Cookie{
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {"Cookie-1=v$1; c2=v2"}},
+ "",
+ []*Cookie{
+ {Name: "Cookie-1", Value: "v$1"},
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {"Cookie-1=v$1; c2=v2"}},
+ "c2",
+ []*Cookie{
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {`Cookie-1="v$1"; c2="v2"`}},
+ "",
+ []*Cookie{
+ {Name: "Cookie-1", Value: "v$1"},
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {`Cookie-1="v$1"; c2=v2;`}},
+ "",
+ []*Cookie{
+ {Name: "Cookie-1", Value: "v$1"},
+ {Name: "c2", Value: "v2"},
+ },
+ },
+ {
+ Header{"Cookie": {``}},
+ "",
+ []*Cookie{},
+ },
+}
+
+func TestReadCookies(t *testing.T) {
+ for i, tt := range readCookiesTests {
+ for n := 0; n < 2; n++ { // to verify readCookies doesn't mutate its input
+ c := readCookies(tt.Header, tt.Filter)
+ if !reflect.DeepEqual(c, tt.Cookies) {
+ t.Errorf("#%d readCookies:\nhave: %s\nwant: %s\n", i, toJSON(c), toJSON(tt.Cookies))
+ continue
+ }
+ }
+ }
+}
+
+func TestSetCookieDoubleQuotes(t *testing.T) {
+ res := &Response{Header: Header{}}
+ res.Header.Add("Set-Cookie", `quoted0=none; max-age=30`)
+ res.Header.Add("Set-Cookie", `quoted1="cookieValue"; max-age=31`)
+ res.Header.Add("Set-Cookie", `quoted2=cookieAV; max-age="32"`)
+ res.Header.Add("Set-Cookie", `quoted3="both"; max-age="33"`)
+ got := res.Cookies()
+ want := []*Cookie{
+ {Name: "quoted0", Value: "none", MaxAge: 30},
+ {Name: "quoted1", Value: "cookieValue", MaxAge: 31},
+ {Name: "quoted2", Value: "cookieAV"},
+ {Name: "quoted3", Value: "both"},
+ }
+ if len(got) != len(want) {
+ t.Fatalf("got %d cookies, want %d", len(got), len(want))
+ }
+ for i, w := range want {
+ g := got[i]
+ if g.Name != w.Name || g.Value != w.Value || g.MaxAge != w.MaxAge {
+ t.Errorf("cookie #%d:\ngot %v\nwant %v", i, g, w)
+ }
+ }
+}
+
+func TestCookieSanitizeValue(t *testing.T) {
+ defer log.SetOutput(os.Stderr)
+ var logbuf strings.Builder
+ log.SetOutput(&logbuf)
+
+ tests := []struct {
+ in, want string
+ }{
+ {"foo", "foo"},
+ {"foo;bar", "foobar"},
+ {"foo\\bar", "foobar"},
+ {"foo\"bar", "foobar"},
+ {"\x00\x7e\x7f\x80", "\x7e"},
+ {`"withquotes"`, "withquotes"},
+ {"a z", `"a z"`},
+ {" z", `" z"`},
+ {"a ", `"a "`},
+ {"a,z", `"a,z"`},
+ {",z", `",z"`},
+ {"a,", `"a,"`},
+ }
+ for _, tt := range tests {
+ if got := sanitizeCookieValue(tt.in); got != tt.want {
+ t.Errorf("sanitizeCookieValue(%q) = %q; want %q", tt.in, got, tt.want)
+ }
+ }
+
+ if got, sub := logbuf.String(), "dropping invalid bytes"; !strings.Contains(got, sub) {
+ t.Errorf("Expected substring %q in log output. Got:\n%s", sub, got)
+ }
+}
+
+func TestCookieSanitizePath(t *testing.T) {
+ defer log.SetOutput(os.Stderr)
+ var logbuf strings.Builder
+ log.SetOutput(&logbuf)
+
+ tests := []struct {
+ in, want string
+ }{
+ {"/path", "/path"},
+ {"/path with space/", "/path with space/"},
+ {"/just;no;semicolon\x00orstuff/", "/justnosemicolonorstuff/"},
+ }
+ for _, tt := range tests {
+ if got := sanitizeCookiePath(tt.in); got != tt.want {
+ t.Errorf("sanitizeCookiePath(%q) = %q; want %q", tt.in, got, tt.want)
+ }
+ }
+
+ if got, sub := logbuf.String(), "dropping invalid bytes"; !strings.Contains(got, sub) {
+ t.Errorf("Expected substring %q in log output. Got:\n%s", sub, got)
+ }
+}
+
+func TestCookieValid(t *testing.T) {
+ tests := []struct {
+ cookie *Cookie
+ valid bool
+ }{
+ {nil, false},
+ {&Cookie{Name: ""}, false},
+ {&Cookie{Name: "invalid-value", Value: "foo\"bar"}, false},
+ {&Cookie{Name: "invalid-path", Path: "/foo;bar/"}, false},
+ {&Cookie{Name: "invalid-domain", Domain: "example.com:80"}, false},
+ {&Cookie{Name: "invalid-expiry", Value: "", Expires: time.Date(1600, 1, 1, 1, 1, 1, 1, time.UTC)}, false},
+ {&Cookie{Name: "valid-empty"}, true},
+ {&Cookie{Name: "valid-expires", Value: "foo", Path: "/bar", Domain: "example.com", Expires: time.Unix(0, 0)}, true},
+ {&Cookie{Name: "valid-max-age", Value: "foo", Path: "/bar", Domain: "example.com", MaxAge: 60}, true},
+ {&Cookie{Name: "valid-all-fields", Value: "foo", Path: "/bar", Domain: "example.com", Expires: time.Unix(0, 0), MaxAge: 0}, true},
+ }
+
+ for _, tt := range tests {
+ err := tt.cookie.Valid()
+ if err != nil && tt.valid {
+ t.Errorf("%#v.Valid() returned error %v; want nil", tt.cookie, err)
+ }
+ if err == nil && !tt.valid {
+ t.Errorf("%#v.Valid() returned nil; want error", tt.cookie)
+ }
+ }
+}
+
+func BenchmarkCookieString(b *testing.B) {
+ const wantCookieString = `cookie-9=i3e01nf61b6t23bvfmplnanol3; Path=/restricted/; Domain=example.com; Expires=Tue, 10 Nov 2009 23:00:00 GMT; Max-Age=3600`
+ c := &Cookie{
+ Name: "cookie-9",
+ Value: "i3e01nf61b6t23bvfmplnanol3",
+ Expires: time.Unix(1257894000, 0),
+ Path: "/restricted/",
+ Domain: ".example.com",
+ MaxAge: 3600,
+ }
+ var benchmarkCookieString string
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ benchmarkCookieString = c.String()
+ }
+ if have, want := benchmarkCookieString, wantCookieString; have != want {
+ b.Fatalf("Have: %v Want: %v", have, want)
+ }
+}
+
+func BenchmarkReadSetCookies(b *testing.B) {
+ header := Header{
+ "Set-Cookie": {
+ "NID=99=YsDT5i3E-CXax-; expires=Wed, 23-Nov-2011 01:05:03 GMT; path=/; domain=.google.ch; HttpOnly",
+ ".ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly",
+ },
+ }
+ wantCookies := []*Cookie{
+ {
+ Name: "NID",
+ Value: "99=YsDT5i3E-CXax-",
+ Path: "/",
+ Domain: ".google.ch",
+ HttpOnly: true,
+ Expires: time.Date(2011, 11, 23, 1, 5, 3, 0, time.UTC),
+ RawExpires: "Wed, 23-Nov-2011 01:05:03 GMT",
+ Raw: "NID=99=YsDT5i3E-CXax-; expires=Wed, 23-Nov-2011 01:05:03 GMT; path=/; domain=.google.ch; HttpOnly",
+ },
+ {
+ Name: ".ASPXAUTH",
+ Value: "7E3AA",
+ Path: "/",
+ Expires: time.Date(2012, 3, 7, 14, 25, 6, 0, time.UTC),
+ RawExpires: "Wed, 07-Mar-2012 14:25:06 GMT",
+ HttpOnly: true,
+ Raw: ".ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly",
+ },
+ }
+ var c []*Cookie
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ c = readSetCookies(header)
+ }
+ if !reflect.DeepEqual(c, wantCookies) {
+ b.Fatalf("readSetCookies:\nhave: %s\nwant: %s\n", toJSON(c), toJSON(wantCookies))
+ }
+}
+
+func BenchmarkReadCookies(b *testing.B) {
+ header := Header{
+ "Cookie": {
+ `de=; client_region=0; rpld1=0:hispeed.ch|20:che|21:zh|22:zurich|23:47.36|24:8.53|; rpld0=1:08|; backplane-channel=newspaper.com:1471; devicetype=0; osfam=0; rplmct=2; s_pers=%20s_vmonthnum%3D1472680800496%2526vn%253D1%7C1472680800496%3B%20s_nr%3D1471686767664-New%7C1474278767664%3B%20s_lv%3D1471686767669%7C1566294767669%3B%20s_lv_s%3DFirst%2520Visit%7C1471688567669%3B%20s_monthinvisit%3Dtrue%7C1471688567677%3B%20gvp_p5%3Dsports%253Ablog%253Aearly-lead%2520-%2520184693%2520-%252020160820%2520-%2520u-s%7C1471688567681%3B%20gvp_p51%3Dwp%2520-%2520sports%7C1471688567684%3B; s_sess=%20s_wp_ep%3Dhomepage%3B%20s._ref%3Dhttps%253A%252F%252Fwww.google.ch%252F%3B%20s_cc%3Dtrue%3B%20s_ppvl%3Dsports%25253Ablog%25253Aearly-lead%252520-%252520184693%252520-%25252020160820%252520-%252520u-lawyer%252C12%252C12%252C502%252C1231%252C502%252C1680%252C1050%252C2%252CP%3B%20s_ppv%3Dsports%25253Ablog%25253Aearly-lead%252520-%252520184693%252520-%25252020160820%252520-%252520u-s-lawyer%252C12%252C12%252C502%252C1231%252C502%252C1680%252C1050%252C2%252CP%3B%20s_dslv%3DFirst%2520Visit%3B%20s_sq%3Dwpninewspapercom%253D%252526pid%25253Dsports%2525253Ablog%2525253Aearly-lead%25252520-%25252520184693%25252520-%2525252020160820%25252520-%25252520u-s%252526pidt%25253D1%252526oid%25253Dhttps%2525253A%2525252F%2525252Fwww.newspaper.com%2525252F%2525253Fnid%2525253Dmenu_nav_homepage%252526ot%25253DA%3B`,
+ },
+ }
+ wantCookies := []*Cookie{
+ {Name: "de", Value: ""},
+ {Name: "client_region", Value: "0"},
+ {Name: "rpld1", Value: "0:hispeed.ch|20:che|21:zh|22:zurich|23:47.36|24:8.53|"},
+ {Name: "rpld0", Value: "1:08|"},
+ {Name: "backplane-channel", Value: "newspaper.com:1471"},
+ {Name: "devicetype", Value: "0"},
+ {Name: "osfam", Value: "0"},
+ {Name: "rplmct", Value: "2"},
+ {Name: "s_pers", Value: "%20s_vmonthnum%3D1472680800496%2526vn%253D1%7C1472680800496%3B%20s_nr%3D1471686767664-New%7C1474278767664%3B%20s_lv%3D1471686767669%7C1566294767669%3B%20s_lv_s%3DFirst%2520Visit%7C1471688567669%3B%20s_monthinvisit%3Dtrue%7C1471688567677%3B%20gvp_p5%3Dsports%253Ablog%253Aearly-lead%2520-%2520184693%2520-%252020160820%2520-%2520u-s%7C1471688567681%3B%20gvp_p51%3Dwp%2520-%2520sports%7C1471688567684%3B"},
+ {Name: "s_sess", Value: "%20s_wp_ep%3Dhomepage%3B%20s._ref%3Dhttps%253A%252F%252Fwww.google.ch%252F%3B%20s_cc%3Dtrue%3B%20s_ppvl%3Dsports%25253Ablog%25253Aearly-lead%252520-%252520184693%252520-%25252020160820%252520-%252520u-lawyer%252C12%252C12%252C502%252C1231%252C502%252C1680%252C1050%252C2%252CP%3B%20s_ppv%3Dsports%25253Ablog%25253Aearly-lead%252520-%252520184693%252520-%25252020160820%252520-%252520u-s-lawyer%252C12%252C12%252C502%252C1231%252C502%252C1680%252C1050%252C2%252CP%3B%20s_dslv%3DFirst%2520Visit%3B%20s_sq%3Dwpninewspapercom%253D%252526pid%25253Dsports%2525253Ablog%2525253Aearly-lead%25252520-%25252520184693%25252520-%2525252020160820%25252520-%25252520u-s%252526pidt%25253D1%252526oid%25253Dhttps%2525253A%2525252F%2525252Fwww.newspaper.com%2525252F%2525253Fnid%2525253Dmenu_nav_homepage%252526ot%25253DA%3B"},
+ }
+ var c []*Cookie
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ c = readCookies(header, "")
+ }
+ if !reflect.DeepEqual(c, wantCookies) {
+ b.Fatalf("readCookies:\nhave: %s\nwant: %s\n", toJSON(c), toJSON(wantCookies))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/dummy_publicsuffix_test.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/dummy_publicsuffix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9b3117358f8a879ff5ba38d585e238abd639ceda
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/dummy_publicsuffix_test.go
@@ -0,0 +1,21 @@
+// 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 cookiejar_test
+
+import "net/http/cookiejar"
+
+type dummypsl struct {
+ List cookiejar.PublicSuffixList
+}
+
+func (dummypsl) PublicSuffix(domain string) string {
+ return domain
+}
+
+func (dummypsl) String() string {
+ return "dummy"
+}
+
+var publicsuffix = dummypsl{}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/example_test.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..91728ca9821b11924014d72cf7c9d55360cf4d39
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/example_test.go
@@ -0,0 +1,65 @@
+// 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 cookiejar_test
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+)
+
+func ExampleNew() {
+ // Start a server to give us cookies.
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if cookie, err := r.Cookie("Flavor"); err != nil {
+ http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
+ } else {
+ cookie.Value = "Oatmeal Raisin"
+ http.SetCookie(w, cookie)
+ }
+ }))
+ defer ts.Close()
+
+ u, err := url.Parse(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ // All users of cookiejar should import "golang.org/x/net/publicsuffix"
+ jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ client := &http.Client{
+ Jar: jar,
+ }
+
+ if _, err = client.Get(u.String()); err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Println("After 1st request:")
+ for _, cookie := range jar.Cookies(u) {
+ fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
+ }
+
+ if _, err = client.Get(u.String()); err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Println("After 2nd request:")
+ for _, cookie := range jar.Cookies(u) {
+ fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
+ }
+ // Output:
+ // After 1st request:
+ // Flavor: Chocolate Chip
+ // After 2nd request:
+ // Flavor: Oatmeal Raisin
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar.go
new file mode 100644
index 0000000000000000000000000000000000000000..e7f5ddd4d0096b9d036d6b7f4258d5695d9d9761
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar.go
@@ -0,0 +1,546 @@
+// 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 cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
+package cookiejar
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/internal/ascii"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+// PublicSuffixList provides the public suffix of a domain. For example:
+// - the public suffix of "example.com" is "com",
+// - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
+// - the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".
+//
+// Implementations of PublicSuffixList must be safe for concurrent use by
+// multiple goroutines.
+//
+// An implementation that always returns "" is valid and may be useful for
+// testing but it is not secure: it means that the HTTP server for foo.com can
+// set a cookie for bar.com.
+//
+// A public suffix list implementation is in the package
+// golang.org/x/net/publicsuffix.
+type PublicSuffixList interface {
+ // PublicSuffix returns the public suffix of domain.
+ //
+ // TODO: specify which of the caller and callee is responsible for IP
+ // addresses, for leading and trailing dots, for case sensitivity, and
+ // for IDN/Punycode.
+ PublicSuffix(domain string) string
+
+ // String returns a description of the source of this public suffix
+ // list. The description will typically contain something like a time
+ // stamp or version number.
+ String() string
+}
+
+// Options are the options for creating a new Jar.
+type Options struct {
+ // PublicSuffixList is the public suffix list that determines whether
+ // an HTTP server can set a cookie for a domain.
+ //
+ // A nil value is valid and may be useful for testing but it is not
+ // secure: it means that the HTTP server for foo.co.uk can set a cookie
+ // for bar.co.uk.
+ PublicSuffixList PublicSuffixList
+}
+
+// Jar implements the http.CookieJar interface from the net/http package.
+type Jar struct {
+ psList PublicSuffixList
+
+ // mu locks the remaining fields.
+ mu sync.Mutex
+
+ // entries is a set of entries, keyed by their eTLD+1 and subkeyed by
+ // their name/domain/path.
+ entries map[string]map[string]entry
+
+ // nextSeqNum is the next sequence number assigned to a new cookie
+ // created SetCookies.
+ nextSeqNum uint64
+}
+
+// New returns a new cookie jar. A nil [*Options] is equivalent to a zero
+// Options.
+func New(o *Options) (*Jar, error) {
+ jar := &Jar{
+ entries: make(map[string]map[string]entry),
+ }
+ if o != nil {
+ jar.psList = o.PublicSuffixList
+ }
+ return jar, nil
+}
+
+// entry is the internal representation of a cookie.
+//
+// This struct type is not used outside of this package per se, but the exported
+// fields are those of RFC 6265.
+type entry struct {
+ Name string
+ Value string
+ Domain string
+ Path string
+ SameSite string
+ Secure bool
+ HttpOnly bool
+ Persistent bool
+ HostOnly bool
+ Expires time.Time
+ Creation time.Time
+ LastAccess time.Time
+
+ // seqNum is a sequence number so that Cookies returns cookies in a
+ // deterministic order, even for cookies that have equal Path length and
+ // equal Creation time. This simplifies testing.
+ seqNum uint64
+}
+
+// id returns the domain;path;name triple of e as an id.
+func (e *entry) id() string {
+ return fmt.Sprintf("%s;%s;%s", e.Domain, e.Path, e.Name)
+}
+
+// shouldSend determines whether e's cookie qualifies to be included in a
+// request to host/path. It is the caller's responsibility to check if the
+// cookie is expired.
+func (e *entry) shouldSend(https bool, host, path string) bool {
+ return e.domainMatch(host) && e.pathMatch(path) && (https || !e.Secure)
+}
+
+// domainMatch checks whether e's Domain allows sending e back to host.
+// It differs from "domain-match" of RFC 6265 section 5.1.3 because we treat
+// a cookie with an IP address in the Domain always as a host cookie.
+func (e *entry) domainMatch(host string) bool {
+ if e.Domain == host {
+ return true
+ }
+ return !e.HostOnly && hasDotSuffix(host, e.Domain)
+}
+
+// pathMatch implements "path-match" according to RFC 6265 section 5.1.4.
+func (e *entry) pathMatch(requestPath string) bool {
+ if requestPath == e.Path {
+ return true
+ }
+ if strings.HasPrefix(requestPath, e.Path) {
+ if e.Path[len(e.Path)-1] == '/' {
+ return true // The "/any/" matches "/any/path" case.
+ } else if requestPath[len(e.Path)] == '/' {
+ return true // The "/any" matches "/any/path" case.
+ }
+ }
+ return false
+}
+
+// hasDotSuffix reports whether s ends in "."+suffix.
+func hasDotSuffix(s, suffix string) bool {
+ return len(s) > len(suffix) && s[len(s)-len(suffix)-1] == '.' && s[len(s)-len(suffix):] == suffix
+}
+
+// Cookies implements the Cookies method of the [http.CookieJar] interface.
+//
+// It returns an empty slice if the URL's scheme is not HTTP or HTTPS.
+func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie) {
+ return j.cookies(u, time.Now())
+}
+
+// cookies is like Cookies but takes the current time as a parameter.
+func (j *Jar) cookies(u *url.URL, now time.Time) (cookies []*http.Cookie) {
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return cookies
+ }
+ host, err := canonicalHost(u.Host)
+ if err != nil {
+ return cookies
+ }
+ key := jarKey(host, j.psList)
+
+ j.mu.Lock()
+ defer j.mu.Unlock()
+
+ submap := j.entries[key]
+ if submap == nil {
+ return cookies
+ }
+
+ https := u.Scheme == "https"
+ path := u.Path
+ if path == "" {
+ path = "/"
+ }
+
+ modified := false
+ var selected []entry
+ for id, e := range submap {
+ if e.Persistent && !e.Expires.After(now) {
+ delete(submap, id)
+ modified = true
+ continue
+ }
+ if !e.shouldSend(https, host, path) {
+ continue
+ }
+ e.LastAccess = now
+ submap[id] = e
+ selected = append(selected, e)
+ modified = true
+ }
+ if modified {
+ if len(submap) == 0 {
+ delete(j.entries, key)
+ } else {
+ j.entries[key] = submap
+ }
+ }
+
+ // sort according to RFC 6265 section 5.4 point 2: by longest
+ // path and then by earliest creation time.
+ sort.Slice(selected, func(i, j int) bool {
+ s := selected
+ if len(s[i].Path) != len(s[j].Path) {
+ return len(s[i].Path) > len(s[j].Path)
+ }
+ if ret := s[i].Creation.Compare(s[j].Creation); ret != 0 {
+ return ret < 0
+ }
+ return s[i].seqNum < s[j].seqNum
+ })
+ for _, e := range selected {
+ cookies = append(cookies, &http.Cookie{Name: e.Name, Value: e.Value})
+ }
+
+ return cookies
+}
+
+// SetCookies implements the SetCookies method of the [http.CookieJar] interface.
+//
+// It does nothing if the URL's scheme is not HTTP or HTTPS.
+func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
+ j.setCookies(u, cookies, time.Now())
+}
+
+// setCookies is like SetCookies but takes the current time as parameter.
+func (j *Jar) setCookies(u *url.URL, cookies []*http.Cookie, now time.Time) {
+ if len(cookies) == 0 {
+ return
+ }
+ if u.Scheme != "http" && u.Scheme != "https" {
+ return
+ }
+ host, err := canonicalHost(u.Host)
+ if err != nil {
+ return
+ }
+ key := jarKey(host, j.psList)
+ defPath := defaultPath(u.Path)
+
+ j.mu.Lock()
+ defer j.mu.Unlock()
+
+ submap := j.entries[key]
+
+ modified := false
+ for _, cookie := range cookies {
+ e, remove, err := j.newEntry(cookie, now, defPath, host)
+ if err != nil {
+ continue
+ }
+ id := e.id()
+ if remove {
+ if submap != nil {
+ if _, ok := submap[id]; ok {
+ delete(submap, id)
+ modified = true
+ }
+ }
+ continue
+ }
+ if submap == nil {
+ submap = make(map[string]entry)
+ }
+
+ if old, ok := submap[id]; ok {
+ e.Creation = old.Creation
+ e.seqNum = old.seqNum
+ } else {
+ e.Creation = now
+ e.seqNum = j.nextSeqNum
+ j.nextSeqNum++
+ }
+ e.LastAccess = now
+ submap[id] = e
+ modified = true
+ }
+
+ if modified {
+ if len(submap) == 0 {
+ delete(j.entries, key)
+ } else {
+ j.entries[key] = submap
+ }
+ }
+}
+
+// canonicalHost strips port from host if present and returns the canonicalized
+// host name.
+func canonicalHost(host string) (string, error) {
+ var err error
+ if hasPort(host) {
+ host, _, err = net.SplitHostPort(host)
+ if err != nil {
+ return "", err
+ }
+ }
+ // Strip trailing dot from fully qualified domain names.
+ host = strings.TrimSuffix(host, ".")
+ encoded, err := toASCII(host)
+ if err != nil {
+ return "", err
+ }
+ // We know this is ascii, no need to check.
+ lower, _ := ascii.ToLower(encoded)
+ return lower, nil
+}
+
+// hasPort reports whether host contains a port number. host may be a host
+// name, an IPv4 or an IPv6 address.
+func hasPort(host string) bool {
+ colons := strings.Count(host, ":")
+ if colons == 0 {
+ return false
+ }
+ if colons == 1 {
+ return true
+ }
+ return host[0] == '[' && strings.Contains(host, "]:")
+}
+
+// jarKey returns the key to use for a jar.
+func jarKey(host string, psl PublicSuffixList) string {
+ if isIP(host) {
+ return host
+ }
+
+ var i int
+ if psl == nil {
+ i = strings.LastIndex(host, ".")
+ if i <= 0 {
+ return host
+ }
+ } else {
+ suffix := psl.PublicSuffix(host)
+ if suffix == host {
+ return host
+ }
+ i = len(host) - len(suffix)
+ if i <= 0 || host[i-1] != '.' {
+ // The provided public suffix list psl is broken.
+ // Storing cookies under host is a safe stopgap.
+ return host
+ }
+ // Only len(suffix) is used to determine the jar key from
+ // here on, so it is okay if psl.PublicSuffix("www.buggy.psl")
+ // returns "com" as the jar key is generated from host.
+ }
+ prevDot := strings.LastIndex(host[:i-1], ".")
+ return host[prevDot+1:]
+}
+
+// isIP reports whether host is an IP address.
+func isIP(host string) bool {
+ if strings.ContainsAny(host, ":%") {
+ // Probable IPv6 address.
+ // Hostnames can't contain : or %, so this is definitely not a valid host.
+ // Treating it as an IP is the more conservative option, and avoids the risk
+ // of interpeting ::1%.www.example.com as a subtomain of www.example.com.
+ return true
+ }
+ return net.ParseIP(host) != nil
+}
+
+// defaultPath returns the directory part of a URL's path according to
+// RFC 6265 section 5.1.4.
+func defaultPath(path string) string {
+ if len(path) == 0 || path[0] != '/' {
+ return "/" // Path is empty or malformed.
+ }
+
+ i := strings.LastIndex(path, "/") // Path starts with "/", so i != -1.
+ if i == 0 {
+ return "/" // Path has the form "/abc".
+ }
+ return path[:i] // Path is either of form "/abc/xyz" or "/abc/xyz/".
+}
+
+// newEntry creates an entry from an http.Cookie c. now is the current time and
+// is compared to c.Expires to determine deletion of c. defPath and host are the
+// default-path and the canonical host name of the URL c was received from.
+//
+// remove records whether the jar should delete this cookie, as it has already
+// expired with respect to now. In this case, e may be incomplete, but it will
+// be valid to call e.id (which depends on e's Name, Domain and Path).
+//
+// A malformed c.Domain will result in an error.
+func (j *Jar) newEntry(c *http.Cookie, now time.Time, defPath, host string) (e entry, remove bool, err error) {
+ e.Name = c.Name
+
+ if c.Path == "" || c.Path[0] != '/' {
+ e.Path = defPath
+ } else {
+ e.Path = c.Path
+ }
+
+ e.Domain, e.HostOnly, err = j.domainAndType(host, c.Domain)
+ if err != nil {
+ return e, false, err
+ }
+
+ // MaxAge takes precedence over Expires.
+ if c.MaxAge < 0 {
+ return e, true, nil
+ } else if c.MaxAge > 0 {
+ e.Expires = now.Add(time.Duration(c.MaxAge) * time.Second)
+ e.Persistent = true
+ } else {
+ if c.Expires.IsZero() {
+ e.Expires = endOfTime
+ e.Persistent = false
+ } else {
+ if !c.Expires.After(now) {
+ return e, true, nil
+ }
+ e.Expires = c.Expires
+ e.Persistent = true
+ }
+ }
+
+ e.Value = c.Value
+ e.Secure = c.Secure
+ e.HttpOnly = c.HttpOnly
+
+ switch c.SameSite {
+ case http.SameSiteDefaultMode:
+ e.SameSite = "SameSite"
+ case http.SameSiteStrictMode:
+ e.SameSite = "SameSite=Strict"
+ case http.SameSiteLaxMode:
+ e.SameSite = "SameSite=Lax"
+ }
+
+ return e, false, nil
+}
+
+var (
+ errIllegalDomain = errors.New("cookiejar: illegal cookie domain attribute")
+ errMalformedDomain = errors.New("cookiejar: malformed cookie domain attribute")
+)
+
+// endOfTime is the time when session (non-persistent) cookies expire.
+// This instant is representable in most date/time formats (not just
+// Go's time.Time) and should be far enough in the future.
+var endOfTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
+
+// domainAndType determines the cookie's domain and hostOnly attribute.
+func (j *Jar) domainAndType(host, domain string) (string, bool, error) {
+ if domain == "" {
+ // No domain attribute in the SetCookie header indicates a
+ // host cookie.
+ return host, true, nil
+ }
+
+ if isIP(host) {
+ // RFC 6265 is not super clear here, a sensible interpretation
+ // is that cookies with an IP address in the domain-attribute
+ // are allowed.
+
+ // RFC 6265 section 5.2.3 mandates to strip an optional leading
+ // dot in the domain-attribute before processing the cookie.
+ //
+ // Most browsers don't do that for IP addresses, only curl
+ // (version 7.54) and IE (version 11) do not reject a
+ // Set-Cookie: a=1; domain=.127.0.0.1
+ // This leading dot is optional and serves only as hint for
+ // humans to indicate that a cookie with "domain=.bbc.co.uk"
+ // would be sent to every subdomain of bbc.co.uk.
+ // It just doesn't make sense on IP addresses.
+ // The other processing and validation steps in RFC 6265 just
+ // collapse to:
+ if host != domain {
+ return "", false, errIllegalDomain
+ }
+
+ // According to RFC 6265 such cookies should be treated as
+ // domain cookies.
+ // As there are no subdomains of an IP address the treatment
+ // according to RFC 6265 would be exactly the same as that of
+ // a host-only cookie. Contemporary browsers (and curl) do
+ // allows such cookies but treat them as host-only cookies.
+ // So do we as it just doesn't make sense to label them as
+ // domain cookies when there is no domain; the whole notion of
+ // domain cookies requires a domain name to be well defined.
+ return host, true, nil
+ }
+
+ // From here on: If the cookie is valid, it is a domain cookie (with
+ // the one exception of a public suffix below).
+ // See RFC 6265 section 5.2.3.
+ if domain[0] == '.' {
+ domain = domain[1:]
+ }
+
+ if len(domain) == 0 || domain[0] == '.' {
+ // Received either "Domain=." or "Domain=..some.thing",
+ // both are illegal.
+ return "", false, errMalformedDomain
+ }
+
+ domain, isASCII := ascii.ToLower(domain)
+ if !isASCII {
+ // Received non-ASCII domain, e.g. "perché.com" instead of "xn--perch-fsa.com"
+ return "", false, errMalformedDomain
+ }
+
+ if domain[len(domain)-1] == '.' {
+ // We received stuff like "Domain=www.example.com.".
+ // Browsers do handle such stuff (actually differently) but
+ // RFC 6265 seems to be clear here (e.g. section 4.1.2.3) in
+ // requiring a reject. 4.1.2.3 is not normative, but
+ // "Domain Matching" (5.1.3) and "Canonicalized Host Names"
+ // (5.1.2) are.
+ return "", false, errMalformedDomain
+ }
+
+ // See RFC 6265 section 5.3 #5.
+ if j.psList != nil {
+ if ps := j.psList.PublicSuffix(domain); ps != "" && !hasDotSuffix(domain, ps) {
+ if host == domain {
+ // This is the one exception in which a cookie
+ // with a domain attribute is a host cookie.
+ return host, true, nil
+ }
+ return "", false, errIllegalDomain
+ }
+ }
+
+ // The domain must domain-match host: www.mycompany.com cannot
+ // set cookies for .ourcompetitors.com.
+ if host != domain && !hasDotSuffix(host, domain) {
+ return "", false, errIllegalDomain
+ }
+
+ return domain, false, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar_test.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..251f7c16171c3acc40be12a962eb7a48529699f8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/jar_test.go
@@ -0,0 +1,1355 @@
+// 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 cookiejar
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+// tNow is the synthetic current time used as now during testing.
+var tNow = time.Date(2013, 1, 1, 12, 0, 0, 0, time.UTC)
+
+// testPSL implements PublicSuffixList with just two rules: "co.uk"
+// and the default rule "*".
+// The implementation has two intentional bugs:
+//
+// PublicSuffix("www.buggy.psl") == "xy"
+// PublicSuffix("www2.buggy.psl") == "com"
+type testPSL struct{}
+
+func (testPSL) String() string {
+ return "testPSL"
+}
+func (testPSL) PublicSuffix(d string) string {
+ if d == "co.uk" || strings.HasSuffix(d, ".co.uk") {
+ return "co.uk"
+ }
+ if d == "www.buggy.psl" {
+ return "xy"
+ }
+ if d == "www2.buggy.psl" {
+ return "com"
+ }
+ return d[strings.LastIndex(d, ".")+1:]
+}
+
+// newTestJar creates an empty Jar with testPSL as the public suffix list.
+func newTestJar() *Jar {
+ jar, err := New(&Options{PublicSuffixList: testPSL{}})
+ if err != nil {
+ panic(err)
+ }
+ return jar
+}
+
+var hasDotSuffixTests = [...]struct {
+ s, suffix string
+}{
+ {"", ""},
+ {"", "."},
+ {"", "x"},
+ {".", ""},
+ {".", "."},
+ {".", ".."},
+ {".", "x"},
+ {".", "x."},
+ {".", ".x"},
+ {".", ".x."},
+ {"x", ""},
+ {"x", "."},
+ {"x", ".."},
+ {"x", "x"},
+ {"x", "x."},
+ {"x", ".x"},
+ {"x", ".x."},
+ {".x", ""},
+ {".x", "."},
+ {".x", ".."},
+ {".x", "x"},
+ {".x", "x."},
+ {".x", ".x"},
+ {".x", ".x."},
+ {"x.", ""},
+ {"x.", "."},
+ {"x.", ".."},
+ {"x.", "x"},
+ {"x.", "x."},
+ {"x.", ".x"},
+ {"x.", ".x."},
+ {"com", ""},
+ {"com", "m"},
+ {"com", "om"},
+ {"com", "com"},
+ {"com", ".com"},
+ {"com", "x.com"},
+ {"com", "xcom"},
+ {"com", "xorg"},
+ {"com", "org"},
+ {"com", "rg"},
+ {"foo.com", ""},
+ {"foo.com", "m"},
+ {"foo.com", "om"},
+ {"foo.com", "com"},
+ {"foo.com", ".com"},
+ {"foo.com", "o.com"},
+ {"foo.com", "oo.com"},
+ {"foo.com", "foo.com"},
+ {"foo.com", ".foo.com"},
+ {"foo.com", "x.foo.com"},
+ {"foo.com", "xfoo.com"},
+ {"foo.com", "xfoo.org"},
+ {"foo.com", "foo.org"},
+ {"foo.com", "oo.org"},
+ {"foo.com", "o.org"},
+ {"foo.com", ".org"},
+ {"foo.com", "org"},
+ {"foo.com", "rg"},
+}
+
+func TestHasDotSuffix(t *testing.T) {
+ for _, tc := range hasDotSuffixTests {
+ got := hasDotSuffix(tc.s, tc.suffix)
+ want := strings.HasSuffix(tc.s, "."+tc.suffix)
+ if got != want {
+ t.Errorf("s=%q, suffix=%q: got %v, want %v", tc.s, tc.suffix, got, want)
+ }
+ }
+}
+
+var canonicalHostTests = map[string]string{
+ "www.example.com": "www.example.com",
+ "WWW.EXAMPLE.COM": "www.example.com",
+ "wWw.eXAmple.CoM": "www.example.com",
+ "www.example.com:80": "www.example.com",
+ "192.168.0.10": "192.168.0.10",
+ "192.168.0.5:8080": "192.168.0.5",
+ "2001:4860:0:2001::68": "2001:4860:0:2001::68",
+ "[2001:4860:0:::68]:8080": "2001:4860:0:::68",
+ "www.bücher.de": "www.xn--bcher-kva.de",
+ "www.example.com.": "www.example.com",
+ // TODO: Fix canonicalHost so that all of the following malformed
+ // domain names trigger an error. (This list is not exhaustive, e.g.
+ // malformed internationalized domain names are missing.)
+ ".": "",
+ "..": ".",
+ "...": "..",
+ ".net": ".net",
+ ".net.": ".net",
+ "a..": "a.",
+ "b.a..": "b.a.",
+ "weird.stuff...": "weird.stuff..",
+ "[bad.unmatched.bracket:": "error",
+}
+
+func TestCanonicalHost(t *testing.T) {
+ for h, want := range canonicalHostTests {
+ got, err := canonicalHost(h)
+ if want == "error" {
+ if err == nil {
+ t.Errorf("%q: got %q and nil error, want non-nil", h, got)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("%q: %v", h, err)
+ continue
+ }
+ if got != want {
+ t.Errorf("%q: got %q, want %q", h, got, want)
+ continue
+ }
+ }
+}
+
+var hasPortTests = map[string]bool{
+ "www.example.com": false,
+ "www.example.com:80": true,
+ "127.0.0.1": false,
+ "127.0.0.1:8080": true,
+ "2001:4860:0:2001::68": false,
+ "[2001::0:::68]:80": true,
+}
+
+func TestHasPort(t *testing.T) {
+ for host, want := range hasPortTests {
+ if got := hasPort(host); got != want {
+ t.Errorf("%q: got %t, want %t", host, got, want)
+ }
+ }
+}
+
+var jarKeyTests = map[string]string{
+ "foo.www.example.com": "example.com",
+ "www.example.com": "example.com",
+ "example.com": "example.com",
+ "com": "com",
+ "foo.www.bbc.co.uk": "bbc.co.uk",
+ "www.bbc.co.uk": "bbc.co.uk",
+ "bbc.co.uk": "bbc.co.uk",
+ "co.uk": "co.uk",
+ "uk": "uk",
+ "192.168.0.5": "192.168.0.5",
+ "www.buggy.psl": "www.buggy.psl",
+ "www2.buggy.psl": "buggy.psl",
+ // The following are actual outputs of canonicalHost for
+ // malformed inputs to canonicalHost (see above).
+ "": "",
+ ".": ".",
+ "..": ".",
+ ".net": ".net",
+ "a.": "a.",
+ "b.a.": "a.",
+ "weird.stuff..": ".",
+}
+
+func TestJarKey(t *testing.T) {
+ for host, want := range jarKeyTests {
+ if got := jarKey(host, testPSL{}); got != want {
+ t.Errorf("%q: got %q, want %q", host, got, want)
+ }
+ }
+}
+
+var jarKeyNilPSLTests = map[string]string{
+ "foo.www.example.com": "example.com",
+ "www.example.com": "example.com",
+ "example.com": "example.com",
+ "com": "com",
+ "foo.www.bbc.co.uk": "co.uk",
+ "www.bbc.co.uk": "co.uk",
+ "bbc.co.uk": "co.uk",
+ "co.uk": "co.uk",
+ "uk": "uk",
+ "192.168.0.5": "192.168.0.5",
+ // The following are actual outputs of canonicalHost for
+ // malformed inputs to canonicalHost.
+ "": "",
+ ".": ".",
+ "..": "..",
+ ".net": ".net",
+ "a.": "a.",
+ "b.a.": "a.",
+ "weird.stuff..": "stuff..",
+}
+
+func TestJarKeyNilPSL(t *testing.T) {
+ for host, want := range jarKeyNilPSLTests {
+ if got := jarKey(host, nil); got != want {
+ t.Errorf("%q: got %q, want %q", host, got, want)
+ }
+ }
+}
+
+var isIPTests = map[string]bool{
+ "127.0.0.1": true,
+ "1.2.3.4": true,
+ "2001:4860:0:2001::68": true,
+ "::1%zone": true,
+ "example.com": false,
+ "1.1.1.300": false,
+ "www.foo.bar.net": false,
+ "123.foo.bar.net": false,
+}
+
+func TestIsIP(t *testing.T) {
+ for host, want := range isIPTests {
+ if got := isIP(host); got != want {
+ t.Errorf("%q: got %t, want %t", host, got, want)
+ }
+ }
+}
+
+var defaultPathTests = map[string]string{
+ "/": "/",
+ "/abc": "/",
+ "/abc/": "/abc",
+ "/abc/xyz": "/abc",
+ "/abc/xyz/": "/abc/xyz",
+ "/a/b/c.html": "/a/b",
+ "": "/",
+ "strange": "/",
+ "//": "/",
+ "/a//b": "/a/",
+ "/a/./b": "/a/.",
+ "/a/../b": "/a/..",
+}
+
+func TestDefaultPath(t *testing.T) {
+ for path, want := range defaultPathTests {
+ if got := defaultPath(path); got != want {
+ t.Errorf("%q: got %q, want %q", path, got, want)
+ }
+ }
+}
+
+var domainAndTypeTests = [...]struct {
+ host string // host Set-Cookie header was received from
+ domain string // domain attribute in Set-Cookie header
+ wantDomain string // expected domain of cookie
+ wantHostOnly bool // expected host-cookie flag
+ wantErr error // expected error
+}{
+ {"www.example.com", "", "www.example.com", true, nil},
+ {"127.0.0.1", "", "127.0.0.1", true, nil},
+ {"2001:4860:0:2001::68", "", "2001:4860:0:2001::68", true, nil},
+ {"www.example.com", "example.com", "example.com", false, nil},
+ {"www.example.com", ".example.com", "example.com", false, nil},
+ {"www.example.com", "www.example.com", "www.example.com", false, nil},
+ {"www.example.com", ".www.example.com", "www.example.com", false, nil},
+ {"foo.sso.example.com", "sso.example.com", "sso.example.com", false, nil},
+ {"bar.co.uk", "bar.co.uk", "bar.co.uk", false, nil},
+ {"foo.bar.co.uk", ".bar.co.uk", "bar.co.uk", false, nil},
+ {"127.0.0.1", "127.0.0.1", "127.0.0.1", true, nil},
+ {"2001:4860:0:2001::68", "2001:4860:0:2001::68", "2001:4860:0:2001::68", true, nil},
+ {"www.example.com", ".", "", false, errMalformedDomain},
+ {"www.example.com", "..", "", false, errMalformedDomain},
+ {"www.example.com", "other.com", "", false, errIllegalDomain},
+ {"www.example.com", "com", "", false, errIllegalDomain},
+ {"www.example.com", ".com", "", false, errIllegalDomain},
+ {"foo.bar.co.uk", ".co.uk", "", false, errIllegalDomain},
+ {"127.www.0.0.1", "127.0.0.1", "", false, errIllegalDomain},
+ {"com", "", "com", true, nil},
+ {"com", "com", "com", true, nil},
+ {"com", ".com", "com", true, nil},
+ {"co.uk", "", "co.uk", true, nil},
+ {"co.uk", "co.uk", "co.uk", true, nil},
+ {"co.uk", ".co.uk", "co.uk", true, nil},
+}
+
+func TestDomainAndType(t *testing.T) {
+ jar := newTestJar()
+ for _, tc := range domainAndTypeTests {
+ domain, hostOnly, err := jar.domainAndType(tc.host, tc.domain)
+ if err != tc.wantErr {
+ t.Errorf("%q/%q: got %q error, want %v",
+ tc.host, tc.domain, err, tc.wantErr)
+ continue
+ }
+ if err != nil {
+ continue
+ }
+ if domain != tc.wantDomain || hostOnly != tc.wantHostOnly {
+ t.Errorf("%q/%q: got %q/%t want %q/%t",
+ tc.host, tc.domain, domain, hostOnly,
+ tc.wantDomain, tc.wantHostOnly)
+ }
+ }
+}
+
+// expiresIn creates an expires attribute delta seconds from tNow.
+func expiresIn(delta int) string {
+ t := tNow.Add(time.Duration(delta) * time.Second)
+ return "expires=" + t.Format(time.RFC1123)
+}
+
+// mustParseURL parses s to a URL and panics on error.
+func mustParseURL(s string) *url.URL {
+ u, err := url.Parse(s)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ panic(fmt.Sprintf("Unable to parse URL %s.", s))
+ }
+ return u
+}
+
+// jarTest encapsulates the following actions on a jar:
+// 1. Perform SetCookies with fromURL and the cookies from setCookies.
+// (Done at time tNow + 0 ms.)
+// 2. Check that the entries in the jar matches content.
+// (Done at time tNow + 1001 ms.)
+// 3. For each query in tests: Check that Cookies with toURL yields the
+// cookies in want.
+// (Query n done at tNow + (n+2)*1001 ms.)
+type jarTest struct {
+ description string // The description of what this test is supposed to test
+ fromURL string // The full URL of the request from which Set-Cookie headers where received
+ setCookies []string // All the cookies received from fromURL
+ content string // The whole (non-expired) content of the jar
+ queries []query // Queries to test the Jar.Cookies method
+}
+
+// query contains one test of the cookies returned from Jar.Cookies.
+type query struct {
+ toURL string // the URL in the Cookies call
+ want string // the expected list of cookies (order matters)
+}
+
+// run runs the jarTest.
+func (test jarTest) run(t *testing.T, jar *Jar) {
+ now := tNow
+
+ // Populate jar with cookies.
+ setCookies := make([]*http.Cookie, len(test.setCookies))
+ for i, cs := range test.setCookies {
+ cookies := (&http.Response{Header: http.Header{"Set-Cookie": {cs}}}).Cookies()
+ if len(cookies) != 1 {
+ panic(fmt.Sprintf("Wrong cookie line %q: %#v", cs, cookies))
+ }
+ setCookies[i] = cookies[0]
+ }
+ jar.setCookies(mustParseURL(test.fromURL), setCookies, now)
+ now = now.Add(1001 * time.Millisecond)
+
+ // Serialize non-expired entries in the form "name1=val1 name2=val2".
+ var cs []string
+ for _, submap := range jar.entries {
+ for _, cookie := range submap {
+ if !cookie.Expires.After(now) {
+ continue
+ }
+ cs = append(cs, cookie.Name+"="+cookie.Value)
+ }
+ }
+ sort.Strings(cs)
+ got := strings.Join(cs, " ")
+
+ // Make sure jar content matches our expectations.
+ if got != test.content {
+ t.Errorf("Test %q Content\ngot %q\nwant %q",
+ test.description, got, test.content)
+ }
+
+ // Test different calls to Cookies.
+ for i, query := range test.queries {
+ now = now.Add(1001 * time.Millisecond)
+ var s []string
+ for _, c := range jar.cookies(mustParseURL(query.toURL), now) {
+ s = append(s, c.Name+"="+c.Value)
+ }
+ if got := strings.Join(s, " "); got != query.want {
+ t.Errorf("Test %q #%d\ngot %q\nwant %q", test.description, i, got, query.want)
+ }
+ }
+}
+
+// basicsTests contains fundamental tests. Each jarTest has to be performed on
+// a fresh, empty Jar.
+var basicsTests = [...]jarTest{
+ {
+ "Retrieval of a plain host cookie.",
+ "http://www.host.test/",
+ []string{"A=a"},
+ "A=a",
+ []query{
+ {"http://www.host.test", "A=a"},
+ {"http://www.host.test/", "A=a"},
+ {"http://www.host.test/some/path", "A=a"},
+ {"https://www.host.test", "A=a"},
+ {"https://www.host.test/", "A=a"},
+ {"https://www.host.test/some/path", "A=a"},
+ {"ftp://www.host.test", ""},
+ {"ftp://www.host.test/", ""},
+ {"ftp://www.host.test/some/path", ""},
+ {"http://www.other.org", ""},
+ {"http://sibling.host.test", ""},
+ {"http://deep.www.host.test", ""},
+ },
+ },
+ {
+ "Secure cookies are not returned to http.",
+ "http://www.host.test/",
+ []string{"A=a; secure"},
+ "A=a",
+ []query{
+ {"http://www.host.test", ""},
+ {"http://www.host.test/", ""},
+ {"http://www.host.test/some/path", ""},
+ {"https://www.host.test", "A=a"},
+ {"https://www.host.test/", "A=a"},
+ {"https://www.host.test/some/path", "A=a"},
+ },
+ },
+ {
+ "Explicit path.",
+ "http://www.host.test/",
+ []string{"A=a; path=/some/path"},
+ "A=a",
+ []query{
+ {"http://www.host.test", ""},
+ {"http://www.host.test/", ""},
+ {"http://www.host.test/some", ""},
+ {"http://www.host.test/some/", ""},
+ {"http://www.host.test/some/path", "A=a"},
+ {"http://www.host.test/some/paths", ""},
+ {"http://www.host.test/some/path/foo", "A=a"},
+ {"http://www.host.test/some/path/foo/", "A=a"},
+ },
+ },
+ {
+ "Implicit path #1: path is a directory.",
+ "http://www.host.test/some/path/",
+ []string{"A=a"},
+ "A=a",
+ []query{
+ {"http://www.host.test", ""},
+ {"http://www.host.test/", ""},
+ {"http://www.host.test/some", ""},
+ {"http://www.host.test/some/", ""},
+ {"http://www.host.test/some/path", "A=a"},
+ {"http://www.host.test/some/paths", ""},
+ {"http://www.host.test/some/path/foo", "A=a"},
+ {"http://www.host.test/some/path/foo/", "A=a"},
+ },
+ },
+ {
+ "Implicit path #2: path is not a directory.",
+ "http://www.host.test/some/path/index.html",
+ []string{"A=a"},
+ "A=a",
+ []query{
+ {"http://www.host.test", ""},
+ {"http://www.host.test/", ""},
+ {"http://www.host.test/some", ""},
+ {"http://www.host.test/some/", ""},
+ {"http://www.host.test/some/path", "A=a"},
+ {"http://www.host.test/some/paths", ""},
+ {"http://www.host.test/some/path/foo", "A=a"},
+ {"http://www.host.test/some/path/foo/", "A=a"},
+ },
+ },
+ {
+ "Implicit path #3: no path in URL at all.",
+ "http://www.host.test",
+ []string{"A=a"},
+ "A=a",
+ []query{
+ {"http://www.host.test", "A=a"},
+ {"http://www.host.test/", "A=a"},
+ {"http://www.host.test/some/path", "A=a"},
+ },
+ },
+ {
+ "Cookies are sorted by path length.",
+ "http://www.host.test/",
+ []string{
+ "A=a; path=/foo/bar",
+ "B=b; path=/foo/bar/baz/qux",
+ "C=c; path=/foo/bar/baz",
+ "D=d; path=/foo"},
+ "A=a B=b C=c D=d",
+ []query{
+ {"http://www.host.test/foo/bar/baz/qux", "B=b C=c A=a D=d"},
+ {"http://www.host.test/foo/bar/baz/", "C=c A=a D=d"},
+ {"http://www.host.test/foo/bar", "A=a D=d"},
+ },
+ },
+ {
+ "Creation time determines sorting on same length paths.",
+ "http://www.host.test/",
+ []string{
+ "A=a; path=/foo/bar",
+ "X=x; path=/foo/bar",
+ "Y=y; path=/foo/bar/baz/qux",
+ "B=b; path=/foo/bar/baz/qux",
+ "C=c; path=/foo/bar/baz",
+ "W=w; path=/foo/bar/baz",
+ "Z=z; path=/foo",
+ "D=d; path=/foo"},
+ "A=a B=b C=c D=d W=w X=x Y=y Z=z",
+ []query{
+ {"http://www.host.test/foo/bar/baz/qux", "Y=y B=b C=c W=w A=a X=x Z=z D=d"},
+ {"http://www.host.test/foo/bar/baz/", "C=c W=w A=a X=x Z=z D=d"},
+ {"http://www.host.test/foo/bar", "A=a X=x Z=z D=d"},
+ },
+ },
+ {
+ "Sorting of same-name cookies.",
+ "http://www.host.test/",
+ []string{
+ "A=1; path=/",
+ "A=2; path=/path",
+ "A=3; path=/quux",
+ "A=4; path=/path/foo",
+ "A=5; domain=.host.test; path=/path",
+ "A=6; domain=.host.test; path=/quux",
+ "A=7; domain=.host.test; path=/path/foo",
+ },
+ "A=1 A=2 A=3 A=4 A=5 A=6 A=7",
+ []query{
+ {"http://www.host.test/path", "A=2 A=5 A=1"},
+ {"http://www.host.test/path/foo", "A=4 A=7 A=2 A=5 A=1"},
+ },
+ },
+ {
+ "Disallow domain cookie on public suffix.",
+ "http://www.bbc.co.uk",
+ []string{
+ "a=1",
+ "b=2; domain=co.uk",
+ },
+ "a=1",
+ []query{{"http://www.bbc.co.uk", "a=1"}},
+ },
+ {
+ "Host cookie on IP.",
+ "http://192.168.0.10",
+ []string{"a=1"},
+ "a=1",
+ []query{{"http://192.168.0.10", "a=1"}},
+ },
+ {
+ "Domain cookies on IP.",
+ "http://192.168.0.10",
+ []string{
+ "a=1; domain=192.168.0.10", // allowed
+ "b=2; domain=172.31.9.9", // rejected, can't set cookie for other IP
+ "c=3; domain=.192.168.0.10", // rejected like in most browsers
+ },
+ "a=1",
+ []query{
+ {"http://192.168.0.10", "a=1"},
+ {"http://172.31.9.9", ""},
+ {"http://www.fancy.192.168.0.10", ""},
+ },
+ },
+ {
+ "Port is ignored #1.",
+ "http://www.host.test/",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://www.host.test", "a=1"},
+ {"http://www.host.test:8080/", "a=1"},
+ },
+ },
+ {
+ "Port is ignored #2.",
+ "http://www.host.test:8080/",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://www.host.test", "a=1"},
+ {"http://www.host.test:8080/", "a=1"},
+ {"http://www.host.test:1234/", "a=1"},
+ },
+ },
+ {
+ "IPv6 zone is not treated as a host.",
+ "https://example.com/",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"https://[::1%25.example.com]:80/", ""},
+ },
+ },
+}
+
+func TestBasics(t *testing.T) {
+ for _, test := range basicsTests {
+ jar := newTestJar()
+ test.run(t, jar)
+ }
+}
+
+// updateAndDeleteTests contains jarTests which must be performed on the same
+// Jar.
+var updateAndDeleteTests = [...]jarTest{
+ {
+ "Set initial cookies.",
+ "http://www.host.test",
+ []string{
+ "a=1",
+ "b=2; secure",
+ "c=3; httponly",
+ "d=4; secure; httponly"},
+ "a=1 b=2 c=3 d=4",
+ []query{
+ {"http://www.host.test", "a=1 c=3"},
+ {"https://www.host.test", "a=1 b=2 c=3 d=4"},
+ },
+ },
+ {
+ "Update value via http.",
+ "http://www.host.test",
+ []string{
+ "a=w",
+ "b=x; secure",
+ "c=y; httponly",
+ "d=z; secure; httponly"},
+ "a=w b=x c=y d=z",
+ []query{
+ {"http://www.host.test", "a=w c=y"},
+ {"https://www.host.test", "a=w b=x c=y d=z"},
+ },
+ },
+ {
+ "Clear Secure flag from an http.",
+ "http://www.host.test/",
+ []string{
+ "b=xx",
+ "d=zz; httponly"},
+ "a=w b=xx c=y d=zz",
+ []query{{"http://www.host.test", "a=w b=xx c=y d=zz"}},
+ },
+ {
+ "Delete all.",
+ "http://www.host.test/",
+ []string{
+ "a=1; max-Age=-1", // delete via MaxAge
+ "b=2; " + expiresIn(-10), // delete via Expires
+ "c=2; max-age=-1; " + expiresIn(-10), // delete via both
+ "d=4; max-age=-1; " + expiresIn(10)}, // MaxAge takes precedence
+ "",
+ []query{{"http://www.host.test", ""}},
+ },
+ {
+ "Refill #1.",
+ "http://www.host.test",
+ []string{
+ "A=1",
+ "A=2; path=/foo",
+ "A=3; domain=.host.test",
+ "A=4; path=/foo; domain=.host.test"},
+ "A=1 A=2 A=3 A=4",
+ []query{{"http://www.host.test/foo", "A=2 A=4 A=1 A=3"}},
+ },
+ {
+ "Refill #2.",
+ "http://www.google.com",
+ []string{
+ "A=6",
+ "A=7; path=/foo",
+ "A=8; domain=.google.com",
+ "A=9; path=/foo; domain=.google.com"},
+ "A=1 A=2 A=3 A=4 A=6 A=7 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"},
+ {"http://www.google.com/foo", "A=7 A=9 A=6 A=8"},
+ },
+ },
+ {
+ "Delete A7.",
+ "http://www.google.com",
+ []string{"A=; path=/foo; max-age=-1"},
+ "A=1 A=2 A=3 A=4 A=6 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=4 A=1 A=3"},
+ {"http://www.google.com/foo", "A=9 A=6 A=8"},
+ },
+ },
+ {
+ "Delete A4.",
+ "http://www.host.test",
+ []string{"A=; path=/foo; domain=host.test; max-age=-1"},
+ "A=1 A=2 A=3 A=6 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=1 A=3"},
+ {"http://www.google.com/foo", "A=9 A=6 A=8"},
+ },
+ },
+ {
+ "Delete A6.",
+ "http://www.google.com",
+ []string{"A=; max-age=-1"},
+ "A=1 A=2 A=3 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=1 A=3"},
+ {"http://www.google.com/foo", "A=9 A=8"},
+ },
+ },
+ {
+ "Delete A3.",
+ "http://www.host.test",
+ []string{"A=; domain=host.test; max-age=-1"},
+ "A=1 A=2 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=1"},
+ {"http://www.google.com/foo", "A=9 A=8"},
+ },
+ },
+ {
+ "No cross-domain delete.",
+ "http://www.host.test",
+ []string{
+ "A=; domain=google.com; max-age=-1",
+ "A=; path=/foo; domain=google.com; max-age=-1"},
+ "A=1 A=2 A=8 A=9",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=1"},
+ {"http://www.google.com/foo", "A=9 A=8"},
+ },
+ },
+ {
+ "Delete A8 and A9.",
+ "http://www.google.com",
+ []string{
+ "A=; domain=google.com; max-age=-1",
+ "A=; path=/foo; domain=google.com; max-age=-1"},
+ "A=1 A=2",
+ []query{
+ {"http://www.host.test/foo", "A=2 A=1"},
+ {"http://www.google.com/foo", ""},
+ },
+ },
+}
+
+func TestUpdateAndDelete(t *testing.T) {
+ jar := newTestJar()
+ for _, test := range updateAndDeleteTests {
+ test.run(t, jar)
+ }
+}
+
+func TestExpiration(t *testing.T) {
+ jar := newTestJar()
+ jarTest{
+ "Expiration.",
+ "http://www.host.test",
+ []string{
+ "a=1",
+ "b=2; max-age=3",
+ "c=3; " + expiresIn(3),
+ "d=4; max-age=5",
+ "e=5; " + expiresIn(5),
+ "f=6; max-age=100",
+ },
+ "a=1 b=2 c=3 d=4 e=5 f=6", // executed at t0 + 1001 ms
+ []query{
+ {"http://www.host.test", "a=1 b=2 c=3 d=4 e=5 f=6"}, // t0 + 2002 ms
+ {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 3003 ms
+ {"http://www.host.test", "a=1 d=4 e=5 f=6"}, // t0 + 4004 ms
+ {"http://www.host.test", "a=1 f=6"}, // t0 + 5005 ms
+ {"http://www.host.test", "a=1 f=6"}, // t0 + 6006 ms
+ },
+ }.run(t, jar)
+}
+
+//
+// Tests derived from Chromium's cookie_store_unittest.h.
+//
+
+// See http://src.chromium.org/viewvc/chrome/trunk/src/net/cookies/cookie_store_unittest.h?revision=159685&content-type=text/plain
+// Some of the original tests are in a bad condition (e.g.
+// DomainWithTrailingDotTest) or are not RFC 6265 conforming (e.g.
+// TestNonDottedAndTLD #1 and #6) and have not been ported.
+
+// chromiumBasicsTests contains fundamental tests. Each jarTest has to be
+// performed on a fresh, empty Jar.
+var chromiumBasicsTests = [...]jarTest{
+ {
+ "DomainWithTrailingDotTest.",
+ "http://www.google.com/",
+ []string{
+ "a=1; domain=.www.google.com.",
+ "b=2; domain=.www.google.com.."},
+ "",
+ []query{
+ {"http://www.google.com", ""},
+ },
+ },
+ {
+ "ValidSubdomainTest #1.",
+ "http://a.b.c.d.com",
+ []string{
+ "a=1; domain=.a.b.c.d.com",
+ "b=2; domain=.b.c.d.com",
+ "c=3; domain=.c.d.com",
+ "d=4; domain=.d.com"},
+ "a=1 b=2 c=3 d=4",
+ []query{
+ {"http://a.b.c.d.com", "a=1 b=2 c=3 d=4"},
+ {"http://b.c.d.com", "b=2 c=3 d=4"},
+ {"http://c.d.com", "c=3 d=4"},
+ {"http://d.com", "d=4"},
+ },
+ },
+ {
+ "ValidSubdomainTest #2.",
+ "http://a.b.c.d.com",
+ []string{
+ "a=1; domain=.a.b.c.d.com",
+ "b=2; domain=.b.c.d.com",
+ "c=3; domain=.c.d.com",
+ "d=4; domain=.d.com",
+ "X=bcd; domain=.b.c.d.com",
+ "X=cd; domain=.c.d.com"},
+ "X=bcd X=cd a=1 b=2 c=3 d=4",
+ []query{
+ {"http://b.c.d.com", "b=2 c=3 d=4 X=bcd X=cd"},
+ {"http://c.d.com", "c=3 d=4 X=cd"},
+ },
+ },
+ {
+ "InvalidDomainTest #1.",
+ "http://foo.bar.com",
+ []string{
+ "a=1; domain=.yo.foo.bar.com",
+ "b=2; domain=.foo.com",
+ "c=3; domain=.bar.foo.com",
+ "d=4; domain=.foo.bar.com.net",
+ "e=5; domain=ar.com",
+ "f=6; domain=.",
+ "g=7; domain=/",
+ "h=8; domain=http://foo.bar.com",
+ "i=9; domain=..foo.bar.com",
+ "j=10; domain=..bar.com",
+ "k=11; domain=.foo.bar.com?blah",
+ "l=12; domain=.foo.bar.com/blah",
+ "m=12; domain=.foo.bar.com:80",
+ "n=14; domain=.foo.bar.com:",
+ "o=15; domain=.foo.bar.com#sup",
+ },
+ "", // Jar is empty.
+ []query{{"http://foo.bar.com", ""}},
+ },
+ {
+ "InvalidDomainTest #2.",
+ "http://foo.com.com",
+ []string{"a=1; domain=.foo.com.com.com"},
+ "",
+ []query{{"http://foo.bar.com", ""}},
+ },
+ {
+ "DomainWithoutLeadingDotTest #1.",
+ "http://manage.hosted.filefront.com",
+ []string{"a=1; domain=filefront.com"},
+ "a=1",
+ []query{{"http://www.filefront.com", "a=1"}},
+ },
+ {
+ "DomainWithoutLeadingDotTest #2.",
+ "http://www.google.com",
+ []string{"a=1; domain=www.google.com"},
+ "a=1",
+ []query{
+ {"http://www.google.com", "a=1"},
+ {"http://sub.www.google.com", "a=1"},
+ {"http://something-else.com", ""},
+ },
+ },
+ {
+ "CaseInsensitiveDomainTest.",
+ "http://www.google.com",
+ []string{
+ "a=1; domain=.GOOGLE.COM",
+ "b=2; domain=.www.gOOgLE.coM"},
+ "a=1 b=2",
+ []query{{"http://www.google.com", "a=1 b=2"}},
+ },
+ {
+ "TestIpAddress #1.",
+ "http://1.2.3.4/foo",
+ []string{"a=1; path=/"},
+ "a=1",
+ []query{{"http://1.2.3.4/foo", "a=1"}},
+ },
+ {
+ "TestIpAddress #2.",
+ "http://1.2.3.4/foo",
+ []string{
+ "a=1; domain=.1.2.3.4",
+ "b=2; domain=.3.4"},
+ "",
+ []query{{"http://1.2.3.4/foo", ""}},
+ },
+ {
+ "TestIpAddress #3.",
+ "http://1.2.3.4/foo",
+ []string{"a=1; domain=1.2.3.3"},
+ "",
+ []query{{"http://1.2.3.4/foo", ""}},
+ },
+ {
+ "TestIpAddress #4.",
+ "http://1.2.3.4/foo",
+ []string{"a=1; domain=1.2.3.4"},
+ "a=1",
+ []query{{"http://1.2.3.4/foo", "a=1"}},
+ },
+ {
+ "TestNonDottedAndTLD #2.",
+ "http://com./index.html",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://com./index.html", "a=1"},
+ {"http://no-cookies.com./index.html", ""},
+ },
+ },
+ {
+ "TestNonDottedAndTLD #3.",
+ "http://a.b",
+ []string{
+ "a=1; domain=.b",
+ "b=2; domain=b"},
+ "",
+ []query{{"http://bar.foo", ""}},
+ },
+ {
+ "TestNonDottedAndTLD #4.",
+ "http://google.com",
+ []string{
+ "a=1; domain=.com",
+ "b=2; domain=com"},
+ "",
+ []query{{"http://google.com", ""}},
+ },
+ {
+ "TestNonDottedAndTLD #5.",
+ "http://google.co.uk",
+ []string{
+ "a=1; domain=.co.uk",
+ "b=2; domain=.uk"},
+ "",
+ []query{
+ {"http://google.co.uk", ""},
+ {"http://else.co.com", ""},
+ {"http://else.uk", ""},
+ },
+ },
+ {
+ "TestHostEndsWithDot.",
+ "http://www.google.com",
+ []string{
+ "a=1",
+ "b=2; domain=.www.google.com."},
+ "a=1",
+ []query{{"http://www.google.com", "a=1"}},
+ },
+ {
+ "PathTest",
+ "http://www.google.izzle",
+ []string{"a=1; path=/wee"},
+ "a=1",
+ []query{
+ {"http://www.google.izzle/wee", "a=1"},
+ {"http://www.google.izzle/wee/", "a=1"},
+ {"http://www.google.izzle/wee/war", "a=1"},
+ {"http://www.google.izzle/wee/war/more/more", "a=1"},
+ {"http://www.google.izzle/weehee", ""},
+ {"http://www.google.izzle/", ""},
+ },
+ },
+}
+
+func TestChromiumBasics(t *testing.T) {
+ for _, test := range chromiumBasicsTests {
+ jar := newTestJar()
+ test.run(t, jar)
+ }
+}
+
+// chromiumDomainTests contains jarTests which must be executed all on the
+// same Jar.
+var chromiumDomainTests = [...]jarTest{
+ {
+ "Fill #1.",
+ "http://www.google.izzle",
+ []string{"A=B"},
+ "A=B",
+ []query{{"http://www.google.izzle", "A=B"}},
+ },
+ {
+ "Fill #2.",
+ "http://www.google.izzle",
+ []string{"C=D; domain=.google.izzle"},
+ "A=B C=D",
+ []query{{"http://www.google.izzle", "A=B C=D"}},
+ },
+ {
+ "Verify A is a host cookie and not accessible from subdomain.",
+ "http://unused.nil",
+ []string{},
+ "A=B C=D",
+ []query{{"http://foo.www.google.izzle", "C=D"}},
+ },
+ {
+ "Verify domain cookies are found on proper domain.",
+ "http://www.google.izzle",
+ []string{"E=F; domain=.www.google.izzle"},
+ "A=B C=D E=F",
+ []query{{"http://www.google.izzle", "A=B C=D E=F"}},
+ },
+ {
+ "Leading dots in domain attributes are optional.",
+ "http://www.google.izzle",
+ []string{"G=H; domain=www.google.izzle"},
+ "A=B C=D E=F G=H",
+ []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}},
+ },
+ {
+ "Verify domain enforcement works #1.",
+ "http://www.google.izzle",
+ []string{"K=L; domain=.bar.www.google.izzle"},
+ "A=B C=D E=F G=H",
+ []query{{"http://bar.www.google.izzle", "C=D E=F G=H"}},
+ },
+ {
+ "Verify domain enforcement works #2.",
+ "http://unused.nil",
+ []string{},
+ "A=B C=D E=F G=H",
+ []query{{"http://www.google.izzle", "A=B C=D E=F G=H"}},
+ },
+}
+
+func TestChromiumDomain(t *testing.T) {
+ jar := newTestJar()
+ for _, test := range chromiumDomainTests {
+ test.run(t, jar)
+ }
+
+}
+
+// chromiumDeletionTests must be performed all on the same Jar.
+var chromiumDeletionTests = [...]jarTest{
+ {
+ "Create session cookie a1.",
+ "http://www.google.com",
+ []string{"a=1"},
+ "a=1",
+ []query{{"http://www.google.com", "a=1"}},
+ },
+ {
+ "Delete sc a1 via MaxAge.",
+ "http://www.google.com",
+ []string{"a=1; max-age=-1"},
+ "",
+ []query{{"http://www.google.com", ""}},
+ },
+ {
+ "Create session cookie b2.",
+ "http://www.google.com",
+ []string{"b=2"},
+ "b=2",
+ []query{{"http://www.google.com", "b=2"}},
+ },
+ {
+ "Delete sc b2 via Expires.",
+ "http://www.google.com",
+ []string{"b=2; " + expiresIn(-10)},
+ "",
+ []query{{"http://www.google.com", ""}},
+ },
+ {
+ "Create persistent cookie c3.",
+ "http://www.google.com",
+ []string{"c=3; max-age=3600"},
+ "c=3",
+ []query{{"http://www.google.com", "c=3"}},
+ },
+ {
+ "Delete pc c3 via MaxAge.",
+ "http://www.google.com",
+ []string{"c=3; max-age=-1"},
+ "",
+ []query{{"http://www.google.com", ""}},
+ },
+ {
+ "Create persistent cookie d4.",
+ "http://www.google.com",
+ []string{"d=4; max-age=3600"},
+ "d=4",
+ []query{{"http://www.google.com", "d=4"}},
+ },
+ {
+ "Delete pc d4 via Expires.",
+ "http://www.google.com",
+ []string{"d=4; " + expiresIn(-10)},
+ "",
+ []query{{"http://www.google.com", ""}},
+ },
+}
+
+func TestChromiumDeletion(t *testing.T) {
+ jar := newTestJar()
+ for _, test := range chromiumDeletionTests {
+ test.run(t, jar)
+ }
+}
+
+// domainHandlingTests tests and documents the rules for domain handling.
+// Each test must be performed on an empty new Jar.
+var domainHandlingTests = [...]jarTest{
+ {
+ "Host cookie",
+ "http://www.host.test",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://www.host.test", "a=1"},
+ {"http://host.test", ""},
+ {"http://bar.host.test", ""},
+ {"http://foo.www.host.test", ""},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Domain cookie #1",
+ "http://www.host.test",
+ []string{"a=1; domain=host.test"},
+ "a=1",
+ []query{
+ {"http://www.host.test", "a=1"},
+ {"http://host.test", "a=1"},
+ {"http://bar.host.test", "a=1"},
+ {"http://foo.www.host.test", "a=1"},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Domain cookie #2",
+ "http://www.host.test",
+ []string{"a=1; domain=.host.test"},
+ "a=1",
+ []query{
+ {"http://www.host.test", "a=1"},
+ {"http://host.test", "a=1"},
+ {"http://bar.host.test", "a=1"},
+ {"http://foo.www.host.test", "a=1"},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Host cookie on IDNA domain #1",
+ "http://www.bücher.test",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://www.bücher.test", "a=1"},
+ {"http://www.xn--bcher-kva.test", "a=1"},
+ {"http://bücher.test", ""},
+ {"http://xn--bcher-kva.test", ""},
+ {"http://bar.bücher.test", ""},
+ {"http://bar.xn--bcher-kva.test", ""},
+ {"http://foo.www.bücher.test", ""},
+ {"http://foo.www.xn--bcher-kva.test", ""},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Host cookie on IDNA domain #2",
+ "http://www.xn--bcher-kva.test",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://www.bücher.test", "a=1"},
+ {"http://www.xn--bcher-kva.test", "a=1"},
+ {"http://bücher.test", ""},
+ {"http://xn--bcher-kva.test", ""},
+ {"http://bar.bücher.test", ""},
+ {"http://bar.xn--bcher-kva.test", ""},
+ {"http://foo.www.bücher.test", ""},
+ {"http://foo.www.xn--bcher-kva.test", ""},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Domain cookie on IDNA domain #1",
+ "http://www.bücher.test",
+ []string{"a=1; domain=xn--bcher-kva.test"},
+ "a=1",
+ []query{
+ {"http://www.bücher.test", "a=1"},
+ {"http://www.xn--bcher-kva.test", "a=1"},
+ {"http://bücher.test", "a=1"},
+ {"http://xn--bcher-kva.test", "a=1"},
+ {"http://bar.bücher.test", "a=1"},
+ {"http://bar.xn--bcher-kva.test", "a=1"},
+ {"http://foo.www.bücher.test", "a=1"},
+ {"http://foo.www.xn--bcher-kva.test", "a=1"},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Domain cookie on IDNA domain #2",
+ "http://www.xn--bcher-kva.test",
+ []string{"a=1; domain=xn--bcher-kva.test"},
+ "a=1",
+ []query{
+ {"http://www.bücher.test", "a=1"},
+ {"http://www.xn--bcher-kva.test", "a=1"},
+ {"http://bücher.test", "a=1"},
+ {"http://xn--bcher-kva.test", "a=1"},
+ {"http://bar.bücher.test", "a=1"},
+ {"http://bar.xn--bcher-kva.test", "a=1"},
+ {"http://foo.www.bücher.test", "a=1"},
+ {"http://foo.www.xn--bcher-kva.test", "a=1"},
+ {"http://other.test", ""},
+ {"http://test", ""},
+ },
+ },
+ {
+ "Host cookie on TLD.",
+ "http://com",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://com", "a=1"},
+ {"http://any.com", ""},
+ {"http://any.test", ""},
+ },
+ },
+ {
+ "Domain cookie on TLD becomes a host cookie.",
+ "http://com",
+ []string{"a=1; domain=com"},
+ "a=1",
+ []query{
+ {"http://com", "a=1"},
+ {"http://any.com", ""},
+ {"http://any.test", ""},
+ },
+ },
+ {
+ "Host cookie on public suffix.",
+ "http://co.uk",
+ []string{"a=1"},
+ "a=1",
+ []query{
+ {"http://co.uk", "a=1"},
+ {"http://uk", ""},
+ {"http://some.co.uk", ""},
+ {"http://foo.some.co.uk", ""},
+ {"http://any.uk", ""},
+ },
+ },
+ {
+ "Domain cookie on public suffix is ignored.",
+ "http://some.co.uk",
+ []string{"a=1; domain=co.uk"},
+ "",
+ []query{
+ {"http://co.uk", ""},
+ {"http://uk", ""},
+ {"http://some.co.uk", ""},
+ {"http://foo.some.co.uk", ""},
+ {"http://any.uk", ""},
+ },
+ },
+}
+
+func TestDomainHandling(t *testing.T) {
+ for _, test := range domainHandlingTests {
+ jar := newTestJar()
+ test.run(t, jar)
+ }
+}
+
+func TestIssue19384(t *testing.T) {
+ cookies := []*http.Cookie{{Name: "name", Value: "value"}}
+ for _, host := range []string{"", ".", "..", "..."} {
+ jar, _ := New(nil)
+ u := &url.URL{Scheme: "http", Host: host, Path: "/"}
+ if got := jar.Cookies(u); len(got) != 0 {
+ t.Errorf("host %q, got %v", host, got)
+ }
+ jar.SetCookies(u, cookies)
+ if got := jar.Cookies(u); len(got) != 1 || got[0].Value != "value" {
+ t.Errorf("host %q, got %v", host, got)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode.go
new file mode 100644
index 0000000000000000000000000000000000000000..c7f438dd00707a87014d801592be92c2e498a811
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode.go
@@ -0,0 +1,151 @@
+// 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 cookiejar
+
+// This file implements the Punycode algorithm from RFC 3492.
+
+import (
+ "fmt"
+ "net/http/internal/ascii"
+ "strings"
+ "unicode/utf8"
+)
+
+// These parameter values are specified in section 5.
+//
+// All computation is done with int32s, so that overflow behavior is identical
+// regardless of whether int is 32-bit or 64-bit.
+const (
+ base int32 = 36
+ damp int32 = 700
+ initialBias int32 = 72
+ initialN int32 = 128
+ skew int32 = 38
+ tmax int32 = 26
+ tmin int32 = 1
+)
+
+// encode encodes a string as specified in section 6.3 and prepends prefix to
+// the result.
+//
+// The "while h < length(input)" line in the specification becomes "for
+// remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes.
+func encode(prefix, s string) (string, error) {
+ output := make([]byte, len(prefix), len(prefix)+1+2*len(s))
+ copy(output, prefix)
+ delta, n, bias := int32(0), initialN, initialBias
+ b, remaining := int32(0), int32(0)
+ for _, r := range s {
+ if r < utf8.RuneSelf {
+ b++
+ output = append(output, byte(r))
+ } else {
+ remaining++
+ }
+ }
+ h := b
+ if b > 0 {
+ output = append(output, '-')
+ }
+ for remaining != 0 {
+ m := int32(0x7fffffff)
+ for _, r := range s {
+ if m > r && r >= n {
+ m = r
+ }
+ }
+ delta += (m - n) * (h + 1)
+ if delta < 0 {
+ return "", fmt.Errorf("cookiejar: invalid label %q", s)
+ }
+ n = m
+ for _, r := range s {
+ if r < n {
+ delta++
+ if delta < 0 {
+ return "", fmt.Errorf("cookiejar: invalid label %q", s)
+ }
+ continue
+ }
+ if r > n {
+ continue
+ }
+ q := delta
+ for k := base; ; k += base {
+ t := k - bias
+ if t < tmin {
+ t = tmin
+ } else if t > tmax {
+ t = tmax
+ }
+ if q < t {
+ break
+ }
+ output = append(output, encodeDigit(t+(q-t)%(base-t)))
+ q = (q - t) / (base - t)
+ }
+ output = append(output, encodeDigit(q))
+ bias = adapt(delta, h+1, h == b)
+ delta = 0
+ h++
+ remaining--
+ }
+ delta++
+ n++
+ }
+ return string(output), nil
+}
+
+func encodeDigit(digit int32) byte {
+ switch {
+ case 0 <= digit && digit < 26:
+ return byte(digit + 'a')
+ case 26 <= digit && digit < 36:
+ return byte(digit + ('0' - 26))
+ }
+ panic("cookiejar: internal error in punycode encoding")
+}
+
+// adapt is the bias adaptation function specified in section 6.1.
+func adapt(delta, numPoints int32, firstTime bool) int32 {
+ if firstTime {
+ delta /= damp
+ } else {
+ delta /= 2
+ }
+ delta += delta / numPoints
+ k := int32(0)
+ for delta > ((base-tmin)*tmax)/2 {
+ delta /= base - tmin
+ k += base
+ }
+ return k + (base-tmin+1)*delta/(delta+skew)
+}
+
+// Strictly speaking, the remaining code below deals with IDNA (RFC 5890 and
+// friends) and not Punycode (RFC 3492) per se.
+
+// acePrefix is the ASCII Compatible Encoding prefix.
+const acePrefix = "xn--"
+
+// toASCII converts a domain or domain label to its ASCII form. For example,
+// toASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
+// toASCII("golang") is "golang".
+func toASCII(s string) (string, error) {
+ if ascii.Is(s) {
+ return s, nil
+ }
+ labels := strings.Split(s, ".")
+ for i, label := range labels {
+ if !ascii.Is(label) {
+ a, err := encode(acePrefix, label)
+ if err != nil {
+ return "", err
+ }
+ labels[i] = a
+ }
+ }
+ return strings.Join(labels, "."), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode_test.go b/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0301de14e46c894450990d1bf6d59385f4b54afd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/cookiejar/punycode_test.go
@@ -0,0 +1,161 @@
+// 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 cookiejar
+
+import (
+ "testing"
+)
+
+var punycodeTestCases = [...]struct {
+ s, encoded string
+}{
+ {"", ""},
+ {"-", "--"},
+ {"-a", "-a-"},
+ {"-a-", "-a--"},
+ {"a", "a-"},
+ {"a-", "a--"},
+ {"a-b", "a-b-"},
+ {"books", "books-"},
+ {"bücher", "bcher-kva"},
+ {"Hello世界", "Hello-ck1hg65u"},
+ {"ü", "tda"},
+ {"üý", "tdac"},
+
+ // The test cases below come from RFC 3492 section 7.1 with Errata 3026.
+ {
+ // (A) Arabic (Egyptian).
+ "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" +
+ "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F",
+ "egbpdaj6bu4bxfgehfvwxn",
+ },
+ {
+ // (B) Chinese (simplified).
+ "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587",
+ "ihqwcrb4cv8a8dqg056pqjye",
+ },
+ {
+ // (C) Chinese (traditional).
+ "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587",
+ "ihqwctvzc91f659drss3x8bo0yb",
+ },
+ {
+ // (D) Czech.
+ "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" +
+ "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" +
+ "\u0065\u0073\u006B\u0079",
+ "Proprostnemluvesky-uyb24dma41a",
+ },
+ {
+ // (E) Hebrew.
+ "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" +
+ "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" +
+ "\u05D1\u05E8\u05D9\u05EA",
+ "4dbcagdahymbxekheh6e0a7fei0b",
+ },
+ {
+ // (F) Hindi (Devanagari).
+ "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" +
+ "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" +
+ "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" +
+ "\u0939\u0948\u0902",
+ "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd",
+ },
+ {
+ // (G) Japanese (kanji and hiragana).
+ "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" +
+ "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B",
+ "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa",
+ },
+ {
+ // (H) Korean (Hangul syllables).
+ "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" +
+ "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" +
+ "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C",
+ "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" +
+ "psd879ccm6fea98c",
+ },
+ {
+ // (I) Russian (Cyrillic).
+ "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" +
+ "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" +
+ "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" +
+ "\u0438",
+ "b1abfaaepdrnnbgefbadotcwatmq2g4l",
+ },
+ {
+ // (J) Spanish.
+ "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" +
+ "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" +
+ "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" +
+ "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" +
+ "\u0061\u00F1\u006F\u006C",
+ "PorqunopuedensimplementehablarenEspaol-fmd56a",
+ },
+ {
+ // (K) Vietnamese.
+ "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" +
+ "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" +
+ "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" +
+ "\u0056\u0069\u1EC7\u0074",
+ "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g",
+ },
+ {
+ // (L) 3B.
+ "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F",
+ "3B-ww4c5e180e575a65lsy2b",
+ },
+ {
+ // (M) -with-SUPER-MONKEYS.
+ "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" +
+ "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" +
+ "\u004F\u004E\u004B\u0045\u0059\u0053",
+ "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n",
+ },
+ {
+ // (N) Hello-Another-Way-.
+ "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" +
+ "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" +
+ "\u305D\u308C\u305E\u308C\u306E\u5834\u6240",
+ "Hello-Another-Way--fc4qua05auwb3674vfr0b",
+ },
+ {
+ // (O) 2.
+ "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032",
+ "2-u9tlzr9756bt3uc0v",
+ },
+ {
+ // (P) MajiKoi5
+ "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" +
+ "\u308B\u0035\u79D2\u524D",
+ "MajiKoi5-783gue6qz075azm5e",
+ },
+ {
+ // (Q) de
+ "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0",
+ "de-jg4avhby1noc0d",
+ },
+ {
+ // (R)
+ "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067",
+ "d9juau41awczczp",
+ },
+ {
+ // (S) -> $1.00 <-
+ "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" +
+ "\u003C\u002D",
+ "-> $1.00 <--",
+ },
+}
+
+func TestPunycode(t *testing.T) {
+ for _, tc := range punycodeTestCases {
+ if got, err := encode("", tc.s); err != nil {
+ t.Errorf(`encode("", %q): %v`, tc.s, err)
+ } else if got != tc.encoded {
+ t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/doc.go b/platform/dbops/binaries/go/go/src/net/http/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7ad3ae762fb6c8669ee28c2425a97bdb41eb672
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/doc.go
@@ -0,0 +1,110 @@
+// 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 http provides HTTP client and server implementations.
+
+[Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests:
+
+ resp, err := http.Get("http://example.com/")
+ ...
+ resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
+ ...
+ resp, err := http.PostForm("http://example.com/form",
+ url.Values{"key": {"Value"}, "id": {"123"}})
+
+The caller must close the response body when finished with it:
+
+ resp, err := http.Get("http://example.com/")
+ if err != nil {
+ // handle error
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(resp.Body)
+ // ...
+
+# Clients and Transports
+
+For control over HTTP client headers, redirect policy, and other
+settings, create a [Client]:
+
+ client := &http.Client{
+ CheckRedirect: redirectPolicyFunc,
+ }
+
+ resp, err := client.Get("http://example.com")
+ // ...
+
+ req, err := http.NewRequest("GET", "http://example.com", nil)
+ // ...
+ req.Header.Add("If-None-Match", `W/"wyzzy"`)
+ resp, err := client.Do(req)
+ // ...
+
+For control over proxies, TLS configuration, keep-alives,
+compression, and other settings, create a [Transport]:
+
+ tr := &http.Transport{
+ MaxIdleConns: 10,
+ IdleConnTimeout: 30 * time.Second,
+ DisableCompression: true,
+ }
+ client := &http.Client{Transport: tr}
+ resp, err := client.Get("https://example.com")
+
+Clients and Transports are safe for concurrent use by multiple
+goroutines and for efficiency should only be created once and re-used.
+
+# Servers
+
+ListenAndServe starts an HTTP server with a given address and handler.
+The handler is usually nil, which means to use [DefaultServeMux].
+[Handle] and [HandleFunc] add handlers to [DefaultServeMux]:
+
+ http.Handle("/foo", fooHandler)
+
+ http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
+ })
+
+ log.Fatal(http.ListenAndServe(":8080", nil))
+
+More control over the server's behavior is available by creating a
+custom Server:
+
+ s := &http.Server{
+ Addr: ":8080",
+ Handler: myHandler,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 10 * time.Second,
+ MaxHeaderBytes: 1 << 20,
+ }
+ log.Fatal(s.ListenAndServe())
+
+# HTTP/2
+
+Starting with Go 1.6, the http package has transparent support for the
+HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2
+can do so by setting [Transport.TLSNextProto] (for clients) or
+[Server.TLSNextProto] (for servers) to a non-nil, empty
+map. Alternatively, the following GODEBUG settings are
+currently supported:
+
+ GODEBUG=http2client=0 # disable HTTP/2 client support
+ GODEBUG=http2server=0 # disable HTTP/2 server support
+ GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs
+ GODEBUG=http2debug=2 # ... even more verbose, with frame dumps
+
+Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug
+
+The http package's [Transport] and [Server] both automatically enable
+HTTP/2 support for simple configurations. To enable HTTP/2 for more
+complex configurations, to use lower-level HTTP/2 features, or to use
+a newer version of Go's http2 package, import "golang.org/x/net/http2"
+directly and use its ConfigureTransport and/or ConfigureServer
+functions. Manually configuring HTTP/2 via the golang.org/x/net/http2
+package takes precedence over the net/http package's built-in HTTP/2
+support.
+*/
+package http
diff --git a/platform/dbops/binaries/go/go/src/net/http/example_filesystem_test.go b/platform/dbops/binaries/go/go/src/net/http/example_filesystem_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0e81458a07196655393062149d25571b2d6cf965
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/example_filesystem_test.go
@@ -0,0 +1,71 @@
+// 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 http_test
+
+import (
+ "io/fs"
+ "log"
+ "net/http"
+ "strings"
+)
+
+// containsDotFile reports whether name contains a path element starting with a period.
+// The name is assumed to be a delimited by forward slashes, as guaranteed
+// by the http.FileSystem interface.
+func containsDotFile(name string) bool {
+ parts := strings.Split(name, "/")
+ for _, part := range parts {
+ if strings.HasPrefix(part, ".") {
+ return true
+ }
+ }
+ return false
+}
+
+// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
+// It is used to wrap the Readdir method of http.File so that we can
+// remove files and directories that start with a period from its output.
+type dotFileHidingFile struct {
+ http.File
+}
+
+// Readdir is a wrapper around the Readdir method of the embedded File
+// that filters out all files that start with a period in their name.
+func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
+ files, err := f.File.Readdir(n)
+ for _, file := range files { // Filters out the dot files
+ if !strings.HasPrefix(file.Name(), ".") {
+ fis = append(fis, file)
+ }
+ }
+ return
+}
+
+// dotFileHidingFileSystem is an http.FileSystem that hides
+// hidden "dot files" from being served.
+type dotFileHidingFileSystem struct {
+ http.FileSystem
+}
+
+// Open is a wrapper around the Open method of the embedded FileSystem
+// that serves a 403 permission error when name has a file or directory
+// with whose name starts with a period in its path.
+func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
+ if containsDotFile(name) { // If dot file, return 403 response
+ return nil, fs.ErrPermission
+ }
+
+ file, err := fsys.FileSystem.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ return dotFileHidingFile{file}, err
+}
+
+func ExampleFileServer_dotFileHiding() {
+ fsys := dotFileHidingFileSystem{http.Dir(".")}
+ http.Handle("/", http.FileServer(fsys))
+ log.Fatal(http.ListenAndServe(":8080", nil))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/example_handle_test.go b/platform/dbops/binaries/go/go/src/net/http/example_handle_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..10a62f64c2f4847859fd32e54df4de89abacca9f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/example_handle_test.go
@@ -0,0 +1,29 @@
+// 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 http_test
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "sync"
+)
+
+type countHandler struct {
+ mu sync.Mutex // guards n
+ n int
+}
+
+func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.n++
+ fmt.Fprintf(w, "count is %d\n", h.n)
+}
+
+func ExampleHandle() {
+ http.Handle("/count", new(countHandler))
+ log.Fatal(http.ListenAndServe(":8080", nil))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/example_test.go b/platform/dbops/binaries/go/go/src/net/http/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2f411d1d2ec23b3131567bc27bb9a614f08c92d0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/example_test.go
@@ -0,0 +1,195 @@
+// 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 http_test
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "os/signal"
+)
+
+func ExampleHijacker() {
+ http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
+ return
+ }
+ conn, bufrw, err := hj.Hijack()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ // Don't forget to close the connection:
+ defer conn.Close()
+ bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
+ bufrw.Flush()
+ s, err := bufrw.ReadString('\n')
+ if err != nil {
+ log.Printf("error reading string: %v", err)
+ return
+ }
+ fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
+ bufrw.Flush()
+ })
+}
+
+func ExampleGet() {
+ res, err := http.Get("http://www.google.com/robots.txt")
+ if err != nil {
+ log.Fatal(err)
+ }
+ body, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if res.StatusCode > 299 {
+ log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Printf("%s", body)
+}
+
+func ExampleFileServer() {
+ // Simple static webserver:
+ log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
+}
+
+func ExampleFileServer_stripPrefix() {
+ // To serve a directory on disk (/tmp) under an alternate URL
+ // path (/tmpfiles/), use StripPrefix to modify the request
+ // URL's path before the FileServer sees it:
+ http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
+}
+
+func ExampleStripPrefix() {
+ // To serve a directory on disk (/tmp) under an alternate URL
+ // path (/tmpfiles/), use StripPrefix to modify the request
+ // URL's path before the FileServer sees it:
+ http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
+}
+
+type apiHandler struct{}
+
+func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
+
+func ExampleServeMux_Handle() {
+ mux := http.NewServeMux()
+ mux.Handle("/api/", apiHandler{})
+ mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
+ // The "/" pattern matches everything, so we need to check
+ // that we're at the root here.
+ if req.URL.Path != "/" {
+ http.NotFound(w, req)
+ return
+ }
+ fmt.Fprintf(w, "Welcome to the home page!")
+ })
+}
+
+// HTTP Trailers are a set of key/value pairs like headers that come
+// after the HTTP response, instead of before.
+func ExampleResponseWriter_trailers() {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
+ // Before any call to WriteHeader or Write, declare
+ // the trailers you will set during the HTTP
+ // response. These three headers are actually sent in
+ // the trailer.
+ w.Header().Set("Trailer", "AtEnd1, AtEnd2")
+ w.Header().Add("Trailer", "AtEnd3")
+
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
+ w.WriteHeader(http.StatusOK)
+
+ w.Header().Set("AtEnd1", "value 1")
+ io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
+ w.Header().Set("AtEnd2", "value 2")
+ w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
+ })
+}
+
+func ExampleServer_Shutdown() {
+ var srv http.Server
+
+ idleConnsClosed := make(chan struct{})
+ go func() {
+ sigint := make(chan os.Signal, 1)
+ signal.Notify(sigint, os.Interrupt)
+ <-sigint
+
+ // We received an interrupt signal, shut down.
+ if err := srv.Shutdown(context.Background()); err != nil {
+ // Error from closing listeners, or context timeout:
+ log.Printf("HTTP server Shutdown: %v", err)
+ }
+ close(idleConnsClosed)
+ }()
+
+ if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+ // Error starting or closing listener:
+ log.Fatalf("HTTP server ListenAndServe: %v", err)
+ }
+
+ <-idleConnsClosed
+}
+
+func ExampleListenAndServeTLS() {
+ http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
+ io.WriteString(w, "Hello, TLS!\n")
+ })
+
+ // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
+ log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
+ err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
+ log.Fatal(err)
+}
+
+func ExampleListenAndServe() {
+ // Hello world, the web server
+
+ helloHandler := func(w http.ResponseWriter, req *http.Request) {
+ io.WriteString(w, "Hello, world!\n")
+ }
+
+ http.HandleFunc("/hello", helloHandler)
+ log.Fatal(http.ListenAndServe(":8080", nil))
+}
+
+func ExampleHandleFunc() {
+ h1 := func(w http.ResponseWriter, _ *http.Request) {
+ io.WriteString(w, "Hello from a HandleFunc #1!\n")
+ }
+ h2 := func(w http.ResponseWriter, _ *http.Request) {
+ io.WriteString(w, "Hello from a HandleFunc #2!\n")
+ }
+
+ http.HandleFunc("/", h1)
+ http.HandleFunc("/endpoint", h2)
+
+ log.Fatal(http.ListenAndServe(":8080", nil))
+}
+
+func newPeopleHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "This is the people handler.")
+ })
+}
+
+func ExampleNotFoundHandler() {
+ mux := http.NewServeMux()
+
+ // Create sample handler to returns 404
+ mux.Handle("/resources", http.NotFoundHandler())
+
+ // Create sample handler that returns 200
+ mux.Handle("/resources/people/", newPeopleHandler())
+
+ log.Fatal(http.ListenAndServe(":8080", mux))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/export_test.go b/platform/dbops/binaries/go/go/src/net/http/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7e6d3d8e304495aa075adf5b698ad4d0cce6ff7f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/export_test.go
@@ -0,0 +1,335 @@
+// 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.
+
+// Bridge package to expose http internals to tests in the http_test
+// package.
+
+package http
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/url"
+ "sort"
+ "sync"
+ "testing"
+ "time"
+)
+
+var (
+ DefaultUserAgent = defaultUserAgent
+ NewLoggingConn = newLoggingConn
+ ExportAppendTime = appendTime
+ ExportRefererForURL = refererForURL
+ ExportServerNewConn = (*Server).newConn
+ ExportCloseWriteAndWait = (*conn).closeWriteAndWait
+ ExportErrRequestCanceled = errRequestCanceled
+ ExportErrRequestCanceledConn = errRequestCanceledConn
+ ExportErrServerClosedIdle = errServerClosedIdle
+ ExportServeFile = serveFile
+ ExportScanETag = scanETag
+ ExportHttp2ConfigureServer = http2ConfigureServer
+ Export_shouldCopyHeaderOnRedirect = shouldCopyHeaderOnRedirect
+ Export_writeStatusLine = writeStatusLine
+ Export_is408Message = is408Message
+)
+
+var MaxWriteWaitBeforeConnReuse = &maxWriteWaitBeforeConnReuse
+
+func init() {
+ // We only want to pay for this cost during testing.
+ // When not under test, these values are always nil
+ // and never assigned to.
+ testHookMu = new(sync.Mutex)
+
+ testHookClientDoResult = func(res *Response, err error) {
+ if err != nil {
+ if _, ok := err.(*url.Error); !ok {
+ panic(fmt.Sprintf("unexpected Client.Do error of type %T; want *url.Error", err))
+ }
+ } else {
+ if res == nil {
+ panic("Client.Do returned nil, nil")
+ }
+ if res.Body == nil {
+ panic("Client.Do returned nil res.Body and no error")
+ }
+ }
+ }
+}
+
+func CondSkipHTTP2(t testing.TB) {
+ if omitBundledHTTP2 {
+ t.Skip("skipping HTTP/2 test when nethttpomithttp2 build tag in use")
+ }
+}
+
+var (
+ SetEnterRoundTripHook = hookSetter(&testHookEnterRoundTrip)
+ SetRoundTripRetried = hookSetter(&testHookRoundTripRetried)
+)
+
+func SetReadLoopBeforeNextReadHook(f func()) {
+ unnilTestHook(&f)
+ testHookReadLoopBeforeNextRead = f
+}
+
+// SetPendingDialHooks sets the hooks that run before and after handling
+// pending dials.
+func SetPendingDialHooks(before, after func()) {
+ unnilTestHook(&before)
+ unnilTestHook(&after)
+ testHookPrePendingDial, testHookPostPendingDial = before, after
+}
+
+func SetTestHookServerServe(fn func(*Server, net.Listener)) { testHookServerServe = fn }
+
+func NewTestTimeoutHandler(handler Handler, ctx context.Context) Handler {
+ return &timeoutHandler{
+ handler: handler,
+ testContext: ctx,
+ // (no body)
+ }
+}
+
+func ResetCachedEnvironment() {
+ resetProxyConfig()
+}
+
+func (t *Transport) NumPendingRequestsForTesting() int {
+ t.reqMu.Lock()
+ defer t.reqMu.Unlock()
+ return len(t.reqCanceler)
+}
+
+func (t *Transport) IdleConnKeysForTesting() (keys []string) {
+ keys = make([]string, 0)
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ for key := range t.idleConn {
+ keys = append(keys, key.String())
+ }
+ sort.Strings(keys)
+ return
+}
+
+func (t *Transport) IdleConnKeyCountForTesting() int {
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ return len(t.idleConn)
+}
+
+func (t *Transport) IdleConnStrsForTesting() []string {
+ var ret []string
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ for _, conns := range t.idleConn {
+ for _, pc := range conns {
+ ret = append(ret, pc.conn.LocalAddr().String()+"/"+pc.conn.RemoteAddr().String())
+ }
+ }
+ sort.Strings(ret)
+ return ret
+}
+
+func (t *Transport) IdleConnStrsForTesting_h2() []string {
+ var ret []string
+ noDialPool := t.h2transport.(*http2Transport).ConnPool.(http2noDialClientConnPool)
+ pool := noDialPool.http2clientConnPool
+
+ pool.mu.Lock()
+ defer pool.mu.Unlock()
+
+ for k, ccs := range pool.conns {
+ for _, cc := range ccs {
+ if cc.idleState().canTakeNewRequest {
+ ret = append(ret, k)
+ }
+ }
+ }
+
+ sort.Strings(ret)
+ return ret
+}
+
+func (t *Transport) IdleConnCountForTesting(scheme, addr string) int {
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ key := connectMethodKey{"", scheme, addr, false}
+ cacheKey := key.String()
+ for k, conns := range t.idleConn {
+ if k.String() == cacheKey {
+ return len(conns)
+ }
+ }
+ return 0
+}
+
+func (t *Transport) IdleConnWaitMapSizeForTesting() int {
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ return len(t.idleConnWait)
+}
+
+func (t *Transport) IsIdleForTesting() bool {
+ t.idleMu.Lock()
+ defer t.idleMu.Unlock()
+ return t.closeIdle
+}
+
+func (t *Transport) QueueForIdleConnForTesting() {
+ t.queueForIdleConn(nil)
+}
+
+// PutIdleTestConn reports whether it was able to insert a fresh
+// persistConn for scheme, addr into the idle connection pool.
+func (t *Transport) PutIdleTestConn(scheme, addr string) bool {
+ c, _ := net.Pipe()
+ key := connectMethodKey{"", scheme, addr, false}
+
+ if t.MaxConnsPerHost > 0 {
+ // Transport is tracking conns-per-host.
+ // Increment connection count to account
+ // for new persistConn created below.
+ t.connsPerHostMu.Lock()
+ if t.connsPerHost == nil {
+ t.connsPerHost = make(map[connectMethodKey]int)
+ }
+ t.connsPerHost[key]++
+ t.connsPerHostMu.Unlock()
+ }
+
+ return t.tryPutIdleConn(&persistConn{
+ t: t,
+ conn: c, // dummy
+ closech: make(chan struct{}), // so it can be closed
+ cacheKey: key,
+ }) == nil
+}
+
+// PutIdleTestConnH2 reports whether it was able to insert a fresh
+// HTTP/2 persistConn for scheme, addr into the idle connection pool.
+func (t *Transport) PutIdleTestConnH2(scheme, addr string, alt RoundTripper) bool {
+ key := connectMethodKey{"", scheme, addr, false}
+
+ if t.MaxConnsPerHost > 0 {
+ // Transport is tracking conns-per-host.
+ // Increment connection count to account
+ // for new persistConn created below.
+ t.connsPerHostMu.Lock()
+ if t.connsPerHost == nil {
+ t.connsPerHost = make(map[connectMethodKey]int)
+ }
+ t.connsPerHost[key]++
+ t.connsPerHostMu.Unlock()
+ }
+
+ return t.tryPutIdleConn(&persistConn{
+ t: t,
+ alt: alt,
+ cacheKey: key,
+ }) == nil
+}
+
+// All test hooks must be non-nil so they can be called directly,
+// but the tests use nil to mean hook disabled.
+func unnilTestHook(f *func()) {
+ if *f == nil {
+ *f = nop
+ }
+}
+
+func hookSetter(dst *func()) func(func()) {
+ return func(fn func()) {
+ unnilTestHook(&fn)
+ *dst = fn
+ }
+}
+
+func ExportHttp2ConfigureTransport(t *Transport) error {
+ t2, err := http2configureTransports(t)
+ if err != nil {
+ return err
+ }
+ t.h2transport = t2
+ return nil
+}
+
+func (s *Server) ExportAllConnsIdle() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for c := range s.activeConn {
+ st, unixSec := c.getState()
+ if unixSec == 0 || st != StateIdle {
+ return false
+ }
+ }
+ return true
+}
+
+func (s *Server) ExportAllConnsByState() map[ConnState]int {
+ states := map[ConnState]int{}
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for c := range s.activeConn {
+ st, _ := c.getState()
+ states[st] += 1
+ }
+ return states
+}
+
+func (r *Request) WithT(t *testing.T) *Request {
+ return r.WithContext(context.WithValue(r.Context(), tLogKey{}, t.Logf))
+}
+
+func ExportSetH2GoawayTimeout(d time.Duration) (restore func()) {
+ old := http2goAwayTimeout
+ http2goAwayTimeout = d
+ return func() { http2goAwayTimeout = old }
+}
+
+func (r *Request) ExportIsReplayable() bool { return r.isReplayable() }
+
+// ExportCloseTransportConnsAbruptly closes all idle connections from
+// tr in an abrupt way, just reaching into the underlying Conns and
+// closing them, without telling the Transport or its persistConns
+// that it's doing so. This is to simulate the server closing connections
+// on the Transport.
+func ExportCloseTransportConnsAbruptly(tr *Transport) {
+ tr.idleMu.Lock()
+ for _, pcs := range tr.idleConn {
+ for _, pc := range pcs {
+ pc.conn.Close()
+ }
+ }
+ tr.idleMu.Unlock()
+}
+
+// ResponseWriterConnForTesting returns w's underlying connection, if w
+// is a regular *response ResponseWriter.
+func ResponseWriterConnForTesting(w ResponseWriter) (c net.Conn, ok bool) {
+ if r, ok := w.(*response); ok {
+ return r.conn.rwc, true
+ }
+ return nil, false
+}
+
+func init() {
+ // Set the default rstAvoidanceDelay to the minimum possible value to shake
+ // out tests that unexpectedly depend on it. Such tests should use
+ // runTimeSensitiveTest and SetRSTAvoidanceDelay to explicitly raise the delay
+ // if needed.
+ rstAvoidanceDelay = 1 * time.Nanosecond
+}
+
+// SetRSTAvoidanceDelay sets how long we are willing to wait between calling
+// CloseWrite on a connection and fully closing the connection.
+func SetRSTAvoidanceDelay(t *testing.T, d time.Duration) {
+ prevDelay := rstAvoidanceDelay
+ t.Cleanup(func() {
+ rstAvoidanceDelay = prevDelay
+ })
+ rstAvoidanceDelay = d
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/fcgi/child.go b/platform/dbops/binaries/go/go/src/net/http/fcgi/child.go
new file mode 100644
index 0000000000000000000000000000000000000000..7665e7d25240978e9d367bf6649bc0ca9df5de77
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/fcgi/child.go
@@ -0,0 +1,395 @@
+// 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 fcgi
+
+// This file implements FastCGI from the perspective of a child process.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/cgi"
+ "os"
+ "strings"
+ "time"
+)
+
+// request holds the state for an in-progress request. As soon as it's complete,
+// it's converted to an http.Request.
+type request struct {
+ pw *io.PipeWriter
+ reqId uint16
+ params map[string]string
+ buf [1024]byte
+ rawParams []byte
+ keepConn bool
+}
+
+// envVarsContextKey uniquely identifies a mapping of CGI
+// environment variables to their values in a request context
+type envVarsContextKey struct{}
+
+func newRequest(reqId uint16, flags uint8) *request {
+ r := &request{
+ reqId: reqId,
+ params: map[string]string{},
+ keepConn: flags&flagKeepConn != 0,
+ }
+ r.rawParams = r.buf[:0]
+ return r
+}
+
+// parseParams reads an encoded []byte into Params.
+func (r *request) parseParams() {
+ text := r.rawParams
+ r.rawParams = nil
+ for len(text) > 0 {
+ keyLen, n := readSize(text)
+ if n == 0 {
+ return
+ }
+ text = text[n:]
+ valLen, n := readSize(text)
+ if n == 0 {
+ return
+ }
+ text = text[n:]
+ if int(keyLen)+int(valLen) > len(text) {
+ return
+ }
+ key := readString(text, keyLen)
+ text = text[keyLen:]
+ val := readString(text, valLen)
+ text = text[valLen:]
+ r.params[key] = val
+ }
+}
+
+// response implements http.ResponseWriter.
+type response struct {
+ req *request
+ header http.Header
+ code int
+ wroteHeader bool
+ wroteCGIHeader bool
+ w *bufWriter
+}
+
+func newResponse(c *child, req *request) *response {
+ return &response{
+ req: req,
+ header: http.Header{},
+ w: newWriter(c.conn, typeStdout, req.reqId),
+ }
+}
+
+func (r *response) Header() http.Header {
+ return r.header
+}
+
+func (r *response) Write(p []byte) (n int, err error) {
+ if !r.wroteHeader {
+ r.WriteHeader(http.StatusOK)
+ }
+ if !r.wroteCGIHeader {
+ r.writeCGIHeader(p)
+ }
+ return r.w.Write(p)
+}
+
+func (r *response) WriteHeader(code int) {
+ if r.wroteHeader {
+ return
+ }
+ r.wroteHeader = true
+ r.code = code
+ if code == http.StatusNotModified {
+ // Must not have body.
+ r.header.Del("Content-Type")
+ r.header.Del("Content-Length")
+ r.header.Del("Transfer-Encoding")
+ }
+ if r.header.Get("Date") == "" {
+ r.header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
+ }
+}
+
+// writeCGIHeader finalizes the header sent to the client and writes it to the output.
+// p is not written by writeHeader, but is the first chunk of the body
+// that will be written. It is sniffed for a Content-Type if none is
+// set explicitly.
+func (r *response) writeCGIHeader(p []byte) {
+ if r.wroteCGIHeader {
+ return
+ }
+ r.wroteCGIHeader = true
+ fmt.Fprintf(r.w, "Status: %d %s\r\n", r.code, http.StatusText(r.code))
+ if _, hasType := r.header["Content-Type"]; r.code != http.StatusNotModified && !hasType {
+ r.header.Set("Content-Type", http.DetectContentType(p))
+ }
+ r.header.Write(r.w)
+ r.w.WriteString("\r\n")
+ r.w.Flush()
+}
+
+func (r *response) Flush() {
+ if !r.wroteHeader {
+ r.WriteHeader(http.StatusOK)
+ }
+ r.w.Flush()
+}
+
+func (r *response) Close() error {
+ r.Flush()
+ return r.w.Close()
+}
+
+type child struct {
+ conn *conn
+ handler http.Handler
+
+ requests map[uint16]*request // keyed by request ID
+}
+
+func newChild(rwc io.ReadWriteCloser, handler http.Handler) *child {
+ return &child{
+ conn: newConn(rwc),
+ handler: handler,
+ requests: make(map[uint16]*request),
+ }
+}
+
+func (c *child) serve() {
+ defer c.conn.Close()
+ defer c.cleanUp()
+ var rec record
+ for {
+ if err := rec.read(c.conn.rwc); err != nil {
+ return
+ }
+ if err := c.handleRecord(&rec); err != nil {
+ return
+ }
+ }
+}
+
+var errCloseConn = errors.New("fcgi: connection should be closed")
+
+var emptyBody = io.NopCloser(strings.NewReader(""))
+
+// ErrRequestAborted is returned by Read when a handler attempts to read the
+// body of a request that has been aborted by the web server.
+var ErrRequestAborted = errors.New("fcgi: request aborted by web server")
+
+// ErrConnClosed is returned by Read when a handler attempts to read the body of
+// a request after the connection to the web server has been closed.
+var ErrConnClosed = errors.New("fcgi: connection to web server closed")
+
+func (c *child) handleRecord(rec *record) error {
+ req, ok := c.requests[rec.h.Id]
+ if !ok && rec.h.Type != typeBeginRequest && rec.h.Type != typeGetValues {
+ // The spec says to ignore unknown request IDs.
+ return nil
+ }
+
+ switch rec.h.Type {
+ case typeBeginRequest:
+ if req != nil {
+ // The server is trying to begin a request with the same ID
+ // as an in-progress request. This is an error.
+ return errors.New("fcgi: received ID that is already in-flight")
+ }
+
+ var br beginRequest
+ if err := br.read(rec.content()); err != nil {
+ return err
+ }
+ if br.role != roleResponder {
+ c.conn.writeEndRequest(rec.h.Id, 0, statusUnknownRole)
+ return nil
+ }
+ req = newRequest(rec.h.Id, br.flags)
+ c.requests[rec.h.Id] = req
+ return nil
+ case typeParams:
+ // NOTE(eds): Technically a key-value pair can straddle the boundary
+ // between two packets. We buffer until we've received all parameters.
+ if len(rec.content()) > 0 {
+ req.rawParams = append(req.rawParams, rec.content()...)
+ return nil
+ }
+ req.parseParams()
+ return nil
+ case typeStdin:
+ content := rec.content()
+ if req.pw == nil {
+ var body io.ReadCloser
+ if len(content) > 0 {
+ // body could be an io.LimitReader, but it shouldn't matter
+ // as long as both sides are behaving.
+ body, req.pw = io.Pipe()
+ } else {
+ body = emptyBody
+ }
+ go c.serveRequest(req, body)
+ }
+ if len(content) > 0 {
+ // TODO(eds): This blocks until the handler reads from the pipe.
+ // If the handler takes a long time, it might be a problem.
+ req.pw.Write(content)
+ } else {
+ delete(c.requests, req.reqId)
+ if req.pw != nil {
+ req.pw.Close()
+ }
+ }
+ return nil
+ case typeGetValues:
+ values := map[string]string{"FCGI_MPXS_CONNS": "1"}
+ c.conn.writePairs(typeGetValuesResult, 0, values)
+ return nil
+ case typeData:
+ // If the filter role is implemented, read the data stream here.
+ return nil
+ case typeAbortRequest:
+ delete(c.requests, rec.h.Id)
+ c.conn.writeEndRequest(rec.h.Id, 0, statusRequestComplete)
+ if req.pw != nil {
+ req.pw.CloseWithError(ErrRequestAborted)
+ }
+ if !req.keepConn {
+ // connection will close upon return
+ return errCloseConn
+ }
+ return nil
+ default:
+ b := make([]byte, 8)
+ b[0] = byte(rec.h.Type)
+ c.conn.writeRecord(typeUnknownType, 0, b)
+ return nil
+ }
+}
+
+// filterOutUsedEnvVars returns a new map of env vars without the
+// variables in the given envVars map that are read for creating each http.Request
+func filterOutUsedEnvVars(envVars map[string]string) map[string]string {
+ withoutUsedEnvVars := make(map[string]string)
+ for k, v := range envVars {
+ if addFastCGIEnvToContext(k) {
+ withoutUsedEnvVars[k] = v
+ }
+ }
+ return withoutUsedEnvVars
+}
+
+func (c *child) serveRequest(req *request, body io.ReadCloser) {
+ r := newResponse(c, req)
+ httpReq, err := cgi.RequestFromMap(req.params)
+ if err != nil {
+ // there was an error reading the request
+ r.WriteHeader(http.StatusInternalServerError)
+ c.conn.writeRecord(typeStderr, req.reqId, []byte(err.Error()))
+ } else {
+ httpReq.Body = body
+ withoutUsedEnvVars := filterOutUsedEnvVars(req.params)
+ envVarCtx := context.WithValue(httpReq.Context(), envVarsContextKey{}, withoutUsedEnvVars)
+ httpReq = httpReq.WithContext(envVarCtx)
+ c.handler.ServeHTTP(r, httpReq)
+ }
+ // Make sure we serve something even if nothing was written to r
+ r.Write(nil)
+ r.Close()
+ c.conn.writeEndRequest(req.reqId, 0, statusRequestComplete)
+
+ // Consume the entire body, so the host isn't still writing to
+ // us when we close the socket below in the !keepConn case,
+ // otherwise we'd send a RST. (golang.org/issue/4183)
+ // TODO(bradfitz): also bound this copy in time. Or send
+ // some sort of abort request to the host, so the host
+ // can properly cut off the client sending all the data.
+ // For now just bound it a little and
+ io.CopyN(io.Discard, body, 100<<20)
+ body.Close()
+
+ if !req.keepConn {
+ c.conn.Close()
+ }
+}
+
+func (c *child) cleanUp() {
+ for _, req := range c.requests {
+ if req.pw != nil {
+ // race with call to Close in c.serveRequest doesn't matter because
+ // Pipe(Reader|Writer).Close are idempotent
+ req.pw.CloseWithError(ErrConnClosed)
+ }
+ }
+}
+
+// Serve accepts incoming FastCGI connections on the listener l, creating a new
+// goroutine for each. The goroutine reads requests and then calls handler
+// to reply to them.
+// If l is nil, Serve accepts connections from os.Stdin.
+// If handler is nil, [http.DefaultServeMux] is used.
+func Serve(l net.Listener, handler http.Handler) error {
+ if l == nil {
+ var err error
+ l, err = net.FileListener(os.Stdin)
+ if err != nil {
+ return err
+ }
+ defer l.Close()
+ }
+ if handler == nil {
+ handler = http.DefaultServeMux
+ }
+ for {
+ rw, err := l.Accept()
+ if err != nil {
+ return err
+ }
+ c := newChild(rw, handler)
+ go c.serve()
+ }
+}
+
+// ProcessEnv returns FastCGI environment variables associated with the request r
+// for which no effort was made to be included in the request itself - the data
+// is hidden in the request's context. As an example, if REMOTE_USER is set for a
+// request, it will not be found anywhere in r, but it will be included in
+// ProcessEnv's response (via r's context).
+func ProcessEnv(r *http.Request) map[string]string {
+ env, _ := r.Context().Value(envVarsContextKey{}).(map[string]string)
+ return env
+}
+
+// addFastCGIEnvToContext reports whether to include the FastCGI environment variable s
+// in the http.Request.Context, accessible via ProcessEnv.
+func addFastCGIEnvToContext(s string) bool {
+ // Exclude things supported by net/http natively:
+ switch s {
+ case "CONTENT_LENGTH", "CONTENT_TYPE", "HTTPS",
+ "PATH_INFO", "QUERY_STRING", "REMOTE_ADDR",
+ "REMOTE_HOST", "REMOTE_PORT", "REQUEST_METHOD",
+ "REQUEST_URI", "SCRIPT_NAME", "SERVER_PROTOCOL":
+ return false
+ }
+ if strings.HasPrefix(s, "HTTP_") {
+ return false
+ }
+ // Explicitly include FastCGI-specific things.
+ // This list is redundant with the default "return true" below.
+ // Consider this documentation of the sorts of things we expect
+ // to maybe see.
+ switch s {
+ case "REMOTE_USER":
+ return true
+ }
+ // Unknown, so include it to be safe.
+ return true
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi.go b/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi.go
new file mode 100644
index 0000000000000000000000000000000000000000..56f7d4078982f2d35504291472d7f324467a343d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi.go
@@ -0,0 +1,277 @@
+// 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 fcgi implements the FastCGI protocol.
+//
+// See https://fast-cgi.github.io/ for an unofficial mirror of the
+// original documentation.
+//
+// Currently only the responder role is supported.
+package fcgi
+
+// This file defines the raw protocol and some utilities used by the child and
+// the host.
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "sync"
+)
+
+// recType is a record type, as defined by
+// https://web.archive.org/web/20150420080736/http://www.fastcgi.com/drupal/node/6?q=node/22#S8
+type recType uint8
+
+const (
+ typeBeginRequest recType = 1
+ typeAbortRequest recType = 2
+ typeEndRequest recType = 3
+ typeParams recType = 4
+ typeStdin recType = 5
+ typeStdout recType = 6
+ typeStderr recType = 7
+ typeData recType = 8
+ typeGetValues recType = 9
+ typeGetValuesResult recType = 10
+ typeUnknownType recType = 11
+)
+
+// keep the connection between web-server and responder open after request
+const flagKeepConn = 1
+
+const (
+ maxWrite = 65535 // maximum record body
+ maxPad = 255
+)
+
+const (
+ roleResponder = iota + 1 // only Responders are implemented.
+ roleAuthorizer
+ roleFilter
+)
+
+const (
+ statusRequestComplete = iota
+ statusCantMultiplex
+ statusOverloaded
+ statusUnknownRole
+)
+
+type header struct {
+ Version uint8
+ Type recType
+ Id uint16
+ ContentLength uint16
+ PaddingLength uint8
+ Reserved uint8
+}
+
+type beginRequest struct {
+ role uint16
+ flags uint8
+ reserved [5]uint8
+}
+
+func (br *beginRequest) read(content []byte) error {
+ if len(content) != 8 {
+ return errors.New("fcgi: invalid begin request record")
+ }
+ br.role = binary.BigEndian.Uint16(content)
+ br.flags = content[2]
+ return nil
+}
+
+// for padding so we don't have to allocate all the time
+// not synchronized because we don't care what the contents are
+var pad [maxPad]byte
+
+func (h *header) init(recType recType, reqId uint16, contentLength int) {
+ h.Version = 1
+ h.Type = recType
+ h.Id = reqId
+ h.ContentLength = uint16(contentLength)
+ h.PaddingLength = uint8(-contentLength & 7)
+}
+
+// conn sends records over rwc
+type conn struct {
+ mutex sync.Mutex
+ rwc io.ReadWriteCloser
+ closeErr error
+ closed bool
+
+ // to avoid allocations
+ buf bytes.Buffer
+ h header
+}
+
+func newConn(rwc io.ReadWriteCloser) *conn {
+ return &conn{rwc: rwc}
+}
+
+// Close closes the conn if it is not already closed.
+func (c *conn) Close() error {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+ if !c.closed {
+ c.closeErr = c.rwc.Close()
+ c.closed = true
+ }
+ return c.closeErr
+}
+
+type record struct {
+ h header
+ buf [maxWrite + maxPad]byte
+}
+
+func (rec *record) read(r io.Reader) (err error) {
+ if err = binary.Read(r, binary.BigEndian, &rec.h); err != nil {
+ return err
+ }
+ if rec.h.Version != 1 {
+ return errors.New("fcgi: invalid header version")
+ }
+ n := int(rec.h.ContentLength) + int(rec.h.PaddingLength)
+ if _, err = io.ReadFull(r, rec.buf[:n]); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (r *record) content() []byte {
+ return r.buf[:r.h.ContentLength]
+}
+
+// writeRecord writes and sends a single record.
+func (c *conn) writeRecord(recType recType, reqId uint16, b []byte) error {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+ c.buf.Reset()
+ c.h.init(recType, reqId, len(b))
+ if err := binary.Write(&c.buf, binary.BigEndian, c.h); err != nil {
+ return err
+ }
+ if _, err := c.buf.Write(b); err != nil {
+ return err
+ }
+ if _, err := c.buf.Write(pad[:c.h.PaddingLength]); err != nil {
+ return err
+ }
+ _, err := c.rwc.Write(c.buf.Bytes())
+ return err
+}
+
+func (c *conn) writeEndRequest(reqId uint16, appStatus int, protocolStatus uint8) error {
+ b := make([]byte, 8)
+ binary.BigEndian.PutUint32(b, uint32(appStatus))
+ b[4] = protocolStatus
+ return c.writeRecord(typeEndRequest, reqId, b)
+}
+
+func (c *conn) writePairs(recType recType, reqId uint16, pairs map[string]string) error {
+ w := newWriter(c, recType, reqId)
+ b := make([]byte, 8)
+ for k, v := range pairs {
+ n := encodeSize(b, uint32(len(k)))
+ n += encodeSize(b[n:], uint32(len(v)))
+ if _, err := w.Write(b[:n]); err != nil {
+ return err
+ }
+ if _, err := w.WriteString(k); err != nil {
+ return err
+ }
+ if _, err := w.WriteString(v); err != nil {
+ return err
+ }
+ }
+ w.Close()
+ return nil
+}
+
+func readSize(s []byte) (uint32, int) {
+ if len(s) == 0 {
+ return 0, 0
+ }
+ size, n := uint32(s[0]), 1
+ if size&(1<<7) != 0 {
+ if len(s) < 4 {
+ return 0, 0
+ }
+ n = 4
+ size = binary.BigEndian.Uint32(s)
+ size &^= 1 << 31
+ }
+ return size, n
+}
+
+func readString(s []byte, size uint32) string {
+ if size > uint32(len(s)) {
+ return ""
+ }
+ return string(s[:size])
+}
+
+func encodeSize(b []byte, size uint32) int {
+ if size > 127 {
+ size |= 1 << 31
+ binary.BigEndian.PutUint32(b, size)
+ return 4
+ }
+ b[0] = byte(size)
+ return 1
+}
+
+// bufWriter encapsulates bufio.Writer but also closes the underlying stream when
+// Closed.
+type bufWriter struct {
+ closer io.Closer
+ *bufio.Writer
+}
+
+func (w *bufWriter) Close() error {
+ if err := w.Writer.Flush(); err != nil {
+ w.closer.Close()
+ return err
+ }
+ return w.closer.Close()
+}
+
+func newWriter(c *conn, recType recType, reqId uint16) *bufWriter {
+ s := &streamWriter{c: c, recType: recType, reqId: reqId}
+ w := bufio.NewWriterSize(s, maxWrite)
+ return &bufWriter{s, w}
+}
+
+// streamWriter abstracts out the separation of a stream into discrete records.
+// It only writes maxWrite bytes at a time.
+type streamWriter struct {
+ c *conn
+ recType recType
+ reqId uint16
+}
+
+func (w *streamWriter) Write(p []byte) (int, error) {
+ nn := 0
+ for len(p) > 0 {
+ n := len(p)
+ if n > maxWrite {
+ n = maxWrite
+ }
+ if err := w.c.writeRecord(w.recType, w.reqId, p[:n]); err != nil {
+ return nn, err
+ }
+ nn += n
+ p = p[n:]
+ }
+ return nn, nil
+}
+
+func (w *streamWriter) Close() error {
+ // send empty record to close the stream
+ return w.c.writeRecord(w.recType, w.reqId, nil)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi_test.go b/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..03c422420f01d2acb1cd3f7c7ca502085c9e0953
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/fcgi/fcgi_test.go
@@ -0,0 +1,453 @@
+// 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 fcgi
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+)
+
+var sizeTests = []struct {
+ size uint32
+ bytes []byte
+}{
+ {0, []byte{0x00}},
+ {127, []byte{0x7F}},
+ {128, []byte{0x80, 0x00, 0x00, 0x80}},
+ {1000, []byte{0x80, 0x00, 0x03, 0xE8}},
+ {33554431, []byte{0x81, 0xFF, 0xFF, 0xFF}},
+}
+
+func TestSize(t *testing.T) {
+ b := make([]byte, 4)
+ for i, test := range sizeTests {
+ n := encodeSize(b, test.size)
+ if !bytes.Equal(b[:n], test.bytes) {
+ t.Errorf("%d expected %x, encoded %x", i, test.bytes, b)
+ }
+ size, n := readSize(test.bytes)
+ if size != test.size {
+ t.Errorf("%d expected %d, read %d", i, test.size, size)
+ }
+ if len(test.bytes) != n {
+ t.Errorf("%d did not consume all the bytes", i)
+ }
+ }
+}
+
+var streamTests = []struct {
+ desc string
+ recType recType
+ reqId uint16
+ content []byte
+ raw []byte
+}{
+ {"single record", typeStdout, 1, nil,
+ []byte{1, byte(typeStdout), 0, 1, 0, 0, 0, 0},
+ },
+ // this data will have to be split into two records
+ {"two records", typeStdin, 300, make([]byte, 66000),
+ bytes.Join([][]byte{
+ // header for the first record
+ {1, byte(typeStdin), 0x01, 0x2C, 0xFF, 0xFF, 1, 0},
+ make([]byte, 65536),
+ // header for the second
+ {1, byte(typeStdin), 0x01, 0x2C, 0x01, 0xD1, 7, 0},
+ make([]byte, 472),
+ // header for the empty record
+ {1, byte(typeStdin), 0x01, 0x2C, 0, 0, 0, 0},
+ },
+ nil),
+ },
+}
+
+type nilCloser struct {
+ io.ReadWriter
+}
+
+func (c *nilCloser) Close() error { return nil }
+
+func TestStreams(t *testing.T) {
+ var rec record
+outer:
+ for _, test := range streamTests {
+ buf := bytes.NewBuffer(test.raw)
+ var content []byte
+ for buf.Len() > 0 {
+ if err := rec.read(buf); err != nil {
+ t.Errorf("%s: error reading record: %v", test.desc, err)
+ continue outer
+ }
+ content = append(content, rec.content()...)
+ }
+ if rec.h.Type != test.recType {
+ t.Errorf("%s: got type %d expected %d", test.desc, rec.h.Type, test.recType)
+ continue
+ }
+ if rec.h.Id != test.reqId {
+ t.Errorf("%s: got request ID %d expected %d", test.desc, rec.h.Id, test.reqId)
+ continue
+ }
+ if !bytes.Equal(content, test.content) {
+ t.Errorf("%s: read wrong content", test.desc)
+ continue
+ }
+ buf.Reset()
+ c := newConn(&nilCloser{buf})
+ w := newWriter(c, test.recType, test.reqId)
+ if _, err := w.Write(test.content); err != nil {
+ t.Errorf("%s: error writing record: %v", test.desc, err)
+ continue
+ }
+ if err := w.Close(); err != nil {
+ t.Errorf("%s: error closing stream: %v", test.desc, err)
+ continue
+ }
+ if !bytes.Equal(buf.Bytes(), test.raw) {
+ t.Errorf("%s: wrote wrong content", test.desc)
+ }
+ }
+}
+
+type writeOnlyConn struct {
+ buf []byte
+}
+
+func (c *writeOnlyConn) Write(p []byte) (int, error) {
+ c.buf = append(c.buf, p...)
+ return len(p), nil
+}
+
+func (c *writeOnlyConn) Read(p []byte) (int, error) {
+ return 0, errors.New("conn is write-only")
+}
+
+func (c *writeOnlyConn) Close() error {
+ return nil
+}
+
+func TestGetValues(t *testing.T) {
+ var rec record
+ rec.h.Type = typeGetValues
+
+ wc := new(writeOnlyConn)
+ c := newChild(wc, nil)
+ err := c.handleRecord(&rec)
+ if err != nil {
+ t.Fatalf("handleRecord: %v", err)
+ }
+
+ const want = "\x01\n\x00\x00\x00\x12\x06\x00" +
+ "\x0f\x01FCGI_MPXS_CONNS1" +
+ "\x00\x00\x00\x00\x00\x00\x01\n\x00\x00\x00\x00\x00\x00"
+ if got := string(wc.buf); got != want {
+ t.Errorf(" got: %q\nwant: %q\n", got, want)
+ }
+}
+
+func nameValuePair11(nameData, valueData string) []byte {
+ return bytes.Join(
+ [][]byte{
+ {byte(len(nameData)), byte(len(valueData))},
+ []byte(nameData),
+ []byte(valueData),
+ },
+ nil,
+ )
+}
+
+func makeRecord(
+ recordType recType,
+ requestId uint16,
+ contentData []byte,
+) []byte {
+ requestIdB1 := byte(requestId >> 8)
+ requestIdB0 := byte(requestId)
+
+ contentLength := len(contentData)
+ contentLengthB1 := byte(contentLength >> 8)
+ contentLengthB0 := byte(contentLength)
+ return bytes.Join([][]byte{
+ {1, byte(recordType), requestIdB1, requestIdB0, contentLengthB1,
+ contentLengthB0, 0, 0},
+ contentData,
+ },
+ nil)
+}
+
+// a series of FastCGI records that start a request and begin sending the
+// request body
+var streamBeginTypeStdin = bytes.Join([][]byte{
+ // set up request 1
+ makeRecord(typeBeginRequest, 1,
+ []byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}),
+ // add required parameters to request 1
+ makeRecord(typeParams, 1, nameValuePair11("REQUEST_METHOD", "GET")),
+ makeRecord(typeParams, 1, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")),
+ makeRecord(typeParams, 1, nil),
+ // begin sending body of request 1
+ makeRecord(typeStdin, 1, []byte("0123456789abcdef")),
+},
+ nil)
+
+var cleanUpTests = []struct {
+ input []byte
+ err error
+}{
+ // confirm that child.handleRecord closes req.pw after aborting req
+ {
+ bytes.Join([][]byte{
+ streamBeginTypeStdin,
+ makeRecord(typeAbortRequest, 1, nil),
+ },
+ nil),
+ ErrRequestAborted,
+ },
+ // confirm that child.serve closes all pipes after error reading record
+ {
+ bytes.Join([][]byte{
+ streamBeginTypeStdin,
+ nil,
+ },
+ nil),
+ ErrConnClosed,
+ },
+}
+
+type nopWriteCloser struct {
+ io.Reader
+}
+
+func (nopWriteCloser) Write(buf []byte) (int, error) {
+ return len(buf), nil
+}
+
+func (nopWriteCloser) Close() error {
+ return nil
+}
+
+// Test that child.serve closes the bodies of aborted requests and closes the
+// bodies of all requests before returning. Causes deadlock if either condition
+// isn't met. See issue 6934.
+func TestChildServeCleansUp(t *testing.T) {
+ for _, tt := range cleanUpTests {
+ input := make([]byte, len(tt.input))
+ copy(input, tt.input)
+ rc := nopWriteCloser{bytes.NewReader(input)}
+ done := make(chan struct{})
+ c := newChild(rc, http.HandlerFunc(func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+ // block on reading body of request
+ _, err := io.Copy(io.Discard, r.Body)
+ if err != tt.err {
+ t.Errorf("Expected %#v, got %#v", tt.err, err)
+ }
+ // not reached if body of request isn't closed
+ close(done)
+ }))
+ c.serve()
+ // wait for body of request to be closed or all goroutines to block
+ <-done
+ }
+}
+
+type rwNopCloser struct {
+ io.Reader
+ io.Writer
+}
+
+func (rwNopCloser) Close() error {
+ return nil
+}
+
+// Verifies it doesn't crash. Issue 11824.
+func TestMalformedParams(t *testing.T) {
+ input := []byte{
+ // beginRequest, requestId=1, contentLength=8, role=1, keepConn=1
+ 1, 1, 0, 1, 0, 8, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
+ // params, requestId=1, contentLength=10, k1Len=50, v1Len=50 (malformed, wrong length)
+ 1, 4, 0, 1, 0, 10, 0, 0, 50, 50, 3, 4, 5, 6, 7, 8, 9, 10,
+ // end of params
+ 1, 4, 0, 1, 0, 0, 0, 0,
+ }
+ rw := rwNopCloser{bytes.NewReader(input), io.Discard}
+ c := newChild(rw, http.DefaultServeMux)
+ c.serve()
+}
+
+// a series of FastCGI records that start and end a request
+var streamFullRequestStdin = bytes.Join([][]byte{
+ // set up request
+ makeRecord(typeBeginRequest, 1,
+ []byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}),
+ // add required parameters
+ makeRecord(typeParams, 1, nameValuePair11("REQUEST_METHOD", "GET")),
+ makeRecord(typeParams, 1, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")),
+ // set optional parameters
+ makeRecord(typeParams, 1, nameValuePair11("REMOTE_USER", "jane.doe")),
+ makeRecord(typeParams, 1, nameValuePair11("QUERY_STRING", "/foo/bar")),
+ makeRecord(typeParams, 1, nil),
+ // begin sending body of request
+ makeRecord(typeStdin, 1, []byte("0123456789abcdef")),
+ // end request
+ makeRecord(typeEndRequest, 1, nil),
+},
+ nil)
+
+var envVarTests = []struct {
+ input []byte
+ envVar string
+ expectedVal string
+ expectedFilteredOut bool
+}{
+ {
+ streamFullRequestStdin,
+ "REMOTE_USER",
+ "jane.doe",
+ false,
+ },
+ {
+ streamFullRequestStdin,
+ "QUERY_STRING",
+ "",
+ true,
+ },
+}
+
+// Test that environment variables set for a request can be
+// read by a handler. Ensures that variables not set will not
+// be exposed to a handler.
+func TestChildServeReadsEnvVars(t *testing.T) {
+ for _, tt := range envVarTests {
+ input := make([]byte, len(tt.input))
+ copy(input, tt.input)
+ rc := nopWriteCloser{bytes.NewReader(input)}
+ done := make(chan struct{})
+ c := newChild(rc, http.HandlerFunc(func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+ env := ProcessEnv(r)
+ if _, ok := env[tt.envVar]; ok && tt.expectedFilteredOut {
+ t.Errorf("Expected environment variable %s to not be set, but set to %s",
+ tt.envVar, env[tt.envVar])
+ } else if env[tt.envVar] != tt.expectedVal {
+ t.Errorf("Expected %s, got %s", tt.expectedVal, env[tt.envVar])
+ }
+ close(done)
+ }))
+ c.serve()
+ <-done
+ }
+}
+
+func TestResponseWriterSniffsContentType(t *testing.T) {
+ var tests = []struct {
+ name string
+ body string
+ wantCT string
+ }{
+ {
+ name: "no body",
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "html",
+ body: "test pageThis is a body",
+ wantCT: "text/html; charset=utf-8",
+ },
+ {
+ name: "text",
+ body: strings.Repeat("gopher", 86),
+ wantCT: "text/plain; charset=utf-8",
+ },
+ {
+ name: "jpg",
+ body: "\xFF\xD8\xFF" + strings.Repeat("B", 1024),
+ wantCT: "image/jpeg",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ input := make([]byte, len(streamFullRequestStdin))
+ copy(input, streamFullRequestStdin)
+ rc := nopWriteCloser{bytes.NewReader(input)}
+ done := make(chan struct{})
+ var resp *response
+ c := newChild(rc, http.HandlerFunc(func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+ io.WriteString(w, tt.body)
+ resp = w.(*response)
+ close(done)
+ }))
+ c.serve()
+ <-done
+ if got := resp.Header().Get("Content-Type"); got != tt.wantCT {
+ t.Errorf("got a Content-Type of %q; expected it to start with %q", got, tt.wantCT)
+ }
+ })
+ }
+}
+
+type signalingNopWriteCloser struct {
+ io.ReadCloser
+ closed chan bool
+}
+
+func (*signalingNopWriteCloser) Write(buf []byte) (int, error) {
+ return len(buf), nil
+}
+
+func (rc *signalingNopWriteCloser) Close() error {
+ close(rc.closed)
+ return rc.ReadCloser.Close()
+}
+
+// Test whether server properly closes connection when processing slow
+// requests
+func TestSlowRequest(t *testing.T) {
+ pr, pw := io.Pipe()
+
+ writerDone := make(chan struct{})
+ go func() {
+ for _, buf := range [][]byte{
+ streamBeginTypeStdin,
+ makeRecord(typeStdin, 1, nil),
+ } {
+ pw.Write(buf)
+ time.Sleep(100 * time.Millisecond)
+ }
+ close(writerDone)
+ }()
+ defer func() {
+ <-writerDone
+ pw.Close()
+ }()
+
+ rc := &signalingNopWriteCloser{pr, make(chan bool)}
+ handlerDone := make(chan bool)
+
+ c := newChild(rc, http.HandlerFunc(func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+ w.WriteHeader(200)
+ close(handlerDone)
+ }))
+ c.serve()
+
+ <-handlerDone
+ <-rc.closed
+ t.Log("FastCGI child closed connection")
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/filetransport.go b/platform/dbops/binaries/go/go/src/net/http/filetransport.go
new file mode 100644
index 0000000000000000000000000000000000000000..7384b22fbe927c4781b6d1161a6d56673e8fe0fd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/filetransport.go
@@ -0,0 +1,142 @@
+// 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 http
+
+import (
+ "fmt"
+ "io"
+ "io/fs"
+)
+
+// fileTransport implements RoundTripper for the 'file' protocol.
+type fileTransport struct {
+ fh fileHandler
+}
+
+// NewFileTransport returns a new [RoundTripper], serving the provided
+// [FileSystem]. The returned RoundTripper ignores the URL host in its
+// incoming requests, as well as most other properties of the
+// request.
+//
+// The typical use case for NewFileTransport is to register the "file"
+// protocol with a [Transport], as in:
+//
+// t := &http.Transport{}
+// t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
+// c := &http.Client{Transport: t}
+// res, err := c.Get("file:///etc/passwd")
+// ...
+func NewFileTransport(fs FileSystem) RoundTripper {
+ return fileTransport{fileHandler{fs}}
+}
+
+// NewFileTransportFS returns a new [RoundTripper], serving the provided
+// file system fsys. The returned RoundTripper ignores the URL host in its
+// incoming requests, as well as most other properties of the
+// request.
+//
+// The typical use case for NewFileTransportFS is to register the "file"
+// protocol with a [Transport], as in:
+//
+// fsys := os.DirFS("/")
+// t := &http.Transport{}
+// t.RegisterProtocol("file", http.NewFileTransportFS(fsys))
+// c := &http.Client{Transport: t}
+// res, err := c.Get("file:///etc/passwd")
+// ...
+func NewFileTransportFS(fsys fs.FS) RoundTripper {
+ return NewFileTransport(FS(fsys))
+}
+
+func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error) {
+ // We start ServeHTTP in a goroutine, which may take a long
+ // time if the file is large. The newPopulateResponseWriter
+ // call returns a channel which either ServeHTTP or finish()
+ // sends our *Response on, once the *Response itself has been
+ // populated (even if the body itself is still being
+ // written to the res.Body, a pipe)
+ rw, resc := newPopulateResponseWriter()
+ go func() {
+ t.fh.ServeHTTP(rw, req)
+ rw.finish()
+ }()
+ return <-resc, nil
+}
+
+func newPopulateResponseWriter() (*populateResponse, <-chan *Response) {
+ pr, pw := io.Pipe()
+ rw := &populateResponse{
+ ch: make(chan *Response),
+ pw: pw,
+ res: &Response{
+ Proto: "HTTP/1.0",
+ ProtoMajor: 1,
+ Header: make(Header),
+ Close: true,
+ Body: pr,
+ },
+ }
+ return rw, rw.ch
+}
+
+// populateResponse is a ResponseWriter that populates the *Response
+// in res, and writes its body to a pipe connected to the response
+// body. Once writes begin or finish() is called, the response is sent
+// on ch.
+type populateResponse struct {
+ res *Response
+ ch chan *Response
+ wroteHeader bool
+ hasContent bool
+ sentResponse bool
+ pw *io.PipeWriter
+}
+
+func (pr *populateResponse) finish() {
+ if !pr.wroteHeader {
+ pr.WriteHeader(500)
+ }
+ if !pr.sentResponse {
+ pr.sendResponse()
+ }
+ pr.pw.Close()
+}
+
+func (pr *populateResponse) sendResponse() {
+ if pr.sentResponse {
+ return
+ }
+ pr.sentResponse = true
+
+ if pr.hasContent {
+ pr.res.ContentLength = -1
+ }
+ pr.ch <- pr.res
+}
+
+func (pr *populateResponse) Header() Header {
+ return pr.res.Header
+}
+
+func (pr *populateResponse) WriteHeader(code int) {
+ if pr.wroteHeader {
+ return
+ }
+ pr.wroteHeader = true
+
+ pr.res.StatusCode = code
+ pr.res.Status = fmt.Sprintf("%d %s", code, StatusText(code))
+}
+
+func (pr *populateResponse) Write(p []byte) (n int, err error) {
+ if !pr.wroteHeader {
+ pr.WriteHeader(StatusOK)
+ }
+ pr.hasContent = true
+ if !pr.sentResponse {
+ pr.sendResponse()
+ }
+ return pr.pw.Write(p)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/filetransport_test.go b/platform/dbops/binaries/go/go/src/net/http/filetransport_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b3e3301e1073036c81d89db17e9a5ac8ad55ff34
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/filetransport_test.go
@@ -0,0 +1,106 @@
+// 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 http
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+ "testing/fstest"
+)
+
+func checker(t *testing.T) func(string, error) {
+ return func(call string, err error) {
+ if err == nil {
+ return
+ }
+ t.Fatalf("%s: %v", call, err)
+ }
+}
+
+func TestFileTransport(t *testing.T) {
+ check := checker(t)
+
+ dname := t.TempDir()
+ fname := filepath.Join(dname, "foo.txt")
+ err := os.WriteFile(fname, []byte("Bar"), 0644)
+ check("WriteFile", err)
+ defer os.Remove(fname)
+
+ tr := &Transport{}
+ tr.RegisterProtocol("file", NewFileTransport(Dir(dname)))
+ c := &Client{Transport: tr}
+
+ fooURLs := []string{"file:///foo.txt", "file://../foo.txt"}
+ for _, urlstr := range fooURLs {
+ res, err := c.Get(urlstr)
+ check("Get "+urlstr, err)
+ if res.StatusCode != 200 {
+ t.Errorf("for %s, StatusCode = %d, want 200", urlstr, res.StatusCode)
+ }
+ if res.ContentLength != -1 {
+ t.Errorf("for %s, ContentLength = %d, want -1", urlstr, res.ContentLength)
+ }
+ if res.Body == nil {
+ t.Fatalf("for %s, nil Body", urlstr)
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ check("ReadAll "+urlstr, err)
+ if string(slurp) != "Bar" {
+ t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar")
+ }
+ }
+
+ const badURL = "file://../no-exist.txt"
+ res, err := c.Get(badURL)
+ check("Get "+badURL, err)
+ if res.StatusCode != 404 {
+ t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode)
+ }
+ res.Body.Close()
+}
+
+func TestFileTransportFS(t *testing.T) {
+ check := checker(t)
+
+ fsys := fstest.MapFS{
+ "index.html": {Data: []byte("index.html says hello")},
+ }
+
+ tr := &Transport{}
+ tr.RegisterProtocol("file", NewFileTransportFS(fsys))
+ c := &Client{Transport: tr}
+
+ for fname, mfile := range fsys {
+ urlstr := "file:///" + fname
+ res, err := c.Get(urlstr)
+ check("Get "+urlstr, err)
+ if res.StatusCode != 200 {
+ t.Errorf("for %s, StatusCode = %d, want 200", urlstr, res.StatusCode)
+ }
+ if res.ContentLength != -1 {
+ t.Errorf("for %s, ContentLength = %d, want -1", urlstr, res.ContentLength)
+ }
+ if res.Body == nil {
+ t.Fatalf("for %s, nil Body", urlstr)
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ check("ReadAll "+urlstr, err)
+ if string(slurp) != string(mfile.Data) {
+ t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar")
+ }
+ }
+
+ const badURL = "file://../no-exist.txt"
+ res, err := c.Get(badURL)
+ check("Get "+badURL, err)
+ if res.StatusCode != 404 {
+ t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode)
+ }
+ res.Body.Close()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/fs.go b/platform/dbops/binaries/go/go/src/net/http/fs.go
new file mode 100644
index 0000000000000000000000000000000000000000..af7511a7a4bd7e317029ffda09fdd834d77c6da6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/fs.go
@@ -0,0 +1,1057 @@
+// 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.
+
+// HTTP file system request handler
+
+package http
+
+import (
+ "errors"
+ "fmt"
+ "internal/safefilepath"
+ "io"
+ "io/fs"
+ "mime"
+ "mime/multipart"
+ "net/textproto"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// A Dir implements [FileSystem] using the native file system restricted to a
+// specific directory tree.
+//
+// While the [FileSystem.Open] method takes '/'-separated paths, a Dir's string
+// value is a filename on the native file system, not a URL, so it is separated
+// by [filepath.Separator], which isn't necessarily '/'.
+//
+// Note that Dir could expose sensitive files and directories. Dir will follow
+// symlinks pointing out of the directory tree, which can be especially dangerous
+// if serving from a directory in which users are able to create arbitrary symlinks.
+// Dir will also allow access to files and directories starting with a period,
+// which could expose sensitive directories like .git or sensitive files like
+// .htpasswd. To exclude files with a leading period, remove the files/directories
+// from the server or create a custom FileSystem implementation.
+//
+// An empty Dir is treated as ".".
+type Dir string
+
+// mapOpenError maps the provided non-nil error from opening name
+// to a possibly better non-nil error. In particular, it turns OS-specific errors
+// about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552.
+func mapOpenError(originalErr error, name string, sep rune, stat func(string) (fs.FileInfo, error)) error {
+ if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) {
+ return originalErr
+ }
+
+ parts := strings.Split(name, string(sep))
+ for i := range parts {
+ if parts[i] == "" {
+ continue
+ }
+ fi, err := stat(strings.Join(parts[:i+1], string(sep)))
+ if err != nil {
+ return originalErr
+ }
+ if !fi.IsDir() {
+ return fs.ErrNotExist
+ }
+ }
+ return originalErr
+}
+
+// Open implements [FileSystem] using [os.Open], opening files for reading rooted
+// and relative to the directory d.
+func (d Dir) Open(name string) (File, error) {
+ path, err := safefilepath.FromFS(path.Clean("/" + name))
+ if err != nil {
+ return nil, errors.New("http: invalid or unsafe file path")
+ }
+ dir := string(d)
+ if dir == "" {
+ dir = "."
+ }
+ fullName := filepath.Join(dir, path)
+ f, err := os.Open(fullName)
+ if err != nil {
+ return nil, mapOpenError(err, fullName, filepath.Separator, os.Stat)
+ }
+ return f, nil
+}
+
+// A FileSystem implements access to a collection of named files.
+// The elements in a file path are separated by slash ('/', U+002F)
+// characters, regardless of host operating system convention.
+// See the [FileServer] function to convert a FileSystem to a [Handler].
+//
+// This interface predates the [fs.FS] interface, which can be used instead:
+// the [FS] adapter function converts an fs.FS to a FileSystem.
+type FileSystem interface {
+ Open(name string) (File, error)
+}
+
+// A File is returned by a [FileSystem]'s Open method and can be
+// served by the [FileServer] implementation.
+//
+// The methods should behave the same as those on an [*os.File].
+type File interface {
+ io.Closer
+ io.Reader
+ io.Seeker
+ Readdir(count int) ([]fs.FileInfo, error)
+ Stat() (fs.FileInfo, error)
+}
+
+type anyDirs interface {
+ len() int
+ name(i int) string
+ isDir(i int) bool
+}
+
+type fileInfoDirs []fs.FileInfo
+
+func (d fileInfoDirs) len() int { return len(d) }
+func (d fileInfoDirs) isDir(i int) bool { return d[i].IsDir() }
+func (d fileInfoDirs) name(i int) string { return d[i].Name() }
+
+type dirEntryDirs []fs.DirEntry
+
+func (d dirEntryDirs) len() int { return len(d) }
+func (d dirEntryDirs) isDir(i int) bool { return d[i].IsDir() }
+func (d dirEntryDirs) name(i int) string { return d[i].Name() }
+
+func dirList(w ResponseWriter, r *Request, f File) {
+ // Prefer to use ReadDir instead of Readdir,
+ // because the former doesn't require calling
+ // Stat on every entry of a directory on Unix.
+ var dirs anyDirs
+ var err error
+ if d, ok := f.(fs.ReadDirFile); ok {
+ var list dirEntryDirs
+ list, err = d.ReadDir(-1)
+ dirs = list
+ } else {
+ var list fileInfoDirs
+ list, err = f.Readdir(-1)
+ dirs = list
+ }
+
+ if err != nil {
+ logf(r, "http: error reading directory: %v", err)
+ Error(w, "Error reading directory", StatusInternalServerError)
+ return
+ }
+ sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) })
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprintf(w, "\n")
+ for i, n := 0, dirs.len(); i < n; i++ {
+ name := dirs.name(i)
+ if dirs.isDir(i) {
+ name += "/"
+ }
+ // name may contain '?' or '#', which must be escaped to remain
+ // part of the URL path, and not indicate the start of a query
+ // string or fragment.
+ url := url.URL{Path: name}
+ fmt.Fprintf(w, "%s\n", url.String(), htmlReplacer.Replace(name))
+ }
+ fmt.Fprintf(w, "\n")
+}
+
+// ServeContent replies to the request using the content in the
+// provided ReadSeeker. The main benefit of ServeContent over [io.Copy]
+// is that it handles Range requests properly, sets the MIME type, and
+// handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
+// and If-Range requests.
+//
+// If the response's Content-Type header is not set, ServeContent
+// first tries to deduce the type from name's file extension and,
+// if that fails, falls back to reading the first block of the content
+// and passing it to [DetectContentType].
+// The name is otherwise unused; in particular it can be empty and is
+// never sent in the response.
+//
+// If modtime is not the zero time or Unix epoch, ServeContent
+// includes it in a Last-Modified header in the response. If the
+// request includes an If-Modified-Since header, ServeContent uses
+// modtime to decide whether the content needs to be sent at all.
+//
+// The content's Seek method must work: ServeContent uses
+// a seek to the end of the content to determine its size.
+//
+// If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
+// ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
+//
+// Note that [*os.File] implements the [io.ReadSeeker] interface.
+func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
+ sizeFunc := func() (int64, error) {
+ size, err := content.Seek(0, io.SeekEnd)
+ if err != nil {
+ return 0, errSeeker
+ }
+ _, err = content.Seek(0, io.SeekStart)
+ if err != nil {
+ return 0, errSeeker
+ }
+ return size, nil
+ }
+ serveContent(w, req, name, modtime, sizeFunc, content)
+}
+
+// errSeeker is returned by ServeContent's sizeFunc when the content
+// doesn't seek properly. The underlying Seeker's error text isn't
+// included in the sizeFunc reply so it's not sent over HTTP to end
+// users.
+var errSeeker = errors.New("seeker can't seek")
+
+// errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
+// all of the byte-range-spec values is greater than the content size.
+var errNoOverlap = errors.New("invalid range: failed to overlap")
+
+// if name is empty, filename is unknown. (used for mime type, before sniffing)
+// if modtime.IsZero(), modtime is unknown.
+// content must be seeked to the beginning of the file.
+// The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
+func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
+ setLastModified(w, modtime)
+ done, rangeReq := checkPreconditions(w, r, modtime)
+ if done {
+ return
+ }
+
+ code := StatusOK
+
+ // If Content-Type isn't set, use the file's extension to find it, but
+ // if the Content-Type is unset explicitly, do not sniff the type.
+ ctypes, haveType := w.Header()["Content-Type"]
+ var ctype string
+ if !haveType {
+ ctype = mime.TypeByExtension(filepath.Ext(name))
+ if ctype == "" {
+ // read a chunk to decide between utf-8 text and binary
+ var buf [sniffLen]byte
+ n, _ := io.ReadFull(content, buf[:])
+ ctype = DetectContentType(buf[:n])
+ _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
+ if err != nil {
+ Error(w, "seeker can't seek", StatusInternalServerError)
+ return
+ }
+ }
+ w.Header().Set("Content-Type", ctype)
+ } else if len(ctypes) > 0 {
+ ctype = ctypes[0]
+ }
+
+ size, err := sizeFunc()
+ if err != nil {
+ Error(w, err.Error(), StatusInternalServerError)
+ return
+ }
+ if size < 0 {
+ // Should never happen but just to be sure
+ Error(w, "negative content size computed", StatusInternalServerError)
+ return
+ }
+
+ // handle Content-Range header.
+ sendSize := size
+ var sendContent io.Reader = content
+ ranges, err := parseRange(rangeReq, size)
+ switch err {
+ case nil:
+ case errNoOverlap:
+ if size == 0 {
+ // Some clients add a Range header to all requests to
+ // limit the size of the response. If the file is empty,
+ // ignore the range header and respond with a 200 rather
+ // than a 416.
+ ranges = nil
+ break
+ }
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
+ fallthrough
+ default:
+ Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
+ return
+ }
+
+ if sumRangesSize(ranges) > size {
+ // The total number of bytes in all the ranges
+ // is larger than the size of the file by
+ // itself, so this is probably an attack, or a
+ // dumb client. Ignore the range request.
+ ranges = nil
+ }
+ switch {
+ case len(ranges) == 1:
+ // RFC 7233, Section 4.1:
+ // "If a single part is being transferred, the server
+ // generating the 206 response MUST generate a
+ // Content-Range header field, describing what range
+ // of the selected representation is enclosed, and a
+ // payload consisting of the range.
+ // ...
+ // A server MUST NOT generate a multipart response to
+ // a request for a single range, since a client that
+ // does not request multiple parts might not support
+ // multipart responses."
+ ra := ranges[0]
+ if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
+ Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
+ return
+ }
+ sendSize = ra.length
+ code = StatusPartialContent
+ w.Header().Set("Content-Range", ra.contentRange(size))
+ case len(ranges) > 1:
+ sendSize = rangesMIMESize(ranges, ctype, size)
+ code = StatusPartialContent
+
+ pr, pw := io.Pipe()
+ mw := multipart.NewWriter(pw)
+ w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
+ sendContent = pr
+ defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
+ go func() {
+ for _, ra := range ranges {
+ part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
+ if err != nil {
+ pw.CloseWithError(err)
+ return
+ }
+ if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
+ pw.CloseWithError(err)
+ return
+ }
+ if _, err := io.CopyN(part, content, ra.length); err != nil {
+ pw.CloseWithError(err)
+ return
+ }
+ }
+ mw.Close()
+ pw.Close()
+ }()
+ }
+
+ w.Header().Set("Accept-Ranges", "bytes")
+
+ // We should be able to unconditionally set the Content-Length here.
+ //
+ // However, there is a pattern observed in the wild that this breaks:
+ // The user wraps the ResponseWriter in one which gzips data written to it,
+ // and sets "Content-Encoding: gzip".
+ //
+ // The user shouldn't be doing this; the serveContent path here depends
+ // on serving seekable data with a known length. If you want to compress
+ // on the fly, then you shouldn't be using ServeFile/ServeContent, or
+ // you should compress the entire file up-front and provide a seekable
+ // view of the compressed data.
+ //
+ // However, since we've observed this pattern in the wild, and since
+ // setting Content-Length here breaks code that mostly-works today,
+ // skip setting Content-Length if the user set Content-Encoding.
+ //
+ // If this is a range request, always set Content-Length.
+ // If the user isn't changing the bytes sent in the ResponseWrite,
+ // the Content-Length will be correct.
+ // If the user is changing the bytes sent, then the range request wasn't
+ // going to work properly anyway and we aren't worse off.
+ //
+ // A possible future improvement on this might be to look at the type
+ // of the ResponseWriter, and always set Content-Length if it's one
+ // that we recognize.
+ if len(ranges) > 0 || w.Header().Get("Content-Encoding") == "" {
+ w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
+ }
+ w.WriteHeader(code)
+
+ if r.Method != "HEAD" {
+ io.CopyN(w, sendContent, sendSize)
+ }
+}
+
+// scanETag determines if a syntactically valid ETag is present at s. If so,
+// the ETag and remaining text after consuming ETag is returned. Otherwise,
+// it returns "", "".
+func scanETag(s string) (etag string, remain string) {
+ s = textproto.TrimString(s)
+ start := 0
+ if strings.HasPrefix(s, "W/") {
+ start = 2
+ }
+ if len(s[start:]) < 2 || s[start] != '"' {
+ return "", ""
+ }
+ // ETag is either W/"text" or "text".
+ // See RFC 7232 2.3.
+ for i := start + 1; i < len(s); i++ {
+ c := s[i]
+ switch {
+ // Character values allowed in ETags.
+ case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
+ case c == '"':
+ return s[:i+1], s[i+1:]
+ default:
+ return "", ""
+ }
+ }
+ return "", ""
+}
+
+// etagStrongMatch reports whether a and b match using strong ETag comparison.
+// Assumes a and b are valid ETags.
+func etagStrongMatch(a, b string) bool {
+ return a == b && a != "" && a[0] == '"'
+}
+
+// etagWeakMatch reports whether a and b match using weak ETag comparison.
+// Assumes a and b are valid ETags.
+func etagWeakMatch(a, b string) bool {
+ return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
+}
+
+// condResult is the result of an HTTP request precondition check.
+// See https://tools.ietf.org/html/rfc7232 section 3.
+type condResult int
+
+const (
+ condNone condResult = iota
+ condTrue
+ condFalse
+)
+
+func checkIfMatch(w ResponseWriter, r *Request) condResult {
+ im := r.Header.Get("If-Match")
+ if im == "" {
+ return condNone
+ }
+ for {
+ im = textproto.TrimString(im)
+ if len(im) == 0 {
+ break
+ }
+ if im[0] == ',' {
+ im = im[1:]
+ continue
+ }
+ if im[0] == '*' {
+ return condTrue
+ }
+ etag, remain := scanETag(im)
+ if etag == "" {
+ break
+ }
+ if etagStrongMatch(etag, w.Header().get("Etag")) {
+ return condTrue
+ }
+ im = remain
+ }
+
+ return condFalse
+}
+
+func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
+ ius := r.Header.Get("If-Unmodified-Since")
+ if ius == "" || isZeroTime(modtime) {
+ return condNone
+ }
+ t, err := ParseTime(ius)
+ if err != nil {
+ return condNone
+ }
+
+ // The Last-Modified header truncates sub-second precision so
+ // the modtime needs to be truncated too.
+ modtime = modtime.Truncate(time.Second)
+ if ret := modtime.Compare(t); ret <= 0 {
+ return condTrue
+ }
+ return condFalse
+}
+
+func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
+ inm := r.Header.get("If-None-Match")
+ if inm == "" {
+ return condNone
+ }
+ buf := inm
+ for {
+ buf = textproto.TrimString(buf)
+ if len(buf) == 0 {
+ break
+ }
+ if buf[0] == ',' {
+ buf = buf[1:]
+ continue
+ }
+ if buf[0] == '*' {
+ return condFalse
+ }
+ etag, remain := scanETag(buf)
+ if etag == "" {
+ break
+ }
+ if etagWeakMatch(etag, w.Header().get("Etag")) {
+ return condFalse
+ }
+ buf = remain
+ }
+ return condTrue
+}
+
+func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
+ if r.Method != "GET" && r.Method != "HEAD" {
+ return condNone
+ }
+ ims := r.Header.Get("If-Modified-Since")
+ if ims == "" || isZeroTime(modtime) {
+ return condNone
+ }
+ t, err := ParseTime(ims)
+ if err != nil {
+ return condNone
+ }
+ // The Last-Modified header truncates sub-second precision so
+ // the modtime needs to be truncated too.
+ modtime = modtime.Truncate(time.Second)
+ if ret := modtime.Compare(t); ret <= 0 {
+ return condFalse
+ }
+ return condTrue
+}
+
+func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
+ if r.Method != "GET" && r.Method != "HEAD" {
+ return condNone
+ }
+ ir := r.Header.get("If-Range")
+ if ir == "" {
+ return condNone
+ }
+ etag, _ := scanETag(ir)
+ if etag != "" {
+ if etagStrongMatch(etag, w.Header().Get("Etag")) {
+ return condTrue
+ } else {
+ return condFalse
+ }
+ }
+ // The If-Range value is typically the ETag value, but it may also be
+ // the modtime date. See golang.org/issue/8367.
+ if modtime.IsZero() {
+ return condFalse
+ }
+ t, err := ParseTime(ir)
+ if err != nil {
+ return condFalse
+ }
+ if t.Unix() == modtime.Unix() {
+ return condTrue
+ }
+ return condFalse
+}
+
+var unixEpochTime = time.Unix(0, 0)
+
+// isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
+func isZeroTime(t time.Time) bool {
+ return t.IsZero() || t.Equal(unixEpochTime)
+}
+
+func setLastModified(w ResponseWriter, modtime time.Time) {
+ if !isZeroTime(modtime) {
+ w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
+ }
+}
+
+func writeNotModified(w ResponseWriter) {
+ // RFC 7232 section 4.1:
+ // a sender SHOULD NOT generate representation metadata other than the
+ // above listed fields unless said metadata exists for the purpose of
+ // guiding cache updates (e.g., Last-Modified might be useful if the
+ // response does not have an ETag field).
+ h := w.Header()
+ delete(h, "Content-Type")
+ delete(h, "Content-Length")
+ delete(h, "Content-Encoding")
+ if h.Get("Etag") != "" {
+ delete(h, "Last-Modified")
+ }
+ w.WriteHeader(StatusNotModified)
+}
+
+// checkPreconditions evaluates request preconditions and reports whether a precondition
+// resulted in sending StatusNotModified or StatusPreconditionFailed.
+func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
+ // This function carefully follows RFC 7232 section 6.
+ ch := checkIfMatch(w, r)
+ if ch == condNone {
+ ch = checkIfUnmodifiedSince(r, modtime)
+ }
+ if ch == condFalse {
+ w.WriteHeader(StatusPreconditionFailed)
+ return true, ""
+ }
+ switch checkIfNoneMatch(w, r) {
+ case condFalse:
+ if r.Method == "GET" || r.Method == "HEAD" {
+ writeNotModified(w)
+ return true, ""
+ } else {
+ w.WriteHeader(StatusPreconditionFailed)
+ return true, ""
+ }
+ case condNone:
+ if checkIfModifiedSince(r, modtime) == condFalse {
+ writeNotModified(w)
+ return true, ""
+ }
+ }
+
+ rangeHeader = r.Header.get("Range")
+ if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
+ rangeHeader = ""
+ }
+ return false, rangeHeader
+}
+
+// name is '/'-separated, not filepath.Separator.
+func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
+ const indexPage = "/index.html"
+
+ // redirect .../index.html to .../
+ // can't use Redirect() because that would make the path absolute,
+ // which would be a problem running under StripPrefix
+ if strings.HasSuffix(r.URL.Path, indexPage) {
+ localRedirect(w, r, "./")
+ return
+ }
+
+ f, err := fs.Open(name)
+ if err != nil {
+ msg, code := toHTTPError(err)
+ Error(w, msg, code)
+ return
+ }
+ defer f.Close()
+
+ d, err := f.Stat()
+ if err != nil {
+ msg, code := toHTTPError(err)
+ Error(w, msg, code)
+ return
+ }
+
+ if redirect {
+ // redirect to canonical path: / at end of directory url
+ // r.URL.Path always begins with /
+ url := r.URL.Path
+ if d.IsDir() {
+ if url[len(url)-1] != '/' {
+ localRedirect(w, r, path.Base(url)+"/")
+ return
+ }
+ } else {
+ if url[len(url)-1] == '/' {
+ localRedirect(w, r, "../"+path.Base(url))
+ return
+ }
+ }
+ }
+
+ if d.IsDir() {
+ url := r.URL.Path
+ // redirect if the directory name doesn't end in a slash
+ if url == "" || url[len(url)-1] != '/' {
+ localRedirect(w, r, path.Base(url)+"/")
+ return
+ }
+
+ // use contents of index.html for directory, if present
+ index := strings.TrimSuffix(name, "/") + indexPage
+ ff, err := fs.Open(index)
+ if err == nil {
+ defer ff.Close()
+ dd, err := ff.Stat()
+ if err == nil {
+ d = dd
+ f = ff
+ }
+ }
+ }
+
+ // Still a directory? (we didn't find an index.html file)
+ if d.IsDir() {
+ if checkIfModifiedSince(r, d.ModTime()) == condFalse {
+ writeNotModified(w)
+ return
+ }
+ setLastModified(w, d.ModTime())
+ dirList(w, r, f)
+ return
+ }
+
+ // serveContent will check modification time
+ sizeFunc := func() (int64, error) { return d.Size(), nil }
+ serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
+}
+
+// toHTTPError returns a non-specific HTTP error message and status code
+// for a given non-nil error value. It's important that toHTTPError does not
+// actually return err.Error(), since msg and httpStatus are returned to users,
+// and historically Go's ServeContent always returned just "404 Not Found" for
+// all errors. We don't want to start leaking information in error messages.
+func toHTTPError(err error) (msg string, httpStatus int) {
+ if errors.Is(err, fs.ErrNotExist) {
+ return "404 page not found", StatusNotFound
+ }
+ if errors.Is(err, fs.ErrPermission) {
+ return "403 Forbidden", StatusForbidden
+ }
+ // Default:
+ return "500 Internal Server Error", StatusInternalServerError
+}
+
+// localRedirect gives a Moved Permanently response.
+// It does not convert relative paths to absolute paths like Redirect does.
+func localRedirect(w ResponseWriter, r *Request, newPath string) {
+ if q := r.URL.RawQuery; q != "" {
+ newPath += "?" + q
+ }
+ w.Header().Set("Location", newPath)
+ w.WriteHeader(StatusMovedPermanently)
+}
+
+// ServeFile replies to the request with the contents of the named
+// file or directory.
+//
+// If the provided file or directory name is a relative path, it is
+// interpreted relative to the current directory and may ascend to
+// parent directories. If the provided name is constructed from user
+// input, it should be sanitized before calling ServeFile.
+//
+// As a precaution, ServeFile will reject requests where r.URL.Path
+// contains a ".." path element; this protects against callers who
+// might unsafely use [filepath.Join] on r.URL.Path without sanitizing
+// it and then use that filepath.Join result as the name argument.
+//
+// As another special case, ServeFile redirects any request where r.URL.Path
+// ends in "/index.html" to the same path, without the final
+// "index.html". To avoid such redirects either modify the path or
+// use [ServeContent].
+//
+// Outside of those two special cases, ServeFile does not use
+// r.URL.Path for selecting the file or directory to serve; only the
+// file or directory provided in the name argument is used.
+func ServeFile(w ResponseWriter, r *Request, name string) {
+ if containsDotDot(r.URL.Path) {
+ // Too many programs use r.URL.Path to construct the argument to
+ // serveFile. Reject the request under the assumption that happened
+ // here and ".." may not be wanted.
+ // Note that name might not contain "..", for example if code (still
+ // incorrectly) used filepath.Join(myDir, r.URL.Path).
+ Error(w, "invalid URL path", StatusBadRequest)
+ return
+ }
+ dir, file := filepath.Split(name)
+ serveFile(w, r, Dir(dir), file, false)
+}
+
+// ServeFileFS replies to the request with the contents
+// of the named file or directory from the file system fsys.
+//
+// If the provided file or directory name is a relative path, it is
+// interpreted relative to the current directory and may ascend to
+// parent directories. If the provided name is constructed from user
+// input, it should be sanitized before calling [ServeFile].
+//
+// As a precaution, ServeFile will reject requests where r.URL.Path
+// contains a ".." path element; this protects against callers who
+// might unsafely use [filepath.Join] on r.URL.Path without sanitizing
+// it and then use that filepath.Join result as the name argument.
+//
+// As another special case, ServeFile redirects any request where r.URL.Path
+// ends in "/index.html" to the same path, without the final
+// "index.html". To avoid such redirects either modify the path or
+// use ServeContent.
+//
+// Outside of those two special cases, ServeFile does not use
+// r.URL.Path for selecting the file or directory to serve; only the
+// file or directory provided in the name argument is used.
+func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string) {
+ if containsDotDot(r.URL.Path) {
+ // Too many programs use r.URL.Path to construct the argument to
+ // serveFile. Reject the request under the assumption that happened
+ // here and ".." may not be wanted.
+ // Note that name might not contain "..", for example if code (still
+ // incorrectly) used filepath.Join(myDir, r.URL.Path).
+ Error(w, "invalid URL path", StatusBadRequest)
+ return
+ }
+ serveFile(w, r, FS(fsys), name, false)
+}
+
+func containsDotDot(v string) bool {
+ if !strings.Contains(v, "..") {
+ return false
+ }
+ for _, ent := range strings.FieldsFunc(v, isSlashRune) {
+ if ent == ".." {
+ return true
+ }
+ }
+ return false
+}
+
+func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
+
+type fileHandler struct {
+ root FileSystem
+}
+
+type ioFS struct {
+ fsys fs.FS
+}
+
+type ioFile struct {
+ file fs.File
+}
+
+func (f ioFS) Open(name string) (File, error) {
+ if name == "/" {
+ name = "."
+ } else {
+ name = strings.TrimPrefix(name, "/")
+ }
+ file, err := f.fsys.Open(name)
+ if err != nil {
+ return nil, mapOpenError(err, name, '/', func(path string) (fs.FileInfo, error) {
+ return fs.Stat(f.fsys, path)
+ })
+ }
+ return ioFile{file}, nil
+}
+
+func (f ioFile) Close() error { return f.file.Close() }
+func (f ioFile) Read(b []byte) (int, error) { return f.file.Read(b) }
+func (f ioFile) Stat() (fs.FileInfo, error) { return f.file.Stat() }
+
+var errMissingSeek = errors.New("io.File missing Seek method")
+var errMissingReadDir = errors.New("io.File directory missing ReadDir method")
+
+func (f ioFile) Seek(offset int64, whence int) (int64, error) {
+ s, ok := f.file.(io.Seeker)
+ if !ok {
+ return 0, errMissingSeek
+ }
+ return s.Seek(offset, whence)
+}
+
+func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error) {
+ d, ok := f.file.(fs.ReadDirFile)
+ if !ok {
+ return nil, errMissingReadDir
+ }
+ return d.ReadDir(count)
+}
+
+func (f ioFile) Readdir(count int) ([]fs.FileInfo, error) {
+ d, ok := f.file.(fs.ReadDirFile)
+ if !ok {
+ return nil, errMissingReadDir
+ }
+ var list []fs.FileInfo
+ for {
+ dirs, err := d.ReadDir(count - len(list))
+ for _, dir := range dirs {
+ info, err := dir.Info()
+ if err != nil {
+ // Pretend it doesn't exist, like (*os.File).Readdir does.
+ continue
+ }
+ list = append(list, info)
+ }
+ if err != nil {
+ return list, err
+ }
+ if count < 0 || len(list) >= count {
+ break
+ }
+ }
+ return list, nil
+}
+
+// FS converts fsys to a [FileSystem] implementation,
+// for use with [FileServer] and [NewFileTransport].
+// The files provided by fsys must implement [io.Seeker].
+func FS(fsys fs.FS) FileSystem {
+ return ioFS{fsys}
+}
+
+// FileServer returns a handler that serves HTTP requests
+// with the contents of the file system rooted at root.
+//
+// As a special case, the returned file server redirects any request
+// ending in "/index.html" to the same path, without the final
+// "index.html".
+//
+// To use the operating system's file system implementation,
+// use [http.Dir]:
+//
+// http.Handle("/", http.FileServer(http.Dir("/tmp")))
+//
+// To use an [fs.FS] implementation, use [http.FileServerFS] instead.
+func FileServer(root FileSystem) Handler {
+ return &fileHandler{root}
+}
+
+// FileServerFS returns a handler that serves HTTP requests
+// with the contents of the file system fsys.
+//
+// As a special case, the returned file server redirects any request
+// ending in "/index.html" to the same path, without the final
+// "index.html".
+//
+// http.Handle("/", http.FileServerFS(fsys))
+func FileServerFS(root fs.FS) Handler {
+ return FileServer(FS(root))
+}
+
+func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
+ upath := r.URL.Path
+ if !strings.HasPrefix(upath, "/") {
+ upath = "/" + upath
+ r.URL.Path = upath
+ }
+ serveFile(w, r, f.root, path.Clean(upath), true)
+}
+
+// httpRange specifies the byte range to be sent to the client.
+type httpRange struct {
+ start, length int64
+}
+
+func (r httpRange) contentRange(size int64) string {
+ return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
+}
+
+func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
+ return textproto.MIMEHeader{
+ "Content-Range": {r.contentRange(size)},
+ "Content-Type": {contentType},
+ }
+}
+
+// parseRange parses a Range header string as per RFC 7233.
+// errNoOverlap is returned if none of the ranges overlap.
+func parseRange(s string, size int64) ([]httpRange, error) {
+ if s == "" {
+ return nil, nil // header not present
+ }
+ const b = "bytes="
+ if !strings.HasPrefix(s, b) {
+ return nil, errors.New("invalid range")
+ }
+ var ranges []httpRange
+ noOverlap := false
+ for _, ra := range strings.Split(s[len(b):], ",") {
+ ra = textproto.TrimString(ra)
+ if ra == "" {
+ continue
+ }
+ start, end, ok := strings.Cut(ra, "-")
+ if !ok {
+ return nil, errors.New("invalid range")
+ }
+ start, end = textproto.TrimString(start), textproto.TrimString(end)
+ var r httpRange
+ if start == "" {
+ // If no start is specified, end specifies the
+ // range start relative to the end of the file,
+ // and we are dealing with
+ // which has to be a non-negative integer as per
+ // RFC 7233 Section 2.1 "Byte-Ranges".
+ if end == "" || end[0] == '-' {
+ return nil, errors.New("invalid range")
+ }
+ i, err := strconv.ParseInt(end, 10, 64)
+ if i < 0 || err != nil {
+ return nil, errors.New("invalid range")
+ }
+ if i > size {
+ i = size
+ }
+ r.start = size - i
+ r.length = size - r.start
+ } else {
+ i, err := strconv.ParseInt(start, 10, 64)
+ if err != nil || i < 0 {
+ return nil, errors.New("invalid range")
+ }
+ if i >= size {
+ // If the range begins after the size of the content,
+ // then it does not overlap.
+ noOverlap = true
+ continue
+ }
+ r.start = i
+ if end == "" {
+ // If no end is specified, range extends to end of the file.
+ r.length = size - r.start
+ } else {
+ i, err := strconv.ParseInt(end, 10, 64)
+ if err != nil || r.start > i {
+ return nil, errors.New("invalid range")
+ }
+ if i >= size {
+ i = size - 1
+ }
+ r.length = i - r.start + 1
+ }
+ }
+ ranges = append(ranges, r)
+ }
+ if noOverlap && len(ranges) == 0 {
+ // The specified ranges did not overlap with the content.
+ return nil, errNoOverlap
+ }
+ return ranges, nil
+}
+
+// countingWriter counts how many bytes have been written to it.
+type countingWriter int64
+
+func (w *countingWriter) Write(p []byte) (n int, err error) {
+ *w += countingWriter(len(p))
+ return len(p), nil
+}
+
+// rangesMIMESize returns the number of bytes it takes to encode the
+// provided ranges as a multipart response.
+func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
+ var w countingWriter
+ mw := multipart.NewWriter(&w)
+ for _, ra := range ranges {
+ mw.CreatePart(ra.mimeHeader(contentType, contentSize))
+ encSize += ra.length
+ }
+ mw.Close()
+ encSize += int64(w)
+ return
+}
+
+func sumRangesSize(ranges []httpRange) (size int64) {
+ for _, ra := range ranges {
+ size += ra.length
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/fs_test.go b/platform/dbops/binaries/go/go/src/net/http/fs_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..861e70caf23963199559142a77ece6aaae6aa5aa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/fs_test.go
@@ -0,0 +1,1670 @@
+// 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 http_test
+
+import (
+ "bufio"
+ "bytes"
+ "compress/gzip"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "io/fs"
+ "mime"
+ "mime/multipart"
+ "net"
+ "net/http"
+ . "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "runtime"
+ "strings"
+ "testing"
+ "testing/fstest"
+ "time"
+)
+
+const (
+ testFile = "testdata/file"
+ testFileLen = 11
+)
+
+type wantRange struct {
+ start, end int64 // range [start,end)
+}
+
+var ServeFileRangeTests = []struct {
+ r string
+ code int
+ ranges []wantRange
+}{
+ {r: "", code: StatusOK},
+ {r: "bytes=0-4", code: StatusPartialContent, ranges: []wantRange{{0, 5}}},
+ {r: "bytes=2-", code: StatusPartialContent, ranges: []wantRange{{2, testFileLen}}},
+ {r: "bytes=-5", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 5, testFileLen}}},
+ {r: "bytes=3-7", code: StatusPartialContent, ranges: []wantRange{{3, 8}}},
+ {r: "bytes=0-0,-2", code: StatusPartialContent, ranges: []wantRange{{0, 1}, {testFileLen - 2, testFileLen}}},
+ {r: "bytes=0-1,5-8", code: StatusPartialContent, ranges: []wantRange{{0, 2}, {5, 9}}},
+ {r: "bytes=0-1,5-", code: StatusPartialContent, ranges: []wantRange{{0, 2}, {5, testFileLen}}},
+ {r: "bytes=5-1000", code: StatusPartialContent, ranges: []wantRange{{5, testFileLen}}},
+ {r: "bytes=0-,1-,2-,3-,4-", code: StatusOK}, // ignore wasteful range request
+ {r: "bytes=0-9", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen - 1}}},
+ {r: "bytes=0-10", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen}}},
+ {r: "bytes=0-11", code: StatusPartialContent, ranges: []wantRange{{0, testFileLen}}},
+ {r: "bytes=10-11", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 1, testFileLen}}},
+ {r: "bytes=10-", code: StatusPartialContent, ranges: []wantRange{{testFileLen - 1, testFileLen}}},
+ {r: "bytes=11-", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=11-12", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=12-12", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=11-100", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=12-100", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=100-", code: StatusRequestedRangeNotSatisfiable},
+ {r: "bytes=100-1000", code: StatusRequestedRangeNotSatisfiable},
+}
+
+func TestServeFile(t *testing.T) { run(t, testServeFile) }
+func testServeFile(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ ServeFile(w, r, "testdata/file")
+ })).ts
+ c := ts.Client()
+
+ var err error
+
+ file, err := os.ReadFile(testFile)
+ if err != nil {
+ t.Fatal("reading file:", err)
+ }
+
+ // set up the Request (re-used for all tests)
+ var req Request
+ req.Header = make(Header)
+ if req.URL, err = url.Parse(ts.URL); err != nil {
+ t.Fatal("ParseURL:", err)
+ }
+
+ // Get contents via various methods.
+ //
+ // See https://go.dev/issue/59471 for a proposal to limit the set of methods handled.
+ // For now, test the historical behavior.
+ for _, method := range []string{
+ MethodGet,
+ MethodPost,
+ MethodPut,
+ MethodPatch,
+ MethodDelete,
+ MethodOptions,
+ MethodTrace,
+ } {
+ req.Method = method
+ _, body := getBody(t, method, req, c)
+ if !bytes.Equal(body, file) {
+ t.Fatalf("body mismatch for %v request: got %q, want %q", method, body, file)
+ }
+ }
+
+ // HEAD request.
+ req.Method = MethodHead
+ resp, body := getBody(t, "HEAD", req, c)
+ if len(body) != 0 {
+ t.Fatalf("body mismatch for HEAD request: got %q, want empty", body)
+ }
+ if got, want := resp.Header.Get("Content-Length"), fmt.Sprint(len(file)); got != want {
+ t.Fatalf("Content-Length mismatch for HEAD request: got %v, want %v", got, want)
+ }
+
+ // Range tests
+ req.Method = MethodGet
+Cases:
+ for _, rt := range ServeFileRangeTests {
+ if rt.r != "" {
+ req.Header.Set("Range", rt.r)
+ }
+ resp, body := getBody(t, fmt.Sprintf("range test %q", rt.r), req, c)
+ if resp.StatusCode != rt.code {
+ t.Errorf("range=%q: StatusCode=%d, want %d", rt.r, resp.StatusCode, rt.code)
+ }
+ if rt.code == StatusRequestedRangeNotSatisfiable {
+ continue
+ }
+ wantContentRange := ""
+ if len(rt.ranges) == 1 {
+ rng := rt.ranges[0]
+ wantContentRange = fmt.Sprintf("bytes %d-%d/%d", rng.start, rng.end-1, testFileLen)
+ }
+ cr := resp.Header.Get("Content-Range")
+ if cr != wantContentRange {
+ t.Errorf("range=%q: Content-Range = %q, want %q", rt.r, cr, wantContentRange)
+ }
+ ct := resp.Header.Get("Content-Type")
+ if len(rt.ranges) == 1 {
+ rng := rt.ranges[0]
+ wantBody := file[rng.start:rng.end]
+ if !bytes.Equal(body, wantBody) {
+ t.Errorf("range=%q: body = %q, want %q", rt.r, body, wantBody)
+ }
+ if strings.HasPrefix(ct, "multipart/byteranges") {
+ t.Errorf("range=%q content-type = %q; unexpected multipart/byteranges", rt.r, ct)
+ }
+ }
+ if len(rt.ranges) > 1 {
+ typ, params, err := mime.ParseMediaType(ct)
+ if err != nil {
+ t.Errorf("range=%q content-type = %q; %v", rt.r, ct, err)
+ continue
+ }
+ if typ != "multipart/byteranges" {
+ t.Errorf("range=%q content-type = %q; want multipart/byteranges", rt.r, typ)
+ continue
+ }
+ if params["boundary"] == "" {
+ t.Errorf("range=%q content-type = %q; lacks boundary", rt.r, ct)
+ continue
+ }
+ if g, w := resp.ContentLength, int64(len(body)); g != w {
+ t.Errorf("range=%q Content-Length = %d; want %d", rt.r, g, w)
+ continue
+ }
+ mr := multipart.NewReader(bytes.NewReader(body), params["boundary"])
+ for ri, rng := range rt.ranges {
+ part, err := mr.NextPart()
+ if err != nil {
+ t.Errorf("range=%q, reading part index %d: %v", rt.r, ri, err)
+ continue Cases
+ }
+ wantContentRange = fmt.Sprintf("bytes %d-%d/%d", rng.start, rng.end-1, testFileLen)
+ if g, w := part.Header.Get("Content-Range"), wantContentRange; g != w {
+ t.Errorf("range=%q: part Content-Range = %q; want %q", rt.r, g, w)
+ }
+ body, err := io.ReadAll(part)
+ if err != nil {
+ t.Errorf("range=%q, reading part index %d body: %v", rt.r, ri, err)
+ continue Cases
+ }
+ wantBody := file[rng.start:rng.end]
+ if !bytes.Equal(body, wantBody) {
+ t.Errorf("range=%q: body = %q, want %q", rt.r, body, wantBody)
+ }
+ }
+ _, err = mr.NextPart()
+ if err != io.EOF {
+ t.Errorf("range=%q; expected final error io.EOF; got %v", rt.r, err)
+ }
+ }
+ }
+}
+
+func TestServeFile_DotDot(t *testing.T) {
+ tests := []struct {
+ req string
+ wantStatus int
+ }{
+ {"/testdata/file", 200},
+ {"/../file", 400},
+ {"/..", 400},
+ {"/../", 400},
+ {"/../foo", 400},
+ {"/..\\foo", 400},
+ {"/file/a", 200},
+ {"/file/a..", 200},
+ {"/file/a/..", 400},
+ {"/file/a\\..", 400},
+ }
+ for _, tt := range tests {
+ req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + tt.req + " HTTP/1.1\r\nHost: foo\r\n\r\n")))
+ if err != nil {
+ t.Errorf("bad request %q: %v", tt.req, err)
+ continue
+ }
+ rec := httptest.NewRecorder()
+ ServeFile(rec, req, "testdata/file")
+ if rec.Code != tt.wantStatus {
+ t.Errorf("for request %q, status = %d; want %d", tt.req, rec.Code, tt.wantStatus)
+ }
+ }
+}
+
+// Tests that this doesn't panic. (Issue 30165)
+func TestServeFileDirPanicEmptyPath(t *testing.T) {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/", nil)
+ req.URL.Path = ""
+ ServeFile(rec, req, "testdata")
+ res := rec.Result()
+ if res.StatusCode != 301 {
+ t.Errorf("code = %v; want 301", res.Status)
+ }
+}
+
+// Tests that ranges are ignored with serving empty content. (Issue 54794)
+func TestServeContentWithEmptyContentIgnoreRanges(t *testing.T) {
+ for _, r := range []string{
+ "bytes=0-128",
+ "bytes=1-",
+ } {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/", nil)
+ req.Header.Set("Range", r)
+ ServeContent(rec, req, "nothing", time.Now(), bytes.NewReader(nil))
+ res := rec.Result()
+ if res.StatusCode != 200 {
+ t.Errorf("code = %v; want 200", res.Status)
+ }
+ bodyLen := rec.Body.Len()
+ if bodyLen != 0 {
+ t.Errorf("body.Len() = %v; want 0", res.Status)
+ }
+ }
+}
+
+var fsRedirectTestData = []struct {
+ original, redirect string
+}{
+ {"/test/index.html", "/test/"},
+ {"/test/testdata", "/test/testdata/"},
+ {"/test/testdata/file/", "/test/testdata/file"},
+}
+
+func TestFSRedirect(t *testing.T) { run(t, testFSRedirect) }
+func testFSRedirect(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, StripPrefix("/test", FileServer(Dir(".")))).ts
+
+ for _, data := range fsRedirectTestData {
+ res, err := ts.Client().Get(ts.URL + data.original)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if g, e := res.Request.URL.Path, data.redirect; g != e {
+ t.Errorf("redirect from %s: got %s, want %s", data.original, g, e)
+ }
+ }
+}
+
+type testFileSystem struct {
+ open func(name string) (File, error)
+}
+
+func (fs *testFileSystem) Open(name string) (File, error) {
+ return fs.open(name)
+}
+
+func TestFileServerCleans(t *testing.T) {
+ defer afterTest(t)
+ ch := make(chan string, 1)
+ fs := FileServer(&testFileSystem{func(name string) (File, error) {
+ ch <- name
+ return nil, errors.New("file does not exist")
+ }})
+ tests := []struct {
+ reqPath, openArg string
+ }{
+ {"/foo.txt", "/foo.txt"},
+ {"//foo.txt", "/foo.txt"},
+ {"/../foo.txt", "/foo.txt"},
+ }
+ req, _ := NewRequest("GET", "http://example.com", nil)
+ for n, test := range tests {
+ rec := httptest.NewRecorder()
+ req.URL.Path = test.reqPath
+ fs.ServeHTTP(rec, req)
+ if got := <-ch; got != test.openArg {
+ t.Errorf("test %d: got %q, want %q", n, got, test.openArg)
+ }
+ }
+}
+
+func TestFileServerEscapesNames(t *testing.T) { run(t, testFileServerEscapesNames) }
+func testFileServerEscapesNames(t *testing.T, mode testMode) {
+ const dirListPrefix = "\n"
+ const dirListSuffix = "\n
\n"
+ tests := []struct {
+ name, escaped string
+ }{
+ {`simple_name`, `simple_name`},
+ {`"'<>&`, `"'<>&`},
+ {`?foo=bar#baz`, `?foo=bar#baz`},
+ {`?foo`, `<combo>?foo`},
+ {`foo:bar`, `foo:bar`},
+ }
+
+ // We put each test file in its own directory in the fakeFS so we can look at it in isolation.
+ fs := make(fakeFS)
+ for i, test := range tests {
+ testFile := &fakeFileInfo{basename: test.name}
+ fs[fmt.Sprintf("/%d", i)] = &fakeFileInfo{
+ dir: true,
+ modtime: time.Unix(1000000000, 0).UTC(),
+ ents: []*fakeFileInfo{testFile},
+ }
+ fs[fmt.Sprintf("/%d/%s", i, test.name)] = testFile
+ }
+
+ ts := newClientServerTest(t, mode, FileServer(&fs)).ts
+ for i, test := range tests {
+ url := fmt.Sprintf("%s/%d", ts.URL, i)
+ res, err := ts.Client().Get(url)
+ if err != nil {
+ t.Fatalf("test %q: Get: %v", test.name, err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("test %q: read Body: %v", test.name, err)
+ }
+ s := string(b)
+ if !strings.HasPrefix(s, dirListPrefix) || !strings.HasSuffix(s, dirListSuffix) {
+ t.Errorf("test %q: listing dir, full output is %q, want prefix %q and suffix %q", test.name, s, dirListPrefix, dirListSuffix)
+ }
+ if trimmed := strings.TrimSuffix(strings.TrimPrefix(s, dirListPrefix), dirListSuffix); trimmed != test.escaped {
+ t.Errorf("test %q: listing dir, filename escaped to %q, want %q", test.name, trimmed, test.escaped)
+ }
+ res.Body.Close()
+ }
+}
+
+func TestFileServerSortsNames(t *testing.T) { run(t, testFileServerSortsNames) }
+func testFileServerSortsNames(t *testing.T, mode testMode) {
+ const contents = "I am a fake file"
+ dirMod := time.Unix(123, 0).UTC()
+ fileMod := time.Unix(1000000000, 0).UTC()
+ fs := fakeFS{
+ "/": &fakeFileInfo{
+ dir: true,
+ modtime: dirMod,
+ ents: []*fakeFileInfo{
+ {
+ basename: "b",
+ modtime: fileMod,
+ contents: contents,
+ },
+ {
+ basename: "a",
+ modtime: fileMod,
+ contents: contents,
+ },
+ },
+ },
+ }
+
+ ts := newClientServerTest(t, mode, FileServer(&fs)).ts
+
+ res, err := ts.Client().Get(ts.URL)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("read Body: %v", err)
+ }
+ s := string(b)
+ if !strings.Contains(s, "a\nb") {
+ t.Errorf("output appears to be unsorted:\n%s", s)
+ }
+}
+
+func mustRemoveAll(dir string) {
+ err := os.RemoveAll(dir)
+ if err != nil {
+ panic(err)
+ }
+}
+
+func TestFileServerImplicitLeadingSlash(t *testing.T) { run(t, testFileServerImplicitLeadingSlash) }
+func testFileServerImplicitLeadingSlash(t *testing.T, mode testMode) {
+ tempDir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("Hello world"), 0644); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ ts := newClientServerTest(t, mode, StripPrefix("/bar/", FileServer(Dir(tempDir)))).ts
+ get := func(suffix string) string {
+ res, err := ts.Client().Get(ts.URL + suffix)
+ if err != nil {
+ t.Fatalf("Get %s: %v", suffix, err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("ReadAll %s: %v", suffix, err)
+ }
+ res.Body.Close()
+ return string(b)
+ }
+ if s := get("/bar/"); !strings.Contains(s, ">foo.txt<") {
+ t.Logf("expected a directory listing with foo.txt, got %q", s)
+ }
+ if s := get("/bar/foo.txt"); s != "Hello world" {
+ t.Logf("expected %q, got %q", "Hello world", s)
+ }
+}
+
+func TestDirJoin(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("skipping test on windows")
+ }
+ wfi, err := os.Stat("/etc/hosts")
+ if err != nil {
+ t.Skip("skipping test; no /etc/hosts file")
+ }
+ test := func(d Dir, name string) {
+ f, err := d.Open(name)
+ if err != nil {
+ t.Fatalf("open of %s: %v", name, err)
+ }
+ defer f.Close()
+ gfi, err := f.Stat()
+ if err != nil {
+ t.Fatalf("stat of %s: %v", name, err)
+ }
+ if !os.SameFile(gfi, wfi) {
+ t.Errorf("%s got different file", name)
+ }
+ }
+ test(Dir("/etc/"), "/hosts")
+ test(Dir("/etc/"), "hosts")
+ test(Dir("/etc/"), "../../../../hosts")
+ test(Dir("/etc"), "/hosts")
+ test(Dir("/etc"), "hosts")
+ test(Dir("/etc"), "../../../../hosts")
+
+ // Not really directories, but since we use this trick in
+ // ServeFile, test it:
+ test(Dir("/etc/hosts"), "")
+ test(Dir("/etc/hosts"), "/")
+ test(Dir("/etc/hosts"), "../")
+}
+
+func TestEmptyDirOpenCWD(t *testing.T) {
+ test := func(d Dir) {
+ name := "fs_test.go"
+ f, err := d.Open(name)
+ if err != nil {
+ t.Fatalf("open of %s: %v", name, err)
+ }
+ defer f.Close()
+ }
+ test(Dir(""))
+ test(Dir("."))
+ test(Dir("./"))
+}
+
+func TestServeFileContentType(t *testing.T) { run(t, testServeFileContentType) }
+func testServeFileContentType(t *testing.T, mode testMode) {
+ const ctype = "icecream/chocolate"
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ switch r.FormValue("override") {
+ case "1":
+ w.Header().Set("Content-Type", ctype)
+ case "2":
+ // Explicitly inhibit sniffing.
+ w.Header()["Content-Type"] = []string{}
+ }
+ ServeFile(w, r, "testdata/file")
+ })).ts
+ get := func(override string, want []string) {
+ resp, err := ts.Client().Get(ts.URL + "?override=" + override)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h := resp.Header["Content-Type"]; !reflect.DeepEqual(h, want) {
+ t.Errorf("Content-Type mismatch: got %v, want %v", h, want)
+ }
+ resp.Body.Close()
+ }
+ get("0", []string{"text/plain; charset=utf-8"})
+ get("1", []string{ctype})
+ get("2", nil)
+}
+
+func TestServeFileMimeType(t *testing.T) { run(t, testServeFileMimeType) }
+func testServeFileMimeType(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ ServeFile(w, r, "testdata/style.css")
+ })).ts
+ resp, err := ts.Client().Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ want := "text/css; charset=utf-8"
+ if h := resp.Header.Get("Content-Type"); h != want {
+ t.Errorf("Content-Type mismatch: got %q, want %q", h, want)
+ }
+}
+
+func TestServeFileFromCWD(t *testing.T) { run(t, testServeFileFromCWD) }
+func testServeFileFromCWD(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ ServeFile(w, r, "fs_test.go")
+ })).ts
+ r, err := ts.Client().Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.Body.Close()
+ if r.StatusCode != 200 {
+ t.Fatalf("expected 200 OK, got %s", r.Status)
+ }
+}
+
+// Issue 13996
+func TestServeDirWithoutTrailingSlash(t *testing.T) { run(t, testServeDirWithoutTrailingSlash) }
+func testServeDirWithoutTrailingSlash(t *testing.T, mode testMode) {
+ e := "/testdata/"
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ ServeFile(w, r, ".")
+ })).ts
+ r, err := ts.Client().Get(ts.URL + "/testdata")
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.Body.Close()
+ if g := r.Request.URL.Path; g != e {
+ t.Errorf("got %s, want %s", g, e)
+ }
+}
+
+// Tests that ServeFile doesn't add a Content-Length if a Content-Encoding is
+// specified.
+func TestServeFileWithContentEncoding(t *testing.T) { run(t, testServeFileWithContentEncoding) }
+func testServeFileWithContentEncoding(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Encoding", "foo")
+ ServeFile(w, r, "testdata/file")
+
+ // Because the testdata is so small, it would fit in
+ // both the h1 and h2 Server's write buffers. For h1,
+ // sendfile is used, though, forcing a header flush at
+ // the io.Copy. http2 doesn't do a header flush so
+ // buffers all 11 bytes and then adds its own
+ // Content-Length. To prevent the Server's
+ // Content-Length and test ServeFile only, flush here.
+ w.(Flusher).Flush()
+ }))
+ resp, err := cst.c.Get(cst.ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if g, e := resp.ContentLength, int64(-1); g != e {
+ t.Errorf("Content-Length mismatch: got %d, want %d", g, e)
+ }
+}
+
+// Tests that ServeFile does not generate representation metadata when
+// file has not been modified, as per RFC 7232 section 4.1.
+func TestServeFileNotModified(t *testing.T) { run(t, testServeFileNotModified) }
+func testServeFileNotModified(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Encoding", "foo")
+ w.Header().Set("Etag", `"123"`)
+ ServeFile(w, r, "testdata/file")
+
+ // Because the testdata is so small, it would fit in
+ // both the h1 and h2 Server's write buffers. For h1,
+ // sendfile is used, though, forcing a header flush at
+ // the io.Copy. http2 doesn't do a header flush so
+ // buffers all 11 bytes and then adds its own
+ // Content-Length. To prevent the Server's
+ // Content-Length and test ServeFile only, flush here.
+ w.(Flusher).Flush()
+ }))
+ req, err := NewRequest("GET", cst.ts.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("If-None-Match", `"123"`)
+ resp, err := cst.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if len(b) != 0 {
+ t.Errorf("non-empty body")
+ }
+ if g, e := resp.StatusCode, StatusNotModified; g != e {
+ t.Errorf("status mismatch: got %d, want %d", g, e)
+ }
+ // HTTP1 transport sets ContentLength to 0.
+ if g, e1, e2 := resp.ContentLength, int64(-1), int64(0); g != e1 && g != e2 {
+ t.Errorf("Content-Length mismatch: got %d, want %d or %d", g, e1, e2)
+ }
+ if resp.Header.Get("Content-Type") != "" {
+ t.Errorf("Content-Type present, but it should not be")
+ }
+ if resp.Header.Get("Content-Encoding") != "" {
+ t.Errorf("Content-Encoding present, but it should not be")
+ }
+}
+
+func TestServeIndexHtml(t *testing.T) { run(t, testServeIndexHtml) }
+func testServeIndexHtml(t *testing.T, mode testMode) {
+ for i := 0; i < 2; i++ {
+ var h Handler
+ var name string
+ switch i {
+ case 0:
+ h = FileServer(Dir("."))
+ name = "Dir"
+ case 1:
+ h = FileServer(FS(os.DirFS(".")))
+ name = "DirFS"
+ }
+ t.Run(name, func(t *testing.T) {
+ const want = "index.html says hello\n"
+ ts := newClientServerTest(t, mode, h).ts
+
+ for _, path := range []string{"/testdata/", "/testdata/index.html"} {
+ res, err := ts.Client().Get(ts.URL + path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if s := string(b); s != want {
+ t.Errorf("for path %q got %q, want %q", path, s, want)
+ }
+ res.Body.Close()
+ }
+ })
+ }
+}
+
+func TestServeIndexHtmlFS(t *testing.T) { run(t, testServeIndexHtmlFS) }
+func testServeIndexHtmlFS(t *testing.T, mode testMode) {
+ const want = "index.html says hello\n"
+ ts := newClientServerTest(t, mode, FileServer(Dir("."))).ts
+ defer ts.Close()
+
+ for _, path := range []string{"/testdata/", "/testdata/index.html"} {
+ res, err := ts.Client().Get(ts.URL + path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if s := string(b); s != want {
+ t.Errorf("for path %q got %q, want %q", path, s, want)
+ }
+ res.Body.Close()
+ }
+}
+
+func TestFileServerZeroByte(t *testing.T) { run(t, testFileServerZeroByte) }
+func testFileServerZeroByte(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, FileServer(Dir("."))).ts
+
+ c, err := net.Dial("tcp", ts.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ _, err = fmt.Fprintf(c, "GET /..\x00 HTTP/1.0\r\n\r\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got bytes.Buffer
+ bufr := bufio.NewReader(io.TeeReader(c, &got))
+ res, err := ReadResponse(bufr, nil)
+ if err != nil {
+ t.Fatal("ReadResponse: ", err)
+ }
+ if res.StatusCode == 200 {
+ t.Errorf("got status 200; want an error. Body is:\n%s", got.Bytes())
+ }
+}
+
+func TestFileServerNamesEscape(t *testing.T) { run(t, testFileServerNamesEscape) }
+func testFileServerNamesEscape(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, FileServer(Dir("testdata"))).ts
+ for _, path := range []string{
+ "/../testdata/file",
+ "/NUL", // don't read from device files on Windows
+ } {
+ res, err := ts.Client().Get(ts.URL + path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode < 400 || res.StatusCode > 599 {
+ t.Errorf("Get(%q): got status %v, want 4xx or 5xx", path, res.StatusCode)
+ }
+
+ }
+}
+
+type fakeFileInfo struct {
+ dir bool
+ basename string
+ modtime time.Time
+ ents []*fakeFileInfo
+ contents string
+ err error
+}
+
+func (f *fakeFileInfo) Name() string { return f.basename }
+func (f *fakeFileInfo) Sys() any { return nil }
+func (f *fakeFileInfo) ModTime() time.Time { return f.modtime }
+func (f *fakeFileInfo) IsDir() bool { return f.dir }
+func (f *fakeFileInfo) Size() int64 { return int64(len(f.contents)) }
+func (f *fakeFileInfo) Mode() fs.FileMode {
+ if f.dir {
+ return 0755 | fs.ModeDir
+ }
+ return 0644
+}
+
+func (f *fakeFileInfo) String() string {
+ return fs.FormatFileInfo(f)
+}
+
+type fakeFile struct {
+ io.ReadSeeker
+ fi *fakeFileInfo
+ path string // as opened
+ entpos int
+}
+
+func (f *fakeFile) Close() error { return nil }
+func (f *fakeFile) Stat() (fs.FileInfo, error) { return f.fi, nil }
+func (f *fakeFile) Readdir(count int) ([]fs.FileInfo, error) {
+ if !f.fi.dir {
+ return nil, fs.ErrInvalid
+ }
+ var fis []fs.FileInfo
+
+ limit := f.entpos + count
+ if count <= 0 || limit > len(f.fi.ents) {
+ limit = len(f.fi.ents)
+ }
+ for ; f.entpos < limit; f.entpos++ {
+ fis = append(fis, f.fi.ents[f.entpos])
+ }
+
+ if len(fis) == 0 && count > 0 {
+ return fis, io.EOF
+ } else {
+ return fis, nil
+ }
+}
+
+type fakeFS map[string]*fakeFileInfo
+
+func (fsys fakeFS) Open(name string) (File, error) {
+ name = path.Clean(name)
+ f, ok := fsys[name]
+ if !ok {
+ return nil, fs.ErrNotExist
+ }
+ if f.err != nil {
+ return nil, f.err
+ }
+ return &fakeFile{ReadSeeker: strings.NewReader(f.contents), fi: f, path: name}, nil
+}
+
+func TestDirectoryIfNotModified(t *testing.T) { run(t, testDirectoryIfNotModified) }
+func testDirectoryIfNotModified(t *testing.T, mode testMode) {
+ const indexContents = "I am a fake index.html file"
+ fileMod := time.Unix(1000000000, 0).UTC()
+ fileModStr := fileMod.Format(TimeFormat)
+ dirMod := time.Unix(123, 0).UTC()
+ indexFile := &fakeFileInfo{
+ basename: "index.html",
+ modtime: fileMod,
+ contents: indexContents,
+ }
+ fs := fakeFS{
+ "/": &fakeFileInfo{
+ dir: true,
+ modtime: dirMod,
+ ents: []*fakeFileInfo{indexFile},
+ },
+ "/index.html": indexFile,
+ }
+
+ ts := newClientServerTest(t, mode, FileServer(fs)).ts
+
+ res, err := ts.Client().Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(b) != indexContents {
+ t.Fatalf("Got body %q; want %q", b, indexContents)
+ }
+ res.Body.Close()
+
+ lastMod := res.Header.Get("Last-Modified")
+ if lastMod != fileModStr {
+ t.Fatalf("initial Last-Modified = %q; want %q", lastMod, fileModStr)
+ }
+
+ req, _ := NewRequest("GET", ts.URL, nil)
+ req.Header.Set("If-Modified-Since", lastMod)
+
+ c := ts.Client()
+ res, err = c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != 304 {
+ t.Fatalf("Code after If-Modified-Since request = %v; want 304", res.StatusCode)
+ }
+ res.Body.Close()
+
+ // Advance the index.html file's modtime, but not the directory's.
+ indexFile.modtime = indexFile.modtime.Add(1 * time.Hour)
+
+ res, err = c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != 200 {
+ t.Fatalf("Code after second If-Modified-Since request = %v; want 200; res is %#v", res.StatusCode, res)
+ }
+ res.Body.Close()
+}
+
+func mustStat(t *testing.T, fileName string) fs.FileInfo {
+ fi, err := os.Stat(fileName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fi
+}
+
+func TestServeContent(t *testing.T) { run(t, testServeContent) }
+func testServeContent(t *testing.T, mode testMode) {
+ type serveParam struct {
+ name string
+ modtime time.Time
+ content io.ReadSeeker
+ contentType string
+ etag string
+ }
+ servec := make(chan serveParam, 1)
+ ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ p := <-servec
+ if p.etag != "" {
+ w.Header().Set("ETag", p.etag)
+ }
+ if p.contentType != "" {
+ w.Header().Set("Content-Type", p.contentType)
+ }
+ ServeContent(w, r, p.name, p.modtime, p.content)
+ })).ts
+
+ type testCase struct {
+ // One of file or content must be set:
+ file string
+ content io.ReadSeeker
+
+ modtime time.Time
+ serveETag string // optional
+ serveContentType string // optional
+ reqHeader map[string]string
+ wantLastMod string
+ wantContentType string
+ wantContentRange string
+ wantStatus int
+ }
+ htmlModTime := mustStat(t, "testdata/index.html").ModTime()
+ tests := map[string]testCase{
+ "no_last_modified": {
+ file: "testdata/style.css",
+ wantContentType: "text/css; charset=utf-8",
+ wantStatus: 200,
+ },
+ "with_last_modified": {
+ file: "testdata/index.html",
+ wantContentType: "text/html; charset=utf-8",
+ modtime: htmlModTime,
+ wantLastMod: htmlModTime.UTC().Format(TimeFormat),
+ wantStatus: 200,
+ },
+ "not_modified_modtime": {
+ file: "testdata/style.css",
+ serveETag: `"foo"`, // Last-Modified sent only when no ETag
+ modtime: htmlModTime,
+ reqHeader: map[string]string{
+ "If-Modified-Since": htmlModTime.UTC().Format(TimeFormat),
+ },
+ wantStatus: 304,
+ },
+ "not_modified_modtime_with_contenttype": {
+ file: "testdata/style.css",
+ serveContentType: "text/css", // explicit content type
+ serveETag: `"foo"`, // Last-Modified sent only when no ETag
+ modtime: htmlModTime,
+ reqHeader: map[string]string{
+ "If-Modified-Since": htmlModTime.UTC().Format(TimeFormat),
+ },
+ wantStatus: 304,
+ },
+ "not_modified_etag": {
+ file: "testdata/style.css",
+ serveETag: `"foo"`,
+ reqHeader: map[string]string{
+ "If-None-Match": `"foo"`,
+ },
+ wantStatus: 304,
+ },
+ "not_modified_etag_no_seek": {
+ content: panicOnSeek{nil}, // should never be called
+ serveETag: `W/"foo"`, // If-None-Match uses weak ETag comparison
+ reqHeader: map[string]string{
+ "If-None-Match": `"baz", W/"foo"`,
+ },
+ wantStatus: 304,
+ },
+ "if_none_match_mismatch": {
+ file: "testdata/style.css",
+ serveETag: `"foo"`,
+ reqHeader: map[string]string{
+ "If-None-Match": `"Foo"`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "if_none_match_malformed": {
+ file: "testdata/style.css",
+ serveETag: `"foo"`,
+ reqHeader: map[string]string{
+ "If-None-Match": `,`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "range_good": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ },
+ wantStatus: StatusPartialContent,
+ wantContentType: "text/css; charset=utf-8",
+ wantContentRange: "bytes 0-4/8",
+ },
+ "range_match": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": `"A"`,
+ },
+ wantStatus: StatusPartialContent,
+ wantContentType: "text/css; charset=utf-8",
+ wantContentRange: "bytes 0-4/8",
+ },
+ "range_match_weak_etag": {
+ file: "testdata/style.css",
+ serveETag: `W/"A"`,
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": `W/"A"`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "range_no_overlap": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "Range": "bytes=10-20",
+ },
+ wantStatus: StatusRequestedRangeNotSatisfiable,
+ wantContentType: "text/plain; charset=utf-8",
+ wantContentRange: "bytes */8",
+ },
+ // An If-Range resource for entity "A", but entity "B" is now current.
+ // The Range request should be ignored.
+ "range_no_match": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": `"B"`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "range_with_modtime": {
+ file: "testdata/style.css",
+ modtime: time.Date(2014, 6, 25, 17, 12, 18, 0 /* nanos */, time.UTC),
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": "Wed, 25 Jun 2014 17:12:18 GMT",
+ },
+ wantStatus: StatusPartialContent,
+ wantContentType: "text/css; charset=utf-8",
+ wantContentRange: "bytes 0-4/8",
+ wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT",
+ },
+ "range_with_modtime_mismatch": {
+ file: "testdata/style.css",
+ modtime: time.Date(2014, 6, 25, 17, 12, 18, 0 /* nanos */, time.UTC),
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": "Wed, 25 Jun 2014 17:12:19 GMT",
+ },
+ wantStatus: StatusOK,
+ wantContentType: "text/css; charset=utf-8",
+ wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT",
+ },
+ "range_with_modtime_nanos": {
+ file: "testdata/style.css",
+ modtime: time.Date(2014, 6, 25, 17, 12, 18, 123 /* nanos */, time.UTC),
+ reqHeader: map[string]string{
+ "Range": "bytes=0-4",
+ "If-Range": "Wed, 25 Jun 2014 17:12:18 GMT",
+ },
+ wantStatus: StatusPartialContent,
+ wantContentType: "text/css; charset=utf-8",
+ wantContentRange: "bytes 0-4/8",
+ wantLastMod: "Wed, 25 Jun 2014 17:12:18 GMT",
+ },
+ "unix_zero_modtime": {
+ content: strings.NewReader("foo"),
+ modtime: time.Unix(0, 0),
+ wantStatus: StatusOK,
+ wantContentType: "text/html; charset=utf-8",
+ },
+ "ifmatch_matches": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "If-Match": `"Z", "A"`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "ifmatch_star": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "If-Match": `*`,
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ },
+ "ifmatch_failed": {
+ file: "testdata/style.css",
+ serveETag: `"A"`,
+ reqHeader: map[string]string{
+ "If-Match": `"B"`,
+ },
+ wantStatus: 412,
+ },
+ "ifmatch_fails_on_weak_etag": {
+ file: "testdata/style.css",
+ serveETag: `W/"A"`,
+ reqHeader: map[string]string{
+ "If-Match": `W/"A"`,
+ },
+ wantStatus: 412,
+ },
+ "if_unmodified_since_true": {
+ file: "testdata/style.css",
+ modtime: htmlModTime,
+ reqHeader: map[string]string{
+ "If-Unmodified-Since": htmlModTime.UTC().Format(TimeFormat),
+ },
+ wantStatus: 200,
+ wantContentType: "text/css; charset=utf-8",
+ wantLastMod: htmlModTime.UTC().Format(TimeFormat),
+ },
+ "if_unmodified_since_false": {
+ file: "testdata/style.css",
+ modtime: htmlModTime,
+ reqHeader: map[string]string{
+ "If-Unmodified-Since": htmlModTime.Add(-2 * time.Second).UTC().Format(TimeFormat),
+ },
+ wantStatus: 412,
+ wantLastMod: htmlModTime.UTC().Format(TimeFormat),
+ },
+ }
+ for testName, tt := range tests {
+ var content io.ReadSeeker
+ if tt.file != "" {
+ f, err := os.Open(tt.file)
+ if err != nil {
+ t.Fatalf("test %q: %v", testName, err)
+ }
+ defer f.Close()
+ content = f
+ } else {
+ content = tt.content
+ }
+ for _, method := range []string{"GET", "HEAD"} {
+ //restore content in case it is consumed by previous method
+ if content, ok := content.(*strings.Reader); ok {
+ content.Seek(0, io.SeekStart)
+ }
+
+ servec <- serveParam{
+ name: filepath.Base(tt.file),
+ content: content,
+ modtime: tt.modtime,
+ etag: tt.serveETag,
+ contentType: tt.serveContentType,
+ }
+ req, err := NewRequest(method, ts.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k, v := range tt.reqHeader {
+ req.Header.Set(k, v)
+ }
+
+ c := ts.Client()
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ if res.StatusCode != tt.wantStatus {
+ t.Errorf("test %q using %q: got status = %d; want %d", testName, method, res.StatusCode, tt.wantStatus)
+ }
+ if g, e := res.Header.Get("Content-Type"), tt.wantContentType; g != e {
+ t.Errorf("test %q using %q: got content-type = %q, want %q", testName, method, g, e)
+ }
+ if g, e := res.Header.Get("Content-Range"), tt.wantContentRange; g != e {
+ t.Errorf("test %q using %q: got content-range = %q, want %q", testName, method, g, e)
+ }
+ if g, e := res.Header.Get("Last-Modified"), tt.wantLastMod; g != e {
+ t.Errorf("test %q using %q: got last-modified = %q, want %q", testName, method, g, e)
+ }
+ }
+ }
+}
+
+// Issue 12991
+func TestServerFileStatError(t *testing.T) {
+ rec := httptest.NewRecorder()
+ r, _ := NewRequest("GET", "http://foo/", nil)
+ redirect := false
+ name := "file.txt"
+ fs := issue12991FS{}
+ ExportServeFile(rec, r, fs, name, redirect)
+ if body := rec.Body.String(); !strings.Contains(body, "403") || !strings.Contains(body, "Forbidden") {
+ t.Errorf("wanted 403 forbidden message; got: %s", body)
+ }
+}
+
+type issue12991FS struct{}
+
+func (issue12991FS) Open(string) (File, error) { return issue12991File{}, nil }
+
+type issue12991File struct{ File }
+
+func (issue12991File) Stat() (fs.FileInfo, error) { return nil, fs.ErrPermission }
+func (issue12991File) Close() error { return nil }
+
+func TestServeContentErrorMessages(t *testing.T) { run(t, testServeContentErrorMessages) }
+func testServeContentErrorMessages(t *testing.T, mode testMode) {
+ fs := fakeFS{
+ "/500": &fakeFileInfo{
+ err: errors.New("random error"),
+ },
+ "/403": &fakeFileInfo{
+ err: &fs.PathError{Err: fs.ErrPermission},
+ },
+ }
+ ts := newClientServerTest(t, mode, FileServer(fs)).ts
+ c := ts.Client()
+ for _, code := range []int{403, 404, 500} {
+ res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, code))
+ if err != nil {
+ t.Errorf("Error fetching /%d: %v", code, err)
+ continue
+ }
+ if res.StatusCode != code {
+ t.Errorf("For /%d, status code = %d; want %d", code, res.StatusCode, code)
+ }
+ res.Body.Close()
+ }
+}
+
+// verifies that sendfile is being used on Linux
+func TestLinuxSendfile(t *testing.T) {
+ setParallel(t)
+ defer afterTest(t)
+ if runtime.GOOS != "linux" {
+ t.Skip("skipping; linux-only test")
+ }
+ if _, err := exec.LookPath("strace"); err != nil {
+ t.Skip("skipping; strace not found in path")
+ }
+
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ lnf, err := ln.(*net.TCPListener).File()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+
+ // Attempt to run strace, and skip on failure - this test requires SYS_PTRACE.
+ if err := testenv.Command(t, "strace", "-f", "-q", os.Args[0], "-test.run=^$").Run(); err != nil {
+ t.Skipf("skipping; failed to run strace: %v", err)
+ }
+
+ filename := fmt.Sprintf("1kb-%d", os.Getpid())
+ filepath := path.Join(os.TempDir(), filename)
+
+ if err := os.WriteFile(filepath, bytes.Repeat([]byte{'a'}, 1<<10), 0755); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Remove(filepath)
+
+ var buf strings.Builder
+ child := testenv.Command(t, "strace", "-f", "-q", os.Args[0], "-test.run=^TestLinuxSendfileChild$")
+ child.ExtraFiles = append(child.ExtraFiles, lnf)
+ child.Env = append([]string{"GO_WANT_HELPER_PROCESS=1"}, os.Environ()...)
+ child.Stdout = &buf
+ child.Stderr = &buf
+ if err := child.Start(); err != nil {
+ t.Skipf("skipping; failed to start straced child: %v", err)
+ }
+
+ res, err := Get(fmt.Sprintf("http://%s/%s", ln.Addr(), filename))
+ if err != nil {
+ t.Fatalf("http client error: %v", err)
+ }
+ _, err = io.Copy(io.Discard, res.Body)
+ if err != nil {
+ t.Fatalf("client body read error: %v", err)
+ }
+ res.Body.Close()
+
+ // Force child to exit cleanly.
+ Post(fmt.Sprintf("http://%s/quit", ln.Addr()), "", nil)
+ child.Wait()
+
+ rx := regexp.MustCompile(`\b(n64:)?sendfile(64)?\(`)
+ out := buf.String()
+ if !rx.MatchString(out) {
+ t.Errorf("no sendfile system call found in:\n%s", out)
+ }
+}
+
+func getBody(t *testing.T, testName string, req Request, client *Client) (*Response, []byte) {
+ r, err := client.Do(&req)
+ if err != nil {
+ t.Fatalf("%s: for URL %q, send error: %v", testName, req.URL.String(), err)
+ }
+ b, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Fatalf("%s: for URL %q, reading body: %v", testName, req.URL.String(), err)
+ }
+ return r, b
+}
+
+// TestLinuxSendfileChild isn't a real test. It's used as a helper process
+// for TestLinuxSendfile.
+func TestLinuxSendfileChild(*testing.T) {
+ if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
+ return
+ }
+ defer os.Exit(0)
+ fd3 := os.NewFile(3, "ephemeral-port-listener")
+ ln, err := net.FileListener(fd3)
+ if err != nil {
+ panic(err)
+ }
+ mux := NewServeMux()
+ mux.Handle("/", FileServer(Dir(os.TempDir())))
+ mux.HandleFunc("/quit", func(ResponseWriter, *Request) {
+ os.Exit(0)
+ })
+ s := &Server{Handler: mux}
+ err = s.Serve(ln)
+ if err != nil {
+ panic(err)
+ }
+}
+
+// Issues 18984, 49552: tests that requests for paths beyond files return not-found errors
+func TestFileServerNotDirError(t *testing.T) {
+ run(t, func(t *testing.T, mode testMode) {
+ t.Run("Dir", func(t *testing.T) {
+ testFileServerNotDirError(t, mode, func(path string) FileSystem { return Dir(path) })
+ })
+ t.Run("FS", func(t *testing.T) {
+ testFileServerNotDirError(t, mode, func(path string) FileSystem { return FS(os.DirFS(path)) })
+ })
+ })
+}
+
+func testFileServerNotDirError(t *testing.T, mode testMode, newfs func(string) FileSystem) {
+ ts := newClientServerTest(t, mode, FileServer(newfs("testdata"))).ts
+
+ res, err := ts.Client().Get(ts.URL + "/index.html/not-a-file")
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != 404 {
+ t.Errorf("StatusCode = %v; want 404", res.StatusCode)
+ }
+
+ test := func(name string, fsys FileSystem) {
+ t.Run(name, func(t *testing.T) {
+ _, err = fsys.Open("/index.html/not-a-file")
+ if err == nil {
+ t.Fatal("err == nil; want != nil")
+ }
+ if !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("err = %v; errors.Is(err, fs.ErrNotExist) = %v; want true", err,
+ errors.Is(err, fs.ErrNotExist))
+ }
+
+ _, err = fsys.Open("/index.html/not-a-dir/not-a-file")
+ if err == nil {
+ t.Fatal("err == nil; want != nil")
+ }
+ if !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("err = %v; errors.Is(err, fs.ErrNotExist) = %v; want true", err,
+ errors.Is(err, fs.ErrNotExist))
+ }
+ })
+ }
+
+ absPath, err := filepath.Abs("testdata")
+ if err != nil {
+ t.Fatal("get abs path:", err)
+ }
+
+ test("RelativePath", newfs("testdata"))
+ test("AbsolutePath", newfs(absPath))
+}
+
+func TestFileServerCleanPath(t *testing.T) {
+ tests := []struct {
+ path string
+ wantCode int
+ wantOpen []string
+ }{
+ {"/", 200, []string{"/", "/index.html"}},
+ {"/dir", 301, []string{"/dir"}},
+ {"/dir/", 200, []string{"/dir", "/dir/index.html"}},
+ }
+ for _, tt := range tests {
+ var log []string
+ rr := httptest.NewRecorder()
+ req, _ := NewRequest("GET", "http://foo.localhost"+tt.path, nil)
+ FileServer(fileServerCleanPathDir{&log}).ServeHTTP(rr, req)
+ if !reflect.DeepEqual(log, tt.wantOpen) {
+ t.Logf("For %s: Opens = %q; want %q", tt.path, log, tt.wantOpen)
+ }
+ if rr.Code != tt.wantCode {
+ t.Logf("For %s: Response code = %d; want %d", tt.path, rr.Code, tt.wantCode)
+ }
+ }
+}
+
+type fileServerCleanPathDir struct {
+ log *[]string
+}
+
+func (d fileServerCleanPathDir) Open(path string) (File, error) {
+ *(d.log) = append(*(d.log), path)
+ if path == "/" || path == "/dir" || path == "/dir/" {
+ // Just return back something that's a directory.
+ return Dir(".").Open(".")
+ }
+ return nil, fs.ErrNotExist
+}
+
+type panicOnSeek struct{ io.ReadSeeker }
+
+func Test_scanETag(t *testing.T) {
+ tests := []struct {
+ in string
+ wantETag string
+ wantRemain string
+ }{
+ {`W/"etag-1"`, `W/"etag-1"`, ""},
+ {`"etag-2"`, `"etag-2"`, ""},
+ {`"etag-1", "etag-2"`, `"etag-1"`, `, "etag-2"`},
+ {"", "", ""},
+ {"W/", "", ""},
+ {`W/"truc`, "", ""},
+ {`w/"case-sensitive"`, "", ""},
+ {`"spaced etag"`, "", ""},
+ }
+ for _, test := range tests {
+ etag, remain := ExportScanETag(test.in)
+ if etag != test.wantETag || remain != test.wantRemain {
+ t.Errorf("scanETag(%q)=%q %q, want %q %q", test.in, etag, remain, test.wantETag, test.wantRemain)
+ }
+ }
+}
+
+// Issue 40940: Ensure that we only accept non-negative suffix-lengths
+// in "Range": "bytes=-N", and should reject "bytes=--2".
+func TestServeFileRejectsInvalidSuffixLengths(t *testing.T) {
+ run(t, testServeFileRejectsInvalidSuffixLengths, []testMode{http1Mode, https1Mode, http2Mode})
+}
+func testServeFileRejectsInvalidSuffixLengths(t *testing.T, mode testMode) {
+ cst := newClientServerTest(t, mode, FileServer(Dir("testdata"))).ts
+
+ tests := []struct {
+ r string
+ wantCode int
+ wantBody string
+ }{
+ {"bytes=--6", 416, "invalid range\n"},
+ {"bytes=--0", 416, "invalid range\n"},
+ {"bytes=---0", 416, "invalid range\n"},
+ {"bytes=-6", 206, "hello\n"},
+ {"bytes=6-", 206, "html says hello\n"},
+ {"bytes=-6-", 416, "invalid range\n"},
+ {"bytes=-0", 206, ""},
+ {"bytes=", 200, "index.html says hello\n"},
+ }
+
+ for _, tt := range tests {
+ tt := tt
+ t.Run(tt.r, func(t *testing.T) {
+ req, err := NewRequest("GET", cst.URL+"/index.html", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Range", tt.r)
+ res, err := cst.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if g, w := res.StatusCode, tt.wantCode; g != w {
+ t.Errorf("StatusCode mismatch: got %d want %d", g, w)
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if g, w := string(slurp), tt.wantBody; g != w {
+ t.Fatalf("Content mismatch:\nGot: %q\nWant: %q", g, w)
+ }
+ })
+ }
+}
+
+func TestFileServerMethods(t *testing.T) {
+ run(t, testFileServerMethods)
+}
+func testFileServerMethods(t *testing.T, mode testMode) {
+ ts := newClientServerTest(t, mode, FileServer(Dir("testdata"))).ts
+
+ file, err := os.ReadFile(testFile)
+ if err != nil {
+ t.Fatal("reading file:", err)
+ }
+
+ // Get contents via various methods.
+ //
+ // See https://go.dev/issue/59471 for a proposal to limit the set of methods handled.
+ // For now, test the historical behavior.
+ for _, method := range []string{
+ MethodGet,
+ MethodHead,
+ MethodPost,
+ MethodPut,
+ MethodPatch,
+ MethodDelete,
+ MethodOptions,
+ MethodTrace,
+ } {
+ req, _ := NewRequest(method, ts.URL+"/file", nil)
+ t.Log(req.URL)
+ res, err := ts.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantBody := file
+ if method == MethodHead {
+ wantBody = nil
+ }
+ if !bytes.Equal(body, wantBody) {
+ t.Fatalf("%v: got body %q, want %q", method, body, wantBody)
+ }
+ if got, want := res.Header.Get("Content-Length"), fmt.Sprint(len(file)); got != want {
+ t.Fatalf("%v: got Content-Length %q, want %q", method, got, want)
+ }
+ }
+}
+
+func TestFileServerFS(t *testing.T) {
+ filename := "index.html"
+ contents := []byte("index.html says hello")
+ fsys := fstest.MapFS{
+ filename: {Data: contents},
+ }
+ ts := newClientServerTest(t, http1Mode, FileServerFS(fsys)).ts
+ defer ts.Close()
+
+ res, err := ts.Client().Get(ts.URL + "/" + filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if s := string(b); s != string(contents) {
+ t.Errorf("for path %q got %q, want %q", filename, s, contents)
+ }
+ res.Body.Close()
+}
+
+func TestServeFileFS(t *testing.T) {
+ filename := "index.html"
+ contents := []byte("index.html says hello")
+ fsys := fstest.MapFS{
+ filename: {Data: contents},
+ }
+ ts := newClientServerTest(t, http1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ ServeFileFS(w, r, fsys, filename)
+ })).ts
+ defer ts.Close()
+
+ res, err := ts.Client().Get(ts.URL + "/" + filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if s := string(b); s != string(contents) {
+ t.Errorf("for path %q got %q, want %q", filename, s, contents)
+ }
+ res.Body.Close()
+}
+
+func TestServeFileZippingResponseWriter(t *testing.T) {
+ // This test exercises a pattern which is incorrect,
+ // but has been observed enough in the world that we don't want to break it.
+ //
+ // The server is setting "Content-Encoding: gzip",
+ // wrapping the ResponseWriter in an implementation which gzips data written to it,
+ // and passing this ResponseWriter to ServeFile.
+ //
+ // This means ServeFile cannot properly set a Content-Length header, because it
+ // doesn't know what content it is going to send--the ResponseWriter is modifying
+ // the bytes sent.
+ //
+ // Range requests are always going to be broken in this scenario,
+ // but verify that we can serve non-range requests correctly.
+ filename := "index.html"
+ contents := []byte("contents will be sent with Content-Encoding: gzip")
+ fsys := fstest.MapFS{
+ filename: {Data: contents},
+ }
+ ts := newClientServerTest(t, http1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+ w.Header().Set("Content-Encoding", "gzip")
+ gzw := gzip.NewWriter(w)
+ defer gzw.Close()
+ ServeFileFS(gzipResponseWriter{w: gzw, ResponseWriter: w}, r, fsys, filename)
+ })).ts
+ defer ts.Close()
+
+ res, err := ts.Client().Get(ts.URL + "/" + filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal("reading Body:", err)
+ }
+ if s := string(b); s != string(contents) {
+ t.Errorf("for path %q got %q, want %q", filename, s, contents)
+ }
+ res.Body.Close()
+}
+
+type gzipResponseWriter struct {
+ ResponseWriter
+ w *gzip.Writer
+}
+
+func (grw gzipResponseWriter) Write(b []byte) (int, error) {
+ return grw.w.Write(b)
+}
+
+func (grw gzipResponseWriter) Flush() {
+ grw.w.Flush()
+ if fw, ok := grw.ResponseWriter.(http.Flusher); ok {
+ fw.Flush()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/h2_bundle.go b/platform/dbops/binaries/go/go/src/net/http/h2_bundle.go
new file mode 100644
index 0000000000000000000000000000000000000000..c1a2e76ea4d394455bac31756da0ba3cb2f4c5f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/h2_bundle.go
@@ -0,0 +1,11527 @@
+//go:build !nethttpomithttp2
+
+// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.
+// $ bundle -o=h2_bundle.go -prefix=http2 -tags=!nethttpomithttp2 golang.org/x/net/http2
+
+// Package http2 implements the HTTP/2 protocol.
+//
+// This package is low-level and intended to be used directly by very
+// few people. Most users will use it indirectly through the automatic
+// use by the net/http package (from Go 1.6 and later).
+// For use in earlier Go versions see ConfigureServer. (Transport support
+// requires Go 1.6 or later)
+//
+// See https://http2.github.io/ for more information on HTTP/2.
+//
+// See https://http2.golang.org/ for a test server running this code.
+//
+
+package http
+
+import (
+ "bufio"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/rand"
+ "crypto/tls"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "log"
+ "math"
+ "math/bits"
+ mathrand "math/rand"
+ "net"
+ "net/http/httptrace"
+ "net/textproto"
+ "net/url"
+ "os"
+ "reflect"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "golang.org/x/net/http/httpguts"
+ "golang.org/x/net/http2/hpack"
+ "golang.org/x/net/idna"
+)
+
+// The HTTP protocols are defined in terms of ASCII, not Unicode. This file
+// contains helper functions which may use Unicode-aware functions which would
+// otherwise be unsafe and could introduce vulnerabilities if used improperly.
+
+// asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
+// are equal, ASCII-case-insensitively.
+func http2asciiEqualFold(s, t string) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if http2lower(s[i]) != http2lower(t[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// lower returns the ASCII lowercase version of b.
+func http2lower(b byte) byte {
+ if 'A' <= b && b <= 'Z' {
+ return b + ('a' - 'A')
+ }
+ return b
+}
+
+// isASCIIPrint returns whether s is ASCII and printable according to
+// https://tools.ietf.org/html/rfc20#section-4.2.
+func http2isASCIIPrint(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < ' ' || s[i] > '~' {
+ return false
+ }
+ }
+ return true
+}
+
+// asciiToLower returns the lowercase version of s if s is ASCII and printable,
+// and whether or not it was.
+func http2asciiToLower(s string) (lower string, ok bool) {
+ if !http2isASCIIPrint(s) {
+ return "", false
+ }
+ return strings.ToLower(s), true
+}
+
+// A list of the possible cipher suite ids. Taken from
+// https://www.iana.org/assignments/tls-parameters/tls-parameters.txt
+
+const (
+ http2cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000
+ http2cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001
+ http2cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002
+ http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003
+ http2cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004
+ http2cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
+ http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006
+ http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007
+ http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008
+ http2cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009
+ http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A
+ http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B
+ http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C
+ http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D
+ http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E
+ http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F
+ http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010
+ http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
+ http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012
+ http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013
+ http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
+ http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015
+ http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016
+ http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017
+ http2cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018
+ http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
+ http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A
+ http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B
+ // Reserved uint16 = 0x001C-1D
+ http2cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E
+ http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F
+ http2cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020
+ http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021
+ http2cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022
+ http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023
+ http2cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024
+ http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025
+ http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028
+ http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B
+ http2cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E
+ http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F
+ http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030
+ http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031
+ http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033
+ http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034
+ http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
+ http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036
+ http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037
+ http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039
+ http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A
+ http2cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B
+ http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C
+ http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D
+ http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E
+ http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F
+ http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
+ // Reserved uint16 = 0x0047-4F
+ // Reserved uint16 = 0x0050-58
+ // Reserved uint16 = 0x0059-5C
+ // Unassigned uint16 = 0x005D-5F
+ // Reserved uint16 = 0x0060-66
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067
+ http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068
+ http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069
+ http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
+ http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
+ http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
+ // Unassigned uint16 = 0x006E-83
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089
+ http2cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A
+ http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B
+ http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C
+ http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D
+ http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E
+ http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091
+ http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092
+ http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095
+ http2cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096
+ http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097
+ http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098
+ http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099
+ http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A
+ http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B
+ http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C
+ http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F
+ http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0
+ http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1
+ http2cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2
+ http2cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3
+ http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4
+ http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5
+ http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6
+ http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7
+ http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8
+ http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD
+ http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE
+ http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF
+ http2cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0
+ http2cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
+ // Unassigned uint16 = 0x00C6-FE
+ http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF
+ // Unassigned uint16 = 0x01-55,*
+ http2cipher_TLS_FALLBACK_SCSV uint16 = 0x5600
+ // Unassigned uint16 = 0x5601 - 0xC000
+ http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001
+ http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002
+ http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005
+ http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006
+ http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007
+ http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A
+ http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B
+ http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C
+ http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F
+ http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010
+ http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011
+ http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014
+ http2cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015
+ http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016
+ http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017
+ http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018
+ http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019
+ http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A
+ http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B
+ http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C
+ http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D
+ http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E
+ http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F
+ http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020
+ http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021
+ http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032
+ http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033
+ http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B
+ http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C
+ http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D
+ http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E
+ http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F
+ http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040
+ http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045
+ http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046
+ http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F
+ http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050
+ http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053
+ http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054
+ http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057
+ http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058
+ http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059
+ http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A
+ http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063
+ http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064
+ http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069
+ http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A
+ http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F
+ http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070
+ http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D
+ http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E
+ http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093
+ http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094
+ http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099
+ http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A
+ http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B
+ http2cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C
+ http2cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F
+ http2cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0
+ http2cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3
+ http2cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4
+ http2cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7
+ http2cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8
+ http2cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9
+ http2cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA
+ http2cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF
+ // Unassigned uint16 = 0xC0B0-FF
+ // Unassigned uint16 = 0xC1-CB,*
+ // Unassigned uint16 = 0xCC00-A7
+ http2cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
+ http2cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA
+ http2cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB
+ http2cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC
+ http2cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD
+ http2cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE
+)
+
+// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
+// References:
+// https://tools.ietf.org/html/rfc7540#appendix-A
+// Reject cipher suites from Appendix A.
+// "This list includes those cipher suites that do not
+// offer an ephemeral key exchange and those that are
+// based on the TLS null, stream or block cipher type"
+func http2isBadCipher(cipher uint16) bool {
+ switch cipher {
+ case http2cipher_TLS_NULL_WITH_NULL_NULL,
+ http2cipher_TLS_RSA_WITH_NULL_MD5,
+ http2cipher_TLS_RSA_WITH_NULL_SHA,
+ http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5,
+ http2cipher_TLS_RSA_WITH_RC4_128_MD5,
+ http2cipher_TLS_RSA_WITH_RC4_128_SHA,
+ http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
+ http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA,
+ http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_DES_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
+ http2cipher_TLS_DH_anon_WITH_RC4_128_MD5,
+ http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_KRB5_WITH_DES_CBC_SHA,
+ http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_KRB5_WITH_RC4_128_SHA,
+ http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA,
+ http2cipher_TLS_KRB5_WITH_DES_CBC_MD5,
+ http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5,
+ http2cipher_TLS_KRB5_WITH_RC4_128_MD5,
+ http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5,
+ http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA,
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA,
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA,
+ http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5,
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5,
+ http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5,
+ http2cipher_TLS_PSK_WITH_NULL_SHA,
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA,
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA,
+ http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_NULL_SHA256,
+ http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA,
+ http2cipher_TLS_PSK_WITH_RC4_128_SHA,
+ http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA,
+ http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA,
+ http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA,
+ http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_PSK_WITH_NULL_SHA256,
+ http2cipher_TLS_PSK_WITH_NULL_SHA384,
+ http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256,
+ http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256,
+ http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
+ http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA,
+ http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA,
+ http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA,
+ http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDH_anon_WITH_NULL_SHA,
+ http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
+ http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
+ http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA,
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256,
+ http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384,
+ http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
+ http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
+ http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ http2cipher_TLS_RSA_WITH_AES_128_CCM,
+ http2cipher_TLS_RSA_WITH_AES_256_CCM,
+ http2cipher_TLS_RSA_WITH_AES_128_CCM_8,
+ http2cipher_TLS_RSA_WITH_AES_256_CCM_8,
+ http2cipher_TLS_PSK_WITH_AES_128_CCM,
+ http2cipher_TLS_PSK_WITH_AES_256_CCM,
+ http2cipher_TLS_PSK_WITH_AES_128_CCM_8,
+ http2cipher_TLS_PSK_WITH_AES_256_CCM_8:
+ return true
+ default:
+ return false
+ }
+}
+
+// ClientConnPool manages a pool of HTTP/2 client connections.
+type http2ClientConnPool interface {
+ // GetClientConn returns a specific HTTP/2 connection (usually
+ // a TLS-TCP connection) to an HTTP/2 server. On success, the
+ // returned ClientConn accounts for the upcoming RoundTrip
+ // call, so the caller should not omit it. If the caller needs
+ // to, ClientConn.RoundTrip can be called with a bogus
+ // new(http.Request) to release the stream reservation.
+ GetClientConn(req *Request, addr string) (*http2ClientConn, error)
+ MarkDead(*http2ClientConn)
+}
+
+// clientConnPoolIdleCloser is the interface implemented by ClientConnPool
+// implementations which can close their idle connections.
+type http2clientConnPoolIdleCloser interface {
+ http2ClientConnPool
+ closeIdleConnections()
+}
+
+var (
+ _ http2clientConnPoolIdleCloser = (*http2clientConnPool)(nil)
+ _ http2clientConnPoolIdleCloser = http2noDialClientConnPool{}
+)
+
+// TODO: use singleflight for dialing and addConnCalls?
+type http2clientConnPool struct {
+ t *http2Transport
+
+ mu sync.Mutex // TODO: maybe switch to RWMutex
+ // TODO: add support for sharing conns based on cert names
+ // (e.g. share conn for googleapis.com and appspot.com)
+ conns map[string][]*http2ClientConn // key is host:port
+ dialing map[string]*http2dialCall // currently in-flight dials
+ keys map[*http2ClientConn][]string
+ addConnCalls map[string]*http2addConnCall // in-flight addConnIfNeeded calls
+}
+
+func (p *http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error) {
+ return p.getClientConn(req, addr, http2dialOnMiss)
+}
+
+const (
+ http2dialOnMiss = true
+ http2noDialOnMiss = false
+)
+
+func (p *http2clientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error) {
+ // TODO(dneil): Dial a new connection when t.DisableKeepAlives is set?
+ if http2isConnectionCloseRequest(req) && dialOnMiss {
+ // It gets its own connection.
+ http2traceGetConn(req, addr)
+ const singleUse = true
+ cc, err := p.t.dialClientConn(req.Context(), addr, singleUse)
+ if err != nil {
+ return nil, err
+ }
+ return cc, nil
+ }
+ for {
+ p.mu.Lock()
+ for _, cc := range p.conns[addr] {
+ if cc.ReserveNewRequest() {
+ // When a connection is presented to us by the net/http package,
+ // the GetConn hook has already been called.
+ // Don't call it a second time here.
+ if !cc.getConnCalled {
+ http2traceGetConn(req, addr)
+ }
+ cc.getConnCalled = false
+ p.mu.Unlock()
+ return cc, nil
+ }
+ }
+ if !dialOnMiss {
+ p.mu.Unlock()
+ return nil, http2ErrNoCachedConn
+ }
+ http2traceGetConn(req, addr)
+ call := p.getStartDialLocked(req.Context(), addr)
+ p.mu.Unlock()
+ <-call.done
+ if http2shouldRetryDial(call, req) {
+ continue
+ }
+ cc, err := call.res, call.err
+ if err != nil {
+ return nil, err
+ }
+ if cc.ReserveNewRequest() {
+ return cc, nil
+ }
+ }
+}
+
+// dialCall is an in-flight Transport dial call to a host.
+type http2dialCall struct {
+ _ http2incomparable
+ p *http2clientConnPool
+ // the context associated with the request
+ // that created this dialCall
+ ctx context.Context
+ done chan struct{} // closed when done
+ res *http2ClientConn // valid after done is closed
+ err error // valid after done is closed
+}
+
+// requires p.mu is held.
+func (p *http2clientConnPool) getStartDialLocked(ctx context.Context, addr string) *http2dialCall {
+ if call, ok := p.dialing[addr]; ok {
+ // A dial is already in-flight. Don't start another.
+ return call
+ }
+ call := &http2dialCall{p: p, done: make(chan struct{}), ctx: ctx}
+ if p.dialing == nil {
+ p.dialing = make(map[string]*http2dialCall)
+ }
+ p.dialing[addr] = call
+ go call.dial(call.ctx, addr)
+ return call
+}
+
+// run in its own goroutine.
+func (c *http2dialCall) dial(ctx context.Context, addr string) {
+ const singleUse = false // shared conn
+ c.res, c.err = c.p.t.dialClientConn(ctx, addr, singleUse)
+
+ c.p.mu.Lock()
+ delete(c.p.dialing, addr)
+ if c.err == nil {
+ c.p.addConnLocked(addr, c.res)
+ }
+ c.p.mu.Unlock()
+
+ close(c.done)
+}
+
+// addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
+// already exist. It coalesces concurrent calls with the same key.
+// This is used by the http1 Transport code when it creates a new connection. Because
+// the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
+// the protocol), it can get into a situation where it has multiple TLS connections.
+// This code decides which ones live or die.
+// The return value used is whether c was used.
+// c is never closed.
+func (p *http2clientConnPool) addConnIfNeeded(key string, t *http2Transport, c *tls.Conn) (used bool, err error) {
+ p.mu.Lock()
+ for _, cc := range p.conns[key] {
+ if cc.CanTakeNewRequest() {
+ p.mu.Unlock()
+ return false, nil
+ }
+ }
+ call, dup := p.addConnCalls[key]
+ if !dup {
+ if p.addConnCalls == nil {
+ p.addConnCalls = make(map[string]*http2addConnCall)
+ }
+ call = &http2addConnCall{
+ p: p,
+ done: make(chan struct{}),
+ }
+ p.addConnCalls[key] = call
+ go call.run(t, key, c)
+ }
+ p.mu.Unlock()
+
+ <-call.done
+ if call.err != nil {
+ return false, call.err
+ }
+ return !dup, nil
+}
+
+type http2addConnCall struct {
+ _ http2incomparable
+ p *http2clientConnPool
+ done chan struct{} // closed when done
+ err error
+}
+
+func (c *http2addConnCall) run(t *http2Transport, key string, tc *tls.Conn) {
+ cc, err := t.NewClientConn(tc)
+
+ p := c.p
+ p.mu.Lock()
+ if err != nil {
+ c.err = err
+ } else {
+ cc.getConnCalled = true // already called by the net/http package
+ p.addConnLocked(key, cc)
+ }
+ delete(p.addConnCalls, key)
+ p.mu.Unlock()
+ close(c.done)
+}
+
+// p.mu must be held
+func (p *http2clientConnPool) addConnLocked(key string, cc *http2ClientConn) {
+ for _, v := range p.conns[key] {
+ if v == cc {
+ return
+ }
+ }
+ if p.conns == nil {
+ p.conns = make(map[string][]*http2ClientConn)
+ }
+ if p.keys == nil {
+ p.keys = make(map[*http2ClientConn][]string)
+ }
+ p.conns[key] = append(p.conns[key], cc)
+ p.keys[cc] = append(p.keys[cc], key)
+}
+
+func (p *http2clientConnPool) MarkDead(cc *http2ClientConn) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for _, key := range p.keys[cc] {
+ vv, ok := p.conns[key]
+ if !ok {
+ continue
+ }
+ newList := http2filterOutClientConn(vv, cc)
+ if len(newList) > 0 {
+ p.conns[key] = newList
+ } else {
+ delete(p.conns, key)
+ }
+ }
+ delete(p.keys, cc)
+}
+
+func (p *http2clientConnPool) closeIdleConnections() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ // TODO: don't close a cc if it was just added to the pool
+ // milliseconds ago and has never been used. There's currently
+ // a small race window with the HTTP/1 Transport's integration
+ // where it can add an idle conn just before using it, and
+ // somebody else can concurrently call CloseIdleConns and
+ // break some caller's RoundTrip.
+ for _, vv := range p.conns {
+ for _, cc := range vv {
+ cc.closeIfIdle()
+ }
+ }
+}
+
+func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn {
+ out := in[:0]
+ for _, v := range in {
+ if v != exclude {
+ out = append(out, v)
+ }
+ }
+ // If we filtered it out, zero out the last item to prevent
+ // the GC from seeing it.
+ if len(in) != len(out) {
+ in[len(in)-1] = nil
+ }
+ return out
+}
+
+// noDialClientConnPool is an implementation of http2.ClientConnPool
+// which never dials. We let the HTTP/1.1 client dial and use its TLS
+// connection instead.
+type http2noDialClientConnPool struct{ *http2clientConnPool }
+
+func (p http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error) {
+ return p.getClientConn(req, addr, http2noDialOnMiss)
+}
+
+// shouldRetryDial reports whether the current request should
+// retry dialing after the call finished unsuccessfully, for example
+// if the dial was canceled because of a context cancellation or
+// deadline expiry.
+func http2shouldRetryDial(call *http2dialCall, req *Request) bool {
+ if call.err == nil {
+ // No error, no need to retry
+ return false
+ }
+ if call.ctx == req.Context() {
+ // If the call has the same context as the request, the dial
+ // should not be retried, since any cancellation will have come
+ // from this request.
+ return false
+ }
+ if !errors.Is(call.err, context.Canceled) && !errors.Is(call.err, context.DeadlineExceeded) {
+ // If the call error is not because of a context cancellation or a deadline expiry,
+ // the dial should not be retried.
+ return false
+ }
+ // Only retry if the error is a context cancellation error or deadline expiry
+ // and the context associated with the call was canceled or expired.
+ return call.ctx.Err() != nil
+}
+
+// Buffer chunks are allocated from a pool to reduce pressure on GC.
+// The maximum wasted space per dataBuffer is 2x the largest size class,
+// which happens when the dataBuffer has multiple chunks and there is
+// one unread byte in both the first and last chunks. We use a few size
+// classes to minimize overheads for servers that typically receive very
+// small request bodies.
+//
+// TODO: Benchmark to determine if the pools are necessary. The GC may have
+// improved enough that we can instead allocate chunks like this:
+// make([]byte, max(16<<10, expectedBytesRemaining))
+var http2dataChunkPools = [...]sync.Pool{
+ {New: func() interface{} { return new([1 << 10]byte) }},
+ {New: func() interface{} { return new([2 << 10]byte) }},
+ {New: func() interface{} { return new([4 << 10]byte) }},
+ {New: func() interface{} { return new([8 << 10]byte) }},
+ {New: func() interface{} { return new([16 << 10]byte) }},
+}
+
+func http2getDataBufferChunk(size int64) []byte {
+ switch {
+ case size <= 1<<10:
+ return http2dataChunkPools[0].Get().(*[1 << 10]byte)[:]
+ case size <= 2<<10:
+ return http2dataChunkPools[1].Get().(*[2 << 10]byte)[:]
+ case size <= 4<<10:
+ return http2dataChunkPools[2].Get().(*[4 << 10]byte)[:]
+ case size <= 8<<10:
+ return http2dataChunkPools[3].Get().(*[8 << 10]byte)[:]
+ default:
+ return http2dataChunkPools[4].Get().(*[16 << 10]byte)[:]
+ }
+}
+
+func http2putDataBufferChunk(p []byte) {
+ switch len(p) {
+ case 1 << 10:
+ http2dataChunkPools[0].Put((*[1 << 10]byte)(p))
+ case 2 << 10:
+ http2dataChunkPools[1].Put((*[2 << 10]byte)(p))
+ case 4 << 10:
+ http2dataChunkPools[2].Put((*[4 << 10]byte)(p))
+ case 8 << 10:
+ http2dataChunkPools[3].Put((*[8 << 10]byte)(p))
+ case 16 << 10:
+ http2dataChunkPools[4].Put((*[16 << 10]byte)(p))
+ default:
+ panic(fmt.Sprintf("unexpected buffer len=%v", len(p)))
+ }
+}
+
+// dataBuffer is an io.ReadWriter backed by a list of data chunks.
+// Each dataBuffer is used to read DATA frames on a single stream.
+// The buffer is divided into chunks so the server can limit the
+// total memory used by a single connection without limiting the
+// request body size on any single stream.
+type http2dataBuffer struct {
+ chunks [][]byte
+ r int // next byte to read is chunks[0][r]
+ w int // next byte to write is chunks[len(chunks)-1][w]
+ size int // total buffered bytes
+ expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0)
+}
+
+var http2errReadEmpty = errors.New("read from empty dataBuffer")
+
+// Read copies bytes from the buffer into p.
+// It is an error to read when no data is available.
+func (b *http2dataBuffer) Read(p []byte) (int, error) {
+ if b.size == 0 {
+ return 0, http2errReadEmpty
+ }
+ var ntotal int
+ for len(p) > 0 && b.size > 0 {
+ readFrom := b.bytesFromFirstChunk()
+ n := copy(p, readFrom)
+ p = p[n:]
+ ntotal += n
+ b.r += n
+ b.size -= n
+ // If the first chunk has been consumed, advance to the next chunk.
+ if b.r == len(b.chunks[0]) {
+ http2putDataBufferChunk(b.chunks[0])
+ end := len(b.chunks) - 1
+ copy(b.chunks[:end], b.chunks[1:])
+ b.chunks[end] = nil
+ b.chunks = b.chunks[:end]
+ b.r = 0
+ }
+ }
+ return ntotal, nil
+}
+
+func (b *http2dataBuffer) bytesFromFirstChunk() []byte {
+ if len(b.chunks) == 1 {
+ return b.chunks[0][b.r:b.w]
+ }
+ return b.chunks[0][b.r:]
+}
+
+// Len returns the number of bytes of the unread portion of the buffer.
+func (b *http2dataBuffer) Len() int {
+ return b.size
+}
+
+// Write appends p to the buffer.
+func (b *http2dataBuffer) Write(p []byte) (int, error) {
+ ntotal := len(p)
+ for len(p) > 0 {
+ // If the last chunk is empty, allocate a new chunk. Try to allocate
+ // enough to fully copy p plus any additional bytes we expect to
+ // receive. However, this may allocate less than len(p).
+ want := int64(len(p))
+ if b.expected > want {
+ want = b.expected
+ }
+ chunk := b.lastChunkOrAlloc(want)
+ n := copy(chunk[b.w:], p)
+ p = p[n:]
+ b.w += n
+ b.size += n
+ b.expected -= int64(n)
+ }
+ return ntotal, nil
+}
+
+func (b *http2dataBuffer) lastChunkOrAlloc(want int64) []byte {
+ if len(b.chunks) != 0 {
+ last := b.chunks[len(b.chunks)-1]
+ if b.w < len(last) {
+ return last
+ }
+ }
+ chunk := http2getDataBufferChunk(want)
+ b.chunks = append(b.chunks, chunk)
+ b.w = 0
+ return chunk
+}
+
+// An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec.
+type http2ErrCode uint32
+
+const (
+ http2ErrCodeNo http2ErrCode = 0x0
+ http2ErrCodeProtocol http2ErrCode = 0x1
+ http2ErrCodeInternal http2ErrCode = 0x2
+ http2ErrCodeFlowControl http2ErrCode = 0x3
+ http2ErrCodeSettingsTimeout http2ErrCode = 0x4
+ http2ErrCodeStreamClosed http2ErrCode = 0x5
+ http2ErrCodeFrameSize http2ErrCode = 0x6
+ http2ErrCodeRefusedStream http2ErrCode = 0x7
+ http2ErrCodeCancel http2ErrCode = 0x8
+ http2ErrCodeCompression http2ErrCode = 0x9
+ http2ErrCodeConnect http2ErrCode = 0xa
+ http2ErrCodeEnhanceYourCalm http2ErrCode = 0xb
+ http2ErrCodeInadequateSecurity http2ErrCode = 0xc
+ http2ErrCodeHTTP11Required http2ErrCode = 0xd
+)
+
+var http2errCodeName = map[http2ErrCode]string{
+ http2ErrCodeNo: "NO_ERROR",
+ http2ErrCodeProtocol: "PROTOCOL_ERROR",
+ http2ErrCodeInternal: "INTERNAL_ERROR",
+ http2ErrCodeFlowControl: "FLOW_CONTROL_ERROR",
+ http2ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT",
+ http2ErrCodeStreamClosed: "STREAM_CLOSED",
+ http2ErrCodeFrameSize: "FRAME_SIZE_ERROR",
+ http2ErrCodeRefusedStream: "REFUSED_STREAM",
+ http2ErrCodeCancel: "CANCEL",
+ http2ErrCodeCompression: "COMPRESSION_ERROR",
+ http2ErrCodeConnect: "CONNECT_ERROR",
+ http2ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM",
+ http2ErrCodeInadequateSecurity: "INADEQUATE_SECURITY",
+ http2ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED",
+}
+
+func (e http2ErrCode) String() string {
+ if s, ok := http2errCodeName[e]; ok {
+ return s
+ }
+ return fmt.Sprintf("unknown error code 0x%x", uint32(e))
+}
+
+func (e http2ErrCode) stringToken() string {
+ if s, ok := http2errCodeName[e]; ok {
+ return s
+ }
+ return fmt.Sprintf("ERR_UNKNOWN_%d", uint32(e))
+}
+
+// ConnectionError is an error that results in the termination of the
+// entire connection.
+type http2ConnectionError http2ErrCode
+
+func (e http2ConnectionError) Error() string {
+ return fmt.Sprintf("connection error: %s", http2ErrCode(e))
+}
+
+// StreamError is an error that only affects one stream within an
+// HTTP/2 connection.
+type http2StreamError struct {
+ StreamID uint32
+ Code http2ErrCode
+ Cause error // optional additional detail
+}
+
+// errFromPeer is a sentinel error value for StreamError.Cause to
+// indicate that the StreamError was sent from the peer over the wire
+// and wasn't locally generated in the Transport.
+var http2errFromPeer = errors.New("received from peer")
+
+func http2streamError(id uint32, code http2ErrCode) http2StreamError {
+ return http2StreamError{StreamID: id, Code: code}
+}
+
+func (e http2StreamError) Error() string {
+ if e.Cause != nil {
+ return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause)
+ }
+ return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code)
+}
+
+// 6.9.1 The Flow Control Window
+// "If a sender receives a WINDOW_UPDATE that causes a flow control
+// window to exceed this maximum it MUST terminate either the stream
+// or the connection, as appropriate. For streams, [...]; for the
+// connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code."
+type http2goAwayFlowError struct{}
+
+func (http2goAwayFlowError) Error() string { return "connection exceeded flow control window size" }
+
+// connError represents an HTTP/2 ConnectionError error code, along
+// with a string (for debugging) explaining why.
+//
+// Errors of this type are only returned by the frame parser functions
+// and converted into ConnectionError(Code), after stashing away
+// the Reason into the Framer's errDetail field, accessible via
+// the (*Framer).ErrorDetail method.
+type http2connError struct {
+ Code http2ErrCode // the ConnectionError error code
+ Reason string // additional reason
+}
+
+func (e http2connError) Error() string {
+ return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason)
+}
+
+type http2pseudoHeaderError string
+
+func (e http2pseudoHeaderError) Error() string {
+ return fmt.Sprintf("invalid pseudo-header %q", string(e))
+}
+
+type http2duplicatePseudoHeaderError string
+
+func (e http2duplicatePseudoHeaderError) Error() string {
+ return fmt.Sprintf("duplicate pseudo-header %q", string(e))
+}
+
+type http2headerFieldNameError string
+
+func (e http2headerFieldNameError) Error() string {
+ return fmt.Sprintf("invalid header field name %q", string(e))
+}
+
+type http2headerFieldValueError string
+
+func (e http2headerFieldValueError) Error() string {
+ return fmt.Sprintf("invalid header field value for %q", string(e))
+}
+
+var (
+ http2errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers")
+ http2errPseudoAfterRegular = errors.New("pseudo header field after regular")
+)
+
+// inflowMinRefresh is the minimum number of bytes we'll send for a
+// flow control window update.
+const http2inflowMinRefresh = 4 << 10
+
+// inflow accounts for an inbound flow control window.
+// It tracks both the latest window sent to the peer (used for enforcement)
+// and the accumulated unsent window.
+type http2inflow struct {
+ avail int32
+ unsent int32
+}
+
+// init sets the initial window.
+func (f *http2inflow) init(n int32) {
+ f.avail = n
+}
+
+// add adds n bytes to the window, with a maximum window size of max,
+// indicating that the peer can now send us more data.
+// For example, the user read from a {Request,Response} body and consumed
+// some of the buffered data, so the peer can now send more.
+// It returns the number of bytes to send in a WINDOW_UPDATE frame to the peer.
+// Window updates are accumulated and sent when the unsent capacity
+// is at least inflowMinRefresh or will at least double the peer's available window.
+func (f *http2inflow) add(n int) (connAdd int32) {
+ if n < 0 {
+ panic("negative update")
+ }
+ unsent := int64(f.unsent) + int64(n)
+ // "A sender MUST NOT allow a flow-control window to exceed 2^31-1 octets."
+ // RFC 7540 Section 6.9.1.
+ const maxWindow = 1<<31 - 1
+ if unsent+int64(f.avail) > maxWindow {
+ panic("flow control update exceeds maximum window size")
+ }
+ f.unsent = int32(unsent)
+ if f.unsent < http2inflowMinRefresh && f.unsent < f.avail {
+ // If there aren't at least inflowMinRefresh bytes of window to send,
+ // and this update won't at least double the window, buffer the update for later.
+ return 0
+ }
+ f.avail += f.unsent
+ f.unsent = 0
+ return int32(unsent)
+}
+
+// take attempts to take n bytes from the peer's flow control window.
+// It reports whether the window has available capacity.
+func (f *http2inflow) take(n uint32) bool {
+ if n > uint32(f.avail) {
+ return false
+ }
+ f.avail -= int32(n)
+ return true
+}
+
+// takeInflows attempts to take n bytes from two inflows,
+// typically connection-level and stream-level flows.
+// It reports whether both windows have available capacity.
+func http2takeInflows(f1, f2 *http2inflow, n uint32) bool {
+ if n > uint32(f1.avail) || n > uint32(f2.avail) {
+ return false
+ }
+ f1.avail -= int32(n)
+ f2.avail -= int32(n)
+ return true
+}
+
+// outflow is the outbound flow control window's size.
+type http2outflow struct {
+ _ http2incomparable
+
+ // n is the number of DATA bytes we're allowed to send.
+ // An outflow is kept both on a conn and a per-stream.
+ n int32
+
+ // conn points to the shared connection-level outflow that is
+ // shared by all streams on that conn. It is nil for the outflow
+ // that's on the conn directly.
+ conn *http2outflow
+}
+
+func (f *http2outflow) setConnFlow(cf *http2outflow) { f.conn = cf }
+
+func (f *http2outflow) available() int32 {
+ n := f.n
+ if f.conn != nil && f.conn.n < n {
+ n = f.conn.n
+ }
+ return n
+}
+
+func (f *http2outflow) take(n int32) {
+ if n > f.available() {
+ panic("internal error: took too much")
+ }
+ f.n -= n
+ if f.conn != nil {
+ f.conn.n -= n
+ }
+}
+
+// add adds n bytes (positive or negative) to the flow control window.
+// It returns false if the sum would exceed 2^31-1.
+func (f *http2outflow) add(n int32) bool {
+ sum := f.n + n
+ if (sum > n) == (f.n > 0) {
+ f.n = sum
+ return true
+ }
+ return false
+}
+
+const http2frameHeaderLen = 9
+
+var http2padZeros = make([]byte, 255) // zeros for padding
+
+// A FrameType is a registered frame type as defined in
+// https://httpwg.org/specs/rfc7540.html#rfc.section.11.2
+type http2FrameType uint8
+
+const (
+ http2FrameData http2FrameType = 0x0
+ http2FrameHeaders http2FrameType = 0x1
+ http2FramePriority http2FrameType = 0x2
+ http2FrameRSTStream http2FrameType = 0x3
+ http2FrameSettings http2FrameType = 0x4
+ http2FramePushPromise http2FrameType = 0x5
+ http2FramePing http2FrameType = 0x6
+ http2FrameGoAway http2FrameType = 0x7
+ http2FrameWindowUpdate http2FrameType = 0x8
+ http2FrameContinuation http2FrameType = 0x9
+)
+
+var http2frameName = map[http2FrameType]string{
+ http2FrameData: "DATA",
+ http2FrameHeaders: "HEADERS",
+ http2FramePriority: "PRIORITY",
+ http2FrameRSTStream: "RST_STREAM",
+ http2FrameSettings: "SETTINGS",
+ http2FramePushPromise: "PUSH_PROMISE",
+ http2FramePing: "PING",
+ http2FrameGoAway: "GOAWAY",
+ http2FrameWindowUpdate: "WINDOW_UPDATE",
+ http2FrameContinuation: "CONTINUATION",
+}
+
+func (t http2FrameType) String() string {
+ if s, ok := http2frameName[t]; ok {
+ return s
+ }
+ return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
+}
+
+// Flags is a bitmask of HTTP/2 flags.
+// The meaning of flags varies depending on the frame type.
+type http2Flags uint8
+
+// Has reports whether f contains all (0 or more) flags in v.
+func (f http2Flags) Has(v http2Flags) bool {
+ return (f & v) == v
+}
+
+// Frame-specific FrameHeader flag bits.
+const (
+ // Data Frame
+ http2FlagDataEndStream http2Flags = 0x1
+ http2FlagDataPadded http2Flags = 0x8
+
+ // Headers Frame
+ http2FlagHeadersEndStream http2Flags = 0x1
+ http2FlagHeadersEndHeaders http2Flags = 0x4
+ http2FlagHeadersPadded http2Flags = 0x8
+ http2FlagHeadersPriority http2Flags = 0x20
+
+ // Settings Frame
+ http2FlagSettingsAck http2Flags = 0x1
+
+ // Ping Frame
+ http2FlagPingAck http2Flags = 0x1
+
+ // Continuation Frame
+ http2FlagContinuationEndHeaders http2Flags = 0x4
+
+ http2FlagPushPromiseEndHeaders http2Flags = 0x4
+ http2FlagPushPromisePadded http2Flags = 0x8
+)
+
+var http2flagName = map[http2FrameType]map[http2Flags]string{
+ http2FrameData: {
+ http2FlagDataEndStream: "END_STREAM",
+ http2FlagDataPadded: "PADDED",
+ },
+ http2FrameHeaders: {
+ http2FlagHeadersEndStream: "END_STREAM",
+ http2FlagHeadersEndHeaders: "END_HEADERS",
+ http2FlagHeadersPadded: "PADDED",
+ http2FlagHeadersPriority: "PRIORITY",
+ },
+ http2FrameSettings: {
+ http2FlagSettingsAck: "ACK",
+ },
+ http2FramePing: {
+ http2FlagPingAck: "ACK",
+ },
+ http2FrameContinuation: {
+ http2FlagContinuationEndHeaders: "END_HEADERS",
+ },
+ http2FramePushPromise: {
+ http2FlagPushPromiseEndHeaders: "END_HEADERS",
+ http2FlagPushPromisePadded: "PADDED",
+ },
+}
+
+// a frameParser parses a frame given its FrameHeader and payload
+// bytes. The length of payload will always equal fh.Length (which
+// might be 0).
+type http2frameParser func(fc *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error)
+
+var http2frameParsers = map[http2FrameType]http2frameParser{
+ http2FrameData: http2parseDataFrame,
+ http2FrameHeaders: http2parseHeadersFrame,
+ http2FramePriority: http2parsePriorityFrame,
+ http2FrameRSTStream: http2parseRSTStreamFrame,
+ http2FrameSettings: http2parseSettingsFrame,
+ http2FramePushPromise: http2parsePushPromise,
+ http2FramePing: http2parsePingFrame,
+ http2FrameGoAway: http2parseGoAwayFrame,
+ http2FrameWindowUpdate: http2parseWindowUpdateFrame,
+ http2FrameContinuation: http2parseContinuationFrame,
+}
+
+func http2typeFrameParser(t http2FrameType) http2frameParser {
+ if f := http2frameParsers[t]; f != nil {
+ return f
+ }
+ return http2parseUnknownFrame
+}
+
+// A FrameHeader is the 9 byte header of all HTTP/2 frames.
+//
+// See https://httpwg.org/specs/rfc7540.html#FrameHeader
+type http2FrameHeader struct {
+ valid bool // caller can access []byte fields in the Frame
+
+ // Type is the 1 byte frame type. There are ten standard frame
+ // types, but extension frame types may be written by WriteRawFrame
+ // and will be returned by ReadFrame (as UnknownFrame).
+ Type http2FrameType
+
+ // Flags are the 1 byte of 8 potential bit flags per frame.
+ // They are specific to the frame type.
+ Flags http2Flags
+
+ // Length is the length of the frame, not including the 9 byte header.
+ // The maximum size is one byte less than 16MB (uint24), but only
+ // frames up to 16KB are allowed without peer agreement.
+ Length uint32
+
+ // StreamID is which stream this frame is for. Certain frames
+ // are not stream-specific, in which case this field is 0.
+ StreamID uint32
+}
+
+// Header returns h. It exists so FrameHeaders can be embedded in other
+// specific frame types and implement the Frame interface.
+func (h http2FrameHeader) Header() http2FrameHeader { return h }
+
+func (h http2FrameHeader) String() string {
+ var buf bytes.Buffer
+ buf.WriteString("[FrameHeader ")
+ h.writeDebug(&buf)
+ buf.WriteByte(']')
+ return buf.String()
+}
+
+func (h http2FrameHeader) writeDebug(buf *bytes.Buffer) {
+ buf.WriteString(h.Type.String())
+ if h.Flags != 0 {
+ buf.WriteString(" flags=")
+ set := 0
+ for i := uint8(0); i < 8; i++ {
+ if h.Flags&(1< 1 {
+ buf.WriteByte('|')
+ }
+ name := http2flagName[h.Type][http2Flags(1<>24),
+ byte(streamID>>16),
+ byte(streamID>>8),
+ byte(streamID))
+}
+
+func (f *http2Framer) endWrite() error {
+ // Now that we know the final size, fill in the FrameHeader in
+ // the space previously reserved for it. Abuse append.
+ length := len(f.wbuf) - http2frameHeaderLen
+ if length >= (1 << 24) {
+ return http2ErrFrameTooLarge
+ }
+ _ = append(f.wbuf[:0],
+ byte(length>>16),
+ byte(length>>8),
+ byte(length))
+ if f.logWrites {
+ f.logWrite()
+ }
+
+ n, err := f.w.Write(f.wbuf)
+ if err == nil && n != len(f.wbuf) {
+ err = io.ErrShortWrite
+ }
+ return err
+}
+
+func (f *http2Framer) logWrite() {
+ if f.debugFramer == nil {
+ f.debugFramerBuf = new(bytes.Buffer)
+ f.debugFramer = http2NewFramer(nil, f.debugFramerBuf)
+ f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below
+ // Let us read anything, even if we accidentally wrote it
+ // in the wrong order:
+ f.debugFramer.AllowIllegalReads = true
+ }
+ f.debugFramerBuf.Write(f.wbuf)
+ fr, err := f.debugFramer.ReadFrame()
+ if err != nil {
+ f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
+ return
+ }
+ f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, http2summarizeFrame(fr))
+}
+
+func (f *http2Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
+
+func (f *http2Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
+
+func (f *http2Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
+
+func (f *http2Framer) writeUint32(v uint32) {
+ f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
+}
+
+const (
+ http2minMaxFrameSize = 1 << 14
+ http2maxFrameSize = 1<<24 - 1
+)
+
+// SetReuseFrames allows the Framer to reuse Frames.
+// If called on a Framer, Frames returned by calls to ReadFrame are only
+// valid until the next call to ReadFrame.
+func (fr *http2Framer) SetReuseFrames() {
+ if fr.frameCache != nil {
+ return
+ }
+ fr.frameCache = &http2frameCache{}
+}
+
+type http2frameCache struct {
+ dataFrame http2DataFrame
+}
+
+func (fc *http2frameCache) getDataFrame() *http2DataFrame {
+ if fc == nil {
+ return &http2DataFrame{}
+ }
+ return &fc.dataFrame
+}
+
+// NewFramer returns a Framer that writes frames to w and reads them from r.
+func http2NewFramer(w io.Writer, r io.Reader) *http2Framer {
+ fr := &http2Framer{
+ w: w,
+ r: r,
+ countError: func(string) {},
+ logReads: http2logFrameReads,
+ logWrites: http2logFrameWrites,
+ debugReadLoggerf: log.Printf,
+ debugWriteLoggerf: log.Printf,
+ }
+ fr.getReadBuf = func(size uint32) []byte {
+ if cap(fr.readBuf) >= int(size) {
+ return fr.readBuf[:size]
+ }
+ fr.readBuf = make([]byte, size)
+ return fr.readBuf
+ }
+ fr.SetMaxReadFrameSize(http2maxFrameSize)
+ return fr
+}
+
+// SetMaxReadFrameSize sets the maximum size of a frame
+// that will be read by a subsequent call to ReadFrame.
+// It is the caller's responsibility to advertise this
+// limit with a SETTINGS frame.
+func (fr *http2Framer) SetMaxReadFrameSize(v uint32) {
+ if v > http2maxFrameSize {
+ v = http2maxFrameSize
+ }
+ fr.maxReadSize = v
+}
+
+// ErrorDetail returns a more detailed error of the last error
+// returned by Framer.ReadFrame. For instance, if ReadFrame
+// returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
+// will say exactly what was invalid. ErrorDetail is not guaranteed
+// to return a non-nil value and like the rest of the http2 package,
+// its return value is not protected by an API compatibility promise.
+// ErrorDetail is reset after the next call to ReadFrame.
+func (fr *http2Framer) ErrorDetail() error {
+ return fr.errDetail
+}
+
+// ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
+// sends a frame that is larger than declared with SetMaxReadFrameSize.
+var http2ErrFrameTooLarge = errors.New("http2: frame too large")
+
+// terminalReadFrameError reports whether err is an unrecoverable
+// error from ReadFrame and no other frames should be read.
+func http2terminalReadFrameError(err error) bool {
+ if _, ok := err.(http2StreamError); ok {
+ return false
+ }
+ return err != nil
+}
+
+// ReadFrame reads a single frame. The returned Frame is only valid
+// until the next call to ReadFrame.
+//
+// If the frame is larger than previously set with SetMaxReadFrameSize, the
+// returned error is ErrFrameTooLarge. Other errors may be of type
+// ConnectionError, StreamError, or anything else from the underlying
+// reader.
+//
+// If ReadFrame returns an error and a non-nil Frame, the Frame's StreamID
+// indicates the stream responsible for the error.
+func (fr *http2Framer) ReadFrame() (http2Frame, error) {
+ fr.errDetail = nil
+ if fr.lastFrame != nil {
+ fr.lastFrame.invalidate()
+ }
+ fh, err := http2readFrameHeader(fr.headerBuf[:], fr.r)
+ if err != nil {
+ return nil, err
+ }
+ if fh.Length > fr.maxReadSize {
+ return nil, http2ErrFrameTooLarge
+ }
+ payload := fr.getReadBuf(fh.Length)
+ if _, err := io.ReadFull(fr.r, payload); err != nil {
+ return nil, err
+ }
+ f, err := http2typeFrameParser(fh.Type)(fr.frameCache, fh, fr.countError, payload)
+ if err != nil {
+ if ce, ok := err.(http2connError); ok {
+ return nil, fr.connError(ce.Code, ce.Reason)
+ }
+ return nil, err
+ }
+ if err := fr.checkFrameOrder(f); err != nil {
+ return nil, err
+ }
+ if fr.logReads {
+ fr.debugReadLoggerf("http2: Framer %p: read %v", fr, http2summarizeFrame(f))
+ }
+ if fh.Type == http2FrameHeaders && fr.ReadMetaHeaders != nil {
+ return fr.readMetaFrame(f.(*http2HeadersFrame))
+ }
+ return f, nil
+}
+
+// connError returns ConnectionError(code) but first
+// stashes away a public reason to the caller can optionally relay it
+// to the peer before hanging up on them. This might help others debug
+// their implementations.
+func (fr *http2Framer) connError(code http2ErrCode, reason string) error {
+ fr.errDetail = errors.New(reason)
+ return http2ConnectionError(code)
+}
+
+// checkFrameOrder reports an error if f is an invalid frame to return
+// next from ReadFrame. Mostly it checks whether HEADERS and
+// CONTINUATION frames are contiguous.
+func (fr *http2Framer) checkFrameOrder(f http2Frame) error {
+ last := fr.lastFrame
+ fr.lastFrame = f
+ if fr.AllowIllegalReads {
+ return nil
+ }
+
+ fh := f.Header()
+ if fr.lastHeaderStream != 0 {
+ if fh.Type != http2FrameContinuation {
+ return fr.connError(http2ErrCodeProtocol,
+ fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
+ fh.Type, fh.StreamID,
+ last.Header().Type, fr.lastHeaderStream))
+ }
+ if fh.StreamID != fr.lastHeaderStream {
+ return fr.connError(http2ErrCodeProtocol,
+ fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
+ fh.StreamID, fr.lastHeaderStream))
+ }
+ } else if fh.Type == http2FrameContinuation {
+ return fr.connError(http2ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
+ }
+
+ switch fh.Type {
+ case http2FrameHeaders, http2FrameContinuation:
+ if fh.Flags.Has(http2FlagHeadersEndHeaders) {
+ fr.lastHeaderStream = 0
+ } else {
+ fr.lastHeaderStream = fh.StreamID
+ }
+ }
+
+ return nil
+}
+
+// A DataFrame conveys arbitrary, variable-length sequences of octets
+// associated with a stream.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1
+type http2DataFrame struct {
+ http2FrameHeader
+ data []byte
+}
+
+func (f *http2DataFrame) StreamEnded() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagDataEndStream)
+}
+
+// Data returns the frame's data octets, not including any padding
+// size byte or padding suffix bytes.
+// The caller must not retain the returned memory past the next
+// call to ReadFrame.
+func (f *http2DataFrame) Data() []byte {
+ f.checkValid()
+ return f.data
+}
+
+func http2parseDataFrame(fc *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
+ if fh.StreamID == 0 {
+ // DATA frames MUST be associated with a stream. If a
+ // DATA frame is received whose stream identifier
+ // field is 0x0, the recipient MUST respond with a
+ // connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR.
+ countError("frame_data_stream_0")
+ return nil, http2connError{http2ErrCodeProtocol, "DATA frame with stream ID 0"}
+ }
+ f := fc.getDataFrame()
+ f.http2FrameHeader = fh
+
+ var padSize byte
+ if fh.Flags.Has(http2FlagDataPadded) {
+ var err error
+ payload, padSize, err = http2readByte(payload)
+ if err != nil {
+ countError("frame_data_pad_byte_short")
+ return nil, err
+ }
+ }
+ if int(padSize) > len(payload) {
+ // If the length of the padding is greater than the
+ // length of the frame payload, the recipient MUST
+ // treat this as a connection error.
+ // Filed: https://github.com/http2/http2-spec/issues/610
+ countError("frame_data_pad_too_big")
+ return nil, http2connError{http2ErrCodeProtocol, "pad size larger than data payload"}
+ }
+ f.data = payload[:len(payload)-int(padSize)]
+ return f, nil
+}
+
+var (
+ http2errStreamID = errors.New("invalid stream ID")
+ http2errDepStreamID = errors.New("invalid dependent stream ID")
+ http2errPadLength = errors.New("pad length too large")
+ http2errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
+)
+
+func http2validStreamIDOrZero(streamID uint32) bool {
+ return streamID&(1<<31) == 0
+}
+
+func http2validStreamID(streamID uint32) bool {
+ return streamID != 0 && streamID&(1<<31) == 0
+}
+
+// WriteData writes a DATA frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility not to violate the maximum frame size
+// and to not call other Write methods concurrently.
+func (f *http2Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
+ return f.WriteDataPadded(streamID, endStream, data, nil)
+}
+
+// WriteDataPadded writes a DATA frame with optional padding.
+//
+// If pad is nil, the padding bit is not sent.
+// The length of pad must not exceed 255 bytes.
+// The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility not to violate the maximum frame size
+// and to not call other Write methods concurrently.
+func (f *http2Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
+ if err := f.startWriteDataPadded(streamID, endStream, data, pad); err != nil {
+ return err
+ }
+ return f.endWrite()
+}
+
+// startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer.
+// The caller should call endWrite to flush the frame to the underlying writer.
+func (f *http2Framer) startWriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
+ if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ if len(pad) > 0 {
+ if len(pad) > 255 {
+ return http2errPadLength
+ }
+ if !f.AllowIllegalWrites {
+ for _, b := range pad {
+ if b != 0 {
+ // "Padding octets MUST be set to zero when sending."
+ return http2errPadBytes
+ }
+ }
+ }
+ }
+ var flags http2Flags
+ if endStream {
+ flags |= http2FlagDataEndStream
+ }
+ if pad != nil {
+ flags |= http2FlagDataPadded
+ }
+ f.startWrite(http2FrameData, flags, streamID)
+ if pad != nil {
+ f.wbuf = append(f.wbuf, byte(len(pad)))
+ }
+ f.wbuf = append(f.wbuf, data...)
+ f.wbuf = append(f.wbuf, pad...)
+ return nil
+}
+
+// A SettingsFrame conveys configuration parameters that affect how
+// endpoints communicate, such as preferences and constraints on peer
+// behavior.
+//
+// See https://httpwg.org/specs/rfc7540.html#SETTINGS
+type http2SettingsFrame struct {
+ http2FrameHeader
+ p []byte
+}
+
+func http2parseSettingsFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ if fh.Flags.Has(http2FlagSettingsAck) && fh.Length > 0 {
+ // When this (ACK 0x1) bit is set, the payload of the
+ // SETTINGS frame MUST be empty. Receipt of a
+ // SETTINGS frame with the ACK flag set and a length
+ // field value other than 0 MUST be treated as a
+ // connection error (Section 5.4.1) of type
+ // FRAME_SIZE_ERROR.
+ countError("frame_settings_ack_with_length")
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ if fh.StreamID != 0 {
+ // SETTINGS frames always apply to a connection,
+ // never a single stream. The stream identifier for a
+ // SETTINGS frame MUST be zero (0x0). If an endpoint
+ // receives a SETTINGS frame whose stream identifier
+ // field is anything other than 0x0, the endpoint MUST
+ // respond with a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR.
+ countError("frame_settings_has_stream")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ if len(p)%6 != 0 {
+ countError("frame_settings_mod_6")
+ // Expecting even number of 6 byte settings.
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ f := &http2SettingsFrame{http2FrameHeader: fh, p: p}
+ if v, ok := f.Value(http2SettingInitialWindowSize); ok && v > (1<<31)-1 {
+ countError("frame_settings_window_size_too_big")
+ // Values above the maximum flow control window size of 2^31 - 1 MUST
+ // be treated as a connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR.
+ return nil, http2ConnectionError(http2ErrCodeFlowControl)
+ }
+ return f, nil
+}
+
+func (f *http2SettingsFrame) IsAck() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagSettingsAck)
+}
+
+func (f *http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool) {
+ f.checkValid()
+ for i := 0; i < f.NumSettings(); i++ {
+ if s := f.Setting(i); s.ID == id {
+ return s.Val, true
+ }
+ }
+ return 0, false
+}
+
+// Setting returns the setting from the frame at the given 0-based index.
+// The index must be >= 0 and less than f.NumSettings().
+func (f *http2SettingsFrame) Setting(i int) http2Setting {
+ buf := f.p
+ return http2Setting{
+ ID: http2SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])),
+ Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]),
+ }
+}
+
+func (f *http2SettingsFrame) NumSettings() int { return len(f.p) / 6 }
+
+// HasDuplicates reports whether f contains any duplicate setting IDs.
+func (f *http2SettingsFrame) HasDuplicates() bool {
+ num := f.NumSettings()
+ if num == 0 {
+ return false
+ }
+ // If it's small enough (the common case), just do the n^2
+ // thing and avoid a map allocation.
+ if num < 10 {
+ for i := 0; i < num; i++ {
+ idi := f.Setting(i).ID
+ for j := i + 1; j < num; j++ {
+ idj := f.Setting(j).ID
+ if idi == idj {
+ return true
+ }
+ }
+ }
+ return false
+ }
+ seen := map[http2SettingID]bool{}
+ for i := 0; i < num; i++ {
+ id := f.Setting(i).ID
+ if seen[id] {
+ return true
+ }
+ seen[id] = true
+ }
+ return false
+}
+
+// ForeachSetting runs fn for each setting.
+// It stops and returns the first error.
+func (f *http2SettingsFrame) ForeachSetting(fn func(http2Setting) error) error {
+ f.checkValid()
+ for i := 0; i < f.NumSettings(); i++ {
+ if err := fn(f.Setting(i)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// WriteSettings writes a SETTINGS frame with zero or more settings
+// specified and the ACK bit not set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WriteSettings(settings ...http2Setting) error {
+ f.startWrite(http2FrameSettings, 0, 0)
+ for _, s := range settings {
+ f.writeUint16(uint16(s.ID))
+ f.writeUint32(s.Val)
+ }
+ return f.endWrite()
+}
+
+// WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WriteSettingsAck() error {
+ f.startWrite(http2FrameSettings, http2FlagSettingsAck, 0)
+ return f.endWrite()
+}
+
+// A PingFrame is a mechanism for measuring a minimal round trip time
+// from the sender, as well as determining whether an idle connection
+// is still functional.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.7
+type http2PingFrame struct {
+ http2FrameHeader
+ Data [8]byte
+}
+
+func (f *http2PingFrame) IsAck() bool { return f.Flags.Has(http2FlagPingAck) }
+
+func http2parsePingFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
+ if len(payload) != 8 {
+ countError("frame_ping_length")
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ if fh.StreamID != 0 {
+ countError("frame_ping_has_stream")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ f := &http2PingFrame{http2FrameHeader: fh}
+ copy(f.Data[:], payload)
+ return f, nil
+}
+
+func (f *http2Framer) WritePing(ack bool, data [8]byte) error {
+ var flags http2Flags
+ if ack {
+ flags = http2FlagPingAck
+ }
+ f.startWrite(http2FramePing, flags, 0)
+ f.writeBytes(data[:])
+ return f.endWrite()
+}
+
+// A GoAwayFrame informs the remote peer to stop creating streams on this connection.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8
+type http2GoAwayFrame struct {
+ http2FrameHeader
+ LastStreamID uint32
+ ErrCode http2ErrCode
+ debugData []byte
+}
+
+// DebugData returns any debug data in the GOAWAY frame. Its contents
+// are not defined.
+// The caller must not retain the returned memory past the next
+// call to ReadFrame.
+func (f *http2GoAwayFrame) DebugData() []byte {
+ f.checkValid()
+ return f.debugData
+}
+
+func http2parseGoAwayFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ if fh.StreamID != 0 {
+ countError("frame_goaway_has_stream")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ if len(p) < 8 {
+ countError("frame_goaway_short")
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ return &http2GoAwayFrame{
+ http2FrameHeader: fh,
+ LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
+ ErrCode: http2ErrCode(binary.BigEndian.Uint32(p[4:8])),
+ debugData: p[8:],
+ }, nil
+}
+
+func (f *http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error {
+ f.startWrite(http2FrameGoAway, 0, 0)
+ f.writeUint32(maxStreamID & (1<<31 - 1))
+ f.writeUint32(uint32(code))
+ f.writeBytes(debugData)
+ return f.endWrite()
+}
+
+// An UnknownFrame is the frame type returned when the frame type is unknown
+// or no specific frame type parser exists.
+type http2UnknownFrame struct {
+ http2FrameHeader
+ p []byte
+}
+
+// Payload returns the frame's payload (after the header). It is not
+// valid to call this method after a subsequent call to
+// Framer.ReadFrame, nor is it valid to retain the returned slice.
+// The memory is owned by the Framer and is invalidated when the next
+// frame is read.
+func (f *http2UnknownFrame) Payload() []byte {
+ f.checkValid()
+ return f.p
+}
+
+func http2parseUnknownFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ return &http2UnknownFrame{fh, p}, nil
+}
+
+// A WindowUpdateFrame is used to implement flow control.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9
+type http2WindowUpdateFrame struct {
+ http2FrameHeader
+ Increment uint32 // never read with high bit set
+}
+
+func http2parseWindowUpdateFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ if len(p) != 4 {
+ countError("frame_windowupdate_bad_len")
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
+ if inc == 0 {
+ // A receiver MUST treat the receipt of a
+ // WINDOW_UPDATE frame with an flow control window
+ // increment of 0 as a stream error (Section 5.4.2) of
+ // type PROTOCOL_ERROR; errors on the connection flow
+ // control window MUST be treated as a connection
+ // error (Section 5.4.1).
+ if fh.StreamID == 0 {
+ countError("frame_windowupdate_zero_inc_conn")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ countError("frame_windowupdate_zero_inc_stream")
+ return nil, http2streamError(fh.StreamID, http2ErrCodeProtocol)
+ }
+ return &http2WindowUpdateFrame{
+ http2FrameHeader: fh,
+ Increment: inc,
+ }, nil
+}
+
+// WriteWindowUpdate writes a WINDOW_UPDATE frame.
+// The increment value must be between 1 and 2,147,483,647, inclusive.
+// If the Stream ID is zero, the window update applies to the
+// connection as a whole.
+func (f *http2Framer) WriteWindowUpdate(streamID, incr uint32) error {
+ // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
+ if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
+ return errors.New("illegal window increment value")
+ }
+ f.startWrite(http2FrameWindowUpdate, 0, streamID)
+ f.writeUint32(incr)
+ return f.endWrite()
+}
+
+// A HeadersFrame is used to open a stream and additionally carries a
+// header block fragment.
+type http2HeadersFrame struct {
+ http2FrameHeader
+
+ // Priority is set if FlagHeadersPriority is set in the FrameHeader.
+ Priority http2PriorityParam
+
+ headerFragBuf []byte // not owned
+}
+
+func (f *http2HeadersFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *http2HeadersFrame) HeadersEnded() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagHeadersEndHeaders)
+}
+
+func (f *http2HeadersFrame) StreamEnded() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagHeadersEndStream)
+}
+
+func (f *http2HeadersFrame) HasPriority() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagHeadersPriority)
+}
+
+func http2parseHeadersFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (_ http2Frame, err error) {
+ hf := &http2HeadersFrame{
+ http2FrameHeader: fh,
+ }
+ if fh.StreamID == 0 {
+ // HEADERS frames MUST be associated with a stream. If a HEADERS frame
+ // is received whose stream identifier field is 0x0, the recipient MUST
+ // respond with a connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR.
+ countError("frame_headers_zero_stream")
+ return nil, http2connError{http2ErrCodeProtocol, "HEADERS frame with stream ID 0"}
+ }
+ var padLength uint8
+ if fh.Flags.Has(http2FlagHeadersPadded) {
+ if p, padLength, err = http2readByte(p); err != nil {
+ countError("frame_headers_pad_short")
+ return
+ }
+ }
+ if fh.Flags.Has(http2FlagHeadersPriority) {
+ var v uint32
+ p, v, err = http2readUint32(p)
+ if err != nil {
+ countError("frame_headers_prio_short")
+ return nil, err
+ }
+ hf.Priority.StreamDep = v & 0x7fffffff
+ hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
+ p, hf.Priority.Weight, err = http2readByte(p)
+ if err != nil {
+ countError("frame_headers_prio_weight_short")
+ return nil, err
+ }
+ }
+ if len(p)-int(padLength) < 0 {
+ countError("frame_headers_pad_too_big")
+ return nil, http2streamError(fh.StreamID, http2ErrCodeProtocol)
+ }
+ hf.headerFragBuf = p[:len(p)-int(padLength)]
+ return hf, nil
+}
+
+// HeadersFrameParam are the parameters for writing a HEADERS frame.
+type http2HeadersFrameParam struct {
+ // StreamID is the required Stream ID to initiate.
+ StreamID uint32
+ // BlockFragment is part (or all) of a Header Block.
+ BlockFragment []byte
+
+ // EndStream indicates that the header block is the last that
+ // the endpoint will send for the identified stream. Setting
+ // this flag causes the stream to enter one of "half closed"
+ // states.
+ EndStream bool
+
+ // EndHeaders indicates that this frame contains an entire
+ // header block and is not followed by any
+ // CONTINUATION frames.
+ EndHeaders bool
+
+ // PadLength is the optional number of bytes of zeros to add
+ // to this frame.
+ PadLength uint8
+
+ // Priority, if non-zero, includes stream priority information
+ // in the HEADER frame.
+ Priority http2PriorityParam
+}
+
+// WriteHeaders writes a single HEADERS frame.
+//
+// This is a low-level header writing method. Encoding headers and
+// splitting them into any necessary CONTINUATION frames is handled
+// elsewhere.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WriteHeaders(p http2HeadersFrameParam) error {
+ if !http2validStreamID(p.StreamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ var flags http2Flags
+ if p.PadLength != 0 {
+ flags |= http2FlagHeadersPadded
+ }
+ if p.EndStream {
+ flags |= http2FlagHeadersEndStream
+ }
+ if p.EndHeaders {
+ flags |= http2FlagHeadersEndHeaders
+ }
+ if !p.Priority.IsZero() {
+ flags |= http2FlagHeadersPriority
+ }
+ f.startWrite(http2FrameHeaders, flags, p.StreamID)
+ if p.PadLength != 0 {
+ f.writeByte(p.PadLength)
+ }
+ if !p.Priority.IsZero() {
+ v := p.Priority.StreamDep
+ if !http2validStreamIDOrZero(v) && !f.AllowIllegalWrites {
+ return http2errDepStreamID
+ }
+ if p.Priority.Exclusive {
+ v |= 1 << 31
+ }
+ f.writeUint32(v)
+ f.writeByte(p.Priority.Weight)
+ }
+ f.wbuf = append(f.wbuf, p.BlockFragment...)
+ f.wbuf = append(f.wbuf, http2padZeros[:p.PadLength]...)
+ return f.endWrite()
+}
+
+// A PriorityFrame specifies the sender-advised priority of a stream.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3
+type http2PriorityFrame struct {
+ http2FrameHeader
+ http2PriorityParam
+}
+
+// PriorityParam are the stream prioritzation parameters.
+type http2PriorityParam struct {
+ // StreamDep is a 31-bit stream identifier for the
+ // stream that this stream depends on. Zero means no
+ // dependency.
+ StreamDep uint32
+
+ // Exclusive is whether the dependency is exclusive.
+ Exclusive bool
+
+ // Weight is the stream's zero-indexed weight. It should be
+ // set together with StreamDep, or neither should be set. Per
+ // the spec, "Add one to the value to obtain a weight between
+ // 1 and 256."
+ Weight uint8
+}
+
+func (p http2PriorityParam) IsZero() bool {
+ return p == http2PriorityParam{}
+}
+
+func http2parsePriorityFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
+ if fh.StreamID == 0 {
+ countError("frame_priority_zero_stream")
+ return nil, http2connError{http2ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
+ }
+ if len(payload) != 5 {
+ countError("frame_priority_bad_length")
+ return nil, http2connError{http2ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
+ }
+ v := binary.BigEndian.Uint32(payload[:4])
+ streamID := v & 0x7fffffff // mask off high bit
+ return &http2PriorityFrame{
+ http2FrameHeader: fh,
+ http2PriorityParam: http2PriorityParam{
+ Weight: payload[4],
+ StreamDep: streamID,
+ Exclusive: streamID != v, // was high bit set?
+ },
+ }, nil
+}
+
+// WritePriority writes a PRIORITY frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WritePriority(streamID uint32, p http2PriorityParam) error {
+ if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ if !http2validStreamIDOrZero(p.StreamDep) {
+ return http2errDepStreamID
+ }
+ f.startWrite(http2FramePriority, 0, streamID)
+ v := p.StreamDep
+ if p.Exclusive {
+ v |= 1 << 31
+ }
+ f.writeUint32(v)
+ f.writeByte(p.Weight)
+ return f.endWrite()
+}
+
+// A RSTStreamFrame allows for abnormal termination of a stream.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4
+type http2RSTStreamFrame struct {
+ http2FrameHeader
+ ErrCode http2ErrCode
+}
+
+func http2parseRSTStreamFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ if len(p) != 4 {
+ countError("frame_rststream_bad_len")
+ return nil, http2ConnectionError(http2ErrCodeFrameSize)
+ }
+ if fh.StreamID == 0 {
+ countError("frame_rststream_zero_stream")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ return &http2RSTStreamFrame{fh, http2ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
+}
+
+// WriteRSTStream writes a RST_STREAM frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WriteRSTStream(streamID uint32, code http2ErrCode) error {
+ if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ f.startWrite(http2FrameRSTStream, 0, streamID)
+ f.writeUint32(uint32(code))
+ return f.endWrite()
+}
+
+// A ContinuationFrame is used to continue a sequence of header block fragments.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10
+type http2ContinuationFrame struct {
+ http2FrameHeader
+ headerFragBuf []byte
+}
+
+func http2parseContinuationFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
+ if fh.StreamID == 0 {
+ countError("frame_continuation_zero_stream")
+ return nil, http2connError{http2ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
+ }
+ return &http2ContinuationFrame{fh, p}, nil
+}
+
+func (f *http2ContinuationFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *http2ContinuationFrame) HeadersEnded() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagContinuationEndHeaders)
+}
+
+// WriteContinuation writes a CONTINUATION frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
+ if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ var flags http2Flags
+ if endHeaders {
+ flags |= http2FlagContinuationEndHeaders
+ }
+ f.startWrite(http2FrameContinuation, flags, streamID)
+ f.wbuf = append(f.wbuf, headerBlockFragment...)
+ return f.endWrite()
+}
+
+// A PushPromiseFrame is used to initiate a server stream.
+// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.6
+type http2PushPromiseFrame struct {
+ http2FrameHeader
+ PromiseID uint32
+ headerFragBuf []byte // not owned
+}
+
+func (f *http2PushPromiseFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *http2PushPromiseFrame) HeadersEnded() bool {
+ return f.http2FrameHeader.Flags.Has(http2FlagPushPromiseEndHeaders)
+}
+
+func http2parsePushPromise(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (_ http2Frame, err error) {
+ pp := &http2PushPromiseFrame{
+ http2FrameHeader: fh,
+ }
+ if pp.StreamID == 0 {
+ // PUSH_PROMISE frames MUST be associated with an existing,
+ // peer-initiated stream. The stream identifier of a
+ // PUSH_PROMISE frame indicates the stream it is associated
+ // with. If the stream identifier field specifies the value
+ // 0x0, a recipient MUST respond with a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ countError("frame_pushpromise_zero_stream")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ // The PUSH_PROMISE frame includes optional padding.
+ // Padding fields and flags are identical to those defined for DATA frames
+ var padLength uint8
+ if fh.Flags.Has(http2FlagPushPromisePadded) {
+ if p, padLength, err = http2readByte(p); err != nil {
+ countError("frame_pushpromise_pad_short")
+ return
+ }
+ }
+
+ p, pp.PromiseID, err = http2readUint32(p)
+ if err != nil {
+ countError("frame_pushpromise_promiseid_short")
+ return
+ }
+ pp.PromiseID = pp.PromiseID & (1<<31 - 1)
+
+ if int(padLength) > len(p) {
+ // like the DATA frame, error out if padding is longer than the body.
+ countError("frame_pushpromise_pad_too_big")
+ return nil, http2ConnectionError(http2ErrCodeProtocol)
+ }
+ pp.headerFragBuf = p[:len(p)-int(padLength)]
+ return pp, nil
+}
+
+// PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
+type http2PushPromiseParam struct {
+ // StreamID is the required Stream ID to initiate.
+ StreamID uint32
+
+ // PromiseID is the required Stream ID which this
+ // Push Promises
+ PromiseID uint32
+
+ // BlockFragment is part (or all) of a Header Block.
+ BlockFragment []byte
+
+ // EndHeaders indicates that this frame contains an entire
+ // header block and is not followed by any
+ // CONTINUATION frames.
+ EndHeaders bool
+
+ // PadLength is the optional number of bytes of zeros to add
+ // to this frame.
+ PadLength uint8
+}
+
+// WritePushPromise writes a single PushPromise Frame.
+//
+// As with Header Frames, This is the low level call for writing
+// individual frames. Continuation frames are handled elsewhere.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *http2Framer) WritePushPromise(p http2PushPromiseParam) error {
+ if !http2validStreamID(p.StreamID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ var flags http2Flags
+ if p.PadLength != 0 {
+ flags |= http2FlagPushPromisePadded
+ }
+ if p.EndHeaders {
+ flags |= http2FlagPushPromiseEndHeaders
+ }
+ f.startWrite(http2FramePushPromise, flags, p.StreamID)
+ if p.PadLength != 0 {
+ f.writeByte(p.PadLength)
+ }
+ if !http2validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
+ return http2errStreamID
+ }
+ f.writeUint32(p.PromiseID)
+ f.wbuf = append(f.wbuf, p.BlockFragment...)
+ f.wbuf = append(f.wbuf, http2padZeros[:p.PadLength]...)
+ return f.endWrite()
+}
+
+// WriteRawFrame writes a raw frame. This can be used to write
+// extension frames unknown to this package.
+func (f *http2Framer) WriteRawFrame(t http2FrameType, flags http2Flags, streamID uint32, payload []byte) error {
+ f.startWrite(t, flags, streamID)
+ f.writeBytes(payload)
+ return f.endWrite()
+}
+
+func http2readByte(p []byte) (remain []byte, b byte, err error) {
+ if len(p) == 0 {
+ return nil, 0, io.ErrUnexpectedEOF
+ }
+ return p[1:], p[0], nil
+}
+
+func http2readUint32(p []byte) (remain []byte, v uint32, err error) {
+ if len(p) < 4 {
+ return nil, 0, io.ErrUnexpectedEOF
+ }
+ return p[4:], binary.BigEndian.Uint32(p[:4]), nil
+}
+
+type http2streamEnder interface {
+ StreamEnded() bool
+}
+
+type http2headersEnder interface {
+ HeadersEnded() bool
+}
+
+type http2headersOrContinuation interface {
+ http2headersEnder
+ HeaderBlockFragment() []byte
+}
+
+// A MetaHeadersFrame is the representation of one HEADERS frame and
+// zero or more contiguous CONTINUATION frames and the decoding of
+// their HPACK-encoded contents.
+//
+// This type of frame does not appear on the wire and is only returned
+// by the Framer when Framer.ReadMetaHeaders is set.
+type http2MetaHeadersFrame struct {
+ *http2HeadersFrame
+
+ // Fields are the fields contained in the HEADERS and
+ // CONTINUATION frames. The underlying slice is owned by the
+ // Framer and must not be retained after the next call to
+ // ReadFrame.
+ //
+ // Fields are guaranteed to be in the correct http2 order and
+ // not have unknown pseudo header fields or invalid header
+ // field names or values. Required pseudo header fields may be
+ // missing, however. Use the MetaHeadersFrame.Pseudo accessor
+ // method access pseudo headers.
+ Fields []hpack.HeaderField
+
+ // Truncated is whether the max header list size limit was hit
+ // and Fields is incomplete. The hpack decoder state is still
+ // valid, however.
+ Truncated bool
+}
+
+// PseudoValue returns the given pseudo header field's value.
+// The provided pseudo field should not contain the leading colon.
+func (mh *http2MetaHeadersFrame) PseudoValue(pseudo string) string {
+ for _, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return ""
+ }
+ if hf.Name[1:] == pseudo {
+ return hf.Value
+ }
+ }
+ return ""
+}
+
+// RegularFields returns the regular (non-pseudo) header fields of mh.
+// The caller does not own the returned slice.
+func (mh *http2MetaHeadersFrame) RegularFields() []hpack.HeaderField {
+ for i, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return mh.Fields[i:]
+ }
+ }
+ return nil
+}
+
+// PseudoFields returns the pseudo header fields of mh.
+// The caller does not own the returned slice.
+func (mh *http2MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
+ for i, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return mh.Fields[:i]
+ }
+ }
+ return mh.Fields
+}
+
+func (mh *http2MetaHeadersFrame) checkPseudos() error {
+ var isRequest, isResponse bool
+ pf := mh.PseudoFields()
+ for i, hf := range pf {
+ switch hf.Name {
+ case ":method", ":path", ":scheme", ":authority":
+ isRequest = true
+ case ":status":
+ isResponse = true
+ default:
+ return http2pseudoHeaderError(hf.Name)
+ }
+ // Check for duplicates.
+ // This would be a bad algorithm, but N is 4.
+ // And this doesn't allocate.
+ for _, hf2 := range pf[:i] {
+ if hf.Name == hf2.Name {
+ return http2duplicatePseudoHeaderError(hf.Name)
+ }
+ }
+ }
+ if isRequest && isResponse {
+ return http2errMixPseudoHeaderTypes
+ }
+ return nil
+}
+
+func (fr *http2Framer) maxHeaderStringLen() int {
+ v := fr.maxHeaderListSize()
+ if uint32(int(v)) == v {
+ return int(v)
+ }
+ // They had a crazy big number for MaxHeaderBytes anyway,
+ // so give them unlimited header lengths:
+ return 0
+}
+
+// readMetaFrame returns 0 or more CONTINUATION frames from fr and
+// merge them into the provided hf and returns a MetaHeadersFrame
+// with the decoded hpack values.
+func (fr *http2Framer) readMetaFrame(hf *http2HeadersFrame) (http2Frame, error) {
+ if fr.AllowIllegalReads {
+ return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
+ }
+ mh := &http2MetaHeadersFrame{
+ http2HeadersFrame: hf,
+ }
+ var remainSize = fr.maxHeaderListSize()
+ var sawRegular bool
+
+ var invalid error // pseudo header field errors
+ hdec := fr.ReadMetaHeaders
+ hdec.SetEmitEnabled(true)
+ hdec.SetMaxStringLength(fr.maxHeaderStringLen())
+ hdec.SetEmitFunc(func(hf hpack.HeaderField) {
+ if http2VerboseLogs && fr.logReads {
+ fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
+ }
+ if !httpguts.ValidHeaderFieldValue(hf.Value) {
+ // Don't include the value in the error, because it may be sensitive.
+ invalid = http2headerFieldValueError(hf.Name)
+ }
+ isPseudo := strings.HasPrefix(hf.Name, ":")
+ if isPseudo {
+ if sawRegular {
+ invalid = http2errPseudoAfterRegular
+ }
+ } else {
+ sawRegular = true
+ if !http2validWireHeaderFieldName(hf.Name) {
+ invalid = http2headerFieldNameError(hf.Name)
+ }
+ }
+
+ if invalid != nil {
+ hdec.SetEmitEnabled(false)
+ return
+ }
+
+ size := hf.Size()
+ if size > remainSize {
+ hdec.SetEmitEnabled(false)
+ mh.Truncated = true
+ remainSize = 0
+ return
+ }
+ remainSize -= size
+
+ mh.Fields = append(mh.Fields, hf)
+ })
+ // Lose reference to MetaHeadersFrame:
+ defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
+
+ var hc http2headersOrContinuation = hf
+ for {
+ frag := hc.HeaderBlockFragment()
+
+ // Avoid parsing large amounts of headers that we will then discard.
+ // If the sender exceeds the max header list size by too much,
+ // skip parsing the fragment and close the connection.
+ //
+ // "Too much" is either any CONTINUATION frame after we've already
+ // exceeded the max header list size (in which case remainSize is 0),
+ // or a frame whose encoded size is more than twice the remaining
+ // header list bytes we're willing to accept.
+ if int64(len(frag)) > int64(2*remainSize) {
+ if http2VerboseLogs {
+ log.Printf("http2: header list too large")
+ }
+ // It would be nice to send a RST_STREAM before sending the GOAWAY,
+ // but the structure of the server's frame writer makes this difficult.
+ return mh, http2ConnectionError(http2ErrCodeProtocol)
+ }
+
+ // Also close the connection after any CONTINUATION frame following an
+ // invalid header, since we stop tracking the size of the headers after
+ // an invalid one.
+ if invalid != nil {
+ if http2VerboseLogs {
+ log.Printf("http2: invalid header: %v", invalid)
+ }
+ // It would be nice to send a RST_STREAM before sending the GOAWAY,
+ // but the structure of the server's frame writer makes this difficult.
+ return mh, http2ConnectionError(http2ErrCodeProtocol)
+ }
+
+ if _, err := hdec.Write(frag); err != nil {
+ return mh, http2ConnectionError(http2ErrCodeCompression)
+ }
+
+ if hc.HeadersEnded() {
+ break
+ }
+ if f, err := fr.ReadFrame(); err != nil {
+ return nil, err
+ } else {
+ hc = f.(*http2ContinuationFrame) // guaranteed by checkFrameOrder
+ }
+ }
+
+ mh.http2HeadersFrame.headerFragBuf = nil
+ mh.http2HeadersFrame.invalidate()
+
+ if err := hdec.Close(); err != nil {
+ return mh, http2ConnectionError(http2ErrCodeCompression)
+ }
+ if invalid != nil {
+ fr.errDetail = invalid
+ if http2VerboseLogs {
+ log.Printf("http2: invalid header: %v", invalid)
+ }
+ return nil, http2StreamError{mh.StreamID, http2ErrCodeProtocol, invalid}
+ }
+ if err := mh.checkPseudos(); err != nil {
+ fr.errDetail = err
+ if http2VerboseLogs {
+ log.Printf("http2: invalid pseudo headers: %v", err)
+ }
+ return nil, http2StreamError{mh.StreamID, http2ErrCodeProtocol, err}
+ }
+ return mh, nil
+}
+
+func http2summarizeFrame(f http2Frame) string {
+ var buf bytes.Buffer
+ f.Header().writeDebug(&buf)
+ switch f := f.(type) {
+ case *http2SettingsFrame:
+ n := 0
+ f.ForeachSetting(func(s http2Setting) error {
+ n++
+ if n == 1 {
+ buf.WriteString(", settings:")
+ }
+ fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
+ return nil
+ })
+ if n > 0 {
+ buf.Truncate(buf.Len() - 1) // remove trailing comma
+ }
+ case *http2DataFrame:
+ data := f.Data()
+ const max = 256
+ if len(data) > max {
+ data = data[:max]
+ }
+ fmt.Fprintf(&buf, " data=%q", data)
+ if len(f.Data()) > max {
+ fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
+ }
+ case *http2WindowUpdateFrame:
+ if f.StreamID == 0 {
+ buf.WriteString(" (conn)")
+ }
+ fmt.Fprintf(&buf, " incr=%v", f.Increment)
+ case *http2PingFrame:
+ fmt.Fprintf(&buf, " ping=%q", f.Data[:])
+ case *http2GoAwayFrame:
+ fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
+ f.LastStreamID, f.ErrCode, f.debugData)
+ case *http2RSTStreamFrame:
+ fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
+ }
+ return buf.String()
+}
+
+var http2DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1"
+
+type http2goroutineLock uint64
+
+func http2newGoroutineLock() http2goroutineLock {
+ if !http2DebugGoroutines {
+ return 0
+ }
+ return http2goroutineLock(http2curGoroutineID())
+}
+
+func (g http2goroutineLock) check() {
+ if !http2DebugGoroutines {
+ return
+ }
+ if http2curGoroutineID() != uint64(g) {
+ panic("running on the wrong goroutine")
+ }
+}
+
+func (g http2goroutineLock) checkNotOn() {
+ if !http2DebugGoroutines {
+ return
+ }
+ if http2curGoroutineID() == uint64(g) {
+ panic("running on the wrong goroutine")
+ }
+}
+
+var http2goroutineSpace = []byte("goroutine ")
+
+func http2curGoroutineID() uint64 {
+ bp := http2littleBuf.Get().(*[]byte)
+ defer http2littleBuf.Put(bp)
+ b := *bp
+ b = b[:runtime.Stack(b, false)]
+ // Parse the 4707 out of "goroutine 4707 ["
+ b = bytes.TrimPrefix(b, http2goroutineSpace)
+ i := bytes.IndexByte(b, ' ')
+ if i < 0 {
+ panic(fmt.Sprintf("No space found in %q", b))
+ }
+ b = b[:i]
+ n, err := http2parseUintBytes(b, 10, 64)
+ if err != nil {
+ panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
+ }
+ return n
+}
+
+var http2littleBuf = sync.Pool{
+ New: func() interface{} {
+ buf := make([]byte, 64)
+ return &buf
+ },
+}
+
+// parseUintBytes is like strconv.ParseUint, but using a []byte.
+func http2parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) {
+ var cutoff, maxVal uint64
+
+ if bitSize == 0 {
+ bitSize = int(strconv.IntSize)
+ }
+
+ s0 := s
+ switch {
+ case len(s) < 1:
+ err = strconv.ErrSyntax
+ goto Error
+
+ case 2 <= base && base <= 36:
+ // valid base; nothing to do
+
+ case base == 0:
+ // Look for octal, hex prefix.
+ switch {
+ case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'):
+ base = 16
+ s = s[2:]
+ if len(s) < 1 {
+ err = strconv.ErrSyntax
+ goto Error
+ }
+ case s[0] == '0':
+ base = 8
+ default:
+ base = 10
+ }
+
+ default:
+ err = errors.New("invalid base " + strconv.Itoa(base))
+ goto Error
+ }
+
+ n = 0
+ cutoff = http2cutoff64(base)
+ maxVal = 1<= base {
+ n = 0
+ err = strconv.ErrSyntax
+ goto Error
+ }
+
+ if n >= cutoff {
+ // n*base overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ goto Error
+ }
+ n *= uint64(base)
+
+ n1 := n + uint64(v)
+ if n1 < n || n1 > maxVal {
+ // n+v overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ goto Error
+ }
+ n = n1
+ }
+
+ return n, nil
+
+Error:
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+}
+
+// Return the first number n such that n*base >= 1<<64.
+func http2cutoff64(base int) uint64 {
+ if base < 2 {
+ return 0
+ }
+ return (1<<64-1)/uint64(base) + 1
+}
+
+var (
+ http2commonBuildOnce sync.Once
+ http2commonLowerHeader map[string]string // Go-Canonical-Case -> lower-case
+ http2commonCanonHeader map[string]string // lower-case -> Go-Canonical-Case
+)
+
+func http2buildCommonHeaderMapsOnce() {
+ http2commonBuildOnce.Do(http2buildCommonHeaderMaps)
+}
+
+func http2buildCommonHeaderMaps() {
+ common := []string{
+ "accept",
+ "accept-charset",
+ "accept-encoding",
+ "accept-language",
+ "accept-ranges",
+ "age",
+ "access-control-allow-credentials",
+ "access-control-allow-headers",
+ "access-control-allow-methods",
+ "access-control-allow-origin",
+ "access-control-expose-headers",
+ "access-control-max-age",
+ "access-control-request-headers",
+ "access-control-request-method",
+ "allow",
+ "authorization",
+ "cache-control",
+ "content-disposition",
+ "content-encoding",
+ "content-language",
+ "content-length",
+ "content-location",
+ "content-range",
+ "content-type",
+ "cookie",
+ "date",
+ "etag",
+ "expect",
+ "expires",
+ "from",
+ "host",
+ "if-match",
+ "if-modified-since",
+ "if-none-match",
+ "if-unmodified-since",
+ "last-modified",
+ "link",
+ "location",
+ "max-forwards",
+ "origin",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "range",
+ "referer",
+ "refresh",
+ "retry-after",
+ "server",
+ "set-cookie",
+ "strict-transport-security",
+ "trailer",
+ "transfer-encoding",
+ "user-agent",
+ "vary",
+ "via",
+ "www-authenticate",
+ "x-forwarded-for",
+ "x-forwarded-proto",
+ }
+ http2commonLowerHeader = make(map[string]string, len(common))
+ http2commonCanonHeader = make(map[string]string, len(common))
+ for _, v := range common {
+ chk := CanonicalHeaderKey(v)
+ http2commonLowerHeader[chk] = v
+ http2commonCanonHeader[v] = chk
+ }
+}
+
+func http2lowerHeader(v string) (lower string, ascii bool) {
+ http2buildCommonHeaderMapsOnce()
+ if s, ok := http2commonLowerHeader[v]; ok {
+ return s, true
+ }
+ return http2asciiToLower(v)
+}
+
+func http2canonicalHeader(v string) string {
+ http2buildCommonHeaderMapsOnce()
+ if s, ok := http2commonCanonHeader[v]; ok {
+ return s
+ }
+ return CanonicalHeaderKey(v)
+}
+
+var (
+ http2VerboseLogs bool
+ http2logFrameWrites bool
+ http2logFrameReads bool
+ http2inTests bool
+)
+
+func init() {
+ e := os.Getenv("GODEBUG")
+ if strings.Contains(e, "http2debug=1") {
+ http2VerboseLogs = true
+ }
+ if strings.Contains(e, "http2debug=2") {
+ http2VerboseLogs = true
+ http2logFrameWrites = true
+ http2logFrameReads = true
+ }
+}
+
+const (
+ // ClientPreface is the string that must be sent by new
+ // connections from clients.
+ http2ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
+
+ // SETTINGS_MAX_FRAME_SIZE default
+ // https://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2
+ http2initialMaxFrameSize = 16384
+
+ // NextProtoTLS is the NPN/ALPN protocol negotiated during
+ // HTTP/2's TLS setup.
+ http2NextProtoTLS = "h2"
+
+ // https://httpwg.org/specs/rfc7540.html#SettingValues
+ http2initialHeaderTableSize = 4096
+
+ http2initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
+
+ http2defaultMaxReadFrameSize = 1 << 20
+)
+
+var (
+ http2clientPreface = []byte(http2ClientPreface)
+)
+
+type http2streamState int
+
+// HTTP/2 stream states.
+//
+// See http://tools.ietf.org/html/rfc7540#section-5.1.
+//
+// For simplicity, the server code merges "reserved (local)" into
+// "half-closed (remote)". This is one less state transition to track.
+// The only downside is that we send PUSH_PROMISEs slightly less
+// liberally than allowable. More discussion here:
+// https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
+//
+// "reserved (remote)" is omitted since the client code does not
+// support server push.
+const (
+ http2stateIdle http2streamState = iota
+ http2stateOpen
+ http2stateHalfClosedLocal
+ http2stateHalfClosedRemote
+ http2stateClosed
+)
+
+var http2stateName = [...]string{
+ http2stateIdle: "Idle",
+ http2stateOpen: "Open",
+ http2stateHalfClosedLocal: "HalfClosedLocal",
+ http2stateHalfClosedRemote: "HalfClosedRemote",
+ http2stateClosed: "Closed",
+}
+
+func (st http2streamState) String() string {
+ return http2stateName[st]
+}
+
+// Setting is a setting parameter: which setting it is, and its value.
+type http2Setting struct {
+ // ID is which setting is being set.
+ // See https://httpwg.org/specs/rfc7540.html#SettingFormat
+ ID http2SettingID
+
+ // Val is the value.
+ Val uint32
+}
+
+func (s http2Setting) String() string {
+ return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
+}
+
+// Valid reports whether the setting is valid.
+func (s http2Setting) Valid() error {
+ // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
+ switch s.ID {
+ case http2SettingEnablePush:
+ if s.Val != 1 && s.Val != 0 {
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ case http2SettingInitialWindowSize:
+ if s.Val > 1<<31-1 {
+ return http2ConnectionError(http2ErrCodeFlowControl)
+ }
+ case http2SettingMaxFrameSize:
+ if s.Val < 16384 || s.Val > 1<<24-1 {
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ }
+ return nil
+}
+
+// A SettingID is an HTTP/2 setting as defined in
+// https://httpwg.org/specs/rfc7540.html#iana-settings
+type http2SettingID uint16
+
+const (
+ http2SettingHeaderTableSize http2SettingID = 0x1
+ http2SettingEnablePush http2SettingID = 0x2
+ http2SettingMaxConcurrentStreams http2SettingID = 0x3
+ http2SettingInitialWindowSize http2SettingID = 0x4
+ http2SettingMaxFrameSize http2SettingID = 0x5
+ http2SettingMaxHeaderListSize http2SettingID = 0x6
+)
+
+var http2settingName = map[http2SettingID]string{
+ http2SettingHeaderTableSize: "HEADER_TABLE_SIZE",
+ http2SettingEnablePush: "ENABLE_PUSH",
+ http2SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
+ http2SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
+ http2SettingMaxFrameSize: "MAX_FRAME_SIZE",
+ http2SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
+}
+
+func (s http2SettingID) String() string {
+ if v, ok := http2settingName[s]; ok {
+ return v
+ }
+ return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
+}
+
+// validWireHeaderFieldName reports whether v is a valid header field
+// name (key). See httpguts.ValidHeaderName for the base rules.
+//
+// Further, http2 says:
+//
+// "Just as in HTTP/1.x, header field names are strings of ASCII
+// characters that are compared in a case-insensitive
+// fashion. However, header field names MUST be converted to
+// lowercase prior to their encoding in HTTP/2. "
+func http2validWireHeaderFieldName(v string) bool {
+ if len(v) == 0 {
+ return false
+ }
+ for _, r := range v {
+ if !httpguts.IsTokenRune(r) {
+ return false
+ }
+ if 'A' <= r && r <= 'Z' {
+ return false
+ }
+ }
+ return true
+}
+
+func http2httpCodeString(code int) string {
+ switch code {
+ case 200:
+ return "200"
+ case 404:
+ return "404"
+ }
+ return strconv.Itoa(code)
+}
+
+// from pkg io
+type http2stringWriter interface {
+ WriteString(s string) (n int, err error)
+}
+
+// A gate lets two goroutines coordinate their activities.
+type http2gate chan struct{}
+
+func (g http2gate) Done() { g <- struct{}{} }
+
+func (g http2gate) Wait() { <-g }
+
+// A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
+type http2closeWaiter chan struct{}
+
+// Init makes a closeWaiter usable.
+// It exists because so a closeWaiter value can be placed inside a
+// larger struct and have the Mutex and Cond's memory in the same
+// allocation.
+func (cw *http2closeWaiter) Init() {
+ *cw = make(chan struct{})
+}
+
+// Close marks the closeWaiter as closed and unblocks any waiters.
+func (cw http2closeWaiter) Close() {
+ close(cw)
+}
+
+// Wait waits for the closeWaiter to become closed.
+func (cw http2closeWaiter) Wait() {
+ <-cw
+}
+
+// bufferedWriter is a buffered writer that writes to w.
+// Its buffered writer is lazily allocated as needed, to minimize
+// idle memory usage with many connections.
+type http2bufferedWriter struct {
+ _ http2incomparable
+ w io.Writer // immutable
+ bw *bufio.Writer // non-nil when data is buffered
+}
+
+func http2newBufferedWriter(w io.Writer) *http2bufferedWriter {
+ return &http2bufferedWriter{w: w}
+}
+
+// bufWriterPoolBufferSize is the size of bufio.Writer's
+// buffers created using bufWriterPool.
+//
+// TODO: pick a less arbitrary value? this is a bit under
+// (3 x typical 1500 byte MTU) at least. Other than that,
+// not much thought went into it.
+const http2bufWriterPoolBufferSize = 4 << 10
+
+var http2bufWriterPool = sync.Pool{
+ New: func() interface{} {
+ return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize)
+ },
+}
+
+func (w *http2bufferedWriter) Available() int {
+ if w.bw == nil {
+ return http2bufWriterPoolBufferSize
+ }
+ return w.bw.Available()
+}
+
+func (w *http2bufferedWriter) Write(p []byte) (n int, err error) {
+ if w.bw == nil {
+ bw := http2bufWriterPool.Get().(*bufio.Writer)
+ bw.Reset(w.w)
+ w.bw = bw
+ }
+ return w.bw.Write(p)
+}
+
+func (w *http2bufferedWriter) Flush() error {
+ bw := w.bw
+ if bw == nil {
+ return nil
+ }
+ err := bw.Flush()
+ bw.Reset(nil)
+ http2bufWriterPool.Put(bw)
+ w.bw = nil
+ return err
+}
+
+func http2mustUint31(v int32) uint32 {
+ if v < 0 || v > 2147483647 {
+ panic("out of range")
+ }
+ return uint32(v)
+}
+
+// bodyAllowedForStatus reports whether a given response status code
+// permits a body. See RFC 7230, section 3.3.
+func http2bodyAllowedForStatus(status int) bool {
+ switch {
+ case status >= 100 && status <= 199:
+ return false
+ case status == 204:
+ return false
+ case status == 304:
+ return false
+ }
+ return true
+}
+
+type http2httpError struct {
+ _ http2incomparable
+ msg string
+ timeout bool
+}
+
+func (e *http2httpError) Error() string { return e.msg }
+
+func (e *http2httpError) Timeout() bool { return e.timeout }
+
+func (e *http2httpError) Temporary() bool { return true }
+
+var http2errTimeout error = &http2httpError{msg: "http2: timeout awaiting response headers", timeout: true}
+
+type http2connectionStater interface {
+ ConnectionState() tls.ConnectionState
+}
+
+var http2sorterPool = sync.Pool{New: func() interface{} { return new(http2sorter) }}
+
+type http2sorter struct {
+ v []string // owned by sorter
+}
+
+func (s *http2sorter) Len() int { return len(s.v) }
+
+func (s *http2sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
+
+func (s *http2sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
+
+// Keys returns the sorted keys of h.
+//
+// The returned slice is only valid until s used again or returned to
+// its pool.
+func (s *http2sorter) Keys(h Header) []string {
+ keys := s.v[:0]
+ for k := range h {
+ keys = append(keys, k)
+ }
+ s.v = keys
+ sort.Sort(s)
+ return keys
+}
+
+func (s *http2sorter) SortStrings(ss []string) {
+ // Our sorter works on s.v, which sorter owns, so
+ // stash it away while we sort the user's buffer.
+ save := s.v
+ s.v = ss
+ sort.Sort(s)
+ s.v = save
+}
+
+// validPseudoPath reports whether v is a valid :path pseudo-header
+// value. It must be either:
+//
+// - a non-empty string starting with '/'
+// - the string '*', for OPTIONS requests.
+//
+// For now this is only used a quick check for deciding when to clean
+// up Opaque URLs before sending requests from the Transport.
+// See golang.org/issue/16847
+//
+// We used to enforce that the path also didn't start with "//", but
+// Google's GFE accepts such paths and Chrome sends them, so ignore
+// that part of the spec. See golang.org/issue/19103.
+func http2validPseudoPath(v string) bool {
+ return (len(v) > 0 && v[0] == '/') || v == "*"
+}
+
+// incomparable is a zero-width, non-comparable type. Adding it to a struct
+// makes that struct also non-comparable, and generally doesn't add
+// any size (as long as it's first).
+type http2incomparable [0]func()
+
+// pipe is a goroutine-safe io.Reader/io.Writer pair. It's like
+// io.Pipe except there are no PipeReader/PipeWriter halves, and the
+// underlying buffer is an interface. (io.Pipe is always unbuffered)
+type http2pipe struct {
+ mu sync.Mutex
+ c sync.Cond // c.L lazily initialized to &p.mu
+ b http2pipeBuffer // nil when done reading
+ unread int // bytes unread when done
+ err error // read error once empty. non-nil means closed.
+ breakErr error // immediate read error (caller doesn't see rest of b)
+ donec chan struct{} // closed on error
+ readFn func() // optional code to run in Read before error
+}
+
+type http2pipeBuffer interface {
+ Len() int
+ io.Writer
+ io.Reader
+}
+
+// setBuffer initializes the pipe buffer.
+// It has no effect if the pipe is already closed.
+func (p *http2pipe) setBuffer(b http2pipeBuffer) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.err != nil || p.breakErr != nil {
+ return
+ }
+ p.b = b
+}
+
+func (p *http2pipe) Len() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.b == nil {
+ return p.unread
+ }
+ return p.b.Len()
+}
+
+// Read waits until data is available and copies bytes
+// from the buffer into p.
+func (p *http2pipe) Read(d []byte) (n int, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ for {
+ if p.breakErr != nil {
+ return 0, p.breakErr
+ }
+ if p.b != nil && p.b.Len() > 0 {
+ return p.b.Read(d)
+ }
+ if p.err != nil {
+ if p.readFn != nil {
+ p.readFn() // e.g. copy trailers
+ p.readFn = nil // not sticky like p.err
+ }
+ p.b = nil
+ return 0, p.err
+ }
+ p.c.Wait()
+ }
+}
+
+var http2errClosedPipeWrite = errors.New("write on closed buffer")
+
+// Write copies bytes from p into the buffer and wakes a reader.
+// It is an error to write more data than the buffer can hold.
+func (p *http2pipe) Write(d []byte) (n int, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ defer p.c.Signal()
+ if p.err != nil || p.breakErr != nil {
+ return 0, http2errClosedPipeWrite
+ }
+ return p.b.Write(d)
+}
+
+// CloseWithError causes the next Read (waking up a current blocked
+// Read if needed) to return the provided err after all data has been
+// read.
+//
+// The error must be non-nil.
+func (p *http2pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) }
+
+// BreakWithError causes the next Read (waking up a current blocked
+// Read if needed) to return the provided err immediately, without
+// waiting for unread data.
+func (p *http2pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) }
+
+// closeWithErrorAndCode is like CloseWithError but also sets some code to run
+// in the caller's goroutine before returning the error.
+func (p *http2pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) }
+
+func (p *http2pipe) closeWithError(dst *error, err error, fn func()) {
+ if err == nil {
+ panic("err must be non-nil")
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ defer p.c.Signal()
+ if *dst != nil {
+ // Already been done.
+ return
+ }
+ p.readFn = fn
+ if dst == &p.breakErr {
+ if p.b != nil {
+ p.unread += p.b.Len()
+ }
+ p.b = nil
+ }
+ *dst = err
+ p.closeDoneLocked()
+}
+
+// requires p.mu be held.
+func (p *http2pipe) closeDoneLocked() {
+ if p.donec == nil {
+ return
+ }
+ // Close if unclosed. This isn't racy since we always
+ // hold p.mu while closing.
+ select {
+ case <-p.donec:
+ default:
+ close(p.donec)
+ }
+}
+
+// Err returns the error (if any) first set by BreakWithError or CloseWithError.
+func (p *http2pipe) Err() error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.breakErr != nil {
+ return p.breakErr
+ }
+ return p.err
+}
+
+// Done returns a channel which is closed if and when this pipe is closed
+// with CloseWithError.
+func (p *http2pipe) Done() <-chan struct{} {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.donec == nil {
+ p.donec = make(chan struct{})
+ if p.err != nil || p.breakErr != nil {
+ // Already hit an error.
+ p.closeDoneLocked()
+ }
+ }
+ return p.donec
+}
+
+const (
+ http2prefaceTimeout = 10 * time.Second
+ http2firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
+ http2handlerChunkWriteSize = 4 << 10
+ http2defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
+ http2maxQueuedControlFrames = 10000
+)
+
+var (
+ http2errClientDisconnected = errors.New("client disconnected")
+ http2errClosedBody = errors.New("body closed by handler")
+ http2errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
+ http2errStreamClosed = errors.New("http2: stream closed")
+)
+
+var http2responseWriterStatePool = sync.Pool{
+ New: func() interface{} {
+ rws := &http2responseWriterState{}
+ rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize)
+ return rws
+ },
+}
+
+// Test hooks.
+var (
+ http2testHookOnConn func()
+ http2testHookGetServerConn func(*http2serverConn)
+ http2testHookOnPanicMu *sync.Mutex // nil except in tests
+ http2testHookOnPanic func(sc *http2serverConn, panicVal interface{}) (rePanic bool)
+)
+
+// Server is an HTTP/2 server.
+type http2Server struct {
+ // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
+ // which may run at a time over all connections.
+ // Negative or zero no limit.
+ // TODO: implement
+ MaxHandlers int
+
+ // MaxConcurrentStreams optionally specifies the number of
+ // concurrent streams that each client may have open at a
+ // time. This is unrelated to the number of http.Handler goroutines
+ // which may be active globally, which is MaxHandlers.
+ // If zero, MaxConcurrentStreams defaults to at least 100, per
+ // the HTTP/2 spec's recommendations.
+ MaxConcurrentStreams uint32
+
+ // MaxDecoderHeaderTableSize optionally specifies the http2
+ // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
+ // informs the remote endpoint of the maximum size of the header compression
+ // table used to decode header blocks, in octets. If zero, the default value
+ // of 4096 is used.
+ MaxDecoderHeaderTableSize uint32
+
+ // MaxEncoderHeaderTableSize optionally specifies an upper limit for the
+ // header compression table used for encoding request headers. Received
+ // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
+ // the default value of 4096 is used.
+ MaxEncoderHeaderTableSize uint32
+
+ // MaxReadFrameSize optionally specifies the largest frame
+ // this server is willing to read. A valid value is between
+ // 16k and 16M, inclusive. If zero or otherwise invalid, a
+ // default value is used.
+ MaxReadFrameSize uint32
+
+ // PermitProhibitedCipherSuites, if true, permits the use of
+ // cipher suites prohibited by the HTTP/2 spec.
+ PermitProhibitedCipherSuites bool
+
+ // IdleTimeout specifies how long until idle clients should be
+ // closed with a GOAWAY frame. PING frames are not considered
+ // activity for the purposes of IdleTimeout.
+ IdleTimeout time.Duration
+
+ // MaxUploadBufferPerConnection is the size of the initial flow
+ // control window for each connections. The HTTP/2 spec does not
+ // allow this to be smaller than 65535 or larger than 2^32-1.
+ // If the value is outside this range, a default value will be
+ // used instead.
+ MaxUploadBufferPerConnection int32
+
+ // MaxUploadBufferPerStream is the size of the initial flow control
+ // window for each stream. The HTTP/2 spec does not allow this to
+ // be larger than 2^32-1. If the value is zero or larger than the
+ // maximum, a default value will be used instead.
+ MaxUploadBufferPerStream int32
+
+ // NewWriteScheduler constructs a write scheduler for a connection.
+ // If nil, a default scheduler is chosen.
+ NewWriteScheduler func() http2WriteScheduler
+
+ // CountError, if non-nil, is called on HTTP/2 server errors.
+ // It's intended to increment a metric for monitoring, such
+ // as an expvar or Prometheus metric.
+ // The errType consists of only ASCII word characters.
+ CountError func(errType string)
+
+ // Internal state. This is a pointer (rather than embedded directly)
+ // so that we don't embed a Mutex in this struct, which will make the
+ // struct non-copyable, which might break some callers.
+ state *http2serverInternalState
+}
+
+func (s *http2Server) initialConnRecvWindowSize() int32 {
+ if s.MaxUploadBufferPerConnection >= http2initialWindowSize {
+ return s.MaxUploadBufferPerConnection
+ }
+ return 1 << 20
+}
+
+func (s *http2Server) initialStreamRecvWindowSize() int32 {
+ if s.MaxUploadBufferPerStream > 0 {
+ return s.MaxUploadBufferPerStream
+ }
+ return 1 << 20
+}
+
+func (s *http2Server) maxReadFrameSize() uint32 {
+ if v := s.MaxReadFrameSize; v >= http2minMaxFrameSize && v <= http2maxFrameSize {
+ return v
+ }
+ return http2defaultMaxReadFrameSize
+}
+
+func (s *http2Server) maxConcurrentStreams() uint32 {
+ if v := s.MaxConcurrentStreams; v > 0 {
+ return v
+ }
+ return http2defaultMaxStreams
+}
+
+func (s *http2Server) maxDecoderHeaderTableSize() uint32 {
+ if v := s.MaxDecoderHeaderTableSize; v > 0 {
+ return v
+ }
+ return http2initialHeaderTableSize
+}
+
+func (s *http2Server) maxEncoderHeaderTableSize() uint32 {
+ if v := s.MaxEncoderHeaderTableSize; v > 0 {
+ return v
+ }
+ return http2initialHeaderTableSize
+}
+
+// maxQueuedControlFrames is the maximum number of control frames like
+// SETTINGS, PING and RST_STREAM that will be queued for writing before
+// the connection is closed to prevent memory exhaustion attacks.
+func (s *http2Server) maxQueuedControlFrames() int {
+ // TODO: if anybody asks, add a Server field, and remember to define the
+ // behavior of negative values.
+ return http2maxQueuedControlFrames
+}
+
+type http2serverInternalState struct {
+ mu sync.Mutex
+ activeConns map[*http2serverConn]struct{}
+}
+
+func (s *http2serverInternalState) registerConn(sc *http2serverConn) {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ s.activeConns[sc] = struct{}{}
+ s.mu.Unlock()
+}
+
+func (s *http2serverInternalState) unregisterConn(sc *http2serverConn) {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ delete(s.activeConns, sc)
+ s.mu.Unlock()
+}
+
+func (s *http2serverInternalState) startGracefulShutdown() {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ for sc := range s.activeConns {
+ sc.startGracefulShutdown()
+ }
+ s.mu.Unlock()
+}
+
+// ConfigureServer adds HTTP/2 support to a net/http Server.
+//
+// The configuration conf may be nil.
+//
+// ConfigureServer must be called before s begins serving.
+func http2ConfigureServer(s *Server, conf *http2Server) error {
+ if s == nil {
+ panic("nil *http.Server")
+ }
+ if conf == nil {
+ conf = new(http2Server)
+ }
+ conf.state = &http2serverInternalState{activeConns: make(map[*http2serverConn]struct{})}
+ if h1, h2 := s, conf; h2.IdleTimeout == 0 {
+ if h1.IdleTimeout != 0 {
+ h2.IdleTimeout = h1.IdleTimeout
+ } else {
+ h2.IdleTimeout = h1.ReadTimeout
+ }
+ }
+ s.RegisterOnShutdown(conf.state.startGracefulShutdown)
+
+ if s.TLSConfig == nil {
+ s.TLSConfig = new(tls.Config)
+ } else if s.TLSConfig.CipherSuites != nil && s.TLSConfig.MinVersion < tls.VersionTLS13 {
+ // If they already provided a TLS 1.0–1.2 CipherSuite list, return an
+ // error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or
+ // ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
+ haveRequired := false
+ for _, cs := range s.TLSConfig.CipherSuites {
+ switch cs {
+ case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+ // Alternative MTI cipher to not discourage ECDSA-only servers.
+ // See http://golang.org/cl/30721 for further information.
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
+ haveRequired = true
+ }
+ }
+ if !haveRequired {
+ return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
+ }
+ }
+
+ // Note: not setting MinVersion to tls.VersionTLS12,
+ // as we don't want to interfere with HTTP/1.1 traffic
+ // on the user's server. We enforce TLS 1.2 later once
+ // we accept a connection. Ideally this should be done
+ // during next-proto selection, but using TLS <1.2 with
+ // HTTP/2 is still the client's bug.
+
+ s.TLSConfig.PreferServerCipherSuites = true
+
+ if !http2strSliceContains(s.TLSConfig.NextProtos, http2NextProtoTLS) {
+ s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, http2NextProtoTLS)
+ }
+ if !http2strSliceContains(s.TLSConfig.NextProtos, "http/1.1") {
+ s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1")
+ }
+
+ if s.TLSNextProto == nil {
+ s.TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){}
+ }
+ protoHandler := func(hs *Server, c *tls.Conn, h Handler) {
+ if http2testHookOnConn != nil {
+ http2testHookOnConn()
+ }
+ // The TLSNextProto interface predates contexts, so
+ // the net/http package passes down its per-connection
+ // base context via an exported but unadvertised
+ // method on the Handler. This is for internal
+ // net/http<=>http2 use only.
+ var ctx context.Context
+ type baseContexter interface {
+ BaseContext() context.Context
+ }
+ if bc, ok := h.(baseContexter); ok {
+ ctx = bc.BaseContext()
+ }
+ conf.ServeConn(c, &http2ServeConnOpts{
+ Context: ctx,
+ Handler: h,
+ BaseConfig: hs,
+ })
+ }
+ s.TLSNextProto[http2NextProtoTLS] = protoHandler
+ return nil
+}
+
+// ServeConnOpts are options for the Server.ServeConn method.
+type http2ServeConnOpts struct {
+ // Context is the base context to use.
+ // If nil, context.Background is used.
+ Context context.Context
+
+ // BaseConfig optionally sets the base configuration
+ // for values. If nil, defaults are used.
+ BaseConfig *Server
+
+ // Handler specifies which handler to use for processing
+ // requests. If nil, BaseConfig.Handler is used. If BaseConfig
+ // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
+ Handler Handler
+
+ // UpgradeRequest is an initial request received on a connection
+ // undergoing an h2c upgrade. The request body must have been
+ // completely read from the connection before calling ServeConn,
+ // and the 101 Switching Protocols response written.
+ UpgradeRequest *Request
+
+ // Settings is the decoded contents of the HTTP2-Settings header
+ // in an h2c upgrade request.
+ Settings []byte
+
+ // SawClientPreface is set if the HTTP/2 connection preface
+ // has already been read from the connection.
+ SawClientPreface bool
+}
+
+func (o *http2ServeConnOpts) context() context.Context {
+ if o != nil && o.Context != nil {
+ return o.Context
+ }
+ return context.Background()
+}
+
+func (o *http2ServeConnOpts) baseConfig() *Server {
+ if o != nil && o.BaseConfig != nil {
+ return o.BaseConfig
+ }
+ return new(Server)
+}
+
+func (o *http2ServeConnOpts) handler() Handler {
+ if o != nil {
+ if o.Handler != nil {
+ return o.Handler
+ }
+ if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
+ return o.BaseConfig.Handler
+ }
+ }
+ return DefaultServeMux
+}
+
+// ServeConn serves HTTP/2 requests on the provided connection and
+// blocks until the connection is no longer readable.
+//
+// ServeConn starts speaking HTTP/2 assuming that c has not had any
+// reads or writes. It writes its initial settings frame and expects
+// to be able to read the preface and settings frame from the
+// client. If c has a ConnectionState method like a *tls.Conn, the
+// ConnectionState is used to verify the TLS ciphersuite and to set
+// the Request.TLS field in Handlers.
+//
+// ServeConn does not support h2c by itself. Any h2c support must be
+// implemented in terms of providing a suitably-behaving net.Conn.
+//
+// The opts parameter is optional. If nil, default values are used.
+func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts) {
+ baseCtx, cancel := http2serverConnBaseContext(c, opts)
+ defer cancel()
+
+ sc := &http2serverConn{
+ srv: s,
+ hs: opts.baseConfig(),
+ conn: c,
+ baseCtx: baseCtx,
+ remoteAddrStr: c.RemoteAddr().String(),
+ bw: http2newBufferedWriter(c),
+ handler: opts.handler(),
+ streams: make(map[uint32]*http2stream),
+ readFrameCh: make(chan http2readFrameResult),
+ wantWriteFrameCh: make(chan http2FrameWriteRequest, 8),
+ serveMsgCh: make(chan interface{}, 8),
+ wroteFrameCh: make(chan http2frameWriteResult, 1), // buffered; one send in writeFrameAsync
+ bodyReadCh: make(chan http2bodyReadMsg), // buffering doesn't matter either way
+ doneServing: make(chan struct{}),
+ clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
+ advMaxStreams: s.maxConcurrentStreams(),
+ initialStreamSendWindowSize: http2initialWindowSize,
+ maxFrameSize: http2initialMaxFrameSize,
+ serveG: http2newGoroutineLock(),
+ pushEnabled: true,
+ sawClientPreface: opts.SawClientPreface,
+ }
+
+ s.state.registerConn(sc)
+ defer s.state.unregisterConn(sc)
+
+ // The net/http package sets the write deadline from the
+ // http.Server.WriteTimeout during the TLS handshake, but then
+ // passes the connection off to us with the deadline already set.
+ // Write deadlines are set per stream in serverConn.newStream.
+ // Disarm the net.Conn write deadline here.
+ if sc.hs.WriteTimeout != 0 {
+ sc.conn.SetWriteDeadline(time.Time{})
+ }
+
+ if s.NewWriteScheduler != nil {
+ sc.writeSched = s.NewWriteScheduler()
+ } else {
+ sc.writeSched = http2newRoundRobinWriteScheduler()
+ }
+
+ // These start at the RFC-specified defaults. If there is a higher
+ // configured value for inflow, that will be updated when we send a
+ // WINDOW_UPDATE shortly after sending SETTINGS.
+ sc.flow.add(http2initialWindowSize)
+ sc.inflow.init(http2initialWindowSize)
+ sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
+ sc.hpackEncoder.SetMaxDynamicTableSizeLimit(s.maxEncoderHeaderTableSize())
+
+ fr := http2NewFramer(sc.bw, c)
+ if s.CountError != nil {
+ fr.countError = s.CountError
+ }
+ fr.ReadMetaHeaders = hpack.NewDecoder(s.maxDecoderHeaderTableSize(), nil)
+ fr.MaxHeaderListSize = sc.maxHeaderListSize()
+ fr.SetMaxReadFrameSize(s.maxReadFrameSize())
+ sc.framer = fr
+
+ if tc, ok := c.(http2connectionStater); ok {
+ sc.tlsState = new(tls.ConnectionState)
+ *sc.tlsState = tc.ConnectionState()
+ // 9.2 Use of TLS Features
+ // An implementation of HTTP/2 over TLS MUST use TLS
+ // 1.2 or higher with the restrictions on feature set
+ // and cipher suite described in this section. Due to
+ // implementation limitations, it might not be
+ // possible to fail TLS negotiation. An endpoint MUST
+ // immediately terminate an HTTP/2 connection that
+ // does not meet the TLS requirements described in
+ // this section with a connection error (Section
+ // 5.4.1) of type INADEQUATE_SECURITY.
+ if sc.tlsState.Version < tls.VersionTLS12 {
+ sc.rejectConn(http2ErrCodeInadequateSecurity, "TLS version too low")
+ return
+ }
+
+ if sc.tlsState.ServerName == "" {
+ // Client must use SNI, but we don't enforce that anymore,
+ // since it was causing problems when connecting to bare IP
+ // addresses during development.
+ //
+ // TODO: optionally enforce? Or enforce at the time we receive
+ // a new request, and verify the ServerName matches the :authority?
+ // But that precludes proxy situations, perhaps.
+ //
+ // So for now, do nothing here again.
+ }
+
+ if !s.PermitProhibitedCipherSuites && http2isBadCipher(sc.tlsState.CipherSuite) {
+ // "Endpoints MAY choose to generate a connection error
+ // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
+ // the prohibited cipher suites are negotiated."
+ //
+ // We choose that. In my opinion, the spec is weak
+ // here. It also says both parties must support at least
+ // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
+ // excuses here. If we really must, we could allow an
+ // "AllowInsecureWeakCiphers" option on the server later.
+ // Let's see how it plays out first.
+ sc.rejectConn(http2ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
+ return
+ }
+ }
+
+ if opts.Settings != nil {
+ fr := &http2SettingsFrame{
+ http2FrameHeader: http2FrameHeader{valid: true},
+ p: opts.Settings,
+ }
+ if err := fr.ForeachSetting(sc.processSetting); err != nil {
+ sc.rejectConn(http2ErrCodeProtocol, "invalid settings")
+ return
+ }
+ opts.Settings = nil
+ }
+
+ if hook := http2testHookGetServerConn; hook != nil {
+ hook(sc)
+ }
+
+ if opts.UpgradeRequest != nil {
+ sc.upgradeRequest(opts.UpgradeRequest)
+ opts.UpgradeRequest = nil
+ }
+
+ sc.serve()
+}
+
+func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func()) {
+ ctx, cancel = context.WithCancel(opts.context())
+ ctx = context.WithValue(ctx, LocalAddrContextKey, c.LocalAddr())
+ if hs := opts.baseConfig(); hs != nil {
+ ctx = context.WithValue(ctx, ServerContextKey, hs)
+ }
+ return
+}
+
+func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string) {
+ sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
+ // ignoring errors. hanging up anyway.
+ sc.framer.WriteGoAway(0, err, []byte(debug))
+ sc.bw.Flush()
+ sc.conn.Close()
+}
+
+type http2serverConn struct {
+ // Immutable:
+ srv *http2Server
+ hs *Server
+ conn net.Conn
+ bw *http2bufferedWriter // writing to conn
+ handler Handler
+ baseCtx context.Context
+ framer *http2Framer
+ doneServing chan struct{} // closed when serverConn.serve ends
+ readFrameCh chan http2readFrameResult // written by serverConn.readFrames
+ wantWriteFrameCh chan http2FrameWriteRequest // from handlers -> serve
+ wroteFrameCh chan http2frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
+ bodyReadCh chan http2bodyReadMsg // from handlers -> serve
+ serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop
+ flow http2outflow // conn-wide (not stream-specific) outbound flow control
+ inflow http2inflow // conn-wide inbound flow control
+ tlsState *tls.ConnectionState // shared by all handlers, like net/http
+ remoteAddrStr string
+ writeSched http2WriteScheduler
+
+ // Everything following is owned by the serve loop; use serveG.check():
+ serveG http2goroutineLock // used to verify funcs are on serve()
+ pushEnabled bool
+ sawClientPreface bool // preface has already been read, used in h2c upgrade
+ sawFirstSettings bool // got the initial SETTINGS frame after the preface
+ needToSendSettingsAck bool
+ unackedSettings int // how many SETTINGS have we sent without ACKs?
+ queuedControlFrames int // control frames in the writeSched queue
+ clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
+ advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
+ curClientStreams uint32 // number of open streams initiated by the client
+ curPushedStreams uint32 // number of open streams initiated by server push
+ curHandlers uint32 // number of running handler goroutines
+ maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests
+ maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
+ streams map[uint32]*http2stream
+ unstartedHandlers []http2unstartedHandler
+ initialStreamSendWindowSize int32
+ maxFrameSize int32
+ peerMaxHeaderListSize uint32 // zero means unknown (default)
+ canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
+ canonHeaderKeysSize int // canonHeader keys size in bytes
+ writingFrame bool // started writing a frame (on serve goroutine or separate)
+ writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
+ needsFrameFlush bool // last frame write wasn't a flush
+ inGoAway bool // we've started to or sent GOAWAY
+ inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
+ needToSendGoAway bool // we need to schedule a GOAWAY frame write
+ goAwayCode http2ErrCode
+ shutdownTimer *time.Timer // nil until used
+ idleTimer *time.Timer // nil if unused
+
+ // Owned by the writeFrameAsync goroutine:
+ headerWriteBuf bytes.Buffer
+ hpackEncoder *hpack.Encoder
+
+ // Used by startGracefulShutdown.
+ shutdownOnce sync.Once
+}
+
+func (sc *http2serverConn) maxHeaderListSize() uint32 {
+ n := sc.hs.MaxHeaderBytes
+ if n <= 0 {
+ n = DefaultMaxHeaderBytes
+ }
+ // http2's count is in a slightly different unit and includes 32 bytes per pair.
+ // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
+ const perFieldOverhead = 32 // per http2 spec
+ const typicalHeaders = 10 // conservative
+ return uint32(n + typicalHeaders*perFieldOverhead)
+}
+
+func (sc *http2serverConn) curOpenStreams() uint32 {
+ sc.serveG.check()
+ return sc.curClientStreams + sc.curPushedStreams
+}
+
+// stream represents a stream. This is the minimal metadata needed by
+// the serve goroutine. Most of the actual stream state is owned by
+// the http.Handler's goroutine in the responseWriter. Because the
+// responseWriter's responseWriterState is recycled at the end of a
+// handler, this struct intentionally has no pointer to the
+// *responseWriter{,State} itself, as the Handler ending nils out the
+// responseWriter's state field.
+type http2stream struct {
+ // immutable:
+ sc *http2serverConn
+ id uint32
+ body *http2pipe // non-nil if expecting DATA frames
+ cw http2closeWaiter // closed wait stream transitions to closed state
+ ctx context.Context
+ cancelCtx func()
+
+ // owned by serverConn's serve loop:
+ bodyBytes int64 // body bytes seen so far
+ declBodyBytes int64 // or -1 if undeclared
+ flow http2outflow // limits writing from Handler to client
+ inflow http2inflow // what the client is allowed to POST/etc to us
+ state http2streamState
+ resetQueued bool // RST_STREAM queued for write; set by sc.resetStream
+ gotTrailerHeader bool // HEADER frame for trailers was seen
+ wroteHeaders bool // whether we wrote headers (not status 100)
+ readDeadline *time.Timer // nil if unused
+ writeDeadline *time.Timer // nil if unused
+ closeErr error // set before cw is closed
+
+ trailer Header // accumulated trailers
+ reqTrailer Header // handler's Request.Trailer
+}
+
+func (sc *http2serverConn) Framer() *http2Framer { return sc.framer }
+
+func (sc *http2serverConn) CloseConn() error { return sc.conn.Close() }
+
+func (sc *http2serverConn) Flush() error { return sc.bw.Flush() }
+
+func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
+ return sc.hpackEncoder, &sc.headerWriteBuf
+}
+
+func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream) {
+ sc.serveG.check()
+ // http://tools.ietf.org/html/rfc7540#section-5.1
+ if st, ok := sc.streams[streamID]; ok {
+ return st.state, st
+ }
+ // "The first use of a new stream identifier implicitly closes all
+ // streams in the "idle" state that might have been initiated by
+ // that peer with a lower-valued stream identifier. For example, if
+ // a client sends a HEADERS frame on stream 7 without ever sending a
+ // frame on stream 5, then stream 5 transitions to the "closed"
+ // state when the first frame for stream 7 is sent or received."
+ if streamID%2 == 1 {
+ if streamID <= sc.maxClientStreamID {
+ return http2stateClosed, nil
+ }
+ } else {
+ if streamID <= sc.maxPushPromiseID {
+ return http2stateClosed, nil
+ }
+ }
+ return http2stateIdle, nil
+}
+
+// setConnState calls the net/http ConnState hook for this connection, if configured.
+// Note that the net/http package does StateNew and StateClosed for us.
+// There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
+func (sc *http2serverConn) setConnState(state ConnState) {
+ if sc.hs.ConnState != nil {
+ sc.hs.ConnState(sc.conn, state)
+ }
+}
+
+func (sc *http2serverConn) vlogf(format string, args ...interface{}) {
+ if http2VerboseLogs {
+ sc.logf(format, args...)
+ }
+}
+
+func (sc *http2serverConn) logf(format string, args ...interface{}) {
+ if lg := sc.hs.ErrorLog; lg != nil {
+ lg.Printf(format, args...)
+ } else {
+ log.Printf(format, args...)
+ }
+}
+
+// errno returns v's underlying uintptr, else 0.
+//
+// TODO: remove this helper function once http2 can use build
+// tags. See comment in isClosedConnError.
+func http2errno(v error) uintptr {
+ if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
+ return uintptr(rv.Uint())
+ }
+ return 0
+}
+
+// isClosedConnError reports whether err is an error from use of a closed
+// network connection.
+func http2isClosedConnError(err error) bool {
+ if err == nil {
+ return false
+ }
+
+ // TODO: remove this string search and be more like the Windows
+ // case below. That might involve modifying the standard library
+ // to return better error types.
+ str := err.Error()
+ if strings.Contains(str, "use of closed network connection") {
+ return true
+ }
+
+ // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
+ // build tags, so I can't make an http2_windows.go file with
+ // Windows-specific stuff. Fix that and move this, once we
+ // have a way to bundle this into std's net/http somehow.
+ if runtime.GOOS == "windows" {
+ if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
+ if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
+ const WSAECONNABORTED = 10053
+ const WSAECONNRESET = 10054
+ if n := http2errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (sc *http2serverConn) condlogf(err error, format string, args ...interface{}) {
+ if err == nil {
+ return
+ }
+ if err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err) || err == http2errPrefaceTimeout {
+ // Boring, expected errors.
+ sc.vlogf(format, args...)
+ } else {
+ sc.logf(format, args...)
+ }
+}
+
+// maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
+// of the entries in the canonHeader cache.
+// This should be larger than the size of unique, uncommon header keys likely to
+// be sent by the peer, while not so high as to permit unreasonable memory usage
+// if the peer sends an unbounded number of unique header keys.
+const http2maxCachedCanonicalHeadersKeysSize = 2048
+
+func (sc *http2serverConn) canonicalHeader(v string) string {
+ sc.serveG.check()
+ http2buildCommonHeaderMapsOnce()
+ cv, ok := http2commonCanonHeader[v]
+ if ok {
+ return cv
+ }
+ cv, ok = sc.canonHeader[v]
+ if ok {
+ return cv
+ }
+ if sc.canonHeader == nil {
+ sc.canonHeader = make(map[string]string)
+ }
+ cv = CanonicalHeaderKey(v)
+ size := 100 + len(v)*2 // 100 bytes of map overhead + key + value
+ if sc.canonHeaderKeysSize+size <= http2maxCachedCanonicalHeadersKeysSize {
+ sc.canonHeader[v] = cv
+ sc.canonHeaderKeysSize += size
+ }
+ return cv
+}
+
+type http2readFrameResult struct {
+ f http2Frame // valid until readMore is called
+ err error
+
+ // readMore should be called once the consumer no longer needs or
+ // retains f. After readMore, f is invalid and more frames can be
+ // read.
+ readMore func()
+}
+
+// readFrames is the loop that reads incoming frames.
+// It takes care to only read one frame at a time, blocking until the
+// consumer is done with the frame.
+// It's run on its own goroutine.
+func (sc *http2serverConn) readFrames() {
+ gate := make(http2gate)
+ gateDone := gate.Done
+ for {
+ f, err := sc.framer.ReadFrame()
+ select {
+ case sc.readFrameCh <- http2readFrameResult{f, err, gateDone}:
+ case <-sc.doneServing:
+ return
+ }
+ select {
+ case <-gate:
+ case <-sc.doneServing:
+ return
+ }
+ if http2terminalReadFrameError(err) {
+ return
+ }
+ }
+}
+
+// frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
+type http2frameWriteResult struct {
+ _ http2incomparable
+ wr http2FrameWriteRequest // what was written (or attempted)
+ err error // result of the writeFrame call
+}
+
+// writeFrameAsync runs in its own goroutine and writes a single frame
+// and then reports when it's done.
+// At most one goroutine can be running writeFrameAsync at a time per
+// serverConn.
+func (sc *http2serverConn) writeFrameAsync(wr http2FrameWriteRequest, wd *http2writeData) {
+ var err error
+ if wd == nil {
+ err = wr.write.writeFrame(sc)
+ } else {
+ err = sc.framer.endWrite()
+ }
+ sc.wroteFrameCh <- http2frameWriteResult{wr: wr, err: err}
+}
+
+func (sc *http2serverConn) closeAllStreamsOnConnClose() {
+ sc.serveG.check()
+ for _, st := range sc.streams {
+ sc.closeStream(st, http2errClientDisconnected)
+ }
+}
+
+func (sc *http2serverConn) stopShutdownTimer() {
+ sc.serveG.check()
+ if t := sc.shutdownTimer; t != nil {
+ t.Stop()
+ }
+}
+
+func (sc *http2serverConn) notePanic() {
+ // Note: this is for serverConn.serve panicking, not http.Handler code.
+ if http2testHookOnPanicMu != nil {
+ http2testHookOnPanicMu.Lock()
+ defer http2testHookOnPanicMu.Unlock()
+ }
+ if http2testHookOnPanic != nil {
+ if e := recover(); e != nil {
+ if http2testHookOnPanic(sc, e) {
+ panic(e)
+ }
+ }
+ }
+}
+
+func (sc *http2serverConn) serve() {
+ sc.serveG.check()
+ defer sc.notePanic()
+ defer sc.conn.Close()
+ defer sc.closeAllStreamsOnConnClose()
+ defer sc.stopShutdownTimer()
+ defer close(sc.doneServing) // unblocks handlers trying to send
+
+ if http2VerboseLogs {
+ sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
+ }
+
+ sc.writeFrame(http2FrameWriteRequest{
+ write: http2writeSettings{
+ {http2SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
+ {http2SettingMaxConcurrentStreams, sc.advMaxStreams},
+ {http2SettingMaxHeaderListSize, sc.maxHeaderListSize()},
+ {http2SettingHeaderTableSize, sc.srv.maxDecoderHeaderTableSize()},
+ {http2SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
+ },
+ })
+ sc.unackedSettings++
+
+ // Each connection starts with initialWindowSize inflow tokens.
+ // If a higher value is configured, we add more tokens.
+ if diff := sc.srv.initialConnRecvWindowSize() - http2initialWindowSize; diff > 0 {
+ sc.sendWindowUpdate(nil, int(diff))
+ }
+
+ if err := sc.readPreface(); err != nil {
+ sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
+ return
+ }
+ // Now that we've got the preface, get us out of the
+ // "StateNew" state. We can't go directly to idle, though.
+ // Active means we read some data and anticipate a request. We'll
+ // do another Active when we get a HEADERS frame.
+ sc.setConnState(StateActive)
+ sc.setConnState(StateIdle)
+
+ if sc.srv.IdleTimeout != 0 {
+ sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
+ defer sc.idleTimer.Stop()
+ }
+
+ go sc.readFrames() // closed by defer sc.conn.Close above
+
+ settingsTimer := time.AfterFunc(http2firstSettingsTimeout, sc.onSettingsTimer)
+ defer settingsTimer.Stop()
+
+ loopNum := 0
+ for {
+ loopNum++
+ select {
+ case wr := <-sc.wantWriteFrameCh:
+ if se, ok := wr.write.(http2StreamError); ok {
+ sc.resetStream(se)
+ break
+ }
+ sc.writeFrame(wr)
+ case res := <-sc.wroteFrameCh:
+ sc.wroteFrame(res)
+ case res := <-sc.readFrameCh:
+ // Process any written frames before reading new frames from the client since a
+ // written frame could have triggered a new stream to be started.
+ if sc.writingFrameAsync {
+ select {
+ case wroteRes := <-sc.wroteFrameCh:
+ sc.wroteFrame(wroteRes)
+ default:
+ }
+ }
+ if !sc.processFrameFromReader(res) {
+ return
+ }
+ res.readMore()
+ if settingsTimer != nil {
+ settingsTimer.Stop()
+ settingsTimer = nil
+ }
+ case m := <-sc.bodyReadCh:
+ sc.noteBodyRead(m.st, m.n)
+ case msg := <-sc.serveMsgCh:
+ switch v := msg.(type) {
+ case func(int):
+ v(loopNum) // for testing
+ case *http2serverMessage:
+ switch v {
+ case http2settingsTimerMsg:
+ sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
+ return
+ case http2idleTimerMsg:
+ sc.vlogf("connection is idle")
+ sc.goAway(http2ErrCodeNo)
+ case http2shutdownTimerMsg:
+ sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
+ return
+ case http2gracefulShutdownMsg:
+ sc.startGracefulShutdownInternal()
+ case http2handlerDoneMsg:
+ sc.handlerDone()
+ default:
+ panic("unknown timer")
+ }
+ case *http2startPushRequest:
+ sc.startPush(v)
+ case func(*http2serverConn):
+ v(sc)
+ default:
+ panic(fmt.Sprintf("unexpected type %T", v))
+ }
+ }
+
+ // If the peer is causing us to generate a lot of control frames,
+ // but not reading them from us, assume they are trying to make us
+ // run out of memory.
+ if sc.queuedControlFrames > sc.srv.maxQueuedControlFrames() {
+ sc.vlogf("http2: too many control frames in send queue, closing connection")
+ return
+ }
+
+ // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
+ // with no error code (graceful shutdown), don't start the timer until
+ // all open streams have been completed.
+ sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
+ gracefulShutdownComplete := sc.goAwayCode == http2ErrCodeNo && sc.curOpenStreams() == 0
+ if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != http2ErrCodeNo || gracefulShutdownComplete) {
+ sc.shutDownIn(http2goAwayTimeout)
+ }
+ }
+}
+
+type http2serverMessage int
+
+// Message values sent to serveMsgCh.
+var (
+ http2settingsTimerMsg = new(http2serverMessage)
+ http2idleTimerMsg = new(http2serverMessage)
+ http2shutdownTimerMsg = new(http2serverMessage)
+ http2gracefulShutdownMsg = new(http2serverMessage)
+ http2handlerDoneMsg = new(http2serverMessage)
+)
+
+func (sc *http2serverConn) onSettingsTimer() { sc.sendServeMsg(http2settingsTimerMsg) }
+
+func (sc *http2serverConn) onIdleTimer() { sc.sendServeMsg(http2idleTimerMsg) }
+
+func (sc *http2serverConn) onShutdownTimer() { sc.sendServeMsg(http2shutdownTimerMsg) }
+
+func (sc *http2serverConn) sendServeMsg(msg interface{}) {
+ sc.serveG.checkNotOn() // NOT
+ select {
+ case sc.serveMsgCh <- msg:
+ case <-sc.doneServing:
+ }
+}
+
+var http2errPrefaceTimeout = errors.New("timeout waiting for client preface")
+
+// readPreface reads the ClientPreface greeting from the peer or
+// returns errPrefaceTimeout on timeout, or an error if the greeting
+// is invalid.
+func (sc *http2serverConn) readPreface() error {
+ if sc.sawClientPreface {
+ return nil
+ }
+ errc := make(chan error, 1)
+ go func() {
+ // Read the client preface
+ buf := make([]byte, len(http2ClientPreface))
+ if _, err := io.ReadFull(sc.conn, buf); err != nil {
+ errc <- err
+ } else if !bytes.Equal(buf, http2clientPreface) {
+ errc <- fmt.Errorf("bogus greeting %q", buf)
+ } else {
+ errc <- nil
+ }
+ }()
+ timer := time.NewTimer(http2prefaceTimeout) // TODO: configurable on *Server?
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ return http2errPrefaceTimeout
+ case err := <-errc:
+ if err == nil {
+ if http2VerboseLogs {
+ sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
+ }
+ }
+ return err
+ }
+}
+
+var http2errChanPool = sync.Pool{
+ New: func() interface{} { return make(chan error, 1) },
+}
+
+var http2writeDataPool = sync.Pool{
+ New: func() interface{} { return new(http2writeData) },
+}
+
+// writeDataFromHandler writes DATA response frames from a handler on
+// the given stream.
+func (sc *http2serverConn) writeDataFromHandler(stream *http2stream, data []byte, endStream bool) error {
+ ch := http2errChanPool.Get().(chan error)
+ writeArg := http2writeDataPool.Get().(*http2writeData)
+ *writeArg = http2writeData{stream.id, data, endStream}
+ err := sc.writeFrameFromHandler(http2FrameWriteRequest{
+ write: writeArg,
+ stream: stream,
+ done: ch,
+ })
+ if err != nil {
+ return err
+ }
+ var frameWriteDone bool // the frame write is done (successfully or not)
+ select {
+ case err = <-ch:
+ frameWriteDone = true
+ case <-sc.doneServing:
+ return http2errClientDisconnected
+ case <-stream.cw:
+ // If both ch and stream.cw were ready (as might
+ // happen on the final Write after an http.Handler
+ // ends), prefer the write result. Otherwise this
+ // might just be us successfully closing the stream.
+ // The writeFrameAsync and serve goroutines guarantee
+ // that the ch send will happen before the stream.cw
+ // close.
+ select {
+ case err = <-ch:
+ frameWriteDone = true
+ default:
+ return http2errStreamClosed
+ }
+ }
+ http2errChanPool.Put(ch)
+ if frameWriteDone {
+ http2writeDataPool.Put(writeArg)
+ }
+ return err
+}
+
+// writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
+// if the connection has gone away.
+//
+// This must not be run from the serve goroutine itself, else it might
+// deadlock writing to sc.wantWriteFrameCh (which is only mildly
+// buffered and is read by serve itself). If you're on the serve
+// goroutine, call writeFrame instead.
+func (sc *http2serverConn) writeFrameFromHandler(wr http2FrameWriteRequest) error {
+ sc.serveG.checkNotOn() // NOT
+ select {
+ case sc.wantWriteFrameCh <- wr:
+ return nil
+ case <-sc.doneServing:
+ // Serve loop is gone.
+ // Client has closed their connection to the server.
+ return http2errClientDisconnected
+ }
+}
+
+// writeFrame schedules a frame to write and sends it if there's nothing
+// already being written.
+//
+// There is no pushback here (the serve goroutine never blocks). It's
+// the http.Handlers that block, waiting for their previous frames to
+// make it onto the wire
+//
+// If you're not on the serve goroutine, use writeFrameFromHandler instead.
+func (sc *http2serverConn) writeFrame(wr http2FrameWriteRequest) {
+ sc.serveG.check()
+
+ // If true, wr will not be written and wr.done will not be signaled.
+ var ignoreWrite bool
+
+ // We are not allowed to write frames on closed streams. RFC 7540 Section
+ // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
+ // a closed stream." Our server never sends PRIORITY, so that exception
+ // does not apply.
+ //
+ // The serverConn might close an open stream while the stream's handler
+ // is still running. For example, the server might close a stream when it
+ // receives bad data from the client. If this happens, the handler might
+ // attempt to write a frame after the stream has been closed (since the
+ // handler hasn't yet been notified of the close). In this case, we simply
+ // ignore the frame. The handler will notice that the stream is closed when
+ // it waits for the frame to be written.
+ //
+ // As an exception to this rule, we allow sending RST_STREAM after close.
+ // This allows us to immediately reject new streams without tracking any
+ // state for those streams (except for the queued RST_STREAM frame). This
+ // may result in duplicate RST_STREAMs in some cases, but the client should
+ // ignore those.
+ if wr.StreamID() != 0 {
+ _, isReset := wr.write.(http2StreamError)
+ if state, _ := sc.state(wr.StreamID()); state == http2stateClosed && !isReset {
+ ignoreWrite = true
+ }
+ }
+
+ // Don't send a 100-continue response if we've already sent headers.
+ // See golang.org/issue/14030.
+ switch wr.write.(type) {
+ case *http2writeResHeaders:
+ wr.stream.wroteHeaders = true
+ case http2write100ContinueHeadersFrame:
+ if wr.stream.wroteHeaders {
+ // We do not need to notify wr.done because this frame is
+ // never written with wr.done != nil.
+ if wr.done != nil {
+ panic("wr.done != nil for write100ContinueHeadersFrame")
+ }
+ ignoreWrite = true
+ }
+ }
+
+ if !ignoreWrite {
+ if wr.isControl() {
+ sc.queuedControlFrames++
+ // For extra safety, detect wraparounds, which should not happen,
+ // and pull the plug.
+ if sc.queuedControlFrames < 0 {
+ sc.conn.Close()
+ }
+ }
+ sc.writeSched.Push(wr)
+ }
+ sc.scheduleFrameWrite()
+}
+
+// startFrameWrite starts a goroutine to write wr (in a separate
+// goroutine since that might block on the network), and updates the
+// serve goroutine's state about the world, updated from info in wr.
+func (sc *http2serverConn) startFrameWrite(wr http2FrameWriteRequest) {
+ sc.serveG.check()
+ if sc.writingFrame {
+ panic("internal error: can only be writing one frame at a time")
+ }
+
+ st := wr.stream
+ if st != nil {
+ switch st.state {
+ case http2stateHalfClosedLocal:
+ switch wr.write.(type) {
+ case http2StreamError, http2handlerPanicRST, http2writeWindowUpdate:
+ // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
+ // in this state. (We never send PRIORITY from the server, so that is not checked.)
+ default:
+ panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
+ }
+ case http2stateClosed:
+ panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
+ }
+ }
+ if wpp, ok := wr.write.(*http2writePushPromise); ok {
+ var err error
+ wpp.promisedID, err = wpp.allocatePromisedID()
+ if err != nil {
+ sc.writingFrameAsync = false
+ wr.replyToWriter(err)
+ return
+ }
+ }
+
+ sc.writingFrame = true
+ sc.needsFrameFlush = true
+ if wr.write.staysWithinBuffer(sc.bw.Available()) {
+ sc.writingFrameAsync = false
+ err := wr.write.writeFrame(sc)
+ sc.wroteFrame(http2frameWriteResult{wr: wr, err: err})
+ } else if wd, ok := wr.write.(*http2writeData); ok {
+ // Encode the frame in the serve goroutine, to ensure we don't have
+ // any lingering asynchronous references to data passed to Write.
+ // See https://go.dev/issue/58446.
+ sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
+ sc.writingFrameAsync = true
+ go sc.writeFrameAsync(wr, wd)
+ } else {
+ sc.writingFrameAsync = true
+ go sc.writeFrameAsync(wr, nil)
+ }
+}
+
+// errHandlerPanicked is the error given to any callers blocked in a read from
+// Request.Body when the main goroutine panics. Since most handlers read in the
+// main ServeHTTP goroutine, this will show up rarely.
+var http2errHandlerPanicked = errors.New("http2: handler panicked")
+
+// wroteFrame is called on the serve goroutine with the result of
+// whatever happened on writeFrameAsync.
+func (sc *http2serverConn) wroteFrame(res http2frameWriteResult) {
+ sc.serveG.check()
+ if !sc.writingFrame {
+ panic("internal error: expected to be already writing a frame")
+ }
+ sc.writingFrame = false
+ sc.writingFrameAsync = false
+
+ wr := res.wr
+
+ if http2writeEndsStream(wr.write) {
+ st := wr.stream
+ if st == nil {
+ panic("internal error: expecting non-nil stream")
+ }
+ switch st.state {
+ case http2stateOpen:
+ // Here we would go to stateHalfClosedLocal in
+ // theory, but since our handler is done and
+ // the net/http package provides no mechanism
+ // for closing a ResponseWriter while still
+ // reading data (see possible TODO at top of
+ // this file), we go into closed state here
+ // anyway, after telling the peer we're
+ // hanging up on them. We'll transition to
+ // stateClosed after the RST_STREAM frame is
+ // written.
+ st.state = http2stateHalfClosedLocal
+ // Section 8.1: a server MAY request that the client abort
+ // transmission of a request without error by sending a
+ // RST_STREAM with an error code of NO_ERROR after sending
+ // a complete response.
+ sc.resetStream(http2streamError(st.id, http2ErrCodeNo))
+ case http2stateHalfClosedRemote:
+ sc.closeStream(st, http2errHandlerComplete)
+ }
+ } else {
+ switch v := wr.write.(type) {
+ case http2StreamError:
+ // st may be unknown if the RST_STREAM was generated to reject bad input.
+ if st, ok := sc.streams[v.StreamID]; ok {
+ sc.closeStream(st, v)
+ }
+ case http2handlerPanicRST:
+ sc.closeStream(wr.stream, http2errHandlerPanicked)
+ }
+ }
+
+ // Reply (if requested) to unblock the ServeHTTP goroutine.
+ wr.replyToWriter(res.err)
+
+ sc.scheduleFrameWrite()
+}
+
+// scheduleFrameWrite tickles the frame writing scheduler.
+//
+// If a frame is already being written, nothing happens. This will be called again
+// when the frame is done being written.
+//
+// If a frame isn't being written and we need to send one, the best frame
+// to send is selected by writeSched.
+//
+// If a frame isn't being written and there's nothing else to send, we
+// flush the write buffer.
+func (sc *http2serverConn) scheduleFrameWrite() {
+ sc.serveG.check()
+ if sc.writingFrame || sc.inFrameScheduleLoop {
+ return
+ }
+ sc.inFrameScheduleLoop = true
+ for !sc.writingFrameAsync {
+ if sc.needToSendGoAway {
+ sc.needToSendGoAway = false
+ sc.startFrameWrite(http2FrameWriteRequest{
+ write: &http2writeGoAway{
+ maxStreamID: sc.maxClientStreamID,
+ code: sc.goAwayCode,
+ },
+ })
+ continue
+ }
+ if sc.needToSendSettingsAck {
+ sc.needToSendSettingsAck = false
+ sc.startFrameWrite(http2FrameWriteRequest{write: http2writeSettingsAck{}})
+ continue
+ }
+ if !sc.inGoAway || sc.goAwayCode == http2ErrCodeNo {
+ if wr, ok := sc.writeSched.Pop(); ok {
+ if wr.isControl() {
+ sc.queuedControlFrames--
+ }
+ sc.startFrameWrite(wr)
+ continue
+ }
+ }
+ if sc.needsFrameFlush {
+ sc.startFrameWrite(http2FrameWriteRequest{write: http2flushFrameWriter{}})
+ sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
+ continue
+ }
+ break
+ }
+ sc.inFrameScheduleLoop = false
+}
+
+// startGracefulShutdown gracefully shuts down a connection. This
+// sends GOAWAY with ErrCodeNo to tell the client we're gracefully
+// shutting down. The connection isn't closed until all current
+// streams are done.
+//
+// startGracefulShutdown returns immediately; it does not wait until
+// the connection has shut down.
+func (sc *http2serverConn) startGracefulShutdown() {
+ sc.serveG.checkNotOn() // NOT
+ sc.shutdownOnce.Do(func() { sc.sendServeMsg(http2gracefulShutdownMsg) })
+}
+
+// After sending GOAWAY with an error code (non-graceful shutdown), the
+// connection will close after goAwayTimeout.
+//
+// If we close the connection immediately after sending GOAWAY, there may
+// be unsent data in our kernel receive buffer, which will cause the kernel
+// to send a TCP RST on close() instead of a FIN. This RST will abort the
+// connection immediately, whether or not the client had received the GOAWAY.
+//
+// Ideally we should delay for at least 1 RTT + epsilon so the client has
+// a chance to read the GOAWAY and stop sending messages. Measuring RTT
+// is hard, so we approximate with 1 second. See golang.org/issue/18701.
+//
+// This is a var so it can be shorter in tests, where all requests uses the
+// loopback interface making the expected RTT very small.
+//
+// TODO: configurable?
+var http2goAwayTimeout = 1 * time.Second
+
+func (sc *http2serverConn) startGracefulShutdownInternal() {
+ sc.goAway(http2ErrCodeNo)
+}
+
+func (sc *http2serverConn) goAway(code http2ErrCode) {
+ sc.serveG.check()
+ if sc.inGoAway {
+ if sc.goAwayCode == http2ErrCodeNo {
+ sc.goAwayCode = code
+ }
+ return
+ }
+ sc.inGoAway = true
+ sc.needToSendGoAway = true
+ sc.goAwayCode = code
+ sc.scheduleFrameWrite()
+}
+
+func (sc *http2serverConn) shutDownIn(d time.Duration) {
+ sc.serveG.check()
+ sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
+}
+
+func (sc *http2serverConn) resetStream(se http2StreamError) {
+ sc.serveG.check()
+ sc.writeFrame(http2FrameWriteRequest{write: se})
+ if st, ok := sc.streams[se.StreamID]; ok {
+ st.resetQueued = true
+ }
+}
+
+// processFrameFromReader processes the serve loop's read from readFrameCh from the
+// frame-reading goroutine.
+// processFrameFromReader returns whether the connection should be kept open.
+func (sc *http2serverConn) processFrameFromReader(res http2readFrameResult) bool {
+ sc.serveG.check()
+ err := res.err
+ if err != nil {
+ if err == http2ErrFrameTooLarge {
+ sc.goAway(http2ErrCodeFrameSize)
+ return true // goAway will close the loop
+ }
+ clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err)
+ if clientGone {
+ // TODO: could we also get into this state if
+ // the peer does a half close
+ // (e.g. CloseWrite) because they're done
+ // sending frames but they're still wanting
+ // our open replies? Investigate.
+ // TODO: add CloseWrite to crypto/tls.Conn first
+ // so we have a way to test this? I suppose
+ // just for testing we could have a non-TLS mode.
+ return false
+ }
+ } else {
+ f := res.f
+ if http2VerboseLogs {
+ sc.vlogf("http2: server read frame %v", http2summarizeFrame(f))
+ }
+ err = sc.processFrame(f)
+ if err == nil {
+ return true
+ }
+ }
+
+ switch ev := err.(type) {
+ case http2StreamError:
+ sc.resetStream(ev)
+ return true
+ case http2goAwayFlowError:
+ sc.goAway(http2ErrCodeFlowControl)
+ return true
+ case http2ConnectionError:
+ if res.f != nil {
+ if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
+ sc.maxClientStreamID = id
+ }
+ }
+ sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
+ sc.goAway(http2ErrCode(ev))
+ return true // goAway will handle shutdown
+ default:
+ if res.err != nil {
+ sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
+ } else {
+ sc.logf("http2: server closing client connection: %v", err)
+ }
+ return false
+ }
+}
+
+func (sc *http2serverConn) processFrame(f http2Frame) error {
+ sc.serveG.check()
+
+ // First frame received must be SETTINGS.
+ if !sc.sawFirstSettings {
+ if _, ok := f.(*http2SettingsFrame); !ok {
+ return sc.countError("first_settings", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ sc.sawFirstSettings = true
+ }
+
+ // Discard frames for streams initiated after the identified last
+ // stream sent in a GOAWAY, or all frames after sending an error.
+ // We still need to return connection-level flow control for DATA frames.
+ // RFC 9113 Section 6.8.
+ if sc.inGoAway && (sc.goAwayCode != http2ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
+
+ if f, ok := f.(*http2DataFrame); ok {
+ if !sc.inflow.take(f.Length) {
+ return sc.countError("data_flow", http2streamError(f.Header().StreamID, http2ErrCodeFlowControl))
+ }
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
+ }
+ return nil
+ }
+
+ switch f := f.(type) {
+ case *http2SettingsFrame:
+ return sc.processSettings(f)
+ case *http2MetaHeadersFrame:
+ return sc.processHeaders(f)
+ case *http2WindowUpdateFrame:
+ return sc.processWindowUpdate(f)
+ case *http2PingFrame:
+ return sc.processPing(f)
+ case *http2DataFrame:
+ return sc.processData(f)
+ case *http2RSTStreamFrame:
+ return sc.processResetStream(f)
+ case *http2PriorityFrame:
+ return sc.processPriority(f)
+ case *http2GoAwayFrame:
+ return sc.processGoAway(f)
+ case *http2PushPromiseFrame:
+ // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
+ // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
+ return sc.countError("push_promise", http2ConnectionError(http2ErrCodeProtocol))
+ default:
+ sc.vlogf("http2: server ignoring frame: %v", f.Header())
+ return nil
+ }
+}
+
+func (sc *http2serverConn) processPing(f *http2PingFrame) error {
+ sc.serveG.check()
+ if f.IsAck() {
+ // 6.7 PING: " An endpoint MUST NOT respond to PING frames
+ // containing this flag."
+ return nil
+ }
+ if f.StreamID != 0 {
+ // "PING frames are not associated with any individual
+ // stream. If a PING frame is received with a stream
+ // identifier field value other than 0x0, the recipient MUST
+ // respond with a connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR."
+ return sc.countError("ping_on_stream", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ sc.writeFrame(http2FrameWriteRequest{write: http2writePingAck{f}})
+ return nil
+}
+
+func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error {
+ sc.serveG.check()
+ switch {
+ case f.StreamID != 0: // stream-level flow control
+ state, st := sc.state(f.StreamID)
+ if state == http2stateIdle {
+ // Section 5.1: "Receiving any frame other than HEADERS
+ // or PRIORITY on a stream in this state MUST be
+ // treated as a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR."
+ return sc.countError("stream_idle", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ if st == nil {
+ // "WINDOW_UPDATE can be sent by a peer that has sent a
+ // frame bearing the END_STREAM flag. This means that a
+ // receiver could receive a WINDOW_UPDATE frame on a "half
+ // closed (remote)" or "closed" stream. A receiver MUST
+ // NOT treat this as an error, see Section 5.1."
+ return nil
+ }
+ if !st.flow.add(int32(f.Increment)) {
+ return sc.countError("bad_flow", http2streamError(f.StreamID, http2ErrCodeFlowControl))
+ }
+ default: // connection-level flow control
+ if !sc.flow.add(int32(f.Increment)) {
+ return http2goAwayFlowError{}
+ }
+ }
+ sc.scheduleFrameWrite()
+ return nil
+}
+
+func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error {
+ sc.serveG.check()
+
+ state, st := sc.state(f.StreamID)
+ if state == http2stateIdle {
+ // 6.4 "RST_STREAM frames MUST NOT be sent for a
+ // stream in the "idle" state. If a RST_STREAM frame
+ // identifying an idle stream is received, the
+ // recipient MUST treat this as a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ return sc.countError("reset_idle_stream", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ if st != nil {
+ st.cancelCtx()
+ sc.closeStream(st, http2streamError(f.StreamID, f.ErrCode))
+ }
+ return nil
+}
+
+func (sc *http2serverConn) closeStream(st *http2stream, err error) {
+ sc.serveG.check()
+ if st.state == http2stateIdle || st.state == http2stateClosed {
+ panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
+ }
+ st.state = http2stateClosed
+ if st.readDeadline != nil {
+ st.readDeadline.Stop()
+ }
+ if st.writeDeadline != nil {
+ st.writeDeadline.Stop()
+ }
+ if st.isPushed() {
+ sc.curPushedStreams--
+ } else {
+ sc.curClientStreams--
+ }
+ delete(sc.streams, st.id)
+ if len(sc.streams) == 0 {
+ sc.setConnState(StateIdle)
+ if sc.srv.IdleTimeout != 0 {
+ sc.idleTimer.Reset(sc.srv.IdleTimeout)
+ }
+ if http2h1ServerKeepAlivesDisabled(sc.hs) {
+ sc.startGracefulShutdownInternal()
+ }
+ }
+ if p := st.body; p != nil {
+ // Return any buffered unread bytes worth of conn-level flow control.
+ // See golang.org/issue/16481
+ sc.sendWindowUpdate(nil, p.Len())
+
+ p.CloseWithError(err)
+ }
+ if e, ok := err.(http2StreamError); ok {
+ if e.Cause != nil {
+ err = e.Cause
+ } else {
+ err = http2errStreamClosed
+ }
+ }
+ st.closeErr = err
+ st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
+ sc.writeSched.CloseStream(st.id)
+}
+
+func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error {
+ sc.serveG.check()
+ if f.IsAck() {
+ sc.unackedSettings--
+ if sc.unackedSettings < 0 {
+ // Why is the peer ACKing settings we never sent?
+ // The spec doesn't mention this case, but
+ // hang up on them anyway.
+ return sc.countError("ack_mystery", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ return nil
+ }
+ if f.NumSettings() > 100 || f.HasDuplicates() {
+ // This isn't actually in the spec, but hang up on
+ // suspiciously large settings frames or those with
+ // duplicate entries.
+ return sc.countError("settings_big_or_dups", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ if err := f.ForeachSetting(sc.processSetting); err != nil {
+ return err
+ }
+ // TODO: judging by RFC 7540, Section 6.5.3 each SETTINGS frame should be
+ // acknowledged individually, even if multiple are received before the ACK.
+ sc.needToSendSettingsAck = true
+ sc.scheduleFrameWrite()
+ return nil
+}
+
+func (sc *http2serverConn) processSetting(s http2Setting) error {
+ sc.serveG.check()
+ if err := s.Valid(); err != nil {
+ return err
+ }
+ if http2VerboseLogs {
+ sc.vlogf("http2: server processing setting %v", s)
+ }
+ switch s.ID {
+ case http2SettingHeaderTableSize:
+ sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
+ case http2SettingEnablePush:
+ sc.pushEnabled = s.Val != 0
+ case http2SettingMaxConcurrentStreams:
+ sc.clientMaxStreams = s.Val
+ case http2SettingInitialWindowSize:
+ return sc.processSettingInitialWindowSize(s.Val)
+ case http2SettingMaxFrameSize:
+ sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
+ case http2SettingMaxHeaderListSize:
+ sc.peerMaxHeaderListSize = s.Val
+ default:
+ // Unknown setting: "An endpoint that receives a SETTINGS
+ // frame with any unknown or unsupported identifier MUST
+ // ignore that setting."
+ if http2VerboseLogs {
+ sc.vlogf("http2: server ignoring unknown setting %v", s)
+ }
+ }
+ return nil
+}
+
+func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error {
+ sc.serveG.check()
+ // Note: val already validated to be within range by
+ // processSetting's Valid call.
+
+ // "A SETTINGS frame can alter the initial flow control window
+ // size for all current streams. When the value of
+ // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
+ // adjust the size of all stream flow control windows that it
+ // maintains by the difference between the new value and the
+ // old value."
+ old := sc.initialStreamSendWindowSize
+ sc.initialStreamSendWindowSize = int32(val)
+ growth := int32(val) - old // may be negative
+ for _, st := range sc.streams {
+ if !st.flow.add(growth) {
+ // 6.9.2 Initial Flow Control Window Size
+ // "An endpoint MUST treat a change to
+ // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
+ // control window to exceed the maximum size as a
+ // connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR."
+ return sc.countError("setting_win_size", http2ConnectionError(http2ErrCodeFlowControl))
+ }
+ }
+ return nil
+}
+
+func (sc *http2serverConn) processData(f *http2DataFrame) error {
+ sc.serveG.check()
+ id := f.Header().StreamID
+
+ data := f.Data()
+ state, st := sc.state(id)
+ if id == 0 || state == http2stateIdle {
+ // Section 6.1: "DATA frames MUST be associated with a
+ // stream. If a DATA frame is received whose stream
+ // identifier field is 0x0, the recipient MUST respond
+ // with a connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR."
+ //
+ // Section 5.1: "Receiving any frame other than HEADERS
+ // or PRIORITY on a stream in this state MUST be
+ // treated as a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR."
+ return sc.countError("data_on_idle", http2ConnectionError(http2ErrCodeProtocol))
+ }
+
+ // "If a DATA frame is received whose stream is not in "open"
+ // or "half closed (local)" state, the recipient MUST respond
+ // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
+ if st == nil || state != http2stateOpen || st.gotTrailerHeader || st.resetQueued {
+ // This includes sending a RST_STREAM if the stream is
+ // in stateHalfClosedLocal (which currently means that
+ // the http.Handler returned, so it's done reading &
+ // done writing). Try to stop the client from sending
+ // more DATA.
+
+ // But still enforce their connection-level flow control,
+ // and return any flow control bytes since we're not going
+ // to consume them.
+ if !sc.inflow.take(f.Length) {
+ return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
+ }
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
+
+ if st != nil && st.resetQueued {
+ // Already have a stream error in flight. Don't send another.
+ return nil
+ }
+ return sc.countError("closed", http2streamError(id, http2ErrCodeStreamClosed))
+ }
+ if st.body == nil {
+ panic("internal error: should have a body in this state")
+ }
+
+ // Sender sending more than they'd declared?
+ if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
+ if !sc.inflow.take(f.Length) {
+ return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
+ }
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
+
+ st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
+ // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the
+ // value of a content-length header field does not equal the sum of the
+ // DATA frame payload lengths that form the body.
+ return sc.countError("send_too_much", http2streamError(id, http2ErrCodeProtocol))
+ }
+ if f.Length > 0 {
+ // Check whether the client has flow control quota.
+ if !http2takeInflows(&sc.inflow, &st.inflow, f.Length) {
+ return sc.countError("flow_on_data_length", http2streamError(id, http2ErrCodeFlowControl))
+ }
+
+ if len(data) > 0 {
+ st.bodyBytes += int64(len(data))
+ wrote, err := st.body.Write(data)
+ if err != nil {
+ // The handler has closed the request body.
+ // Return the connection-level flow control for the discarded data,
+ // but not the stream-level flow control.
+ sc.sendWindowUpdate(nil, int(f.Length)-wrote)
+ return nil
+ }
+ if wrote != len(data) {
+ panic("internal error: bad Writer")
+ }
+ }
+
+ // Return any padded flow control now, since we won't
+ // refund it later on body reads.
+ // Call sendWindowUpdate even if there is no padding,
+ // to return buffered flow control credit if the sent
+ // window has shrunk.
+ pad := int32(f.Length) - int32(len(data))
+ sc.sendWindowUpdate32(nil, pad)
+ sc.sendWindowUpdate32(st, pad)
+ }
+ if f.StreamEnded() {
+ st.endStream()
+ }
+ return nil
+}
+
+func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error {
+ sc.serveG.check()
+ if f.ErrCode != http2ErrCodeNo {
+ sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
+ } else {
+ sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
+ }
+ sc.startGracefulShutdownInternal()
+ // http://tools.ietf.org/html/rfc7540#section-6.8
+ // We should not create any new streams, which means we should disable push.
+ sc.pushEnabled = false
+ return nil
+}
+
+// isPushed reports whether the stream is server-initiated.
+func (st *http2stream) isPushed() bool {
+ return st.id%2 == 0
+}
+
+// endStream closes a Request.Body's pipe. It is called when a DATA
+// frame says a request body is over (or after trailers).
+func (st *http2stream) endStream() {
+ sc := st.sc
+ sc.serveG.check()
+
+ if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
+ st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
+ st.declBodyBytes, st.bodyBytes))
+ } else {
+ st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
+ st.body.CloseWithError(io.EOF)
+ }
+ st.state = http2stateHalfClosedRemote
+}
+
+// copyTrailersToHandlerRequest is run in the Handler's goroutine in
+// its Request.Body.Read just before it gets io.EOF.
+func (st *http2stream) copyTrailersToHandlerRequest() {
+ for k, vv := range st.trailer {
+ if _, ok := st.reqTrailer[k]; ok {
+ // Only copy it over it was pre-declared.
+ st.reqTrailer[k] = vv
+ }
+ }
+}
+
+// onReadTimeout is run on its own goroutine (from time.AfterFunc)
+// when the stream's ReadTimeout has fired.
+func (st *http2stream) onReadTimeout() {
+ if st.body != nil {
+ // Wrap the ErrDeadlineExceeded to avoid callers depending on us
+ // returning the bare error.
+ st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
+ }
+}
+
+// onWriteTimeout is run on its own goroutine (from time.AfterFunc)
+// when the stream's WriteTimeout has fired.
+func (st *http2stream) onWriteTimeout() {
+ st.sc.writeFrameFromHandler(http2FrameWriteRequest{write: http2StreamError{
+ StreamID: st.id,
+ Code: http2ErrCodeInternal,
+ Cause: os.ErrDeadlineExceeded,
+ }})
+}
+
+func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error {
+ sc.serveG.check()
+ id := f.StreamID
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1
+ // Streams initiated by a client MUST use odd-numbered stream
+ // identifiers. [...] An endpoint that receives an unexpected
+ // stream identifier MUST respond with a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ if id%2 != 1 {
+ return sc.countError("headers_even", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ // A HEADERS frame can be used to create a new stream or
+ // send a trailer for an open one. If we already have a stream
+ // open, let it process its own HEADERS frame (trailers at this
+ // point, if it's valid).
+ if st := sc.streams[f.StreamID]; st != nil {
+ if st.resetQueued {
+ // We're sending RST_STREAM to close the stream, so don't bother
+ // processing this frame.
+ return nil
+ }
+ // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than
+ // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in
+ // this state, it MUST respond with a stream error (Section 5.4.2) of
+ // type STREAM_CLOSED.
+ if st.state == http2stateHalfClosedRemote {
+ return sc.countError("headers_half_closed", http2streamError(id, http2ErrCodeStreamClosed))
+ }
+ return st.processTrailerHeaders(f)
+ }
+
+ // [...] The identifier of a newly established stream MUST be
+ // numerically greater than all streams that the initiating
+ // endpoint has opened or reserved. [...] An endpoint that
+ // receives an unexpected stream identifier MUST respond with
+ // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
+ if id <= sc.maxClientStreamID {
+ return sc.countError("stream_went_down", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ sc.maxClientStreamID = id
+
+ if sc.idleTimer != nil {
+ sc.idleTimer.Stop()
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-5.1.2
+ // [...] Endpoints MUST NOT exceed the limit set by their peer. An
+ // endpoint that receives a HEADERS frame that causes their
+ // advertised concurrent stream limit to be exceeded MUST treat
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
+ // or REFUSED_STREAM.
+ if sc.curClientStreams+1 > sc.advMaxStreams {
+ if sc.unackedSettings == 0 {
+ // They should know better.
+ return sc.countError("over_max_streams", http2streamError(id, http2ErrCodeProtocol))
+ }
+ // Assume it's a network race, where they just haven't
+ // received our last SETTINGS update. But actually
+ // this can't happen yet, because we don't yet provide
+ // a way for users to adjust server parameters at
+ // runtime.
+ return sc.countError("over_max_streams_race", http2streamError(id, http2ErrCodeRefusedStream))
+ }
+
+ initialState := http2stateOpen
+ if f.StreamEnded() {
+ initialState = http2stateHalfClosedRemote
+ }
+ st := sc.newStream(id, 0, initialState)
+
+ if f.HasPriority() {
+ if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
+ return err
+ }
+ sc.writeSched.AdjustStream(st.id, f.Priority)
+ }
+
+ rw, req, err := sc.newWriterAndRequest(st, f)
+ if err != nil {
+ return err
+ }
+ st.reqTrailer = req.Trailer
+ if st.reqTrailer != nil {
+ st.trailer = make(Header)
+ }
+ st.body = req.Body.(*http2requestBody).pipe // may be nil
+ st.declBodyBytes = req.ContentLength
+
+ handler := sc.handler.ServeHTTP
+ if f.Truncated {
+ // Their header list was too long. Send a 431 error.
+ handler = http2handleHeaderListTooLong
+ } else if err := http2checkValidHTTP2RequestHeaders(req.Header); err != nil {
+ handler = http2new400Handler(err)
+ }
+
+ // The net/http package sets the read deadline from the
+ // http.Server.ReadTimeout during the TLS handshake, but then
+ // passes the connection off to us with the deadline already
+ // set. Disarm it here after the request headers are read,
+ // similar to how the http1 server works. Here it's
+ // technically more like the http1 Server's ReadHeaderTimeout
+ // (in Go 1.8), though. That's a more sane option anyway.
+ if sc.hs.ReadTimeout != 0 {
+ sc.conn.SetReadDeadline(time.Time{})
+ st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout)
+ }
+
+ return sc.scheduleHandler(id, rw, req, handler)
+}
+
+func (sc *http2serverConn) upgradeRequest(req *Request) {
+ sc.serveG.check()
+ id := uint32(1)
+ sc.maxClientStreamID = id
+ st := sc.newStream(id, 0, http2stateHalfClosedRemote)
+ st.reqTrailer = req.Trailer
+ if st.reqTrailer != nil {
+ st.trailer = make(Header)
+ }
+ rw := sc.newResponseWriter(st, req)
+
+ // Disable any read deadline set by the net/http package
+ // prior to the upgrade.
+ if sc.hs.ReadTimeout != 0 {
+ sc.conn.SetReadDeadline(time.Time{})
+ }
+
+ // This is the first request on the connection,
+ // so start the handler directly rather than going
+ // through scheduleHandler.
+ sc.curHandlers++
+ go sc.runHandler(rw, req, sc.handler.ServeHTTP)
+}
+
+func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error {
+ sc := st.sc
+ sc.serveG.check()
+ if st.gotTrailerHeader {
+ return sc.countError("dup_trailers", http2ConnectionError(http2ErrCodeProtocol))
+ }
+ st.gotTrailerHeader = true
+ if !f.StreamEnded() {
+ return sc.countError("trailers_not_ended", http2streamError(st.id, http2ErrCodeProtocol))
+ }
+
+ if len(f.PseudoFields()) > 0 {
+ return sc.countError("trailers_pseudo", http2streamError(st.id, http2ErrCodeProtocol))
+ }
+ if st.trailer != nil {
+ for _, hf := range f.RegularFields() {
+ key := sc.canonicalHeader(hf.Name)
+ if !httpguts.ValidTrailerHeader(key) {
+ // TODO: send more details to the peer somehow. But http2 has
+ // no way to send debug data at a stream level. Discuss with
+ // HTTP folk.
+ return sc.countError("trailers_bogus", http2streamError(st.id, http2ErrCodeProtocol))
+ }
+ st.trailer[key] = append(st.trailer[key], hf.Value)
+ }
+ }
+ st.endStream()
+ return nil
+}
+
+func (sc *http2serverConn) checkPriority(streamID uint32, p http2PriorityParam) error {
+ if streamID == p.StreamDep {
+ // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
+ // Section 5.3.3 says that a stream can depend on one of its dependencies,
+ // so it's only self-dependencies that are forbidden.
+ return sc.countError("priority", http2streamError(streamID, http2ErrCodeProtocol))
+ }
+ return nil
+}
+
+func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error {
+ if err := sc.checkPriority(f.StreamID, f.http2PriorityParam); err != nil {
+ return err
+ }
+ sc.writeSched.AdjustStream(f.StreamID, f.http2PriorityParam)
+ return nil
+}
+
+func (sc *http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream {
+ sc.serveG.check()
+ if id == 0 {
+ panic("internal error: cannot create stream with id 0")
+ }
+
+ ctx, cancelCtx := context.WithCancel(sc.baseCtx)
+ st := &http2stream{
+ sc: sc,
+ id: id,
+ state: state,
+ ctx: ctx,
+ cancelCtx: cancelCtx,
+ }
+ st.cw.Init()
+ st.flow.conn = &sc.flow // link to conn-level counter
+ st.flow.add(sc.initialStreamSendWindowSize)
+ st.inflow.init(sc.srv.initialStreamRecvWindowSize())
+ if sc.hs.WriteTimeout != 0 {
+ st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
+ }
+
+ sc.streams[id] = st
+ sc.writeSched.OpenStream(st.id, http2OpenStreamOptions{PusherID: pusherID})
+ if st.isPushed() {
+ sc.curPushedStreams++
+ } else {
+ sc.curClientStreams++
+ }
+ if sc.curOpenStreams() == 1 {
+ sc.setConnState(StateActive)
+ }
+
+ return st
+}
+
+func (sc *http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error) {
+ sc.serveG.check()
+
+ rp := http2requestParam{
+ method: f.PseudoValue("method"),
+ scheme: f.PseudoValue("scheme"),
+ authority: f.PseudoValue("authority"),
+ path: f.PseudoValue("path"),
+ }
+
+ isConnect := rp.method == "CONNECT"
+ if isConnect {
+ if rp.path != "" || rp.scheme != "" || rp.authority == "" {
+ return nil, nil, sc.countError("bad_connect", http2streamError(f.StreamID, http2ErrCodeProtocol))
+ }
+ } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
+ // See 8.1.2.6 Malformed Requests and Responses:
+ //
+ // Malformed requests or responses that are detected
+ // MUST be treated as a stream error (Section 5.4.2)
+ // of type PROTOCOL_ERROR."
+ //
+ // 8.1.2.3 Request Pseudo-Header Fields
+ // "All HTTP/2 requests MUST include exactly one valid
+ // value for the :method, :scheme, and :path
+ // pseudo-header fields"
+ return nil, nil, sc.countError("bad_path_method", http2streamError(f.StreamID, http2ErrCodeProtocol))
+ }
+
+ rp.header = make(Header)
+ for _, hf := range f.RegularFields() {
+ rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
+ }
+ if rp.authority == "" {
+ rp.authority = rp.header.Get("Host")
+ }
+
+ rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
+ if err != nil {
+ return nil, nil, err
+ }
+ bodyOpen := !f.StreamEnded()
+ if bodyOpen {
+ if vv, ok := rp.header["Content-Length"]; ok {
+ if cl, err := strconv.ParseUint(vv[0], 10, 63); err == nil {
+ req.ContentLength = int64(cl)
+ } else {
+ req.ContentLength = 0
+ }
+ } else {
+ req.ContentLength = -1
+ }
+ req.Body.(*http2requestBody).pipe = &http2pipe{
+ b: &http2dataBuffer{expected: req.ContentLength},
+ }
+ }
+ return rw, req, nil
+}
+
+type http2requestParam struct {
+ method string
+ scheme, authority, path string
+ header Header
+}
+
+func (sc *http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error) {
+ sc.serveG.check()
+
+ var tlsState *tls.ConnectionState // nil if not scheme https
+ if rp.scheme == "https" {
+ tlsState = sc.tlsState
+ }
+
+ needsContinue := httpguts.HeaderValuesContainsToken(rp.header["Expect"], "100-continue")
+ if needsContinue {
+ rp.header.Del("Expect")
+ }
+ // Merge Cookie headers into one "; "-delimited value.
+ if cookies := rp.header["Cookie"]; len(cookies) > 1 {
+ rp.header.Set("Cookie", strings.Join(cookies, "; "))
+ }
+
+ // Setup Trailers
+ var trailer Header
+ for _, v := range rp.header["Trailer"] {
+ for _, key := range strings.Split(v, ",") {
+ key = CanonicalHeaderKey(textproto.TrimString(key))
+ switch key {
+ case "Transfer-Encoding", "Trailer", "Content-Length":
+ // Bogus. (copy of http1 rules)
+ // Ignore.
+ default:
+ if trailer == nil {
+ trailer = make(Header)
+ }
+ trailer[key] = nil
+ }
+ }
+ }
+ delete(rp.header, "Trailer")
+
+ var url_ *url.URL
+ var requestURI string
+ if rp.method == "CONNECT" {
+ url_ = &url.URL{Host: rp.authority}
+ requestURI = rp.authority // mimic HTTP/1 server behavior
+ } else {
+ var err error
+ url_, err = url.ParseRequestURI(rp.path)
+ if err != nil {
+ return nil, nil, sc.countError("bad_path", http2streamError(st.id, http2ErrCodeProtocol))
+ }
+ requestURI = rp.path
+ }
+
+ body := &http2requestBody{
+ conn: sc,
+ stream: st,
+ needsContinue: needsContinue,
+ }
+ req := &Request{
+ Method: rp.method,
+ URL: url_,
+ RemoteAddr: sc.remoteAddrStr,
+ Header: rp.header,
+ RequestURI: requestURI,
+ Proto: "HTTP/2.0",
+ ProtoMajor: 2,
+ ProtoMinor: 0,
+ TLS: tlsState,
+ Host: rp.authority,
+ Body: body,
+ Trailer: trailer,
+ }
+ req = req.WithContext(st.ctx)
+
+ rw := sc.newResponseWriter(st, req)
+ return rw, req, nil
+}
+
+func (sc *http2serverConn) newResponseWriter(st *http2stream, req *Request) *http2responseWriter {
+ rws := http2responseWriterStatePool.Get().(*http2responseWriterState)
+ bwSave := rws.bw
+ *rws = http2responseWriterState{} // zero all the fields
+ rws.conn = sc
+ rws.bw = bwSave
+ rws.bw.Reset(http2chunkWriter{rws})
+ rws.stream = st
+ rws.req = req
+ return &http2responseWriter{rws: rws}
+}
+
+type http2unstartedHandler struct {
+ streamID uint32
+ rw *http2responseWriter
+ req *Request
+ handler func(ResponseWriter, *Request)
+}
+
+// scheduleHandler starts a handler goroutine,
+// or schedules one to start as soon as an existing handler finishes.
+func (sc *http2serverConn) scheduleHandler(streamID uint32, rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) error {
+ sc.serveG.check()
+ maxHandlers := sc.advMaxStreams
+ if sc.curHandlers < maxHandlers {
+ sc.curHandlers++
+ go sc.runHandler(rw, req, handler)
+ return nil
+ }
+ if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
+ return sc.countError("too_many_early_resets", http2ConnectionError(http2ErrCodeEnhanceYourCalm))
+ }
+ sc.unstartedHandlers = append(sc.unstartedHandlers, http2unstartedHandler{
+ streamID: streamID,
+ rw: rw,
+ req: req,
+ handler: handler,
+ })
+ return nil
+}
+
+func (sc *http2serverConn) handlerDone() {
+ sc.serveG.check()
+ sc.curHandlers--
+ i := 0
+ maxHandlers := sc.advMaxStreams
+ for ; i < len(sc.unstartedHandlers); i++ {
+ u := sc.unstartedHandlers[i]
+ if sc.streams[u.streamID] == nil {
+ // This stream was reset before its goroutine had a chance to start.
+ continue
+ }
+ if sc.curHandlers >= maxHandlers {
+ break
+ }
+ sc.curHandlers++
+ go sc.runHandler(u.rw, u.req, u.handler)
+ sc.unstartedHandlers[i] = http2unstartedHandler{} // don't retain references
+ }
+ sc.unstartedHandlers = sc.unstartedHandlers[i:]
+ if len(sc.unstartedHandlers) == 0 {
+ sc.unstartedHandlers = nil
+ }
+}
+
+// Run on its own goroutine.
+func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) {
+ defer sc.sendServeMsg(http2handlerDoneMsg)
+ didPanic := true
+ defer func() {
+ rw.rws.stream.cancelCtx()
+ if req.MultipartForm != nil {
+ req.MultipartForm.RemoveAll()
+ }
+ if didPanic {
+ e := recover()
+ sc.writeFrameFromHandler(http2FrameWriteRequest{
+ write: http2handlerPanicRST{rw.rws.stream.id},
+ stream: rw.rws.stream,
+ })
+ // Same as net/http:
+ if e != nil && e != ErrAbortHandler {
+ const size = 64 << 10
+ buf := make([]byte, size)
+ buf = buf[:runtime.Stack(buf, false)]
+ sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
+ }
+ return
+ }
+ rw.handlerDone()
+ }()
+ handler(rw, req)
+ didPanic = false
+}
+
+func http2handleHeaderListTooLong(w ResponseWriter, r *Request) {
+ // 10.5.1 Limits on Header Block Size:
+ // .. "A server that receives a larger header block than it is
+ // willing to handle can send an HTTP 431 (Request Header Fields Too
+ // Large) status code"
+ const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
+ w.WriteHeader(statusRequestHeaderFieldsTooLarge)
+ io.WriteString(w, "HTTP Error 431
Request Header Field(s) Too Large
")
+}
+
+// called from handler goroutines.
+// h may be nil.
+func (sc *http2serverConn) writeHeaders(st *http2stream, headerData *http2writeResHeaders) error {
+ sc.serveG.checkNotOn() // NOT on
+ var errc chan error
+ if headerData.h != nil {
+ // If there's a header map (which we don't own), so we have to block on
+ // waiting for this frame to be written, so an http.Flush mid-handler
+ // writes out the correct value of keys, before a handler later potentially
+ // mutates it.
+ errc = http2errChanPool.Get().(chan error)
+ }
+ if err := sc.writeFrameFromHandler(http2FrameWriteRequest{
+ write: headerData,
+ stream: st,
+ done: errc,
+ }); err != nil {
+ return err
+ }
+ if errc != nil {
+ select {
+ case err := <-errc:
+ http2errChanPool.Put(errc)
+ return err
+ case <-sc.doneServing:
+ return http2errClientDisconnected
+ case <-st.cw:
+ return http2errStreamClosed
+ }
+ }
+ return nil
+}
+
+// called from handler goroutines.
+func (sc *http2serverConn) write100ContinueHeaders(st *http2stream) {
+ sc.writeFrameFromHandler(http2FrameWriteRequest{
+ write: http2write100ContinueHeadersFrame{st.id},
+ stream: st,
+ })
+}
+
+// A bodyReadMsg tells the server loop that the http.Handler read n
+// bytes of the DATA from the client on the given stream.
+type http2bodyReadMsg struct {
+ st *http2stream
+ n int
+}
+
+// called from handler goroutines.
+// Notes that the handler for the given stream ID read n bytes of its body
+// and schedules flow control tokens to be sent.
+func (sc *http2serverConn) noteBodyReadFromHandler(st *http2stream, n int, err error) {
+ sc.serveG.checkNotOn() // NOT on
+ if n > 0 {
+ select {
+ case sc.bodyReadCh <- http2bodyReadMsg{st, n}:
+ case <-sc.doneServing:
+ }
+ }
+}
+
+func (sc *http2serverConn) noteBodyRead(st *http2stream, n int) {
+ sc.serveG.check()
+ sc.sendWindowUpdate(nil, n) // conn-level
+ if st.state != http2stateHalfClosedRemote && st.state != http2stateClosed {
+ // Don't send this WINDOW_UPDATE if the stream is closed
+ // remotely.
+ sc.sendWindowUpdate(st, n)
+ }
+}
+
+// st may be nil for conn-level
+func (sc *http2serverConn) sendWindowUpdate32(st *http2stream, n int32) {
+ sc.sendWindowUpdate(st, int(n))
+}
+
+// st may be nil for conn-level
+func (sc *http2serverConn) sendWindowUpdate(st *http2stream, n int) {
+ sc.serveG.check()
+ var streamID uint32
+ var send int32
+ if st == nil {
+ send = sc.inflow.add(n)
+ } else {
+ streamID = st.id
+ send = st.inflow.add(n)
+ }
+ if send == 0 {
+ return
+ }
+ sc.writeFrame(http2FrameWriteRequest{
+ write: http2writeWindowUpdate{streamID: streamID, n: uint32(send)},
+ stream: st,
+ })
+}
+
+// requestBody is the Handler's Request.Body type.
+// Read and Close may be called concurrently.
+type http2requestBody struct {
+ _ http2incomparable
+ stream *http2stream
+ conn *http2serverConn
+ closeOnce sync.Once // for use by Close only
+ sawEOF bool // for use by Read only
+ pipe *http2pipe // non-nil if we have an HTTP entity message body
+ needsContinue bool // need to send a 100-continue
+}
+
+func (b *http2requestBody) Close() error {
+ b.closeOnce.Do(func() {
+ if b.pipe != nil {
+ b.pipe.BreakWithError(http2errClosedBody)
+ }
+ })
+ return nil
+}
+
+func (b *http2requestBody) Read(p []byte) (n int, err error) {
+ if b.needsContinue {
+ b.needsContinue = false
+ b.conn.write100ContinueHeaders(b.stream)
+ }
+ if b.pipe == nil || b.sawEOF {
+ return 0, io.EOF
+ }
+ n, err = b.pipe.Read(p)
+ if err == io.EOF {
+ b.sawEOF = true
+ }
+ if b.conn == nil && http2inTests {
+ return
+ }
+ b.conn.noteBodyReadFromHandler(b.stream, n, err)
+ return
+}
+
+// responseWriter is the http.ResponseWriter implementation. It's
+// intentionally small (1 pointer wide) to minimize garbage. The
+// responseWriterState pointer inside is zeroed at the end of a
+// request (in handlerDone) and calls on the responseWriter thereafter
+// simply crash (caller's mistake), but the much larger responseWriterState
+// and buffers are reused between multiple requests.
+type http2responseWriter struct {
+ rws *http2responseWriterState
+}
+
+// Optional http.ResponseWriter interfaces implemented.
+var (
+ _ CloseNotifier = (*http2responseWriter)(nil)
+ _ Flusher = (*http2responseWriter)(nil)
+ _ http2stringWriter = (*http2responseWriter)(nil)
+)
+
+type http2responseWriterState struct {
+ // immutable within a request:
+ stream *http2stream
+ req *Request
+ conn *http2serverConn
+
+ // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
+ bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
+
+ // mutated by http.Handler goroutine:
+ handlerHeader Header // nil until called
+ snapHeader Header // snapshot of handlerHeader at WriteHeader time
+ trailers []string // set in writeChunk
+ status int // status code passed to WriteHeader
+ wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
+ sentHeader bool // have we sent the header frame?
+ handlerDone bool // handler has finished
+
+ sentContentLen int64 // non-zero if handler set a Content-Length header
+ wroteBytes int64
+
+ closeNotifierMu sync.Mutex // guards closeNotifierCh
+ closeNotifierCh chan bool // nil until first used
+}
+
+type http2chunkWriter struct{ rws *http2responseWriterState }
+
+func (cw http2chunkWriter) Write(p []byte) (n int, err error) {
+ n, err = cw.rws.writeChunk(p)
+ if err == http2errStreamClosed {
+ // If writing failed because the stream has been closed,
+ // return the reason it was closed.
+ err = cw.rws.stream.closeErr
+ }
+ return n, err
+}
+
+func (rws *http2responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
+
+func (rws *http2responseWriterState) hasNonemptyTrailers() bool {
+ for _, trailer := range rws.trailers {
+ if _, ok := rws.handlerHeader[trailer]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+// declareTrailer is called for each Trailer header when the
+// response header is written. It notes that a header will need to be
+// written in the trailers at the end of the response.
+func (rws *http2responseWriterState) declareTrailer(k string) {
+ k = CanonicalHeaderKey(k)
+ if !httpguts.ValidTrailerHeader(k) {
+ // Forbidden by RFC 7230, section 4.1.2.
+ rws.conn.logf("ignoring invalid trailer %q", k)
+ return
+ }
+ if !http2strSliceContains(rws.trailers, k) {
+ rws.trailers = append(rws.trailers, k)
+ }
+}
+
+// writeChunk writes chunks from the bufio.Writer. But because
+// bufio.Writer may bypass its chunking, sometimes p may be
+// arbitrarily large.
+//
+// writeChunk is also responsible (on the first chunk) for sending the
+// HEADER response.
+func (rws *http2responseWriterState) writeChunk(p []byte) (n int, err error) {
+ if !rws.wroteHeader {
+ rws.writeHeader(200)
+ }
+
+ if rws.handlerDone {
+ rws.promoteUndeclaredTrailers()
+ }
+
+ isHeadResp := rws.req.Method == "HEAD"
+ if !rws.sentHeader {
+ rws.sentHeader = true
+ var ctype, clen string
+ if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
+ rws.snapHeader.Del("Content-Length")
+ if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
+ rws.sentContentLen = int64(cl)
+ } else {
+ clen = ""
+ }
+ }
+ _, hasContentLength := rws.snapHeader["Content-Length"]
+ if !hasContentLength && clen == "" && rws.handlerDone && http2bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
+ clen = strconv.Itoa(len(p))
+ }
+ _, hasContentType := rws.snapHeader["Content-Type"]
+ // If the Content-Encoding is non-blank, we shouldn't
+ // sniff the body. See Issue golang.org/issue/31753.
+ ce := rws.snapHeader.Get("Content-Encoding")
+ hasCE := len(ce) > 0
+ if !hasCE && !hasContentType && http2bodyAllowedForStatus(rws.status) && len(p) > 0 {
+ ctype = DetectContentType(p)
+ }
+ var date string
+ if _, ok := rws.snapHeader["Date"]; !ok {
+ // TODO(bradfitz): be faster here, like net/http? measure.
+ date = time.Now().UTC().Format(TimeFormat)
+ }
+
+ for _, v := range rws.snapHeader["Trailer"] {
+ http2foreachHeaderElement(v, rws.declareTrailer)
+ }
+
+ // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),
+ // but respect "Connection" == "close" to mean sending a GOAWAY and tearing
+ // down the TCP connection when idle, like we do for HTTP/1.
+ // TODO: remove more Connection-specific header fields here, in addition
+ // to "Connection".
+ if _, ok := rws.snapHeader["Connection"]; ok {
+ v := rws.snapHeader.Get("Connection")
+ delete(rws.snapHeader, "Connection")
+ if v == "close" {
+ rws.conn.startGracefulShutdown()
+ }
+ }
+
+ endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
+ err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
+ streamID: rws.stream.id,
+ httpResCode: rws.status,
+ h: rws.snapHeader,
+ endStream: endStream,
+ contentType: ctype,
+ contentLength: clen,
+ date: date,
+ })
+ if err != nil {
+ return 0, err
+ }
+ if endStream {
+ return 0, nil
+ }
+ }
+ if isHeadResp {
+ return len(p), nil
+ }
+ if len(p) == 0 && !rws.handlerDone {
+ return 0, nil
+ }
+
+ // only send trailers if they have actually been defined by the
+ // server handler.
+ hasNonemptyTrailers := rws.hasNonemptyTrailers()
+ endStream := rws.handlerDone && !hasNonemptyTrailers
+ if len(p) > 0 || endStream {
+ // only send a 0 byte DATA frame if we're ending the stream.
+ if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
+ return 0, err
+ }
+ }
+
+ if rws.handlerDone && hasNonemptyTrailers {
+ err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
+ streamID: rws.stream.id,
+ h: rws.handlerHeader,
+ trailers: rws.trailers,
+ endStream: true,
+ })
+ return len(p), err
+ }
+ return len(p), nil
+}
+
+// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
+// that, if present, signals that the map entry is actually for
+// the response trailers, and not the response headers. The prefix
+// is stripped after the ServeHTTP call finishes and the values are
+// sent in the trailers.
+//
+// This mechanism is intended only for trailers that are not known
+// prior to the headers being written. If the set of trailers is fixed
+// or known before the header is written, the normal Go trailers mechanism
+// is preferred:
+//
+// https://golang.org/pkg/net/http/#ResponseWriter
+// https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
+const http2TrailerPrefix = "Trailer:"
+
+// promoteUndeclaredTrailers permits http.Handlers to set trailers
+// after the header has already been flushed. Because the Go
+// ResponseWriter interface has no way to set Trailers (only the
+// Header), and because we didn't want to expand the ResponseWriter
+// interface, and because nobody used trailers, and because RFC 7230
+// says you SHOULD (but not must) predeclare any trailers in the
+// header, the official ResponseWriter rules said trailers in Go must
+// be predeclared, and then we reuse the same ResponseWriter.Header()
+// map to mean both Headers and Trailers. When it's time to write the
+// Trailers, we pick out the fields of Headers that were declared as
+// trailers. That worked for a while, until we found the first major
+// user of Trailers in the wild: gRPC (using them only over http2),
+// and gRPC libraries permit setting trailers mid-stream without
+// predeclaring them. So: change of plans. We still permit the old
+// way, but we also permit this hack: if a Header() key begins with
+// "Trailer:", the suffix of that key is a Trailer. Because ':' is an
+// invalid token byte anyway, there is no ambiguity. (And it's already
+// filtered out) It's mildly hacky, but not terrible.
+//
+// This method runs after the Handler is done and promotes any Header
+// fields to be trailers.
+func (rws *http2responseWriterState) promoteUndeclaredTrailers() {
+ for k, vv := range rws.handlerHeader {
+ if !strings.HasPrefix(k, http2TrailerPrefix) {
+ continue
+ }
+ trailerKey := strings.TrimPrefix(k, http2TrailerPrefix)
+ rws.declareTrailer(trailerKey)
+ rws.handlerHeader[CanonicalHeaderKey(trailerKey)] = vv
+ }
+
+ if len(rws.trailers) > 1 {
+ sorter := http2sorterPool.Get().(*http2sorter)
+ sorter.SortStrings(rws.trailers)
+ http2sorterPool.Put(sorter)
+ }
+}
+
+func (w *http2responseWriter) SetReadDeadline(deadline time.Time) error {
+ st := w.rws.stream
+ if !deadline.IsZero() && deadline.Before(time.Now()) {
+ // If we're setting a deadline in the past, reset the stream immediately
+ // so writes after SetWriteDeadline returns will fail.
+ st.onReadTimeout()
+ return nil
+ }
+ w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
+ if st.readDeadline != nil {
+ if !st.readDeadline.Stop() {
+ // Deadline already exceeded, or stream has been closed.
+ return
+ }
+ }
+ if deadline.IsZero() {
+ st.readDeadline = nil
+ } else if st.readDeadline == nil {
+ st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
+ } else {
+ st.readDeadline.Reset(deadline.Sub(time.Now()))
+ }
+ })
+ return nil
+}
+
+func (w *http2responseWriter) SetWriteDeadline(deadline time.Time) error {
+ st := w.rws.stream
+ if !deadline.IsZero() && deadline.Before(time.Now()) {
+ // If we're setting a deadline in the past, reset the stream immediately
+ // so writes after SetWriteDeadline returns will fail.
+ st.onWriteTimeout()
+ return nil
+ }
+ w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
+ if st.writeDeadline != nil {
+ if !st.writeDeadline.Stop() {
+ // Deadline already exceeded, or stream has been closed.
+ return
+ }
+ }
+ if deadline.IsZero() {
+ st.writeDeadline = nil
+ } else if st.writeDeadline == nil {
+ st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
+ } else {
+ st.writeDeadline.Reset(deadline.Sub(time.Now()))
+ }
+ })
+ return nil
+}
+
+func (w *http2responseWriter) Flush() {
+ w.FlushError()
+}
+
+func (w *http2responseWriter) FlushError() error {
+ rws := w.rws
+ if rws == nil {
+ panic("Header called after Handler finished")
+ }
+ var err error
+ if rws.bw.Buffered() > 0 {
+ err = rws.bw.Flush()
+ } else {
+ // The bufio.Writer won't call chunkWriter.Write
+ // (writeChunk with zero bytes), so we have to do it
+ // ourselves to force the HTTP response header and/or
+ // final DATA frame (with END_STREAM) to be sent.
+ _, err = http2chunkWriter{rws}.Write(nil)
+ if err == nil {
+ select {
+ case <-rws.stream.cw:
+ err = rws.stream.closeErr
+ default:
+ }
+ }
+ }
+ return err
+}
+
+func (w *http2responseWriter) CloseNotify() <-chan bool {
+ rws := w.rws
+ if rws == nil {
+ panic("CloseNotify called after Handler finished")
+ }
+ rws.closeNotifierMu.Lock()
+ ch := rws.closeNotifierCh
+ if ch == nil {
+ ch = make(chan bool, 1)
+ rws.closeNotifierCh = ch
+ cw := rws.stream.cw
+ go func() {
+ cw.Wait() // wait for close
+ ch <- true
+ }()
+ }
+ rws.closeNotifierMu.Unlock()
+ return ch
+}
+
+func (w *http2responseWriter) Header() Header {
+ rws := w.rws
+ if rws == nil {
+ panic("Header called after Handler finished")
+ }
+ if rws.handlerHeader == nil {
+ rws.handlerHeader = make(Header)
+ }
+ return rws.handlerHeader
+}
+
+// checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
+func http2checkWriteHeaderCode(code int) {
+ // Issue 22880: require valid WriteHeader status codes.
+ // For now we only enforce that it's three digits.
+ // In the future we might block things over 599 (600 and above aren't defined
+ // at http://httpwg.org/specs/rfc7231.html#status.codes).
+ // But for now any three digits.
+ //
+ // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
+ // no equivalent bogus thing we can realistically send in HTTP/2,
+ // so we'll consistently panic instead and help people find their bugs
+ // early. (We can't return an error from WriteHeader even if we wanted to.)
+ if code < 100 || code > 999 {
+ panic(fmt.Sprintf("invalid WriteHeader code %v", code))
+ }
+}
+
+func (w *http2responseWriter) WriteHeader(code int) {
+ rws := w.rws
+ if rws == nil {
+ panic("WriteHeader called after Handler finished")
+ }
+ rws.writeHeader(code)
+}
+
+func (rws *http2responseWriterState) writeHeader(code int) {
+ if rws.wroteHeader {
+ return
+ }
+
+ http2checkWriteHeaderCode(code)
+
+ // Handle informational headers
+ if code >= 100 && code <= 199 {
+ // Per RFC 8297 we must not clear the current header map
+ h := rws.handlerHeader
+
+ _, cl := h["Content-Length"]
+ _, te := h["Transfer-Encoding"]
+ if cl || te {
+ h = h.Clone()
+ h.Del("Content-Length")
+ h.Del("Transfer-Encoding")
+ }
+
+ rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
+ streamID: rws.stream.id,
+ httpResCode: code,
+ h: h,
+ endStream: rws.handlerDone && !rws.hasTrailers(),
+ })
+
+ return
+ }
+
+ rws.wroteHeader = true
+ rws.status = code
+ if len(rws.handlerHeader) > 0 {
+ rws.snapHeader = http2cloneHeader(rws.handlerHeader)
+ }
+}
+
+func http2cloneHeader(h Header) Header {
+ h2 := make(Header, len(h))
+ for k, vv := range h {
+ vv2 := make([]string, len(vv))
+ copy(vv2, vv)
+ h2[k] = vv2
+ }
+ return h2
+}
+
+// The Life Of A Write is like this:
+//
+// * Handler calls w.Write or w.WriteString ->
+// * -> rws.bw (*bufio.Writer) ->
+// * (Handler might call Flush)
+// * -> chunkWriter{rws}
+// * -> responseWriterState.writeChunk(p []byte)
+// * -> responseWriterState.writeChunk (most of the magic; see comment there)
+func (w *http2responseWriter) Write(p []byte) (n int, err error) {
+ return w.write(len(p), p, "")
+}
+
+func (w *http2responseWriter) WriteString(s string) (n int, err error) {
+ return w.write(len(s), nil, s)
+}
+
+// either dataB or dataS is non-zero.
+func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
+ rws := w.rws
+ if rws == nil {
+ panic("Write called after Handler finished")
+ }
+ if !rws.wroteHeader {
+ w.WriteHeader(200)
+ }
+ if !http2bodyAllowedForStatus(rws.status) {
+ return 0, ErrBodyNotAllowed
+ }
+ rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
+ if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
+ // TODO: send a RST_STREAM
+ return 0, errors.New("http2: handler wrote more than declared Content-Length")
+ }
+
+ if dataB != nil {
+ return rws.bw.Write(dataB)
+ } else {
+ return rws.bw.WriteString(dataS)
+ }
+}
+
+func (w *http2responseWriter) handlerDone() {
+ rws := w.rws
+ rws.handlerDone = true
+ w.Flush()
+ w.rws = nil
+ http2responseWriterStatePool.Put(rws)
+}
+
+// Push errors.
+var (
+ http2ErrRecursivePush = errors.New("http2: recursive push not allowed")
+ http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
+)
+
+var _ Pusher = (*http2responseWriter)(nil)
+
+func (w *http2responseWriter) Push(target string, opts *PushOptions) error {
+ st := w.rws.stream
+ sc := st.sc
+ sc.serveG.checkNotOn()
+
+ // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
+ // http://tools.ietf.org/html/rfc7540#section-6.6
+ if st.isPushed() {
+ return http2ErrRecursivePush
+ }
+
+ if opts == nil {
+ opts = new(PushOptions)
+ }
+
+ // Default options.
+ if opts.Method == "" {
+ opts.Method = "GET"
+ }
+ if opts.Header == nil {
+ opts.Header = Header{}
+ }
+ wantScheme := "http"
+ if w.rws.req.TLS != nil {
+ wantScheme = "https"
+ }
+
+ // Validate the request.
+ u, err := url.Parse(target)
+ if err != nil {
+ return err
+ }
+ if u.Scheme == "" {
+ if !strings.HasPrefix(target, "/") {
+ return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
+ }
+ u.Scheme = wantScheme
+ u.Host = w.rws.req.Host
+ } else {
+ if u.Scheme != wantScheme {
+ return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
+ }
+ if u.Host == "" {
+ return errors.New("URL must have a host")
+ }
+ }
+ for k := range opts.Header {
+ if strings.HasPrefix(k, ":") {
+ return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
+ }
+ // These headers are meaningful only if the request has a body,
+ // but PUSH_PROMISE requests cannot have a body.
+ // http://tools.ietf.org/html/rfc7540#section-8.2
+ // Also disallow Host, since the promised URL must be absolute.
+ if http2asciiEqualFold(k, "content-length") ||
+ http2asciiEqualFold(k, "content-encoding") ||
+ http2asciiEqualFold(k, "trailer") ||
+ http2asciiEqualFold(k, "te") ||
+ http2asciiEqualFold(k, "expect") ||
+ http2asciiEqualFold(k, "host") {
+ return fmt.Errorf("promised request headers cannot include %q", k)
+ }
+ }
+ if err := http2checkValidHTTP2RequestHeaders(opts.Header); err != nil {
+ return err
+ }
+
+ // The RFC effectively limits promised requests to GET and HEAD:
+ // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
+ // http://tools.ietf.org/html/rfc7540#section-8.2
+ if opts.Method != "GET" && opts.Method != "HEAD" {
+ return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
+ }
+
+ msg := &http2startPushRequest{
+ parent: st,
+ method: opts.Method,
+ url: u,
+ header: http2cloneHeader(opts.Header),
+ done: http2errChanPool.Get().(chan error),
+ }
+
+ select {
+ case <-sc.doneServing:
+ return http2errClientDisconnected
+ case <-st.cw:
+ return http2errStreamClosed
+ case sc.serveMsgCh <- msg:
+ }
+
+ select {
+ case <-sc.doneServing:
+ return http2errClientDisconnected
+ case <-st.cw:
+ return http2errStreamClosed
+ case err := <-msg.done:
+ http2errChanPool.Put(msg.done)
+ return err
+ }
+}
+
+type http2startPushRequest struct {
+ parent *http2stream
+ method string
+ url *url.URL
+ header Header
+ done chan error
+}
+
+func (sc *http2serverConn) startPush(msg *http2startPushRequest) {
+ sc.serveG.check()
+
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
+ // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
+ // is in either the "open" or "half-closed (remote)" state.
+ if msg.parent.state != http2stateOpen && msg.parent.state != http2stateHalfClosedRemote {
+ // responseWriter.Push checks that the stream is peer-initiated.
+ msg.done <- http2errStreamClosed
+ return
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
+ if !sc.pushEnabled {
+ msg.done <- ErrNotSupported
+ return
+ }
+
+ // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
+ // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
+ // is written. Once the ID is allocated, we start the request handler.
+ allocatePromisedID := func() (uint32, error) {
+ sc.serveG.check()
+
+ // Check this again, just in case. Technically, we might have received
+ // an updated SETTINGS by the time we got around to writing this frame.
+ if !sc.pushEnabled {
+ return 0, ErrNotSupported
+ }
+ // http://tools.ietf.org/html/rfc7540#section-6.5.2.
+ if sc.curPushedStreams+1 > sc.clientMaxStreams {
+ return 0, http2ErrPushLimitReached
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1.
+ // Streams initiated by the server MUST use even-numbered identifiers.
+ // A server that is unable to establish a new stream identifier can send a GOAWAY
+ // frame so that the client is forced to open a new connection for new streams.
+ if sc.maxPushPromiseID+2 >= 1<<31 {
+ sc.startGracefulShutdownInternal()
+ return 0, http2ErrPushLimitReached
+ }
+ sc.maxPushPromiseID += 2
+ promisedID := sc.maxPushPromiseID
+
+ // http://tools.ietf.org/html/rfc7540#section-8.2.
+ // Strictly speaking, the new stream should start in "reserved (local)", then
+ // transition to "half closed (remote)" after sending the initial HEADERS, but
+ // we start in "half closed (remote)" for simplicity.
+ // See further comments at the definition of stateHalfClosedRemote.
+ promised := sc.newStream(promisedID, msg.parent.id, http2stateHalfClosedRemote)
+ rw, req, err := sc.newWriterAndRequestNoBody(promised, http2requestParam{
+ method: msg.method,
+ scheme: msg.url.Scheme,
+ authority: msg.url.Host,
+ path: msg.url.RequestURI(),
+ header: http2cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
+ })
+ if err != nil {
+ // Should not happen, since we've already validated msg.url.
+ panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
+ }
+
+ sc.curHandlers++
+ go sc.runHandler(rw, req, sc.handler.ServeHTTP)
+ return promisedID, nil
+ }
+
+ sc.writeFrame(http2FrameWriteRequest{
+ write: &http2writePushPromise{
+ streamID: msg.parent.id,
+ method: msg.method,
+ url: msg.url,
+ h: msg.header,
+ allocatePromisedID: allocatePromisedID,
+ },
+ stream: msg.parent,
+ done: msg.done,
+ })
+}
+
+// foreachHeaderElement splits v according to the "#rule" construction
+// in RFC 7230 section 7 and calls fn for each non-empty element.
+func http2foreachHeaderElement(v string, fn func(string)) {
+ v = textproto.TrimString(v)
+ if v == "" {
+ return
+ }
+ if !strings.Contains(v, ",") {
+ fn(v)
+ return
+ }
+ for _, f := range strings.Split(v, ",") {
+ if f = textproto.TrimString(f); f != "" {
+ fn(f)
+ }
+ }
+}
+
+// From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
+var http2connHeaders = []string{
+ "Connection",
+ "Keep-Alive",
+ "Proxy-Connection",
+ "Transfer-Encoding",
+ "Upgrade",
+}
+
+// checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
+// per RFC 7540 Section 8.1.2.2.
+// The returned error is reported to users.
+func http2checkValidHTTP2RequestHeaders(h Header) error {
+ for _, k := range http2connHeaders {
+ if _, ok := h[k]; ok {
+ return fmt.Errorf("request header %q is not valid in HTTP/2", k)
+ }
+ }
+ te := h["Te"]
+ if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
+ return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
+ }
+ return nil
+}
+
+func http2new400Handler(err error) HandlerFunc {
+ return func(w ResponseWriter, r *Request) {
+ Error(w, err.Error(), StatusBadRequest)
+ }
+}
+
+// h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
+// disabled. See comments on h1ServerShutdownChan above for why
+// the code is written this way.
+func http2h1ServerKeepAlivesDisabled(hs *Server) bool {
+ var x interface{} = hs
+ type I interface {
+ doKeepAlives() bool
+ }
+ if hs, ok := x.(I); ok {
+ return !hs.doKeepAlives()
+ }
+ return false
+}
+
+func (sc *http2serverConn) countError(name string, err error) error {
+ if sc == nil || sc.srv == nil {
+ return err
+ }
+ f := sc.srv.CountError
+ if f == nil {
+ return err
+ }
+ var typ string
+ var code http2ErrCode
+ switch e := err.(type) {
+ case http2ConnectionError:
+ typ = "conn"
+ code = http2ErrCode(e)
+ case http2StreamError:
+ typ = "stream"
+ code = http2ErrCode(e.Code)
+ default:
+ return err
+ }
+ codeStr := http2errCodeName[code]
+ if codeStr == "" {
+ codeStr = strconv.Itoa(int(code))
+ }
+ f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
+ return err
+}
+
+const (
+ // transportDefaultConnFlow is how many connection-level flow control
+ // tokens we give the server at start-up, past the default 64k.
+ http2transportDefaultConnFlow = 1 << 30
+
+ // transportDefaultStreamFlow is how many stream-level flow
+ // control tokens we announce to the peer, and how many bytes
+ // we buffer per stream.
+ http2transportDefaultStreamFlow = 4 << 20
+
+ http2defaultUserAgent = "Go-http-client/2.0"
+
+ // initialMaxConcurrentStreams is a connections maxConcurrentStreams until
+ // it's received servers initial SETTINGS frame, which corresponds with the
+ // spec's minimum recommended value.
+ http2initialMaxConcurrentStreams = 100
+
+ // defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
+ // if the server doesn't include one in its initial SETTINGS frame.
+ http2defaultMaxConcurrentStreams = 1000
+)
+
+// Transport is an HTTP/2 Transport.
+//
+// A Transport internally caches connections to servers. It is safe
+// for concurrent use by multiple goroutines.
+type http2Transport struct {
+ // DialTLSContext specifies an optional dial function with context for
+ // creating TLS connections for requests.
+ //
+ // If DialTLSContext and DialTLS is nil, tls.Dial is used.
+ //
+ // If the returned net.Conn has a ConnectionState method like tls.Conn,
+ // it will be used to set http.Response.TLS.
+ DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
+
+ // DialTLS specifies an optional dial function for creating
+ // TLS connections for requests.
+ //
+ // If DialTLSContext and DialTLS is nil, tls.Dial is used.
+ //
+ // Deprecated: Use DialTLSContext instead, which allows the transport
+ // to cancel dials as soon as they are no longer needed.
+ // If both are set, DialTLSContext takes priority.
+ DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
+
+ // TLSClientConfig specifies the TLS configuration to use with
+ // tls.Client. If nil, the default configuration is used.
+ TLSClientConfig *tls.Config
+
+ // ConnPool optionally specifies an alternate connection pool to use.
+ // If nil, the default is used.
+ ConnPool http2ClientConnPool
+
+ // DisableCompression, if true, prevents the Transport from
+ // requesting compression with an "Accept-Encoding: gzip"
+ // request header when the Request contains no existing
+ // Accept-Encoding value. If the Transport requests gzip on
+ // its own and gets a gzipped response, it's transparently
+ // decoded in the Response.Body. However, if the user
+ // explicitly requested gzip it is not automatically
+ // uncompressed.
+ DisableCompression bool
+
+ // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
+ // plain-text "http" scheme. Note that this does not enable h2c support.
+ AllowHTTP bool
+
+ // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
+ // send in the initial settings frame. It is how many bytes
+ // of response headers are allowed. Unlike the http2 spec, zero here
+ // means to use a default limit (currently 10MB). If you actually
+ // want to advertise an unlimited value to the peer, Transport
+ // interprets the highest possible value here (0xffffffff or 1<<32-1)
+ // to mean no limit.
+ MaxHeaderListSize uint32
+
+ // MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
+ // initial settings frame. It is the size in bytes of the largest frame
+ // payload that the sender is willing to receive. If 0, no setting is
+ // sent, and the value is provided by the peer, which should be 16384
+ // according to the spec:
+ // https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
+ // Values are bounded in the range 16k to 16M.
+ MaxReadFrameSize uint32
+
+ // MaxDecoderHeaderTableSize optionally specifies the http2
+ // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
+ // informs the remote endpoint of the maximum size of the header compression
+ // table used to decode header blocks, in octets. If zero, the default value
+ // of 4096 is used.
+ MaxDecoderHeaderTableSize uint32
+
+ // MaxEncoderHeaderTableSize optionally specifies an upper limit for the
+ // header compression table used for encoding request headers. Received
+ // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
+ // the default value of 4096 is used.
+ MaxEncoderHeaderTableSize uint32
+
+ // StrictMaxConcurrentStreams controls whether the server's
+ // SETTINGS_MAX_CONCURRENT_STREAMS should be respected
+ // globally. If false, new TCP connections are created to the
+ // server as needed to keep each under the per-connection
+ // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
+ // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
+ // a global limit and callers of RoundTrip block when needed,
+ // waiting for their turn.
+ StrictMaxConcurrentStreams bool
+
+ // ReadIdleTimeout is the timeout after which a health check using ping
+ // frame will be carried out if no frame is received on the connection.
+ // Note that a ping response will is considered a received frame, so if
+ // there is no other traffic on the connection, the health check will
+ // be performed every ReadIdleTimeout interval.
+ // If zero, no health check is performed.
+ ReadIdleTimeout time.Duration
+
+ // PingTimeout is the timeout after which the connection will be closed
+ // if a response to Ping is not received.
+ // Defaults to 15s.
+ PingTimeout time.Duration
+
+ // WriteByteTimeout is the timeout after which the connection will be
+ // closed no data can be written to it. The timeout begins when data is
+ // available to write, and is extended whenever any bytes are written.
+ WriteByteTimeout time.Duration
+
+ // CountError, if non-nil, is called on HTTP/2 transport errors.
+ // It's intended to increment a metric for monitoring, such
+ // as an expvar or Prometheus metric.
+ // The errType consists of only ASCII word characters.
+ CountError func(errType string)
+
+ // t1, if non-nil, is the standard library Transport using
+ // this transport. Its settings are used (but not its
+ // RoundTrip method, etc).
+ t1 *Transport
+
+ connPoolOnce sync.Once
+ connPoolOrDef http2ClientConnPool // non-nil version of ConnPool
+}
+
+func (t *http2Transport) maxHeaderListSize() uint32 {
+ if t.MaxHeaderListSize == 0 {
+ return 10 << 20
+ }
+ if t.MaxHeaderListSize == 0xffffffff {
+ return 0
+ }
+ return t.MaxHeaderListSize
+}
+
+func (t *http2Transport) maxFrameReadSize() uint32 {
+ if t.MaxReadFrameSize == 0 {
+ return 0 // use the default provided by the peer
+ }
+ if t.MaxReadFrameSize < http2minMaxFrameSize {
+ return http2minMaxFrameSize
+ }
+ if t.MaxReadFrameSize > http2maxFrameSize {
+ return http2maxFrameSize
+ }
+ return t.MaxReadFrameSize
+}
+
+func (t *http2Transport) disableCompression() bool {
+ return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
+}
+
+func (t *http2Transport) pingTimeout() time.Duration {
+ if t.PingTimeout == 0 {
+ return 15 * time.Second
+ }
+ return t.PingTimeout
+
+}
+
+// ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
+// It returns an error if t1 has already been HTTP/2-enabled.
+//
+// Use ConfigureTransports instead to configure the HTTP/2 Transport.
+func http2ConfigureTransport(t1 *Transport) error {
+ _, err := http2ConfigureTransports(t1)
+ return err
+}
+
+// ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
+// It returns a new HTTP/2 Transport for further configuration.
+// It returns an error if t1 has already been HTTP/2-enabled.
+func http2ConfigureTransports(t1 *Transport) (*http2Transport, error) {
+ return http2configureTransports(t1)
+}
+
+func http2configureTransports(t1 *Transport) (*http2Transport, error) {
+ connPool := new(http2clientConnPool)
+ t2 := &http2Transport{
+ ConnPool: http2noDialClientConnPool{connPool},
+ t1: t1,
+ }
+ connPool.t = t2
+ if err := http2registerHTTPSProtocol(t1, http2noDialH2RoundTripper{t2}); err != nil {
+ return nil, err
+ }
+ if t1.TLSClientConfig == nil {
+ t1.TLSClientConfig = new(tls.Config)
+ }
+ if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
+ t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
+ }
+ if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
+ t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
+ }
+ upgradeFn := func(authority string, c *tls.Conn) RoundTripper {
+ addr := http2authorityAddr("https", authority)
+ if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
+ go c.Close()
+ return http2erringRoundTripper{err}
+ } else if !used {
+ // Turns out we don't need this c.
+ // For example, two goroutines made requests to the same host
+ // at the same time, both kicking off TCP dials. (since protocol
+ // was unknown)
+ go c.Close()
+ }
+ return t2
+ }
+ if m := t1.TLSNextProto; len(m) == 0 {
+ t1.TLSNextProto = map[string]func(string, *tls.Conn) RoundTripper{
+ "h2": upgradeFn,
+ }
+ } else {
+ m["h2"] = upgradeFn
+ }
+ return t2, nil
+}
+
+func (t *http2Transport) connPool() http2ClientConnPool {
+ t.connPoolOnce.Do(t.initConnPool)
+ return t.connPoolOrDef
+}
+
+func (t *http2Transport) initConnPool() {
+ if t.ConnPool != nil {
+ t.connPoolOrDef = t.ConnPool
+ } else {
+ t.connPoolOrDef = &http2clientConnPool{t: t}
+ }
+}
+
+// ClientConn is the state of a single HTTP/2 client connection to an
+// HTTP/2 server.
+type http2ClientConn struct {
+ t *http2Transport
+ tconn net.Conn // usually *tls.Conn, except specialized impls
+ tlsState *tls.ConnectionState // nil only for specialized impls
+ reused uint32 // whether conn is being reused; atomic
+ singleUse bool // whether being used for a single http.Request
+ getConnCalled bool // used by clientConnPool
+
+ // readLoop goroutine fields:
+ readerDone chan struct{} // closed on error
+ readerErr error // set before readerDone is closed
+
+ idleTimeout time.Duration // or 0 for never
+ idleTimer *time.Timer
+
+ mu sync.Mutex // guards following
+ cond *sync.Cond // hold mu; broadcast on flow/closed changes
+ flow http2outflow // our conn-level flow control quota (cs.outflow is per stream)
+ inflow http2inflow // peer's conn-level flow control
+ doNotReuse bool // whether conn is marked to not be reused for any future requests
+ closing bool
+ closed bool
+ seenSettings bool // true if we've seen a settings frame, false otherwise
+ wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
+ goAway *http2GoAwayFrame // if non-nil, the GoAwayFrame we received
+ goAwayDebug string // goAway frame's debug data, retained as a string
+ streams map[uint32]*http2clientStream // client-initiated
+ streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip
+ nextStreamID uint32
+ pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
+ pings map[[8]byte]chan struct{} // in flight ping data to notification channel
+ br *bufio.Reader
+ lastActive time.Time
+ lastIdle time.Time // time last idle
+ // Settings from peer: (also guarded by wmu)
+ maxFrameSize uint32
+ maxConcurrentStreams uint32
+ peerMaxHeaderListSize uint64
+ peerMaxHeaderTableSize uint32
+ initialWindowSize uint32
+
+ // reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
+ // Write to reqHeaderMu to lock it, read from it to unlock.
+ // Lock reqmu BEFORE mu or wmu.
+ reqHeaderMu chan struct{}
+
+ // wmu is held while writing.
+ // Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
+ // Only acquire both at the same time when changing peer settings.
+ wmu sync.Mutex
+ bw *bufio.Writer
+ fr *http2Framer
+ werr error // first write error that has occurred
+ hbuf bytes.Buffer // HPACK encoder writes into this
+ henc *hpack.Encoder
+}
+
+// clientStream is the state for a single HTTP/2 stream. One of these
+// is created for each Transport.RoundTrip call.
+type http2clientStream struct {
+ cc *http2ClientConn
+
+ // Fields of Request that we may access even after the response body is closed.
+ ctx context.Context
+ reqCancel <-chan struct{}
+
+ trace *httptrace.ClientTrace // or nil
+ ID uint32
+ bufPipe http2pipe // buffered pipe with the flow-controlled response payload
+ requestedGzip bool
+ isHead bool
+
+ abortOnce sync.Once
+ abort chan struct{} // closed to signal stream should end immediately
+ abortErr error // set if abort is closed
+
+ peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
+ donec chan struct{} // closed after the stream is in the closed state
+ on100 chan struct{} // buffered; written to if a 100 is received
+
+ respHeaderRecv chan struct{} // closed when headers are received
+ res *Response // set if respHeaderRecv is closed
+
+ flow http2outflow // guarded by cc.mu
+ inflow http2inflow // guarded by cc.mu
+ bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
+ readErr error // sticky read error; owned by transportResponseBody.Read
+
+ reqBody io.ReadCloser
+ reqBodyContentLength int64 // -1 means unknown
+ reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done
+
+ // owned by writeRequest:
+ sentEndStream bool // sent an END_STREAM flag to the peer
+ sentHeaders bool
+
+ // owned by clientConnReadLoop:
+ firstByte bool // got the first response byte
+ pastHeaders bool // got first MetaHeadersFrame (actual headers)
+ pastTrailers bool // got optional second MetaHeadersFrame (trailers)
+ num1xx uint8 // number of 1xx responses seen
+ readClosed bool // peer sent an END_STREAM flag
+ readAborted bool // read loop reset the stream
+
+ trailer Header // accumulated trailers
+ resTrailer *Header // client's Response.Trailer
+}
+
+var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
+
+// get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
+// if any. It returns nil if not set or if the Go version is too old.
+func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
+ if fn := http2got1xxFuncForTests; fn != nil {
+ return fn
+ }
+ return http2traceGot1xxResponseFunc(cs.trace)
+}
+
+func (cs *http2clientStream) abortStream(err error) {
+ cs.cc.mu.Lock()
+ defer cs.cc.mu.Unlock()
+ cs.abortStreamLocked(err)
+}
+
+func (cs *http2clientStream) abortStreamLocked(err error) {
+ cs.abortOnce.Do(func() {
+ cs.abortErr = err
+ close(cs.abort)
+ })
+ if cs.reqBody != nil {
+ cs.closeReqBodyLocked()
+ }
+ // TODO(dneil): Clean up tests where cs.cc.cond is nil.
+ if cs.cc.cond != nil {
+ // Wake up writeRequestBody if it is waiting on flow control.
+ cs.cc.cond.Broadcast()
+ }
+}
+
+func (cs *http2clientStream) abortRequestBodyWrite() {
+ cc := cs.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ if cs.reqBody != nil && cs.reqBodyClosed == nil {
+ cs.closeReqBodyLocked()
+ cc.cond.Broadcast()
+ }
+}
+
+func (cs *http2clientStream) closeReqBodyLocked() {
+ if cs.reqBodyClosed != nil {
+ return
+ }
+ cs.reqBodyClosed = make(chan struct{})
+ reqBodyClosed := cs.reqBodyClosed
+ go func() {
+ cs.reqBody.Close()
+ close(reqBodyClosed)
+ }()
+}
+
+type http2stickyErrWriter struct {
+ conn net.Conn
+ timeout time.Duration
+ err *error
+}
+
+func (sew http2stickyErrWriter) Write(p []byte) (n int, err error) {
+ if *sew.err != nil {
+ return 0, *sew.err
+ }
+ for {
+ if sew.timeout != 0 {
+ sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
+ }
+ nn, err := sew.conn.Write(p[n:])
+ n += nn
+ if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
+ // Keep extending the deadline so long as we're making progress.
+ continue
+ }
+ if sew.timeout != 0 {
+ sew.conn.SetWriteDeadline(time.Time{})
+ }
+ *sew.err = err
+ return n, err
+ }
+}
+
+// noCachedConnError is the concrete type of ErrNoCachedConn, which
+// needs to be detected by net/http regardless of whether it's its
+// bundled version (in h2_bundle.go with a rewritten type name) or
+// from a user's x/net/http2. As such, as it has a unique method name
+// (IsHTTP2NoCachedConnError) that net/http sniffs for via func
+// isNoCachedConnError.
+type http2noCachedConnError struct{}
+
+func (http2noCachedConnError) IsHTTP2NoCachedConnError() {}
+
+func (http2noCachedConnError) Error() string { return "http2: no cached connection was available" }
+
+// isNoCachedConnError reports whether err is of type noCachedConnError
+// or its equivalent renamed type in net/http2's h2_bundle.go. Both types
+// may coexist in the same running program.
+func http2isNoCachedConnError(err error) bool {
+ _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
+ return ok
+}
+
+var http2ErrNoCachedConn error = http2noCachedConnError{}
+
+// RoundTripOpt are options for the Transport.RoundTripOpt method.
+type http2RoundTripOpt struct {
+ // OnlyCachedConn controls whether RoundTripOpt may
+ // create a new TCP connection. If set true and
+ // no cached connection is available, RoundTripOpt
+ // will return ErrNoCachedConn.
+ OnlyCachedConn bool
+}
+
+func (t *http2Transport) RoundTrip(req *Request) (*Response, error) {
+ return t.RoundTripOpt(req, http2RoundTripOpt{})
+}
+
+// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
+// and returns a host:port. The port 443 is added if needed.
+func http2authorityAddr(scheme string, authority string) (addr string) {
+ host, port, err := net.SplitHostPort(authority)
+ if err != nil { // authority didn't have a port
+ host = authority
+ port = ""
+ }
+ if port == "" { // authority's port was empty
+ port = "443"
+ if scheme == "http" {
+ port = "80"
+ }
+ }
+ if a, err := idna.ToASCII(host); err == nil {
+ host = a
+ }
+ // IPv6 address literal, without a port:
+ if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
+ return host + ":" + port
+ }
+ return net.JoinHostPort(host, port)
+}
+
+var http2retryBackoffHook func(time.Duration) *time.Timer
+
+func http2backoffNewTimer(d time.Duration) *time.Timer {
+ if http2retryBackoffHook != nil {
+ return http2retryBackoffHook(d)
+ }
+ return time.NewTimer(d)
+}
+
+// RoundTripOpt is like RoundTrip, but takes options.
+func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error) {
+ if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
+ return nil, errors.New("http2: unsupported scheme")
+ }
+
+ addr := http2authorityAddr(req.URL.Scheme, req.URL.Host)
+ for retry := 0; ; retry++ {
+ cc, err := t.connPool().GetClientConn(req, addr)
+ if err != nil {
+ t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
+ return nil, err
+ }
+ reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
+ http2traceGotConn(req, cc, reused)
+ res, err := cc.RoundTrip(req)
+ if err != nil && retry <= 6 {
+ roundTripErr := err
+ if req, err = http2shouldRetryRequest(req, err); err == nil {
+ // After the first retry, do exponential backoff with 10% jitter.
+ if retry == 0 {
+ t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
+ continue
+ }
+ backoff := float64(uint(1) << (uint(retry) - 1))
+ backoff += backoff * (0.1 * mathrand.Float64())
+ d := time.Second * time.Duration(backoff)
+ timer := http2backoffNewTimer(d)
+ select {
+ case <-timer.C:
+ t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
+ continue
+ case <-req.Context().Done():
+ timer.Stop()
+ err = req.Context().Err()
+ }
+ }
+ }
+ if err != nil {
+ t.vlogf("RoundTrip failure: %v", err)
+ return nil, err
+ }
+ return res, nil
+ }
+}
+
+// CloseIdleConnections closes any connections which were previously
+// connected from previous requests but are now sitting idle.
+// It does not interrupt any connections currently in use.
+func (t *http2Transport) CloseIdleConnections() {
+ if cp, ok := t.connPool().(http2clientConnPoolIdleCloser); ok {
+ cp.closeIdleConnections()
+ }
+}
+
+var (
+ http2errClientConnClosed = errors.New("http2: client conn is closed")
+ http2errClientConnUnusable = errors.New("http2: client conn not usable")
+ http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
+)
+
+// shouldRetryRequest is called by RoundTrip when a request fails to get
+// response headers. It is always called with a non-nil error.
+// It returns either a request to retry (either the same request, or a
+// modified clone), or an error if the request can't be replayed.
+func http2shouldRetryRequest(req *Request, err error) (*Request, error) {
+ if !http2canRetryError(err) {
+ return nil, err
+ }
+ // If the Body is nil (or http.NoBody), it's safe to reuse
+ // this request and its Body.
+ if req.Body == nil || req.Body == NoBody {
+ return req, nil
+ }
+
+ // If the request body can be reset back to its original
+ // state via the optional req.GetBody, do that.
+ if req.GetBody != nil {
+ body, err := req.GetBody()
+ if err != nil {
+ return nil, err
+ }
+ newReq := *req
+ newReq.Body = body
+ return &newReq, nil
+ }
+
+ // The Request.Body can't reset back to the beginning, but we
+ // don't seem to have started to read from it yet, so reuse
+ // the request directly.
+ if err == http2errClientConnUnusable {
+ return req, nil
+ }
+
+ return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
+}
+
+func http2canRetryError(err error) bool {
+ if err == http2errClientConnUnusable || err == http2errClientConnGotGoAway {
+ return true
+ }
+ if se, ok := err.(http2StreamError); ok {
+ if se.Code == http2ErrCodeProtocol && se.Cause == http2errFromPeer {
+ // See golang/go#47635, golang/go#42777
+ return true
+ }
+ return se.Code == http2ErrCodeRefusedStream
+ }
+ return false
+}
+
+func (t *http2Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error) {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, err
+ }
+ tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
+ if err != nil {
+ return nil, err
+ }
+ return t.newClientConn(tconn, singleUse)
+}
+
+func (t *http2Transport) newTLSConfig(host string) *tls.Config {
+ cfg := new(tls.Config)
+ if t.TLSClientConfig != nil {
+ *cfg = *t.TLSClientConfig.Clone()
+ }
+ if !http2strSliceContains(cfg.NextProtos, http2NextProtoTLS) {
+ cfg.NextProtos = append([]string{http2NextProtoTLS}, cfg.NextProtos...)
+ }
+ if cfg.ServerName == "" {
+ cfg.ServerName = host
+ }
+ return cfg
+}
+
+func (t *http2Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
+ if t.DialTLSContext != nil {
+ return t.DialTLSContext(ctx, network, addr, tlsCfg)
+ } else if t.DialTLS != nil {
+ return t.DialTLS(network, addr, tlsCfg)
+ }
+
+ tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
+ if err != nil {
+ return nil, err
+ }
+ state := tlsCn.ConnectionState()
+ if p := state.NegotiatedProtocol; p != http2NextProtoTLS {
+ return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2NextProtoTLS)
+ }
+ if !state.NegotiatedProtocolIsMutual {
+ return nil, errors.New("http2: could not negotiate protocol mutually")
+ }
+ return tlsCn, nil
+}
+
+// disableKeepAlives reports whether connections should be closed as
+// soon as possible after handling the first request.
+func (t *http2Transport) disableKeepAlives() bool {
+ return t.t1 != nil && t.t1.DisableKeepAlives
+}
+
+func (t *http2Transport) expectContinueTimeout() time.Duration {
+ if t.t1 == nil {
+ return 0
+ }
+ return t.t1.ExpectContinueTimeout
+}
+
+func (t *http2Transport) maxDecoderHeaderTableSize() uint32 {
+ if v := t.MaxDecoderHeaderTableSize; v > 0 {
+ return v
+ }
+ return http2initialHeaderTableSize
+}
+
+func (t *http2Transport) maxEncoderHeaderTableSize() uint32 {
+ if v := t.MaxEncoderHeaderTableSize; v > 0 {
+ return v
+ }
+ return http2initialHeaderTableSize
+}
+
+func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error) {
+ return t.newClientConn(c, t.disableKeepAlives())
+}
+
+func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error) {
+ cc := &http2ClientConn{
+ t: t,
+ tconn: c,
+ readerDone: make(chan struct{}),
+ nextStreamID: 1,
+ maxFrameSize: 16 << 10, // spec default
+ initialWindowSize: 65535, // spec default
+ maxConcurrentStreams: http2initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
+ peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
+ streams: make(map[uint32]*http2clientStream),
+ singleUse: singleUse,
+ wantSettingsAck: true,
+ pings: make(map[[8]byte]chan struct{}),
+ reqHeaderMu: make(chan struct{}, 1),
+ }
+ if d := t.idleConnTimeout(); d != 0 {
+ cc.idleTimeout = d
+ cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
+ }
+ if http2VerboseLogs {
+ t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
+ }
+
+ cc.cond = sync.NewCond(&cc.mu)
+ cc.flow.add(int32(http2initialWindowSize))
+
+ // TODO: adjust this writer size to account for frame size +
+ // MTU + crypto/tls record padding.
+ cc.bw = bufio.NewWriter(http2stickyErrWriter{
+ conn: c,
+ timeout: t.WriteByteTimeout,
+ err: &cc.werr,
+ })
+ cc.br = bufio.NewReader(c)
+ cc.fr = http2NewFramer(cc.bw, cc.br)
+ if t.maxFrameReadSize() != 0 {
+ cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
+ }
+ if t.CountError != nil {
+ cc.fr.countError = t.CountError
+ }
+ maxHeaderTableSize := t.maxDecoderHeaderTableSize()
+ cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
+ cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
+
+ cc.henc = hpack.NewEncoder(&cc.hbuf)
+ cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
+ cc.peerMaxHeaderTableSize = http2initialHeaderTableSize
+
+ if t.AllowHTTP {
+ cc.nextStreamID = 3
+ }
+
+ if cs, ok := c.(http2connectionStater); ok {
+ state := cs.ConnectionState()
+ cc.tlsState = &state
+ }
+
+ initialSettings := []http2Setting{
+ {ID: http2SettingEnablePush, Val: 0},
+ {ID: http2SettingInitialWindowSize, Val: http2transportDefaultStreamFlow},
+ }
+ if max := t.maxFrameReadSize(); max != 0 {
+ initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxFrameSize, Val: max})
+ }
+ if max := t.maxHeaderListSize(); max != 0 {
+ initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxHeaderListSize, Val: max})
+ }
+ if maxHeaderTableSize != http2initialHeaderTableSize {
+ initialSettings = append(initialSettings, http2Setting{ID: http2SettingHeaderTableSize, Val: maxHeaderTableSize})
+ }
+
+ cc.bw.Write(http2clientPreface)
+ cc.fr.WriteSettings(initialSettings...)
+ cc.fr.WriteWindowUpdate(0, http2transportDefaultConnFlow)
+ cc.inflow.init(http2transportDefaultConnFlow + http2initialWindowSize)
+ cc.bw.Flush()
+ if cc.werr != nil {
+ cc.Close()
+ return nil, cc.werr
+ }
+
+ go cc.readLoop()
+ return cc, nil
+}
+
+func (cc *http2ClientConn) healthCheck() {
+ pingTimeout := cc.t.pingTimeout()
+ // We don't need to periodically ping in the health check, because the readLoop of ClientConn will
+ // trigger the healthCheck again if there is no frame received.
+ ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
+ defer cancel()
+ cc.vlogf("http2: Transport sending health check")
+ err := cc.Ping(ctx)
+ if err != nil {
+ cc.vlogf("http2: Transport health check failure: %v", err)
+ cc.closeForLostPing()
+ } else {
+ cc.vlogf("http2: Transport health check success")
+ }
+}
+
+// SetDoNotReuse marks cc as not reusable for future HTTP requests.
+func (cc *http2ClientConn) SetDoNotReuse() {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ cc.doNotReuse = true
+}
+
+func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame) {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ old := cc.goAway
+ cc.goAway = f
+
+ // Merge the previous and current GoAway error frames.
+ if cc.goAwayDebug == "" {
+ cc.goAwayDebug = string(f.DebugData())
+ }
+ if old != nil && old.ErrCode != http2ErrCodeNo {
+ cc.goAway.ErrCode = old.ErrCode
+ }
+ last := f.LastStreamID
+ for streamID, cs := range cc.streams {
+ if streamID > last {
+ cs.abortStreamLocked(http2errClientConnGotGoAway)
+ }
+ }
+}
+
+// CanTakeNewRequest reports whether the connection can take a new request,
+// meaning it has not been closed or received or sent a GOAWAY.
+//
+// If the caller is going to immediately make a new request on this
+// connection, use ReserveNewRequest instead.
+func (cc *http2ClientConn) CanTakeNewRequest() bool {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.canTakeNewRequestLocked()
+}
+
+// ReserveNewRequest is like CanTakeNewRequest but also reserves a
+// concurrent stream in cc. The reservation is decremented on the
+// next call to RoundTrip.
+func (cc *http2ClientConn) ReserveNewRequest() bool {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ if st := cc.idleStateLocked(); !st.canTakeNewRequest {
+ return false
+ }
+ cc.streamsReserved++
+ return true
+}
+
+// ClientConnState describes the state of a ClientConn.
+type http2ClientConnState struct {
+ // Closed is whether the connection is closed.
+ Closed bool
+
+ // Closing is whether the connection is in the process of
+ // closing. It may be closing due to shutdown, being a
+ // single-use connection, being marked as DoNotReuse, or
+ // having received a GOAWAY frame.
+ Closing bool
+
+ // StreamsActive is how many streams are active.
+ StreamsActive int
+
+ // StreamsReserved is how many streams have been reserved via
+ // ClientConn.ReserveNewRequest.
+ StreamsReserved int
+
+ // StreamsPending is how many requests have been sent in excess
+ // of the peer's advertised MaxConcurrentStreams setting and
+ // are waiting for other streams to complete.
+ StreamsPending int
+
+ // MaxConcurrentStreams is how many concurrent streams the
+ // peer advertised as acceptable. Zero means no SETTINGS
+ // frame has been received yet.
+ MaxConcurrentStreams uint32
+
+ // LastIdle, if non-zero, is when the connection last
+ // transitioned to idle state.
+ LastIdle time.Time
+}
+
+// State returns a snapshot of cc's state.
+func (cc *http2ClientConn) State() http2ClientConnState {
+ cc.wmu.Lock()
+ maxConcurrent := cc.maxConcurrentStreams
+ if !cc.seenSettings {
+ maxConcurrent = 0
+ }
+ cc.wmu.Unlock()
+
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return http2ClientConnState{
+ Closed: cc.closed,
+ Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
+ StreamsActive: len(cc.streams),
+ StreamsReserved: cc.streamsReserved,
+ StreamsPending: cc.pendingRequests,
+ LastIdle: cc.lastIdle,
+ MaxConcurrentStreams: maxConcurrent,
+ }
+}
+
+// clientConnIdleState describes the suitability of a client
+// connection to initiate a new RoundTrip request.
+type http2clientConnIdleState struct {
+ canTakeNewRequest bool
+}
+
+func (cc *http2ClientConn) idleState() http2clientConnIdleState {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.idleStateLocked()
+}
+
+func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState) {
+ if cc.singleUse && cc.nextStreamID > 1 {
+ return
+ }
+ var maxConcurrentOkay bool
+ if cc.t.StrictMaxConcurrentStreams {
+ // We'll tell the caller we can take a new request to
+ // prevent the caller from dialing a new TCP
+ // connection, but then we'll block later before
+ // writing it.
+ maxConcurrentOkay = true
+ } else {
+ maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
+ }
+
+ st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
+ !cc.doNotReuse &&
+ int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
+ !cc.tooIdleLocked()
+ return
+}
+
+func (cc *http2ClientConn) canTakeNewRequestLocked() bool {
+ st := cc.idleStateLocked()
+ return st.canTakeNewRequest
+}
+
+// tooIdleLocked reports whether this connection has been been sitting idle
+// for too much wall time.
+func (cc *http2ClientConn) tooIdleLocked() bool {
+ // The Round(0) strips the monontonic clock reading so the
+ // times are compared based on their wall time. We don't want
+ // to reuse a connection that's been sitting idle during
+ // VM/laptop suspend if monotonic time was also frozen.
+ return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
+}
+
+// onIdleTimeout is called from a time.AfterFunc goroutine. It will
+// only be called when we're idle, but because we're coming from a new
+// goroutine, there could be a new request coming in at the same time,
+// so this simply calls the synchronized closeIfIdle to shut down this
+// connection. The timer could just call closeIfIdle, but this is more
+// clear.
+func (cc *http2ClientConn) onIdleTimeout() {
+ cc.closeIfIdle()
+}
+
+func (cc *http2ClientConn) closeConn() {
+ t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
+ defer t.Stop()
+ cc.tconn.Close()
+}
+
+// A tls.Conn.Close can hang for a long time if the peer is unresponsive.
+// Try to shut it down more aggressively.
+func (cc *http2ClientConn) forceCloseConn() {
+ tc, ok := cc.tconn.(*tls.Conn)
+ if !ok {
+ return
+ }
+ if nc := tc.NetConn(); nc != nil {
+ nc.Close()
+ }
+}
+
+func (cc *http2ClientConn) closeIfIdle() {
+ cc.mu.Lock()
+ if len(cc.streams) > 0 || cc.streamsReserved > 0 {
+ cc.mu.Unlock()
+ return
+ }
+ cc.closed = true
+ nextID := cc.nextStreamID
+ // TODO: do clients send GOAWAY too? maybe? Just Close:
+ cc.mu.Unlock()
+
+ if http2VerboseLogs {
+ cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
+ }
+ cc.closeConn()
+}
+
+func (cc *http2ClientConn) isDoNotReuseAndIdle() bool {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.doNotReuse && len(cc.streams) == 0
+}
+
+var http2shutdownEnterWaitStateHook = func() {}
+
+// Shutdown gracefully closes the client connection, waiting for running streams to complete.
+func (cc *http2ClientConn) Shutdown(ctx context.Context) error {
+ if err := cc.sendGoAway(); err != nil {
+ return err
+ }
+ // Wait for all in-flight streams to complete or connection to close
+ done := make(chan struct{})
+ cancelled := false // guarded by cc.mu
+ go func() {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ for {
+ if len(cc.streams) == 0 || cc.closed {
+ cc.closed = true
+ close(done)
+ break
+ }
+ if cancelled {
+ break
+ }
+ cc.cond.Wait()
+ }
+ }()
+ http2shutdownEnterWaitStateHook()
+ select {
+ case <-done:
+ cc.closeConn()
+ return nil
+ case <-ctx.Done():
+ cc.mu.Lock()
+ // Free the goroutine above
+ cancelled = true
+ cc.cond.Broadcast()
+ cc.mu.Unlock()
+ return ctx.Err()
+ }
+}
+
+func (cc *http2ClientConn) sendGoAway() error {
+ cc.mu.Lock()
+ closing := cc.closing
+ cc.closing = true
+ maxStreamID := cc.nextStreamID
+ cc.mu.Unlock()
+ if closing {
+ // GOAWAY sent already
+ return nil
+ }
+
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ // Send a graceful shutdown frame to server
+ if err := cc.fr.WriteGoAway(maxStreamID, http2ErrCodeNo, nil); err != nil {
+ return err
+ }
+ if err := cc.bw.Flush(); err != nil {
+ return err
+ }
+ // Prevent new requests
+ return nil
+}
+
+// closes the client connection immediately. In-flight requests are interrupted.
+// err is sent to streams.
+func (cc *http2ClientConn) closeForError(err error) {
+ cc.mu.Lock()
+ cc.closed = true
+ for _, cs := range cc.streams {
+ cs.abortStreamLocked(err)
+ }
+ cc.cond.Broadcast()
+ cc.mu.Unlock()
+ cc.closeConn()
+}
+
+// Close closes the client connection immediately.
+//
+// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
+func (cc *http2ClientConn) Close() error {
+ err := errors.New("http2: client connection force closed via ClientConn.Close")
+ cc.closeForError(err)
+ return nil
+}
+
+// closes the client connection immediately. In-flight requests are interrupted.
+func (cc *http2ClientConn) closeForLostPing() {
+ err := errors.New("http2: client connection lost")
+ if f := cc.t.CountError; f != nil {
+ f("conn_close_lost_ping")
+ }
+ cc.closeForError(err)
+}
+
+// errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
+// exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
+var http2errRequestCanceled = errors.New("net/http: request canceled")
+
+func http2commaSeparatedTrailers(req *Request) (string, error) {
+ keys := make([]string, 0, len(req.Trailer))
+ for k := range req.Trailer {
+ k = http2canonicalHeader(k)
+ switch k {
+ case "Transfer-Encoding", "Trailer", "Content-Length":
+ return "", fmt.Errorf("invalid Trailer key %q", k)
+ }
+ keys = append(keys, k)
+ }
+ if len(keys) > 0 {
+ sort.Strings(keys)
+ return strings.Join(keys, ","), nil
+ }
+ return "", nil
+}
+
+func (cc *http2ClientConn) responseHeaderTimeout() time.Duration {
+ if cc.t.t1 != nil {
+ return cc.t.t1.ResponseHeaderTimeout
+ }
+ // No way to do this (yet?) with just an http2.Transport. Probably
+ // no need. Request.Cancel this is the new way. We only need to support
+ // this for compatibility with the old http.Transport fields when
+ // we're doing transparent http2.
+ return 0
+}
+
+// checkConnHeaders checks whether req has any invalid connection-level headers.
+// per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
+// Certain headers are special-cased as okay but not transmitted later.
+func http2checkConnHeaders(req *Request) error {
+ if v := req.Header.Get("Upgrade"); v != "" {
+ return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
+ }
+ if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
+ return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
+ }
+ if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !http2asciiEqualFold(vv[0], "close") && !http2asciiEqualFold(vv[0], "keep-alive")) {
+ return fmt.Errorf("http2: invalid Connection request header: %q", vv)
+ }
+ return nil
+}
+
+// actualContentLength returns a sanitized version of
+// req.ContentLength, where 0 actually means zero (not unknown) and -1
+// means unknown.
+func http2actualContentLength(req *Request) int64 {
+ if req.Body == nil || req.Body == NoBody {
+ return 0
+ }
+ if req.ContentLength != 0 {
+ return req.ContentLength
+ }
+ return -1
+}
+
+func (cc *http2ClientConn) decrStreamReservations() {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ cc.decrStreamReservationsLocked()
+}
+
+func (cc *http2ClientConn) decrStreamReservationsLocked() {
+ if cc.streamsReserved > 0 {
+ cc.streamsReserved--
+ }
+}
+
+func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error) {
+ ctx := req.Context()
+ cs := &http2clientStream{
+ cc: cc,
+ ctx: ctx,
+ reqCancel: req.Cancel,
+ isHead: req.Method == "HEAD",
+ reqBody: req.Body,
+ reqBodyContentLength: http2actualContentLength(req),
+ trace: httptrace.ContextClientTrace(ctx),
+ peerClosed: make(chan struct{}),
+ abort: make(chan struct{}),
+ respHeaderRecv: make(chan struct{}),
+ donec: make(chan struct{}),
+ }
+ go cs.doRequest(req)
+
+ waitDone := func() error {
+ select {
+ case <-cs.donec:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-cs.reqCancel:
+ return http2errRequestCanceled
+ }
+ }
+
+ handleResponseHeaders := func() (*Response, error) {
+ res := cs.res
+ if res.StatusCode > 299 {
+ // On error or status code 3xx, 4xx, 5xx, etc abort any
+ // ongoing write, assuming that the server doesn't care
+ // about our request body. If the server replied with 1xx or
+ // 2xx, however, then assume the server DOES potentially
+ // want our body (e.g. full-duplex streaming:
+ // golang.org/issue/13444). If it turns out the server
+ // doesn't, they'll RST_STREAM us soon enough. This is a
+ // heuristic to avoid adding knobs to Transport. Hopefully
+ // we can keep it.
+ cs.abortRequestBodyWrite()
+ }
+ res.Request = req
+ res.TLS = cc.tlsState
+ if res.Body == http2noBody && http2actualContentLength(req) == 0 {
+ // If there isn't a request or response body still being
+ // written, then wait for the stream to be closed before
+ // RoundTrip returns.
+ if err := waitDone(); err != nil {
+ return nil, err
+ }
+ }
+ return res, nil
+ }
+
+ cancelRequest := func(cs *http2clientStream, err error) error {
+ cs.cc.mu.Lock()
+ bodyClosed := cs.reqBodyClosed
+ cs.cc.mu.Unlock()
+ // Wait for the request body to be closed.
+ //
+ // If nothing closed the body before now, abortStreamLocked
+ // will have started a goroutine to close it.
+ //
+ // Closing the body before returning avoids a race condition
+ // with net/http checking its readTrackingBody to see if the
+ // body was read from or closed. See golang/go#60041.
+ //
+ // The body is closed in a separate goroutine without the
+ // connection mutex held, but dropping the mutex before waiting
+ // will keep us from holding it indefinitely if the body
+ // close is slow for some reason.
+ if bodyClosed != nil {
+ <-bodyClosed
+ }
+ return err
+ }
+
+ for {
+ select {
+ case <-cs.respHeaderRecv:
+ return handleResponseHeaders()
+ case <-cs.abort:
+ select {
+ case <-cs.respHeaderRecv:
+ // If both cs.respHeaderRecv and cs.abort are signaling,
+ // pick respHeaderRecv. The server probably wrote the
+ // response and immediately reset the stream.
+ // golang.org/issue/49645
+ return handleResponseHeaders()
+ default:
+ waitDone()
+ return nil, cs.abortErr
+ }
+ case <-ctx.Done():
+ err := ctx.Err()
+ cs.abortStream(err)
+ return nil, cancelRequest(cs, err)
+ case <-cs.reqCancel:
+ cs.abortStream(http2errRequestCanceled)
+ return nil, cancelRequest(cs, http2errRequestCanceled)
+ }
+ }
+}
+
+// doRequest runs for the duration of the request lifetime.
+//
+// It sends the request and performs post-request cleanup (closing Request.Body, etc.).
+func (cs *http2clientStream) doRequest(req *Request) {
+ err := cs.writeRequest(req)
+ cs.cleanupWriteRequest(err)
+}
+
+// writeRequest sends a request.
+//
+// It returns nil after the request is written, the response read,
+// and the request stream is half-closed by the peer.
+//
+// It returns non-nil if the request ends otherwise.
+// If the returned error is StreamError, the error Code may be used in resetting the stream.
+func (cs *http2clientStream) writeRequest(req *Request) (err error) {
+ cc := cs.cc
+ ctx := cs.ctx
+
+ if err := http2checkConnHeaders(req); err != nil {
+ return err
+ }
+
+ // Acquire the new-request lock by writing to reqHeaderMu.
+ // This lock guards the critical section covering allocating a new stream ID
+ // (requires mu) and creating the stream (requires wmu).
+ if cc.reqHeaderMu == nil {
+ panic("RoundTrip on uninitialized ClientConn") // for tests
+ }
+ select {
+ case cc.reqHeaderMu <- struct{}{}:
+ case <-cs.reqCancel:
+ return http2errRequestCanceled
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ cc.mu.Lock()
+ if cc.idleTimer != nil {
+ cc.idleTimer.Stop()
+ }
+ cc.decrStreamReservationsLocked()
+ if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
+ cc.mu.Unlock()
+ <-cc.reqHeaderMu
+ return err
+ }
+ cc.addStreamLocked(cs) // assigns stream ID
+ if http2isConnectionCloseRequest(req) {
+ cc.doNotReuse = true
+ }
+ cc.mu.Unlock()
+
+ // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
+ if !cc.t.disableCompression() &&
+ req.Header.Get("Accept-Encoding") == "" &&
+ req.Header.Get("Range") == "" &&
+ !cs.isHead {
+ // Request gzip only, not deflate. Deflate is ambiguous and
+ // not as universally supported anyway.
+ // See: https://zlib.net/zlib_faq.html#faq39
+ //
+ // Note that we don't request this for HEAD requests,
+ // due to a bug in nginx:
+ // http://trac.nginx.org/nginx/ticket/358
+ // https://golang.org/issue/5522
+ //
+ // We don't request gzip if the request is for a range, since
+ // auto-decoding a portion of a gzipped document will just fail
+ // anyway. See https://golang.org/issue/8923
+ cs.requestedGzip = true
+ }
+
+ continueTimeout := cc.t.expectContinueTimeout()
+ if continueTimeout != 0 {
+ if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
+ continueTimeout = 0
+ } else {
+ cs.on100 = make(chan struct{}, 1)
+ }
+ }
+
+ // Past this point (where we send request headers), it is possible for
+ // RoundTrip to return successfully. Since the RoundTrip contract permits
+ // the caller to "mutate or reuse" the Request after closing the Response's Body,
+ // we must take care when referencing the Request from here on.
+ err = cs.encodeAndWriteHeaders(req)
+ <-cc.reqHeaderMu
+ if err != nil {
+ return err
+ }
+
+ hasBody := cs.reqBodyContentLength != 0
+ if !hasBody {
+ cs.sentEndStream = true
+ } else {
+ if continueTimeout != 0 {
+ http2traceWait100Continue(cs.trace)
+ timer := time.NewTimer(continueTimeout)
+ select {
+ case <-timer.C:
+ err = nil
+ case <-cs.on100:
+ err = nil
+ case <-cs.abort:
+ err = cs.abortErr
+ case <-ctx.Done():
+ err = ctx.Err()
+ case <-cs.reqCancel:
+ err = http2errRequestCanceled
+ }
+ timer.Stop()
+ if err != nil {
+ http2traceWroteRequest(cs.trace, err)
+ return err
+ }
+ }
+
+ if err = cs.writeRequestBody(req); err != nil {
+ if err != http2errStopReqBodyWrite {
+ http2traceWroteRequest(cs.trace, err)
+ return err
+ }
+ } else {
+ cs.sentEndStream = true
+ }
+ }
+
+ http2traceWroteRequest(cs.trace, err)
+
+ var respHeaderTimer <-chan time.Time
+ var respHeaderRecv chan struct{}
+ if d := cc.responseHeaderTimeout(); d != 0 {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ respHeaderTimer = timer.C
+ respHeaderRecv = cs.respHeaderRecv
+ }
+ // Wait until the peer half-closes its end of the stream,
+ // or until the request is aborted (via context, error, or otherwise),
+ // whichever comes first.
+ for {
+ select {
+ case <-cs.peerClosed:
+ return nil
+ case <-respHeaderTimer:
+ return http2errTimeout
+ case <-respHeaderRecv:
+ respHeaderRecv = nil
+ respHeaderTimer = nil // keep waiting for END_STREAM
+ case <-cs.abort:
+ return cs.abortErr
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-cs.reqCancel:
+ return http2errRequestCanceled
+ }
+ }
+}
+
+func (cs *http2clientStream) encodeAndWriteHeaders(req *Request) error {
+ cc := cs.cc
+ ctx := cs.ctx
+
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+
+ // If the request was canceled while waiting for cc.mu, just quit.
+ select {
+ case <-cs.abort:
+ return cs.abortErr
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-cs.reqCancel:
+ return http2errRequestCanceled
+ default:
+ }
+
+ // Encode headers.
+ //
+ // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
+ // sent by writeRequestBody below, along with any Trailers,
+ // again in form HEADERS{1}, CONTINUATION{0,})
+ trailers, err := http2commaSeparatedTrailers(req)
+ if err != nil {
+ return err
+ }
+ hasTrailers := trailers != ""
+ contentLen := http2actualContentLength(req)
+ hasBody := contentLen != 0
+ hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
+ if err != nil {
+ return err
+ }
+
+ // Write the request.
+ endStream := !hasBody && !hasTrailers
+ cs.sentHeaders = true
+ err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
+ http2traceWroteHeaders(cs.trace)
+ return err
+}
+
+// cleanupWriteRequest performs post-request tasks.
+//
+// If err (the result of writeRequest) is non-nil and the stream is not closed,
+// cleanupWriteRequest will send a reset to the peer.
+func (cs *http2clientStream) cleanupWriteRequest(err error) {
+ cc := cs.cc
+
+ if cs.ID == 0 {
+ // We were canceled before creating the stream, so return our reservation.
+ cc.decrStreamReservations()
+ }
+
+ // TODO: write h12Compare test showing whether
+ // Request.Body is closed by the Transport,
+ // and in multiple cases: server replies <=299 and >299
+ // while still writing request body
+ cc.mu.Lock()
+ mustCloseBody := false
+ if cs.reqBody != nil && cs.reqBodyClosed == nil {
+ mustCloseBody = true
+ cs.reqBodyClosed = make(chan struct{})
+ }
+ bodyClosed := cs.reqBodyClosed
+ cc.mu.Unlock()
+ if mustCloseBody {
+ cs.reqBody.Close()
+ close(bodyClosed)
+ }
+ if bodyClosed != nil {
+ <-bodyClosed
+ }
+
+ if err != nil && cs.sentEndStream {
+ // If the connection is closed immediately after the response is read,
+ // we may be aborted before finishing up here. If the stream was closed
+ // cleanly on both sides, there is no error.
+ select {
+ case <-cs.peerClosed:
+ err = nil
+ default:
+ }
+ }
+ if err != nil {
+ cs.abortStream(err) // possibly redundant, but harmless
+ if cs.sentHeaders {
+ if se, ok := err.(http2StreamError); ok {
+ if se.Cause != http2errFromPeer {
+ cc.writeStreamReset(cs.ID, se.Code, err)
+ }
+ } else {
+ cc.writeStreamReset(cs.ID, http2ErrCodeCancel, err)
+ }
+ }
+ cs.bufPipe.CloseWithError(err) // no-op if already closed
+ } else {
+ if cs.sentHeaders && !cs.sentEndStream {
+ cc.writeStreamReset(cs.ID, http2ErrCodeNo, nil)
+ }
+ cs.bufPipe.CloseWithError(http2errRequestCanceled)
+ }
+ if cs.ID != 0 {
+ cc.forgetStreamID(cs.ID)
+ }
+
+ cc.wmu.Lock()
+ werr := cc.werr
+ cc.wmu.Unlock()
+ if werr != nil {
+ cc.Close()
+ }
+
+ close(cs.donec)
+}
+
+// awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
+// Must hold cc.mu.
+func (cc *http2ClientConn) awaitOpenSlotForStreamLocked(cs *http2clientStream) error {
+ for {
+ cc.lastActive = time.Now()
+ if cc.closed || !cc.canTakeNewRequestLocked() {
+ return http2errClientConnUnusable
+ }
+ cc.lastIdle = time.Time{}
+ if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
+ return nil
+ }
+ cc.pendingRequests++
+ cc.cond.Wait()
+ cc.pendingRequests--
+ select {
+ case <-cs.abort:
+ return cs.abortErr
+ default:
+ }
+ }
+}
+
+// requires cc.wmu be held
+func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
+ first := true // first frame written (HEADERS is first, then CONTINUATION)
+ for len(hdrs) > 0 && cc.werr == nil {
+ chunk := hdrs
+ if len(chunk) > maxFrameSize {
+ chunk = chunk[:maxFrameSize]
+ }
+ hdrs = hdrs[len(chunk):]
+ endHeaders := len(hdrs) == 0
+ if first {
+ cc.fr.WriteHeaders(http2HeadersFrameParam{
+ StreamID: streamID,
+ BlockFragment: chunk,
+ EndStream: endStream,
+ EndHeaders: endHeaders,
+ })
+ first = false
+ } else {
+ cc.fr.WriteContinuation(streamID, endHeaders, chunk)
+ }
+ }
+ cc.bw.Flush()
+ return cc.werr
+}
+
+// internal error values; they don't escape to callers
+var (
+ // abort request body write; don't send cancel
+ http2errStopReqBodyWrite = errors.New("http2: aborting request body write")
+
+ // abort request body write, but send stream reset of cancel.
+ http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
+
+ http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
+)
+
+// frameScratchBufferLen returns the length of a buffer to use for
+// outgoing request bodies to read/write to/from.
+//
+// It returns max(1, min(peer's advertised max frame size,
+// Request.ContentLength+1, 512KB)).
+func (cs *http2clientStream) frameScratchBufferLen(maxFrameSize int) int {
+ const max = 512 << 10
+ n := int64(maxFrameSize)
+ if n > max {
+ n = max
+ }
+ if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
+ // Add an extra byte past the declared content-length to
+ // give the caller's Request.Body io.Reader a chance to
+ // give us more bytes than they declared, so we can catch it
+ // early.
+ n = cl + 1
+ }
+ if n < 1 {
+ return 1
+ }
+ return int(n) // doesn't truncate; max is 512K
+}
+
+// Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running
+// streaming requests using small frame sizes occupy large buffers initially allocated for prior
+// requests needing big buffers. The size ranges are as follows:
+// {0 KB, 16 KB], {16 KB, 32 KB], {32 KB, 64 KB], {64 KB, 128 KB], {128 KB, 256 KB],
+// {256 KB, 512 KB], {512 KB, infinity}
+// In practice, the maximum scratch buffer size should not exceed 512 KB due to
+// frameScratchBufferLen(maxFrameSize), thus the "infinity pool" should never be used.
+// It exists mainly as a safety measure, for potential future increases in max buffer size.
+var http2bufPools [7]sync.Pool // of *[]byte
+
+func http2bufPoolIndex(size int) int {
+ if size <= 16384 {
+ return 0
+ }
+ size -= 1
+ bits := bits.Len(uint(size))
+ index := bits - 14
+ if index >= len(http2bufPools) {
+ return len(http2bufPools) - 1
+ }
+ return index
+}
+
+func (cs *http2clientStream) writeRequestBody(req *Request) (err error) {
+ cc := cs.cc
+ body := cs.reqBody
+ sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
+
+ hasTrailers := req.Trailer != nil
+ remainLen := cs.reqBodyContentLength
+ hasContentLen := remainLen != -1
+
+ cc.mu.Lock()
+ maxFrameSize := int(cc.maxFrameSize)
+ cc.mu.Unlock()
+
+ // Scratch buffer for reading into & writing from.
+ scratchLen := cs.frameScratchBufferLen(maxFrameSize)
+ var buf []byte
+ index := http2bufPoolIndex(scratchLen)
+ if bp, ok := http2bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
+ defer http2bufPools[index].Put(bp)
+ buf = *bp
+ } else {
+ buf = make([]byte, scratchLen)
+ defer http2bufPools[index].Put(&buf)
+ }
+
+ var sawEOF bool
+ for !sawEOF {
+ n, err := body.Read(buf)
+ if hasContentLen {
+ remainLen -= int64(n)
+ if remainLen == 0 && err == nil {
+ // The request body's Content-Length was predeclared and
+ // we just finished reading it all, but the underlying io.Reader
+ // returned the final chunk with a nil error (which is one of
+ // the two valid things a Reader can do at EOF). Because we'd prefer
+ // to send the END_STREAM bit early, double-check that we're actually
+ // at EOF. Subsequent reads should return (0, EOF) at this point.
+ // If either value is different, we return an error in one of two ways below.
+ var scratch [1]byte
+ var n1 int
+ n1, err = body.Read(scratch[:])
+ remainLen -= int64(n1)
+ }
+ if remainLen < 0 {
+ err = http2errReqBodyTooLong
+ return err
+ }
+ }
+ if err != nil {
+ cc.mu.Lock()
+ bodyClosed := cs.reqBodyClosed != nil
+ cc.mu.Unlock()
+ switch {
+ case bodyClosed:
+ return http2errStopReqBodyWrite
+ case err == io.EOF:
+ sawEOF = true
+ err = nil
+ default:
+ return err
+ }
+ }
+
+ remain := buf[:n]
+ for len(remain) > 0 && err == nil {
+ var allowed int32
+ allowed, err = cs.awaitFlowControl(len(remain))
+ if err != nil {
+ return err
+ }
+ cc.wmu.Lock()
+ data := remain[:allowed]
+ remain = remain[allowed:]
+ sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
+ err = cc.fr.WriteData(cs.ID, sentEnd, data)
+ if err == nil {
+ // TODO(bradfitz): this flush is for latency, not bandwidth.
+ // Most requests won't need this. Make this opt-in or
+ // opt-out? Use some heuristic on the body type? Nagel-like
+ // timers? Based on 'n'? Only last chunk of this for loop,
+ // unless flow control tokens are low? For now, always.
+ // If we change this, see comment below.
+ err = cc.bw.Flush()
+ }
+ cc.wmu.Unlock()
+ }
+ if err != nil {
+ return err
+ }
+ }
+
+ if sentEnd {
+ // Already sent END_STREAM (which implies we have no
+ // trailers) and flushed, because currently all
+ // WriteData frames above get a flush. So we're done.
+ return nil
+ }
+
+ // Since the RoundTrip contract permits the caller to "mutate or reuse"
+ // a request after the Response's Body is closed, verify that this hasn't
+ // happened before accessing the trailers.
+ cc.mu.Lock()
+ trailer := req.Trailer
+ err = cs.abortErr
+ cc.mu.Unlock()
+ if err != nil {
+ return err
+ }
+
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ var trls []byte
+ if len(trailer) > 0 {
+ trls, err = cc.encodeTrailers(trailer)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Two ways to send END_STREAM: either with trailers, or
+ // with an empty DATA frame.
+ if len(trls) > 0 {
+ err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
+ } else {
+ err = cc.fr.WriteData(cs.ID, true, nil)
+ }
+ if ferr := cc.bw.Flush(); ferr != nil && err == nil {
+ err = ferr
+ }
+ return err
+}
+
+// awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
+// control tokens from the server.
+// It returns either the non-zero number of tokens taken or an error
+// if the stream is dead.
+func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
+ cc := cs.cc
+ ctx := cs.ctx
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ for {
+ if cc.closed {
+ return 0, http2errClientConnClosed
+ }
+ if cs.reqBodyClosed != nil {
+ return 0, http2errStopReqBodyWrite
+ }
+ select {
+ case <-cs.abort:
+ return 0, cs.abortErr
+ case <-ctx.Done():
+ return 0, ctx.Err()
+ case <-cs.reqCancel:
+ return 0, http2errRequestCanceled
+ default:
+ }
+ if a := cs.flow.available(); a > 0 {
+ take := a
+ if int(take) > maxBytes {
+
+ take = int32(maxBytes) // can't truncate int; take is int32
+ }
+ if take > int32(cc.maxFrameSize) {
+ take = int32(cc.maxFrameSize)
+ }
+ cs.flow.take(take)
+ return take, nil
+ }
+ cc.cond.Wait()
+ }
+}
+
+var http2errNilRequestURL = errors.New("http2: Request.URI is nil")
+
+// requires cc.wmu be held.
+func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
+ cc.hbuf.Reset()
+ if req.URL == nil {
+ return nil, http2errNilRequestURL
+ }
+
+ host := req.Host
+ if host == "" {
+ host = req.URL.Host
+ }
+ host, err := httpguts.PunycodeHostPort(host)
+ if err != nil {
+ return nil, err
+ }
+ if !httpguts.ValidHostHeader(host) {
+ return nil, errors.New("http2: invalid Host header")
+ }
+
+ var path string
+ if req.Method != "CONNECT" {
+ path = req.URL.RequestURI()
+ if !http2validPseudoPath(path) {
+ orig := path
+ path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
+ if !http2validPseudoPath(path) {
+ if req.URL.Opaque != "" {
+ return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
+ } else {
+ return nil, fmt.Errorf("invalid request :path %q", orig)
+ }
+ }
+ }
+ }
+
+ // Check for any invalid headers and return an error before we
+ // potentially pollute our hpack state. (We want to be able to
+ // continue to reuse the hpack encoder for future requests)
+ for k, vv := range req.Header {
+ if !httpguts.ValidHeaderFieldName(k) {
+ return nil, fmt.Errorf("invalid HTTP header name %q", k)
+ }
+ for _, v := range vv {
+ if !httpguts.ValidHeaderFieldValue(v) {
+ // Don't include the value in the error, because it may be sensitive.
+ return nil, fmt.Errorf("invalid HTTP header value for header %q", k)
+ }
+ }
+ }
+
+ enumerateHeaders := func(f func(name, value string)) {
+ // 8.1.2.3 Request Pseudo-Header Fields
+ // The :path pseudo-header field includes the path and query parts of the
+ // target URI (the path-absolute production and optionally a '?' character
+ // followed by the query production, see Sections 3.3 and 3.4 of
+ // [RFC3986]).
+ f(":authority", host)
+ m := req.Method
+ if m == "" {
+ m = MethodGet
+ }
+ f(":method", m)
+ if req.Method != "CONNECT" {
+ f(":path", path)
+ f(":scheme", req.URL.Scheme)
+ }
+ if trailers != "" {
+ f("trailer", trailers)
+ }
+
+ var didUA bool
+ for k, vv := range req.Header {
+ if http2asciiEqualFold(k, "host") || http2asciiEqualFold(k, "content-length") {
+ // Host is :authority, already sent.
+ // Content-Length is automatic, set below.
+ continue
+ } else if http2asciiEqualFold(k, "connection") ||
+ http2asciiEqualFold(k, "proxy-connection") ||
+ http2asciiEqualFold(k, "transfer-encoding") ||
+ http2asciiEqualFold(k, "upgrade") ||
+ http2asciiEqualFold(k, "keep-alive") {
+ // Per 8.1.2.2 Connection-Specific Header
+ // Fields, don't send connection-specific
+ // fields. We have already checked if any
+ // are error-worthy so just ignore the rest.
+ continue
+ } else if http2asciiEqualFold(k, "user-agent") {
+ // Match Go's http1 behavior: at most one
+ // User-Agent. If set to nil or empty string,
+ // then omit it. Otherwise if not mentioned,
+ // include the default (below).
+ didUA = true
+ if len(vv) < 1 {
+ continue
+ }
+ vv = vv[:1]
+ if vv[0] == "" {
+ continue
+ }
+ } else if http2asciiEqualFold(k, "cookie") {
+ // Per 8.1.2.5 To allow for better compression efficiency, the
+ // Cookie header field MAY be split into separate header fields,
+ // each with one or more cookie-pairs.
+ for _, v := range vv {
+ for {
+ p := strings.IndexByte(v, ';')
+ if p < 0 {
+ break
+ }
+ f("cookie", v[:p])
+ p++
+ // strip space after semicolon if any.
+ for p+1 <= len(v) && v[p] == ' ' {
+ p++
+ }
+ v = v[p:]
+ }
+ if len(v) > 0 {
+ f("cookie", v)
+ }
+ }
+ continue
+ }
+
+ for _, v := range vv {
+ f(k, v)
+ }
+ }
+ if http2shouldSendReqContentLength(req.Method, contentLength) {
+ f("content-length", strconv.FormatInt(contentLength, 10))
+ }
+ if addGzipHeader {
+ f("accept-encoding", "gzip")
+ }
+ if !didUA {
+ f("user-agent", http2defaultUserAgent)
+ }
+ }
+
+ // Do a first pass over the headers counting bytes to ensure
+ // we don't exceed cc.peerMaxHeaderListSize. This is done as a
+ // separate pass before encoding the headers to prevent
+ // modifying the hpack state.
+ hlSize := uint64(0)
+ enumerateHeaders(func(name, value string) {
+ hf := hpack.HeaderField{Name: name, Value: value}
+ hlSize += uint64(hf.Size())
+ })
+
+ if hlSize > cc.peerMaxHeaderListSize {
+ return nil, http2errRequestHeaderListSize
+ }
+
+ trace := httptrace.ContextClientTrace(req.Context())
+ traceHeaders := http2traceHasWroteHeaderField(trace)
+
+ // Header list size is ok. Write the headers.
+ enumerateHeaders(func(name, value string) {
+ name, ascii := http2lowerHeader(name)
+ if !ascii {
+ // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
+ // field names have to be ASCII characters (just as in HTTP/1.x).
+ return
+ }
+ cc.writeHeader(name, value)
+ if traceHeaders {
+ http2traceWroteHeaderField(trace, name, value)
+ }
+ })
+
+ return cc.hbuf.Bytes(), nil
+}
+
+// shouldSendReqContentLength reports whether the http2.Transport should send
+// a "content-length" request header. This logic is basically a copy of the net/http
+// transferWriter.shouldSendContentLength.
+// The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
+// -1 means unknown.
+func http2shouldSendReqContentLength(method string, contentLength int64) bool {
+ if contentLength > 0 {
+ return true
+ }
+ if contentLength < 0 {
+ return false
+ }
+ // For zero bodies, whether we send a content-length depends on the method.
+ // It also kinda doesn't matter for http2 either way, with END_STREAM.
+ switch method {
+ case "POST", "PUT", "PATCH":
+ return true
+ default:
+ return false
+ }
+}
+
+// requires cc.wmu be held.
+func (cc *http2ClientConn) encodeTrailers(trailer Header) ([]byte, error) {
+ cc.hbuf.Reset()
+
+ hlSize := uint64(0)
+ for k, vv := range trailer {
+ for _, v := range vv {
+ hf := hpack.HeaderField{Name: k, Value: v}
+ hlSize += uint64(hf.Size())
+ }
+ }
+ if hlSize > cc.peerMaxHeaderListSize {
+ return nil, http2errRequestHeaderListSize
+ }
+
+ for k, vv := range trailer {
+ lowKey, ascii := http2lowerHeader(k)
+ if !ascii {
+ // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
+ // field names have to be ASCII characters (just as in HTTP/1.x).
+ continue
+ }
+ // Transfer-Encoding, etc.. have already been filtered at the
+ // start of RoundTrip
+ for _, v := range vv {
+ cc.writeHeader(lowKey, v)
+ }
+ }
+ return cc.hbuf.Bytes(), nil
+}
+
+func (cc *http2ClientConn) writeHeader(name, value string) {
+ if http2VerboseLogs {
+ log.Printf("http2: Transport encoding header %q = %q", name, value)
+ }
+ cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
+}
+
+type http2resAndError struct {
+ _ http2incomparable
+ res *Response
+ err error
+}
+
+// requires cc.mu be held.
+func (cc *http2ClientConn) addStreamLocked(cs *http2clientStream) {
+ cs.flow.add(int32(cc.initialWindowSize))
+ cs.flow.setConnFlow(&cc.flow)
+ cs.inflow.init(http2transportDefaultStreamFlow)
+ cs.ID = cc.nextStreamID
+ cc.nextStreamID += 2
+ cc.streams[cs.ID] = cs
+ if cs.ID == 0 {
+ panic("assigned stream ID 0")
+ }
+}
+
+func (cc *http2ClientConn) forgetStreamID(id uint32) {
+ cc.mu.Lock()
+ slen := len(cc.streams)
+ delete(cc.streams, id)
+ if len(cc.streams) != slen-1 {
+ panic("forgetting unknown stream id")
+ }
+ cc.lastActive = time.Now()
+ if len(cc.streams) == 0 && cc.idleTimer != nil {
+ cc.idleTimer.Reset(cc.idleTimeout)
+ cc.lastIdle = time.Now()
+ }
+ // Wake up writeRequestBody via clientStream.awaitFlowControl and
+ // wake up RoundTrip if there is a pending request.
+ cc.cond.Broadcast()
+
+ closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
+ if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
+ if http2VerboseLogs {
+ cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
+ }
+ cc.closed = true
+ defer cc.closeConn()
+ }
+
+ cc.mu.Unlock()
+}
+
+// clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
+type http2clientConnReadLoop struct {
+ _ http2incomparable
+ cc *http2ClientConn
+}
+
+// readLoop runs in its own goroutine and reads and dispatches frames.
+func (cc *http2ClientConn) readLoop() {
+ rl := &http2clientConnReadLoop{cc: cc}
+ defer rl.cleanup()
+ cc.readerErr = rl.run()
+ if ce, ok := cc.readerErr.(http2ConnectionError); ok {
+ cc.wmu.Lock()
+ cc.fr.WriteGoAway(0, http2ErrCode(ce), nil)
+ cc.wmu.Unlock()
+ }
+}
+
+// GoAwayError is returned by the Transport when the server closes the
+// TCP connection after sending a GOAWAY frame.
+type http2GoAwayError struct {
+ LastStreamID uint32
+ ErrCode http2ErrCode
+ DebugData string
+}
+
+func (e http2GoAwayError) Error() string {
+ return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
+ e.LastStreamID, e.ErrCode, e.DebugData)
+}
+
+func http2isEOFOrNetReadError(err error) bool {
+ if err == io.EOF {
+ return true
+ }
+ ne, ok := err.(*net.OpError)
+ return ok && ne.Op == "read"
+}
+
+func (rl *http2clientConnReadLoop) cleanup() {
+ cc := rl.cc
+ cc.t.connPool().MarkDead(cc)
+ defer cc.closeConn()
+ defer close(cc.readerDone)
+
+ if cc.idleTimer != nil {
+ cc.idleTimer.Stop()
+ }
+
+ // Close any response bodies if the server closes prematurely.
+ // TODO: also do this if we've written the headers but not
+ // gotten a response yet.
+ err := cc.readerErr
+ cc.mu.Lock()
+ if cc.goAway != nil && http2isEOFOrNetReadError(err) {
+ err = http2GoAwayError{
+ LastStreamID: cc.goAway.LastStreamID,
+ ErrCode: cc.goAway.ErrCode,
+ DebugData: cc.goAwayDebug,
+ }
+ } else if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ cc.closed = true
+
+ for _, cs := range cc.streams {
+ select {
+ case <-cs.peerClosed:
+ // The server closed the stream before closing the conn,
+ // so no need to interrupt it.
+ default:
+ cs.abortStreamLocked(err)
+ }
+ }
+ cc.cond.Broadcast()
+ cc.mu.Unlock()
+}
+
+// countReadFrameError calls Transport.CountError with a string
+// representing err.
+func (cc *http2ClientConn) countReadFrameError(err error) {
+ f := cc.t.CountError
+ if f == nil || err == nil {
+ return
+ }
+ if ce, ok := err.(http2ConnectionError); ok {
+ errCode := http2ErrCode(ce)
+ f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
+ return
+ }
+ if errors.Is(err, io.EOF) {
+ f("read_frame_eof")
+ return
+ }
+ if errors.Is(err, io.ErrUnexpectedEOF) {
+ f("read_frame_unexpected_eof")
+ return
+ }
+ if errors.Is(err, http2ErrFrameTooLarge) {
+ f("read_frame_too_large")
+ return
+ }
+ f("read_frame_other")
+}
+
+func (rl *http2clientConnReadLoop) run() error {
+ cc := rl.cc
+ gotSettings := false
+ readIdleTimeout := cc.t.ReadIdleTimeout
+ var t *time.Timer
+ if readIdleTimeout != 0 {
+ t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
+ defer t.Stop()
+ }
+ for {
+ f, err := cc.fr.ReadFrame()
+ if t != nil {
+ t.Reset(readIdleTimeout)
+ }
+ if err != nil {
+ cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
+ }
+ if se, ok := err.(http2StreamError); ok {
+ if cs := rl.streamByID(se.StreamID); cs != nil {
+ if se.Cause == nil {
+ se.Cause = cc.fr.errDetail
+ }
+ rl.endStreamError(cs, se)
+ }
+ continue
+ } else if err != nil {
+ cc.countReadFrameError(err)
+ return err
+ }
+ if http2VerboseLogs {
+ cc.vlogf("http2: Transport received %s", http2summarizeFrame(f))
+ }
+ if !gotSettings {
+ if _, ok := f.(*http2SettingsFrame); !ok {
+ cc.logf("protocol error: received %T before a SETTINGS frame", f)
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ gotSettings = true
+ }
+
+ switch f := f.(type) {
+ case *http2MetaHeadersFrame:
+ err = rl.processHeaders(f)
+ case *http2DataFrame:
+ err = rl.processData(f)
+ case *http2GoAwayFrame:
+ err = rl.processGoAway(f)
+ case *http2RSTStreamFrame:
+ err = rl.processResetStream(f)
+ case *http2SettingsFrame:
+ err = rl.processSettings(f)
+ case *http2PushPromiseFrame:
+ err = rl.processPushPromise(f)
+ case *http2WindowUpdateFrame:
+ err = rl.processWindowUpdate(f)
+ case *http2PingFrame:
+ err = rl.processPing(f)
+ default:
+ cc.logf("Transport: unhandled response frame type %T", f)
+ }
+ if err != nil {
+ if http2VerboseLogs {
+ cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, http2summarizeFrame(f), err)
+ }
+ return err
+ }
+ }
+}
+
+func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error {
+ cs := rl.streamByID(f.StreamID)
+ if cs == nil {
+ // We'd get here if we canceled a request while the
+ // server had its response still in flight. So if this
+ // was just something we canceled, ignore it.
+ return nil
+ }
+ if cs.readClosed {
+ rl.endStreamError(cs, http2StreamError{
+ StreamID: f.StreamID,
+ Code: http2ErrCodeProtocol,
+ Cause: errors.New("protocol error: headers after END_STREAM"),
+ })
+ return nil
+ }
+ if !cs.firstByte {
+ if cs.trace != nil {
+ // TODO(bradfitz): move first response byte earlier,
+ // when we first read the 9 byte header, not waiting
+ // until all the HEADERS+CONTINUATION frames have been
+ // merged. This works for now.
+ http2traceFirstResponseByte(cs.trace)
+ }
+ cs.firstByte = true
+ }
+ if !cs.pastHeaders {
+ cs.pastHeaders = true
+ } else {
+ return rl.processTrailers(cs, f)
+ }
+
+ res, err := rl.handleResponse(cs, f)
+ if err != nil {
+ if _, ok := err.(http2ConnectionError); ok {
+ return err
+ }
+ // Any other error type is a stream error.
+ rl.endStreamError(cs, http2StreamError{
+ StreamID: f.StreamID,
+ Code: http2ErrCodeProtocol,
+ Cause: err,
+ })
+ return nil // return nil from process* funcs to keep conn alive
+ }
+ if res == nil {
+ // (nil, nil) special case. See handleResponse docs.
+ return nil
+ }
+ cs.resTrailer = &res.Trailer
+ cs.res = res
+ close(cs.respHeaderRecv)
+ if f.StreamEnded() {
+ rl.endStream(cs)
+ }
+ return nil
+}
+
+// may return error types nil, or ConnectionError. Any other error value
+// is a StreamError of type ErrCodeProtocol. The returned error in that case
+// is the detail.
+//
+// As a special case, handleResponse may return (nil, nil) to skip the
+// frame (currently only used for 1xx responses).
+func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error) {
+ if f.Truncated {
+ return nil, http2errResponseHeaderListSize
+ }
+
+ status := f.PseudoValue("status")
+ if status == "" {
+ return nil, errors.New("malformed response from server: missing status pseudo header")
+ }
+ statusCode, err := strconv.Atoi(status)
+ if err != nil {
+ return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
+ }
+
+ regularFields := f.RegularFields()
+ strs := make([]string, len(regularFields))
+ header := make(Header, len(regularFields))
+ res := &Response{
+ Proto: "HTTP/2.0",
+ ProtoMajor: 2,
+ Header: header,
+ StatusCode: statusCode,
+ Status: status + " " + StatusText(statusCode),
+ }
+ for _, hf := range regularFields {
+ key := http2canonicalHeader(hf.Name)
+ if key == "Trailer" {
+ t := res.Trailer
+ if t == nil {
+ t = make(Header)
+ res.Trailer = t
+ }
+ http2foreachHeaderElement(hf.Value, func(v string) {
+ t[http2canonicalHeader(v)] = nil
+ })
+ } else {
+ vv := header[key]
+ if vv == nil && len(strs) > 0 {
+ // More than likely this will be a single-element key.
+ // Most headers aren't multi-valued.
+ // Set the capacity on strs[0] to 1, so any future append
+ // won't extend the slice into the other strings.
+ vv, strs = strs[:1:1], strs[1:]
+ vv[0] = hf.Value
+ header[key] = vv
+ } else {
+ header[key] = append(vv, hf.Value)
+ }
+ }
+ }
+
+ if statusCode >= 100 && statusCode <= 199 {
+ if f.StreamEnded() {
+ return nil, errors.New("1xx informational response with END_STREAM flag")
+ }
+ cs.num1xx++
+ const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
+ if cs.num1xx > max1xxResponses {
+ return nil, errors.New("http2: too many 1xx informational responses")
+ }
+ if fn := cs.get1xxTraceFunc(); fn != nil {
+ if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
+ return nil, err
+ }
+ }
+ if statusCode == 100 {
+ http2traceGot100Continue(cs.trace)
+ select {
+ case cs.on100 <- struct{}{}:
+ default:
+ }
+ }
+ cs.pastHeaders = false // do it all again
+ return nil, nil
+ }
+
+ res.ContentLength = -1
+ if clens := res.Header["Content-Length"]; len(clens) == 1 {
+ if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
+ res.ContentLength = int64(cl)
+ } else {
+ // TODO: care? unlike http/1, it won't mess up our framing, so it's
+ // more safe smuggling-wise to ignore.
+ }
+ } else if len(clens) > 1 {
+ // TODO: care? unlike http/1, it won't mess up our framing, so it's
+ // more safe smuggling-wise to ignore.
+ } else if f.StreamEnded() && !cs.isHead {
+ res.ContentLength = 0
+ }
+
+ if cs.isHead {
+ res.Body = http2noBody
+ return res, nil
+ }
+
+ if f.StreamEnded() {
+ if res.ContentLength > 0 {
+ res.Body = http2missingBody{}
+ } else {
+ res.Body = http2noBody
+ }
+ return res, nil
+ }
+
+ cs.bufPipe.setBuffer(&http2dataBuffer{expected: res.ContentLength})
+ cs.bytesRemain = res.ContentLength
+ res.Body = http2transportResponseBody{cs}
+
+ if cs.requestedGzip && http2asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
+ res.Header.Del("Content-Encoding")
+ res.Header.Del("Content-Length")
+ res.ContentLength = -1
+ res.Body = &http2gzipReader{body: res.Body}
+ res.Uncompressed = true
+ }
+ return res, nil
+}
+
+func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error {
+ if cs.pastTrailers {
+ // Too many HEADERS frames for this stream.
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ cs.pastTrailers = true
+ if !f.StreamEnded() {
+ // We expect that any headers for trailers also
+ // has END_STREAM.
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ if len(f.PseudoFields()) > 0 {
+ // No pseudo header fields are defined for trailers.
+ // TODO: ConnectionError might be overly harsh? Check.
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+
+ trailer := make(Header)
+ for _, hf := range f.RegularFields() {
+ key := http2canonicalHeader(hf.Name)
+ trailer[key] = append(trailer[key], hf.Value)
+ }
+ cs.trailer = trailer
+
+ rl.endStream(cs)
+ return nil
+}
+
+// transportResponseBody is the concrete type of Transport.RoundTrip's
+// Response.Body. It is an io.ReadCloser.
+type http2transportResponseBody struct {
+ cs *http2clientStream
+}
+
+func (b http2transportResponseBody) Read(p []byte) (n int, err error) {
+ cs := b.cs
+ cc := cs.cc
+
+ if cs.readErr != nil {
+ return 0, cs.readErr
+ }
+ n, err = b.cs.bufPipe.Read(p)
+ if cs.bytesRemain != -1 {
+ if int64(n) > cs.bytesRemain {
+ n = int(cs.bytesRemain)
+ if err == nil {
+ err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
+ cs.abortStream(err)
+ }
+ cs.readErr = err
+ return int(cs.bytesRemain), err
+ }
+ cs.bytesRemain -= int64(n)
+ if err == io.EOF && cs.bytesRemain > 0 {
+ err = io.ErrUnexpectedEOF
+ cs.readErr = err
+ return n, err
+ }
+ }
+ if n == 0 {
+ // No flow control tokens to send back.
+ return
+ }
+
+ cc.mu.Lock()
+ connAdd := cc.inflow.add(n)
+ var streamAdd int32
+ if err == nil { // No need to refresh if the stream is over or failed.
+ streamAdd = cs.inflow.add(n)
+ }
+ cc.mu.Unlock()
+
+ if connAdd != 0 || streamAdd != 0 {
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ if connAdd != 0 {
+ cc.fr.WriteWindowUpdate(0, http2mustUint31(connAdd))
+ }
+ if streamAdd != 0 {
+ cc.fr.WriteWindowUpdate(cs.ID, http2mustUint31(streamAdd))
+ }
+ cc.bw.Flush()
+ }
+ return
+}
+
+var http2errClosedResponseBody = errors.New("http2: response body closed")
+
+func (b http2transportResponseBody) Close() error {
+ cs := b.cs
+ cc := cs.cc
+
+ cs.bufPipe.BreakWithError(http2errClosedResponseBody)
+ cs.abortStream(http2errClosedResponseBody)
+
+ unread := cs.bufPipe.Len()
+ if unread > 0 {
+ cc.mu.Lock()
+ // Return connection-level flow control.
+ connAdd := cc.inflow.add(unread)
+ cc.mu.Unlock()
+
+ // TODO(dneil): Acquiring this mutex can block indefinitely.
+ // Move flow control return to a goroutine?
+ cc.wmu.Lock()
+ // Return connection-level flow control.
+ if connAdd > 0 {
+ cc.fr.WriteWindowUpdate(0, uint32(connAdd))
+ }
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ }
+
+ select {
+ case <-cs.donec:
+ case <-cs.ctx.Done():
+ // See golang/go#49366: The net/http package can cancel the
+ // request context after the response body is fully read.
+ // Don't treat this as an error.
+ return nil
+ case <-cs.reqCancel:
+ return http2errRequestCanceled
+ }
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error {
+ cc := rl.cc
+ cs := rl.streamByID(f.StreamID)
+ data := f.Data()
+ if cs == nil {
+ cc.mu.Lock()
+ neverSent := cc.nextStreamID
+ cc.mu.Unlock()
+ if f.StreamID >= neverSent {
+ // We never asked for this.
+ cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+ // We probably did ask for this, but canceled. Just ignore it.
+ // TODO: be stricter here? only silently ignore things which
+ // we canceled, but not things which were closed normally
+ // by the peer? Tough without accumulating too much state.
+
+ // But at least return their flow control:
+ if f.Length > 0 {
+ cc.mu.Lock()
+ ok := cc.inflow.take(f.Length)
+ connAdd := cc.inflow.add(int(f.Length))
+ cc.mu.Unlock()
+ if !ok {
+ return http2ConnectionError(http2ErrCodeFlowControl)
+ }
+ if connAdd > 0 {
+ cc.wmu.Lock()
+ cc.fr.WriteWindowUpdate(0, uint32(connAdd))
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ }
+ }
+ return nil
+ }
+ if cs.readClosed {
+ cc.logf("protocol error: received DATA after END_STREAM")
+ rl.endStreamError(cs, http2StreamError{
+ StreamID: f.StreamID,
+ Code: http2ErrCodeProtocol,
+ })
+ return nil
+ }
+ if !cs.pastHeaders {
+ cc.logf("protocol error: received DATA before a HEADERS frame")
+ rl.endStreamError(cs, http2StreamError{
+ StreamID: f.StreamID,
+ Code: http2ErrCodeProtocol,
+ })
+ return nil
+ }
+ if f.Length > 0 {
+ if cs.isHead && len(data) > 0 {
+ cc.logf("protocol error: received DATA on a HEAD request")
+ rl.endStreamError(cs, http2StreamError{
+ StreamID: f.StreamID,
+ Code: http2ErrCodeProtocol,
+ })
+ return nil
+ }
+ // Check connection-level flow control.
+ cc.mu.Lock()
+ if !http2takeInflows(&cc.inflow, &cs.inflow, f.Length) {
+ cc.mu.Unlock()
+ return http2ConnectionError(http2ErrCodeFlowControl)
+ }
+ // Return any padded flow control now, since we won't
+ // refund it later on body reads.
+ var refund int
+ if pad := int(f.Length) - len(data); pad > 0 {
+ refund += pad
+ }
+
+ didReset := false
+ var err error
+ if len(data) > 0 {
+ if _, err = cs.bufPipe.Write(data); err != nil {
+ // Return len(data) now if the stream is already closed,
+ // since data will never be read.
+ didReset = true
+ refund += len(data)
+ }
+ }
+
+ sendConn := cc.inflow.add(refund)
+ var sendStream int32
+ if !didReset {
+ sendStream = cs.inflow.add(refund)
+ }
+ cc.mu.Unlock()
+
+ if sendConn > 0 || sendStream > 0 {
+ cc.wmu.Lock()
+ if sendConn > 0 {
+ cc.fr.WriteWindowUpdate(0, uint32(sendConn))
+ }
+ if sendStream > 0 {
+ cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
+ }
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ }
+
+ if err != nil {
+ rl.endStreamError(cs, err)
+ return nil
+ }
+ }
+
+ if f.StreamEnded() {
+ rl.endStream(cs)
+ }
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream) {
+ // TODO: check that any declared content-length matches, like
+ // server.go's (*stream).endStream method.
+ if !cs.readClosed {
+ cs.readClosed = true
+ // Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a
+ // race condition: The caller can read io.EOF from Response.Body
+ // and close the body before we close cs.peerClosed, causing
+ // cleanupWriteRequest to send a RST_STREAM.
+ rl.cc.mu.Lock()
+ defer rl.cc.mu.Unlock()
+ cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
+ close(cs.peerClosed)
+ }
+}
+
+func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error) {
+ cs.readAborted = true
+ cs.abortStream(err)
+}
+
+func (rl *http2clientConnReadLoop) streamByID(id uint32) *http2clientStream {
+ rl.cc.mu.Lock()
+ defer rl.cc.mu.Unlock()
+ cs := rl.cc.streams[id]
+ if cs != nil && !cs.readAborted {
+ return cs
+ }
+ return nil
+}
+
+func (cs *http2clientStream) copyTrailers() {
+ for k, vv := range cs.trailer {
+ t := cs.resTrailer
+ if *t == nil {
+ *t = make(Header)
+ }
+ (*t)[k] = vv
+ }
+}
+
+func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error {
+ cc := rl.cc
+ cc.t.connPool().MarkDead(cc)
+ if f.ErrCode != 0 {
+ // TODO: deal with GOAWAY more. particularly the error code
+ cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
+ if fn := cc.t.CountError; fn != nil {
+ fn("recv_goaway_" + f.ErrCode.stringToken())
+ }
+ }
+ cc.setGoAway(f)
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error {
+ cc := rl.cc
+ // Locking both mu and wmu here allows frame encoding to read settings with only wmu held.
+ // Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless.
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+
+ if err := rl.processSettingsNoWrite(f); err != nil {
+ return err
+ }
+ if !f.IsAck() {
+ cc.fr.WriteSettingsAck()
+ cc.bw.Flush()
+ }
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) processSettingsNoWrite(f *http2SettingsFrame) error {
+ cc := rl.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ if f.IsAck() {
+ if cc.wantSettingsAck {
+ cc.wantSettingsAck = false
+ return nil
+ }
+ return http2ConnectionError(http2ErrCodeProtocol)
+ }
+
+ var seenMaxConcurrentStreams bool
+ err := f.ForeachSetting(func(s http2Setting) error {
+ switch s.ID {
+ case http2SettingMaxFrameSize:
+ cc.maxFrameSize = s.Val
+ case http2SettingMaxConcurrentStreams:
+ cc.maxConcurrentStreams = s.Val
+ seenMaxConcurrentStreams = true
+ case http2SettingMaxHeaderListSize:
+ cc.peerMaxHeaderListSize = uint64(s.Val)
+ case http2SettingInitialWindowSize:
+ // Values above the maximum flow-control
+ // window size of 2^31-1 MUST be treated as a
+ // connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR.
+ if s.Val > math.MaxInt32 {
+ return http2ConnectionError(http2ErrCodeFlowControl)
+ }
+
+ // Adjust flow control of currently-open
+ // frames by the difference of the old initial
+ // window size and this one.
+ delta := int32(s.Val) - int32(cc.initialWindowSize)
+ for _, cs := range cc.streams {
+ cs.flow.add(delta)
+ }
+ cc.cond.Broadcast()
+
+ cc.initialWindowSize = s.Val
+ case http2SettingHeaderTableSize:
+ cc.henc.SetMaxDynamicTableSize(s.Val)
+ cc.peerMaxHeaderTableSize = s.Val
+ default:
+ cc.vlogf("Unhandled Setting: %v", s)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ if !cc.seenSettings {
+ if !seenMaxConcurrentStreams {
+ // This was the servers initial SETTINGS frame and it
+ // didn't contain a MAX_CONCURRENT_STREAMS field so
+ // increase the number of concurrent streams this
+ // connection can establish to our default.
+ cc.maxConcurrentStreams = http2defaultMaxConcurrentStreams
+ }
+ cc.seenSettings = true
+ }
+
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error {
+ cc := rl.cc
+ cs := rl.streamByID(f.StreamID)
+ if f.StreamID != 0 && cs == nil {
+ return nil
+ }
+
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ fl := &cc.flow
+ if cs != nil {
+ fl = &cs.flow
+ }
+ if !fl.add(int32(f.Increment)) {
+ return http2ConnectionError(http2ErrCodeFlowControl)
+ }
+ cc.cond.Broadcast()
+ return nil
+}
+
+func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error {
+ cs := rl.streamByID(f.StreamID)
+ if cs == nil {
+ // TODO: return error if server tries to RST_STREAM an idle stream
+ return nil
+ }
+ serr := http2streamError(cs.ID, f.ErrCode)
+ serr.Cause = http2errFromPeer
+ if f.ErrCode == http2ErrCodeProtocol {
+ rl.cc.SetDoNotReuse()
+ }
+ if fn := cs.cc.t.CountError; fn != nil {
+ fn("recv_rststream_" + f.ErrCode.stringToken())
+ }
+ cs.abortStream(serr)
+
+ cs.bufPipe.CloseWithError(serr)
+ return nil
+}
+
+// Ping sends a PING frame to the server and waits for the ack.
+func (cc *http2ClientConn) Ping(ctx context.Context) error {
+ c := make(chan struct{})
+ // Generate a random payload
+ var p [8]byte
+ for {
+ if _, err := rand.Read(p[:]); err != nil {
+ return err
+ }
+ cc.mu.Lock()
+ // check for dup before insert
+ if _, found := cc.pings[p]; !found {
+ cc.pings[p] = c
+ cc.mu.Unlock()
+ break
+ }
+ cc.mu.Unlock()
+ }
+ errc := make(chan error, 1)
+ go func() {
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ if err := cc.fr.WritePing(false, p); err != nil {
+ errc <- err
+ return
+ }
+ if err := cc.bw.Flush(); err != nil {
+ errc <- err
+ return
+ }
+ }()
+ select {
+ case <-c:
+ return nil
+ case err := <-errc:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-cc.readerDone:
+ // connection closed
+ return cc.readerErr
+ }
+}
+
+func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error {
+ if f.IsAck() {
+ cc := rl.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ // If ack, notify listener if any
+ if c, ok := cc.pings[f.Data]; ok {
+ close(c)
+ delete(cc.pings, f.Data)
+ }
+ return nil
+ }
+ cc := rl.cc
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ if err := cc.fr.WritePing(true, f.Data); err != nil {
+ return err
+ }
+ return cc.bw.Flush()
+}
+
+func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error {
+ // We told the peer we don't want them.
+ // Spec says:
+ // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
+ // setting of the peer endpoint is set to 0. An endpoint that
+ // has set this setting and has received acknowledgement MUST
+ // treat the receipt of a PUSH_PROMISE frame as a connection
+ // error (Section 5.4.1) of type PROTOCOL_ERROR."
+ return http2ConnectionError(http2ErrCodeProtocol)
+}
+
+func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error) {
+ // TODO: map err to more interesting error codes, once the
+ // HTTP community comes up with some. But currently for
+ // RST_STREAM there's no equivalent to GOAWAY frame's debug
+ // data, and the error codes are all pretty vague ("cancel").
+ cc.wmu.Lock()
+ cc.fr.WriteRSTStream(streamID, code)
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+}
+
+var (
+ http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
+ http2errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
+)
+
+func (cc *http2ClientConn) logf(format string, args ...interface{}) {
+ cc.t.logf(format, args...)
+}
+
+func (cc *http2ClientConn) vlogf(format string, args ...interface{}) {
+ cc.t.vlogf(format, args...)
+}
+
+func (t *http2Transport) vlogf(format string, args ...interface{}) {
+ if http2VerboseLogs {
+ t.logf(format, args...)
+ }
+}
+
+func (t *http2Transport) logf(format string, args ...interface{}) {
+ log.Printf(format, args...)
+}
+
+var http2noBody io.ReadCloser = http2noBodyReader{}
+
+type http2noBodyReader struct{}
+
+func (http2noBodyReader) Close() error { return nil }
+
+func (http2noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
+
+type http2missingBody struct{}
+
+func (http2missingBody) Close() error { return nil }
+
+func (http2missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
+
+func http2strSliceContains(ss []string, s string) bool {
+ for _, v := range ss {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+type http2erringRoundTripper struct{ err error }
+
+func (rt http2erringRoundTripper) RoundTripErr() error { return rt.err }
+
+func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error) { return nil, rt.err }
+
+// gzipReader wraps a response body so it can lazily
+// call gzip.NewReader on the first call to Read
+type http2gzipReader struct {
+ _ http2incomparable
+ body io.ReadCloser // underlying Response.Body
+ zr *gzip.Reader // lazily-initialized gzip reader
+ zerr error // sticky error
+}
+
+func (gz *http2gzipReader) Read(p []byte) (n int, err error) {
+ if gz.zerr != nil {
+ return 0, gz.zerr
+ }
+ if gz.zr == nil {
+ gz.zr, err = gzip.NewReader(gz.body)
+ if err != nil {
+ gz.zerr = err
+ return 0, err
+ }
+ }
+ return gz.zr.Read(p)
+}
+
+func (gz *http2gzipReader) Close() error {
+ if err := gz.body.Close(); err != nil {
+ return err
+ }
+ gz.zerr = fs.ErrClosed
+ return nil
+}
+
+type http2errorReader struct{ err error }
+
+func (r http2errorReader) Read(p []byte) (int, error) { return 0, r.err }
+
+// isConnectionCloseRequest reports whether req should use its own
+// connection for a single request and then close the connection.
+func http2isConnectionCloseRequest(req *Request) bool {
+ return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
+}
+
+// registerHTTPSProtocol calls Transport.RegisterProtocol but
+// converting panics into errors.
+func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error) {
+ defer func() {
+ if e := recover(); e != nil {
+ err = fmt.Errorf("%v", e)
+ }
+ }()
+ t.RegisterProtocol("https", rt)
+ return nil
+}
+
+// noDialH2RoundTripper is a RoundTripper which only tries to complete the request
+// if there's already has a cached connection to the host.
+// (The field is exported so it can be accessed via reflect from net/http; tested
+// by TestNoDialH2RoundTripperType)
+type http2noDialH2RoundTripper struct{ *http2Transport }
+
+func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error) {
+ res, err := rt.http2Transport.RoundTrip(req)
+ if http2isNoCachedConnError(err) {
+ return nil, ErrSkipAltProtocol
+ }
+ return res, err
+}
+
+func (t *http2Transport) idleConnTimeout() time.Duration {
+ if t.t1 != nil {
+ return t.t1.IdleConnTimeout
+ }
+ return 0
+}
+
+func http2traceGetConn(req *Request, hostPort string) {
+ trace := httptrace.ContextClientTrace(req.Context())
+ if trace == nil || trace.GetConn == nil {
+ return
+ }
+ trace.GetConn(hostPort)
+}
+
+func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool) {
+ trace := httptrace.ContextClientTrace(req.Context())
+ if trace == nil || trace.GotConn == nil {
+ return
+ }
+ ci := httptrace.GotConnInfo{Conn: cc.tconn}
+ ci.Reused = reused
+ cc.mu.Lock()
+ ci.WasIdle = len(cc.streams) == 0 && reused
+ if ci.WasIdle && !cc.lastActive.IsZero() {
+ ci.IdleTime = time.Since(cc.lastActive)
+ }
+ cc.mu.Unlock()
+
+ trace.GotConn(ci)
+}
+
+func http2traceWroteHeaders(trace *httptrace.ClientTrace) {
+ if trace != nil && trace.WroteHeaders != nil {
+ trace.WroteHeaders()
+ }
+}
+
+func http2traceGot100Continue(trace *httptrace.ClientTrace) {
+ if trace != nil && trace.Got100Continue != nil {
+ trace.Got100Continue()
+ }
+}
+
+func http2traceWait100Continue(trace *httptrace.ClientTrace) {
+ if trace != nil && trace.Wait100Continue != nil {
+ trace.Wait100Continue()
+ }
+}
+
+func http2traceWroteRequest(trace *httptrace.ClientTrace, err error) {
+ if trace != nil && trace.WroteRequest != nil {
+ trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
+ }
+}
+
+func http2traceFirstResponseByte(trace *httptrace.ClientTrace) {
+ if trace != nil && trace.GotFirstResponseByte != nil {
+ trace.GotFirstResponseByte()
+ }
+}
+
+func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool {
+ return trace != nil && trace.WroteHeaderField != nil
+}
+
+func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) {
+ if trace != nil && trace.WroteHeaderField != nil {
+ trace.WroteHeaderField(k, []string{v})
+ }
+}
+
+func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error {
+ if trace != nil {
+ return trace.Got1xxResponse
+ }
+ return nil
+}
+
+// dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
+// connection.
+func (t *http2Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) {
+ dialer := &tls.Dialer{
+ Config: cfg,
+ }
+ cn, err := dialer.DialContext(ctx, network, addr)
+ if err != nil {
+ return nil, err
+ }
+ tlsCn := cn.(*tls.Conn) // DialContext comment promises this will always succeed
+ return tlsCn, nil
+}
+
+// writeFramer is implemented by any type that is used to write frames.
+type http2writeFramer interface {
+ writeFrame(http2writeContext) error
+
+ // staysWithinBuffer reports whether this writer promises that
+ // it will only write less than or equal to size bytes, and it
+ // won't Flush the write context.
+ staysWithinBuffer(size int) bool
+}
+
+// writeContext is the interface needed by the various frame writer
+// types below. All the writeFrame methods below are scheduled via the
+// frame writing scheduler (see writeScheduler in writesched.go).
+//
+// This interface is implemented by *serverConn.
+//
+// TODO: decide whether to a) use this in the client code (which didn't
+// end up using this yet, because it has a simpler design, not
+// currently implementing priorities), or b) delete this and
+// make the server code a bit more concrete.
+type http2writeContext interface {
+ Framer() *http2Framer
+ Flush() error
+ CloseConn() error
+ // HeaderEncoder returns an HPACK encoder that writes to the
+ // returned buffer.
+ HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
+}
+
+// writeEndsStream reports whether w writes a frame that will transition
+// the stream to a half-closed local state. This returns false for RST_STREAM,
+// which closes the entire stream (not just the local half).
+func http2writeEndsStream(w http2writeFramer) bool {
+ switch v := w.(type) {
+ case *http2writeData:
+ return v.endStream
+ case *http2writeResHeaders:
+ return v.endStream
+ case nil:
+ // This can only happen if the caller reuses w after it's
+ // been intentionally nil'ed out to prevent use. Keep this
+ // here to catch future refactoring breaking it.
+ panic("writeEndsStream called on nil writeFramer")
+ }
+ return false
+}
+
+type http2flushFrameWriter struct{}
+
+func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error {
+ return ctx.Flush()
+}
+
+func (http2flushFrameWriter) staysWithinBuffer(max int) bool { return false }
+
+type http2writeSettings []http2Setting
+
+func (s http2writeSettings) staysWithinBuffer(max int) bool {
+ const settingSize = 6 // uint16 + uint32
+ return http2frameHeaderLen+settingSize*len(s) <= max
+
+}
+
+func (s http2writeSettings) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteSettings([]http2Setting(s)...)
+}
+
+type http2writeGoAway struct {
+ maxStreamID uint32
+ code http2ErrCode
+}
+
+func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error {
+ err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
+ ctx.Flush() // ignore error: we're hanging up on them anyway
+ return err
+}
+
+func (*http2writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
+
+type http2writeData struct {
+ streamID uint32
+ p []byte
+ endStream bool
+}
+
+func (w *http2writeData) String() string {
+ return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
+}
+
+func (w *http2writeData) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
+}
+
+func (w *http2writeData) staysWithinBuffer(max int) bool {
+ return http2frameHeaderLen+len(w.p) <= max
+}
+
+// handlerPanicRST is the message sent from handler goroutines when
+// the handler panics.
+type http2handlerPanicRST struct {
+ StreamID uint32
+}
+
+func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteRSTStream(hp.StreamID, http2ErrCodeInternal)
+}
+
+func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
+
+func (se http2StreamError) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
+}
+
+func (se http2StreamError) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
+
+type http2writePingAck struct{ pf *http2PingFrame }
+
+func (w http2writePingAck) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WritePing(true, w.pf.Data)
+}
+
+func (w http2writePingAck) staysWithinBuffer(max int) bool {
+ return http2frameHeaderLen+len(w.pf.Data) <= max
+}
+
+type http2writeSettingsAck struct{}
+
+func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteSettingsAck()
+}
+
+func (http2writeSettingsAck) staysWithinBuffer(max int) bool { return http2frameHeaderLen <= max }
+
+// splitHeaderBlock splits headerBlock into fragments so that each fragment fits
+// in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
+// for the first/last fragment, respectively.
+func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
+ // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
+ // that all peers must support (16KB). Later we could care
+ // more and send larger frames if the peer advertised it, but
+ // there's little point. Most headers are small anyway (so we
+ // generally won't have CONTINUATION frames), and extra frames
+ // only waste 9 bytes anyway.
+ const maxFrameSize = 16384
+
+ first := true
+ for len(headerBlock) > 0 {
+ frag := headerBlock
+ if len(frag) > maxFrameSize {
+ frag = frag[:maxFrameSize]
+ }
+ headerBlock = headerBlock[len(frag):]
+ if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
+ return err
+ }
+ first = false
+ }
+ return nil
+}
+
+// writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
+// for HTTP response headers or trailers from a server handler.
+type http2writeResHeaders struct {
+ streamID uint32
+ httpResCode int // 0 means no ":status" line
+ h Header // may be nil
+ trailers []string // if non-nil, which keys of h to write. nil means all.
+ endStream bool
+
+ date string
+ contentType string
+ contentLength string
+}
+
+func http2encKV(enc *hpack.Encoder, k, v string) {
+ if http2VerboseLogs {
+ log.Printf("http2: server encoding header %q = %q", k, v)
+ }
+ enc.WriteField(hpack.HeaderField{Name: k, Value: v})
+}
+
+func (w *http2writeResHeaders) staysWithinBuffer(max int) bool {
+ // TODO: this is a common one. It'd be nice to return true
+ // here and get into the fast path if we could be clever and
+ // calculate the size fast enough, or at least a conservative
+ // upper bound that usually fires. (Maybe if w.h and
+ // w.trailers are nil, so we don't need to enumerate it.)
+ // Otherwise I'm afraid that just calculating the length to
+ // answer this question would be slower than the ~2µs benefit.
+ return false
+}
+
+func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+
+ if w.httpResCode != 0 {
+ http2encKV(enc, ":status", http2httpCodeString(w.httpResCode))
+ }
+
+ http2encodeHeaders(enc, w.h, w.trailers)
+
+ if w.contentType != "" {
+ http2encKV(enc, "content-type", w.contentType)
+ }
+ if w.contentLength != "" {
+ http2encKV(enc, "content-length", w.contentLength)
+ }
+ if w.date != "" {
+ http2encKV(enc, "date", w.date)
+ }
+
+ headerBlock := buf.Bytes()
+ if len(headerBlock) == 0 && w.trailers == nil {
+ panic("unexpected empty hpack")
+ }
+
+ return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
+}
+
+func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
+ if firstFrag {
+ return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
+ StreamID: w.streamID,
+ BlockFragment: frag,
+ EndStream: w.endStream,
+ EndHeaders: lastFrag,
+ })
+ } else {
+ return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
+ }
+}
+
+// writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
+type http2writePushPromise struct {
+ streamID uint32 // pusher stream
+ method string // for :method
+ url *url.URL // for :scheme, :authority, :path
+ h Header
+
+ // Creates an ID for a pushed stream. This runs on serveG just before
+ // the frame is written. The returned ID is copied to promisedID.
+ allocatePromisedID func() (uint32, error)
+ promisedID uint32
+}
+
+func (w *http2writePushPromise) staysWithinBuffer(max int) bool {
+ // TODO: see writeResHeaders.staysWithinBuffer
+ return false
+}
+
+func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+
+ http2encKV(enc, ":method", w.method)
+ http2encKV(enc, ":scheme", w.url.Scheme)
+ http2encKV(enc, ":authority", w.url.Host)
+ http2encKV(enc, ":path", w.url.RequestURI())
+ http2encodeHeaders(enc, w.h, nil)
+
+ headerBlock := buf.Bytes()
+ if len(headerBlock) == 0 {
+ panic("unexpected empty hpack")
+ }
+
+ return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
+}
+
+func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
+ if firstFrag {
+ return ctx.Framer().WritePushPromise(http2PushPromiseParam{
+ StreamID: w.streamID,
+ PromiseID: w.promisedID,
+ BlockFragment: frag,
+ EndHeaders: lastFrag,
+ })
+ } else {
+ return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
+ }
+}
+
+type http2write100ContinueHeadersFrame struct {
+ streamID uint32
+}
+
+func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+ http2encKV(enc, ":status", "100")
+ return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
+ StreamID: w.streamID,
+ BlockFragment: buf.Bytes(),
+ EndStream: false,
+ EndHeaders: true,
+ })
+}
+
+func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
+ // Sloppy but conservative:
+ return 9+2*(len(":status")+len("100")) <= max
+}
+
+type http2writeWindowUpdate struct {
+ streamID uint32 // or 0 for conn-level
+ n uint32
+}
+
+func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
+
+func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error {
+ return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
+}
+
+// encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k])
+// is encoded only if k is in keys.
+func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string) {
+ if keys == nil {
+ sorter := http2sorterPool.Get().(*http2sorter)
+ // Using defer here, since the returned keys from the
+ // sorter.Keys method is only valid until the sorter
+ // is returned:
+ defer http2sorterPool.Put(sorter)
+ keys = sorter.Keys(h)
+ }
+ for _, k := range keys {
+ vv := h[k]
+ k, ascii := http2lowerHeader(k)
+ if !ascii {
+ // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
+ // field names have to be ASCII characters (just as in HTTP/1.x).
+ continue
+ }
+ if !http2validWireHeaderFieldName(k) {
+ // Skip it as backup paranoia. Per
+ // golang.org/issue/14048, these should
+ // already be rejected at a higher level.
+ continue
+ }
+ isTE := k == "transfer-encoding"
+ for _, v := range vv {
+ if !httpguts.ValidHeaderFieldValue(v) {
+ // TODO: return an error? golang.org/issue/14048
+ // For now just omit it.
+ continue
+ }
+ // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
+ if isTE && v != "trailers" {
+ continue
+ }
+ http2encKV(enc, k, v)
+ }
+ }
+}
+
+// WriteScheduler is the interface implemented by HTTP/2 write schedulers.
+// Methods are never called concurrently.
+type http2WriteScheduler interface {
+ // OpenStream opens a new stream in the write scheduler.
+ // It is illegal to call this with streamID=0 or with a streamID that is
+ // already open -- the call may panic.
+ OpenStream(streamID uint32, options http2OpenStreamOptions)
+
+ // CloseStream closes a stream in the write scheduler. Any frames queued on
+ // this stream should be discarded. It is illegal to call this on a stream
+ // that is not open -- the call may panic.
+ CloseStream(streamID uint32)
+
+ // AdjustStream adjusts the priority of the given stream. This may be called
+ // on a stream that has not yet been opened or has been closed. Note that
+ // RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
+ // https://tools.ietf.org/html/rfc7540#section-5.1
+ AdjustStream(streamID uint32, priority http2PriorityParam)
+
+ // Push queues a frame in the scheduler. In most cases, this will not be
+ // called with wr.StreamID()!=0 unless that stream is currently open. The one
+ // exception is RST_STREAM frames, which may be sent on idle or closed streams.
+ Push(wr http2FrameWriteRequest)
+
+ // Pop dequeues the next frame to write. Returns false if no frames can
+ // be written. Frames with a given wr.StreamID() are Pop'd in the same
+ // order they are Push'd, except RST_STREAM frames. No frames should be
+ // discarded except by CloseStream.
+ Pop() (wr http2FrameWriteRequest, ok bool)
+}
+
+// OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
+type http2OpenStreamOptions struct {
+ // PusherID is zero if the stream was initiated by the client. Otherwise,
+ // PusherID names the stream that pushed the newly opened stream.
+ PusherID uint32
+}
+
+// FrameWriteRequest is a request to write a frame.
+type http2FrameWriteRequest struct {
+ // write is the interface value that does the writing, once the
+ // WriteScheduler has selected this frame to write. The write
+ // functions are all defined in write.go.
+ write http2writeFramer
+
+ // stream is the stream on which this frame will be written.
+ // nil for non-stream frames like PING and SETTINGS.
+ // nil for RST_STREAM streams, which use the StreamError.StreamID field instead.
+ stream *http2stream
+
+ // done, if non-nil, must be a buffered channel with space for
+ // 1 message and is sent the return value from write (or an
+ // earlier error) when the frame has been written.
+ done chan error
+}
+
+// StreamID returns the id of the stream this frame will be written to.
+// 0 is used for non-stream frames such as PING and SETTINGS.
+func (wr http2FrameWriteRequest) StreamID() uint32 {
+ if wr.stream == nil {
+ if se, ok := wr.write.(http2StreamError); ok {
+ // (*serverConn).resetStream doesn't set
+ // stream because it doesn't necessarily have
+ // one. So special case this type of write
+ // message.
+ return se.StreamID
+ }
+ return 0
+ }
+ return wr.stream.id
+}
+
+// isControl reports whether wr is a control frame for MaxQueuedControlFrames
+// purposes. That includes non-stream frames and RST_STREAM frames.
+func (wr http2FrameWriteRequest) isControl() bool {
+ return wr.stream == nil
+}
+
+// DataSize returns the number of flow control bytes that must be consumed
+// to write this entire frame. This is 0 for non-DATA frames.
+func (wr http2FrameWriteRequest) DataSize() int {
+ if wd, ok := wr.write.(*http2writeData); ok {
+ return len(wd.p)
+ }
+ return 0
+}
+
+// Consume consumes min(n, available) bytes from this frame, where available
+// is the number of flow control bytes available on the stream. Consume returns
+// 0, 1, or 2 frames, where the integer return value gives the number of frames
+// returned.
+//
+// If flow control prevents consuming any bytes, this returns (_, _, 0). If
+// the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
+// returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
+// 'rest' contains the remaining bytes. The consumed bytes are deducted from the
+// underlying stream's flow control budget.
+func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int) {
+ var empty http2FrameWriteRequest
+
+ // Non-DATA frames are always consumed whole.
+ wd, ok := wr.write.(*http2writeData)
+ if !ok || len(wd.p) == 0 {
+ return wr, empty, 1
+ }
+
+ // Might need to split after applying limits.
+ allowed := wr.stream.flow.available()
+ if n < allowed {
+ allowed = n
+ }
+ if wr.stream.sc.maxFrameSize < allowed {
+ allowed = wr.stream.sc.maxFrameSize
+ }
+ if allowed <= 0 {
+ return empty, empty, 0
+ }
+ if len(wd.p) > int(allowed) {
+ wr.stream.flow.take(allowed)
+ consumed := http2FrameWriteRequest{
+ stream: wr.stream,
+ write: &http2writeData{
+ streamID: wd.streamID,
+ p: wd.p[:allowed],
+ // Even if the original had endStream set, there
+ // are bytes remaining because len(wd.p) > allowed,
+ // so we know endStream is false.
+ endStream: false,
+ },
+ // Our caller is blocking on the final DATA frame, not
+ // this intermediate frame, so no need to wait.
+ done: nil,
+ }
+ rest := http2FrameWriteRequest{
+ stream: wr.stream,
+ write: &http2writeData{
+ streamID: wd.streamID,
+ p: wd.p[allowed:],
+ endStream: wd.endStream,
+ },
+ done: wr.done,
+ }
+ return consumed, rest, 2
+ }
+
+ // The frame is consumed whole.
+ // NB: This cast cannot overflow because allowed is <= math.MaxInt32.
+ wr.stream.flow.take(int32(len(wd.p)))
+ return wr, empty, 1
+}
+
+// String is for debugging only.
+func (wr http2FrameWriteRequest) String() string {
+ var des string
+ if s, ok := wr.write.(fmt.Stringer); ok {
+ des = s.String()
+ } else {
+ des = fmt.Sprintf("%T", wr.write)
+ }
+ return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
+}
+
+// replyToWriter sends err to wr.done and panics if the send must block
+// This does nothing if wr.done is nil.
+func (wr *http2FrameWriteRequest) replyToWriter(err error) {
+ if wr.done == nil {
+ return
+ }
+ select {
+ case wr.done <- err:
+ default:
+ panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
+ }
+ wr.write = nil // prevent use (assume it's tainted after wr.done send)
+}
+
+// writeQueue is used by implementations of WriteScheduler.
+type http2writeQueue struct {
+ s []http2FrameWriteRequest
+ prev, next *http2writeQueue
+}
+
+func (q *http2writeQueue) empty() bool { return len(q.s) == 0 }
+
+func (q *http2writeQueue) push(wr http2FrameWriteRequest) {
+ q.s = append(q.s, wr)
+}
+
+func (q *http2writeQueue) shift() http2FrameWriteRequest {
+ if len(q.s) == 0 {
+ panic("invalid use of queue")
+ }
+ wr := q.s[0]
+ // TODO: less copy-happy queue.
+ copy(q.s, q.s[1:])
+ q.s[len(q.s)-1] = http2FrameWriteRequest{}
+ q.s = q.s[:len(q.s)-1]
+ return wr
+}
+
+// consume consumes up to n bytes from q.s[0]. If the frame is
+// entirely consumed, it is removed from the queue. If the frame
+// is partially consumed, the frame is kept with the consumed
+// bytes removed. Returns true iff any bytes were consumed.
+func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool) {
+ if len(q.s) == 0 {
+ return http2FrameWriteRequest{}, false
+ }
+ consumed, rest, numresult := q.s[0].Consume(n)
+ switch numresult {
+ case 0:
+ return http2FrameWriteRequest{}, false
+ case 1:
+ q.shift()
+ case 2:
+ q.s[0] = rest
+ }
+ return consumed, true
+}
+
+type http2writeQueuePool []*http2writeQueue
+
+// put inserts an unused writeQueue into the pool.
+
+// put inserts an unused writeQueue into the pool.
+func (p *http2writeQueuePool) put(q *http2writeQueue) {
+ for i := range q.s {
+ q.s[i] = http2FrameWriteRequest{}
+ }
+ q.s = q.s[:0]
+ *p = append(*p, q)
+}
+
+// get returns an empty writeQueue.
+func (p *http2writeQueuePool) get() *http2writeQueue {
+ ln := len(*p)
+ if ln == 0 {
+ return new(http2writeQueue)
+ }
+ x := ln - 1
+ q := (*p)[x]
+ (*p)[x] = nil
+ *p = (*p)[:x]
+ return q
+}
+
+// RFC 7540, Section 5.3.5: the default weight is 16.
+const http2priorityDefaultWeight = 15 // 16 = 15 + 1
+
+// PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
+type http2PriorityWriteSchedulerConfig struct {
+ // MaxClosedNodesInTree controls the maximum number of closed streams to
+ // retain in the priority tree. Setting this to zero saves a small amount
+ // of memory at the cost of performance.
+ //
+ // See RFC 7540, Section 5.3.4:
+ // "It is possible for a stream to become closed while prioritization
+ // information ... is in transit. ... This potentially creates suboptimal
+ // prioritization, since the stream could be given a priority that is
+ // different from what is intended. To avoid these problems, an endpoint
+ // SHOULD retain stream prioritization state for a period after streams
+ // become closed. The longer state is retained, the lower the chance that
+ // streams are assigned incorrect or default priority values."
+ MaxClosedNodesInTree int
+
+ // MaxIdleNodesInTree controls the maximum number of idle streams to
+ // retain in the priority tree. Setting this to zero saves a small amount
+ // of memory at the cost of performance.
+ //
+ // See RFC 7540, Section 5.3.4:
+ // Similarly, streams that are in the "idle" state can be assigned
+ // priority or become a parent of other streams. This allows for the
+ // creation of a grouping node in the dependency tree, which enables
+ // more flexible expressions of priority. Idle streams begin with a
+ // default priority (Section 5.3.5).
+ MaxIdleNodesInTree int
+
+ // ThrottleOutOfOrderWrites enables write throttling to help ensure that
+ // data is delivered in priority order. This works around a race where
+ // stream B depends on stream A and both streams are about to call Write
+ // to queue DATA frames. If B wins the race, a naive scheduler would eagerly
+ // write as much data from B as possible, but this is suboptimal because A
+ // is a higher-priority stream. With throttling enabled, we write a small
+ // amount of data from B to minimize the amount of bandwidth that B can
+ // steal from A.
+ ThrottleOutOfOrderWrites bool
+}
+
+// NewPriorityWriteScheduler constructs a WriteScheduler that schedules
+// frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
+// If cfg is nil, default options are used.
+func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler {
+ if cfg == nil {
+ // For justification of these defaults, see:
+ // https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY
+ cfg = &http2PriorityWriteSchedulerConfig{
+ MaxClosedNodesInTree: 10,
+ MaxIdleNodesInTree: 10,
+ ThrottleOutOfOrderWrites: false,
+ }
+ }
+
+ ws := &http2priorityWriteScheduler{
+ nodes: make(map[uint32]*http2priorityNode),
+ maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
+ maxIdleNodesInTree: cfg.MaxIdleNodesInTree,
+ enableWriteThrottle: cfg.ThrottleOutOfOrderWrites,
+ }
+ ws.nodes[0] = &ws.root
+ if cfg.ThrottleOutOfOrderWrites {
+ ws.writeThrottleLimit = 1024
+ } else {
+ ws.writeThrottleLimit = math.MaxInt32
+ }
+ return ws
+}
+
+type http2priorityNodeState int
+
+const (
+ http2priorityNodeOpen http2priorityNodeState = iota
+ http2priorityNodeClosed
+ http2priorityNodeIdle
+)
+
+// priorityNode is a node in an HTTP/2 priority tree.
+// Each node is associated with a single stream ID.
+// See RFC 7540, Section 5.3.
+type http2priorityNode struct {
+ q http2writeQueue // queue of pending frames to write
+ id uint32 // id of the stream, or 0 for the root of the tree
+ weight uint8 // the actual weight is weight+1, so the value is in [1,256]
+ state http2priorityNodeState // open | closed | idle
+ bytes int64 // number of bytes written by this node, or 0 if closed
+ subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree
+
+ // These links form the priority tree.
+ parent *http2priorityNode
+ kids *http2priorityNode // start of the kids list
+ prev, next *http2priorityNode // doubly-linked list of siblings
+}
+
+func (n *http2priorityNode) setParent(parent *http2priorityNode) {
+ if n == parent {
+ panic("setParent to self")
+ }
+ if n.parent == parent {
+ return
+ }
+ // Unlink from current parent.
+ if parent := n.parent; parent != nil {
+ if n.prev == nil {
+ parent.kids = n.next
+ } else {
+ n.prev.next = n.next
+ }
+ if n.next != nil {
+ n.next.prev = n.prev
+ }
+ }
+ // Link to new parent.
+ // If parent=nil, remove n from the tree.
+ // Always insert at the head of parent.kids (this is assumed by walkReadyInOrder).
+ n.parent = parent
+ if parent == nil {
+ n.next = nil
+ n.prev = nil
+ } else {
+ n.next = parent.kids
+ n.prev = nil
+ if n.next != nil {
+ n.next.prev = n
+ }
+ parent.kids = n
+ }
+}
+
+func (n *http2priorityNode) addBytes(b int64) {
+ n.bytes += b
+ for ; n != nil; n = n.parent {
+ n.subtreeBytes += b
+ }
+}
+
+// walkReadyInOrder iterates over the tree in priority order, calling f for each node
+// with a non-empty write queue. When f returns true, this function returns true and the
+// walk halts. tmp is used as scratch space for sorting.
+//
+// f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
+// if any ancestor p of n is still open (ignoring the root node).
+func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool {
+ if !n.q.empty() && f(n, openParent) {
+ return true
+ }
+ if n.kids == nil {
+ return false
+ }
+
+ // Don't consider the root "open" when updating openParent since
+ // we can't send data frames on the root stream (only control frames).
+ if n.id != 0 {
+ openParent = openParent || (n.state == http2priorityNodeOpen)
+ }
+
+ // Common case: only one kid or all kids have the same weight.
+ // Some clients don't use weights; other clients (like web browsers)
+ // use mostly-linear priority trees.
+ w := n.kids.weight
+ needSort := false
+ for k := n.kids.next; k != nil; k = k.next {
+ if k.weight != w {
+ needSort = true
+ break
+ }
+ }
+ if !needSort {
+ for k := n.kids; k != nil; k = k.next {
+ if k.walkReadyInOrder(openParent, tmp, f) {
+ return true
+ }
+ }
+ return false
+ }
+
+ // Uncommon case: sort the child nodes. We remove the kids from the parent,
+ // then re-insert after sorting so we can reuse tmp for future sort calls.
+ *tmp = (*tmp)[:0]
+ for n.kids != nil {
+ *tmp = append(*tmp, n.kids)
+ n.kids.setParent(nil)
+ }
+ sort.Sort(http2sortPriorityNodeSiblings(*tmp))
+ for i := len(*tmp) - 1; i >= 0; i-- {
+ (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids
+ }
+ for k := n.kids; k != nil; k = k.next {
+ if k.walkReadyInOrder(openParent, tmp, f) {
+ return true
+ }
+ }
+ return false
+}
+
+type http2sortPriorityNodeSiblings []*http2priorityNode
+
+func (z http2sortPriorityNodeSiblings) Len() int { return len(z) }
+
+func (z http2sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
+
+func (z http2sortPriorityNodeSiblings) Less(i, k int) bool {
+ // Prefer the subtree that has sent fewer bytes relative to its weight.
+ // See sections 5.3.2 and 5.3.4.
+ wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
+ wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
+ if bi == 0 && bk == 0 {
+ return wi >= wk
+ }
+ if bk == 0 {
+ return false
+ }
+ return bi/bk <= wi/wk
+}
+
+type http2priorityWriteScheduler struct {
+ // root is the root of the priority tree, where root.id = 0.
+ // The root queues control frames that are not associated with any stream.
+ root http2priorityNode
+
+ // nodes maps stream ids to priority tree nodes.
+ nodes map[uint32]*http2priorityNode
+
+ // maxID is the maximum stream id in nodes.
+ maxID uint32
+
+ // lists of nodes that have been closed or are idle, but are kept in
+ // the tree for improved prioritization. When the lengths exceed either
+ // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
+ closedNodes, idleNodes []*http2priorityNode
+
+ // From the config.
+ maxClosedNodesInTree int
+ maxIdleNodesInTree int
+ writeThrottleLimit int32
+ enableWriteThrottle bool
+
+ // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
+ tmp []*http2priorityNode
+
+ // pool of empty queues for reuse.
+ queuePool http2writeQueuePool
+}
+
+func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
+ // The stream may be currently idle but cannot be opened or closed.
+ if curr := ws.nodes[streamID]; curr != nil {
+ if curr.state != http2priorityNodeIdle {
+ panic(fmt.Sprintf("stream %d already opened", streamID))
+ }
+ curr.state = http2priorityNodeOpen
+ return
+ }
+
+ // RFC 7540, Section 5.3.5:
+ // "All streams are initially assigned a non-exclusive dependency on stream 0x0.
+ // Pushed streams initially depend on their associated stream. In both cases,
+ // streams are assigned a default weight of 16."
+ parent := ws.nodes[options.PusherID]
+ if parent == nil {
+ parent = &ws.root
+ }
+ n := &http2priorityNode{
+ q: *ws.queuePool.get(),
+ id: streamID,
+ weight: http2priorityDefaultWeight,
+ state: http2priorityNodeOpen,
+ }
+ n.setParent(parent)
+ ws.nodes[streamID] = n
+ if streamID > ws.maxID {
+ ws.maxID = streamID
+ }
+}
+
+func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32) {
+ if streamID == 0 {
+ panic("violation of WriteScheduler interface: cannot close stream 0")
+ }
+ if ws.nodes[streamID] == nil {
+ panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
+ }
+ if ws.nodes[streamID].state != http2priorityNodeOpen {
+ panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
+ }
+
+ n := ws.nodes[streamID]
+ n.state = http2priorityNodeClosed
+ n.addBytes(-n.bytes)
+
+ q := n.q
+ ws.queuePool.put(&q)
+ n.q.s = nil
+ if ws.maxClosedNodesInTree > 0 {
+ ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
+ } else {
+ ws.removeNode(n)
+ }
+}
+
+func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
+ if streamID == 0 {
+ panic("adjustPriority on root")
+ }
+
+ // If streamID does not exist, there are two cases:
+ // - A closed stream that has been removed (this will have ID <= maxID)
+ // - An idle stream that is being used for "grouping" (this will have ID > maxID)
+ n := ws.nodes[streamID]
+ if n == nil {
+ if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
+ return
+ }
+ ws.maxID = streamID
+ n = &http2priorityNode{
+ q: *ws.queuePool.get(),
+ id: streamID,
+ weight: http2priorityDefaultWeight,
+ state: http2priorityNodeIdle,
+ }
+ n.setParent(&ws.root)
+ ws.nodes[streamID] = n
+ ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
+ }
+
+ // Section 5.3.1: A dependency on a stream that is not currently in the tree
+ // results in that stream being given a default priority (Section 5.3.5).
+ parent := ws.nodes[priority.StreamDep]
+ if parent == nil {
+ n.setParent(&ws.root)
+ n.weight = http2priorityDefaultWeight
+ return
+ }
+
+ // Ignore if the client tries to make a node its own parent.
+ if n == parent {
+ return
+ }
+
+ // Section 5.3.3:
+ // "If a stream is made dependent on one of its own dependencies, the
+ // formerly dependent stream is first moved to be dependent on the
+ // reprioritized stream's previous parent. The moved dependency retains
+ // its weight."
+ //
+ // That is: if parent depends on n, move parent to depend on n.parent.
+ for x := parent.parent; x != nil; x = x.parent {
+ if x == n {
+ parent.setParent(n.parent)
+ break
+ }
+ }
+
+ // Section 5.3.3: The exclusive flag causes the stream to become the sole
+ // dependency of its parent stream, causing other dependencies to become
+ // dependent on the exclusive stream.
+ if priority.Exclusive {
+ k := parent.kids
+ for k != nil {
+ next := k.next
+ if k != n {
+ k.setParent(n)
+ }
+ k = next
+ }
+ }
+
+ n.setParent(parent)
+ n.weight = priority.Weight
+}
+
+func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest) {
+ var n *http2priorityNode
+ if wr.isControl() {
+ n = &ws.root
+ } else {
+ id := wr.StreamID()
+ n = ws.nodes[id]
+ if n == nil {
+ // id is an idle or closed stream. wr should not be a HEADERS or
+ // DATA frame. In other case, we push wr onto the root, rather
+ // than creating a new priorityNode.
+ if wr.DataSize() > 0 {
+ panic("add DATA on non-open stream")
+ }
+ n = &ws.root
+ }
+ }
+ n.q.push(wr)
+}
+
+func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool) {
+ ws.root.walkReadyInOrder(false, &ws.tmp, func(n *http2priorityNode, openParent bool) bool {
+ limit := int32(math.MaxInt32)
+ if openParent {
+ limit = ws.writeThrottleLimit
+ }
+ wr, ok = n.q.consume(limit)
+ if !ok {
+ return false
+ }
+ n.addBytes(int64(wr.DataSize()))
+ // If B depends on A and B continuously has data available but A
+ // does not, gradually increase the throttling limit to allow B to
+ // steal more and more bandwidth from A.
+ if openParent {
+ ws.writeThrottleLimit += 1024
+ if ws.writeThrottleLimit < 0 {
+ ws.writeThrottleLimit = math.MaxInt32
+ }
+ } else if ws.enableWriteThrottle {
+ ws.writeThrottleLimit = 1024
+ }
+ return true
+ })
+ return wr, ok
+}
+
+func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode) {
+ if maxSize == 0 {
+ return
+ }
+ if len(*list) == maxSize {
+ // Remove the oldest node, then shift left.
+ ws.removeNode((*list)[0])
+ x := (*list)[1:]
+ copy(*list, x)
+ *list = (*list)[:len(x)]
+ }
+ *list = append(*list, n)
+}
+
+func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode) {
+ for k := n.kids; k != nil; k = k.next {
+ k.setParent(n.parent)
+ }
+ n.setParent(nil)
+ delete(ws.nodes, n.id)
+}
+
+// NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
+// priorities. Control frames like SETTINGS and PING are written before DATA
+// frames, but if no control frames are queued and multiple streams have queued
+// HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
+func http2NewRandomWriteScheduler() http2WriteScheduler {
+ return &http2randomWriteScheduler{sq: make(map[uint32]*http2writeQueue)}
+}
+
+type http2randomWriteScheduler struct {
+ // zero are frames not associated with a specific stream.
+ zero http2writeQueue
+
+ // sq contains the stream-specific queues, keyed by stream ID.
+ // When a stream is idle, closed, or emptied, it's deleted
+ // from the map.
+ sq map[uint32]*http2writeQueue
+
+ // pool of empty queues for reuse.
+ queuePool http2writeQueuePool
+}
+
+func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
+ // no-op: idle streams are not tracked
+}
+
+func (ws *http2randomWriteScheduler) CloseStream(streamID uint32) {
+ q, ok := ws.sq[streamID]
+ if !ok {
+ return
+ }
+ delete(ws.sq, streamID)
+ ws.queuePool.put(q)
+}
+
+func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
+ // no-op: priorities are ignored
+}
+
+func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest) {
+ if wr.isControl() {
+ ws.zero.push(wr)
+ return
+ }
+ id := wr.StreamID()
+ q, ok := ws.sq[id]
+ if !ok {
+ q = ws.queuePool.get()
+ ws.sq[id] = q
+ }
+ q.push(wr)
+}
+
+func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
+ // Control and RST_STREAM frames first.
+ if !ws.zero.empty() {
+ return ws.zero.shift(), true
+ }
+ // Iterate over all non-idle streams until finding one that can be consumed.
+ for streamID, q := range ws.sq {
+ if wr, ok := q.consume(math.MaxInt32); ok {
+ if q.empty() {
+ delete(ws.sq, streamID)
+ ws.queuePool.put(q)
+ }
+ return wr, true
+ }
+ }
+ return http2FrameWriteRequest{}, false
+}
+
+type http2roundRobinWriteScheduler struct {
+ // control contains control frames (SETTINGS, PING, etc.).
+ control http2writeQueue
+
+ // streams maps stream ID to a queue.
+ streams map[uint32]*http2writeQueue
+
+ // stream queues are stored in a circular linked list.
+ // head is the next stream to write, or nil if there are no streams open.
+ head *http2writeQueue
+
+ // pool of empty queues for reuse.
+ queuePool http2writeQueuePool
+}
+
+// newRoundRobinWriteScheduler constructs a new write scheduler.
+// The round robin scheduler priorizes control frames
+// like SETTINGS and PING over DATA frames.
+// When there are no control frames to send, it performs a round-robin
+// selection from the ready streams.
+func http2newRoundRobinWriteScheduler() http2WriteScheduler {
+ ws := &http2roundRobinWriteScheduler{
+ streams: make(map[uint32]*http2writeQueue),
+ }
+ return ws
+}
+
+func (ws *http2roundRobinWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
+ if ws.streams[streamID] != nil {
+ panic(fmt.Errorf("stream %d already opened", streamID))
+ }
+ q := ws.queuePool.get()
+ ws.streams[streamID] = q
+ if ws.head == nil {
+ ws.head = q
+ q.next = q
+ q.prev = q
+ } else {
+ // Queues are stored in a ring.
+ // Insert the new stream before ws.head, putting it at the end of the list.
+ q.prev = ws.head.prev
+ q.next = ws.head
+ q.prev.next = q
+ q.next.prev = q
+ }
+}
+
+func (ws *http2roundRobinWriteScheduler) CloseStream(streamID uint32) {
+ q := ws.streams[streamID]
+ if q == nil {
+ return
+ }
+ if q.next == q {
+ // This was the only open stream.
+ ws.head = nil
+ } else {
+ q.prev.next = q.next
+ q.next.prev = q.prev
+ if ws.head == q {
+ ws.head = q.next
+ }
+ }
+ delete(ws.streams, streamID)
+ ws.queuePool.put(q)
+}
+
+func (ws *http2roundRobinWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {}
+
+func (ws *http2roundRobinWriteScheduler) Push(wr http2FrameWriteRequest) {
+ if wr.isControl() {
+ ws.control.push(wr)
+ return
+ }
+ q := ws.streams[wr.StreamID()]
+ if q == nil {
+ // This is a closed stream.
+ // wr should not be a HEADERS or DATA frame.
+ // We push the request onto the control queue.
+ if wr.DataSize() > 0 {
+ panic("add DATA on non-open stream")
+ }
+ ws.control.push(wr)
+ return
+ }
+ q.push(wr)
+}
+
+func (ws *http2roundRobinWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
+ // Control and RST_STREAM frames first.
+ if !ws.control.empty() {
+ return ws.control.shift(), true
+ }
+ if ws.head == nil {
+ return http2FrameWriteRequest{}, false
+ }
+ q := ws.head
+ for {
+ if wr, ok := q.consume(math.MaxInt32); ok {
+ ws.head = q.next
+ return wr, true
+ }
+ q = q.next
+ if q == ws.head {
+ break
+ }
+ }
+ return http2FrameWriteRequest{}, false
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/h2_error.go b/platform/dbops/binaries/go/go/src/net/http/h2_error.go
new file mode 100644
index 0000000000000000000000000000000000000000..2c0b21ec070019ea36bc02a7ecf3df4aaf03d03a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/h2_error.go
@@ -0,0 +1,37 @@
+// 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 !nethttpomithttp2
+
+package http
+
+import (
+ "reflect"
+)
+
+func (e http2StreamError) As(target any) bool {
+ dst := reflect.ValueOf(target).Elem()
+ dstType := dst.Type()
+ if dstType.Kind() != reflect.Struct {
+ return false
+ }
+ src := reflect.ValueOf(e)
+ srcType := src.Type()
+ numField := srcType.NumField()
+ if dstType.NumField() != numField {
+ return false
+ }
+ for i := 0; i < numField; i++ {
+ sf := srcType.Field(i)
+ df := dstType.Field(i)
+ if sf.Name != df.Name || !sf.Type.ConvertibleTo(df.Type) {
+ return false
+ }
+ }
+ for i := 0; i < numField; i++ {
+ df := dst.Field(i)
+ df.Set(src.Field(i).Convert(df.Type()))
+ }
+ return true
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/h2_error_test.go b/platform/dbops/binaries/go/go/src/net/http/h2_error_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5e400683b415e7e47f501d8d845ca513caefe3b6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/h2_error_test.go
@@ -0,0 +1,43 @@
+// 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 !nethttpomithttp2
+
+package http
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+)
+
+type externalStreamErrorCode uint32
+
+type externalStreamError struct {
+ StreamID uint32
+ Code externalStreamErrorCode
+ Cause error
+}
+
+func (e externalStreamError) Error() string {
+ return fmt.Sprintf("ID %v, code %v", e.StreamID, e.Code)
+}
+
+func TestStreamError(t *testing.T) {
+ var target externalStreamError
+ streamErr := http2streamError(42, http2ErrCodeProtocol)
+ ok := errors.As(streamErr, &target)
+ if !ok {
+ t.Fatalf("errors.As failed")
+ }
+ if target.StreamID != streamErr.StreamID {
+ t.Errorf("got StreamID %v, expected %v", target.StreamID, streamErr.StreamID)
+ }
+ if target.Cause != streamErr.Cause {
+ t.Errorf("got Cause %v, expected %v", target.Cause, streamErr.Cause)
+ }
+ if uint32(target.Code) != uint32(streamErr.Code) {
+ t.Errorf("got Code %v, expected %v", target.Code, streamErr.Code)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/header.go b/platform/dbops/binaries/go/go/src/net/http/header.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d0f3a125d645922b4983d0a3803c2be154d3258
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/header.go
@@ -0,0 +1,280 @@
+// 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 http
+
+import (
+ "io"
+ "net/http/httptrace"
+ "net/http/internal/ascii"
+ "net/textproto"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+// A Header represents the key-value pairs in an HTTP header.
+//
+// The keys should be in canonical form, as returned by
+// [CanonicalHeaderKey].
+type Header map[string][]string
+
+// Add adds the key, value pair to the header.
+// It appends to any existing values associated with key.
+// The key is case insensitive; it is canonicalized by
+// [CanonicalHeaderKey].
+func (h Header) Add(key, value string) {
+ textproto.MIMEHeader(h).Add(key, value)
+}
+
+// Set sets the header entries associated with key to the
+// single element value. It replaces any existing values
+// associated with key. The key is case insensitive; it is
+// canonicalized by [textproto.CanonicalMIMEHeaderKey].
+// To use non-canonical keys, assign to the map directly.
+func (h Header) Set(key, value string) {
+ textproto.MIMEHeader(h).Set(key, value)
+}
+
+// Get gets the first value associated with the given key. If
+// there are no values associated with the key, Get returns "".
+// It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is
+// used to canonicalize the provided key. Get assumes that all
+// keys are stored in canonical form. To use non-canonical keys,
+// access the map directly.
+func (h Header) Get(key string) string {
+ return textproto.MIMEHeader(h).Get(key)
+}
+
+// Values returns all values associated with the given key.
+// It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is
+// used to canonicalize the provided key. To use non-canonical
+// keys, access the map directly.
+// The returned slice is not a copy.
+func (h Header) Values(key string) []string {
+ return textproto.MIMEHeader(h).Values(key)
+}
+
+// get is like Get, but key must already be in CanonicalHeaderKey form.
+func (h Header) get(key string) string {
+ if v := h[key]; len(v) > 0 {
+ return v[0]
+ }
+ return ""
+}
+
+// has reports whether h has the provided key defined, even if it's
+// set to 0-length slice.
+func (h Header) has(key string) bool {
+ _, ok := h[key]
+ return ok
+}
+
+// Del deletes the values associated with key.
+// The key is case insensitive; it is canonicalized by
+// [CanonicalHeaderKey].
+func (h Header) Del(key string) {
+ textproto.MIMEHeader(h).Del(key)
+}
+
+// Write writes a header in wire format.
+func (h Header) Write(w io.Writer) error {
+ return h.write(w, nil)
+}
+
+func (h Header) write(w io.Writer, trace *httptrace.ClientTrace) error {
+ return h.writeSubset(w, nil, trace)
+}
+
+// Clone returns a copy of h or nil if h is nil.
+func (h Header) Clone() Header {
+ if h == nil {
+ return nil
+ }
+
+ // Find total number of values.
+ nv := 0
+ for _, vv := range h {
+ nv += len(vv)
+ }
+ sv := make([]string, nv) // shared backing array for headers' values
+ h2 := make(Header, len(h))
+ for k, vv := range h {
+ if vv == nil {
+ // Preserve nil values. ReverseProxy distinguishes
+ // between nil and zero-length header values.
+ h2[k] = nil
+ continue
+ }
+ n := copy(sv, vv)
+ h2[k] = sv[:n:n]
+ sv = sv[n:]
+ }
+ return h2
+}
+
+var timeFormats = []string{
+ TimeFormat,
+ time.RFC850,
+ time.ANSIC,
+}
+
+// ParseTime parses a time header (such as the Date: header),
+// trying each of the three formats allowed by HTTP/1.1:
+// [TimeFormat], [time.RFC850], and [time.ANSIC].
+func ParseTime(text string) (t time.Time, err error) {
+ for _, layout := range timeFormats {
+ t, err = time.Parse(layout, text)
+ if err == nil {
+ return
+ }
+ }
+ return
+}
+
+var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
+
+// stringWriter implements WriteString on a Writer.
+type stringWriter struct {
+ w io.Writer
+}
+
+func (w stringWriter) WriteString(s string) (n int, err error) {
+ return w.w.Write([]byte(s))
+}
+
+type keyValues struct {
+ key string
+ values []string
+}
+
+// A headerSorter implements sort.Interface by sorting a []keyValues
+// by key. It's used as a pointer, so it can fit in a sort.Interface
+// interface value without allocation.
+type headerSorter struct {
+ kvs []keyValues
+}
+
+func (s *headerSorter) Len() int { return len(s.kvs) }
+func (s *headerSorter) Swap(i, j int) { s.kvs[i], s.kvs[j] = s.kvs[j], s.kvs[i] }
+func (s *headerSorter) Less(i, j int) bool { return s.kvs[i].key < s.kvs[j].key }
+
+var headerSorterPool = sync.Pool{
+ New: func() any { return new(headerSorter) },
+}
+
+// sortedKeyValues returns h's keys sorted in the returned kvs
+// slice. The headerSorter used to sort is also returned, for possible
+// return to headerSorterCache.
+func (h Header) sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter) {
+ hs = headerSorterPool.Get().(*headerSorter)
+ if cap(hs.kvs) < len(h) {
+ hs.kvs = make([]keyValues, 0, len(h))
+ }
+ kvs = hs.kvs[:0]
+ for k, vv := range h {
+ if !exclude[k] {
+ kvs = append(kvs, keyValues{k, vv})
+ }
+ }
+ hs.kvs = kvs
+ sort.Sort(hs)
+ return kvs, hs
+}
+
+// WriteSubset writes a header in wire format.
+// If exclude is not nil, keys where exclude[key] == true are not written.
+// Keys are not canonicalized before checking the exclude map.
+func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error {
+ return h.writeSubset(w, exclude, nil)
+}
+
+func (h Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error {
+ ws, ok := w.(io.StringWriter)
+ if !ok {
+ ws = stringWriter{w}
+ }
+ kvs, sorter := h.sortedKeyValues(exclude)
+ var formattedVals []string
+ for _, kv := range kvs {
+ if !httpguts.ValidHeaderFieldName(kv.key) {
+ // This could be an error. In the common case of
+ // writing response headers, however, we have no good
+ // way to provide the error back to the server
+ // handler, so just drop invalid headers instead.
+ continue
+ }
+ for _, v := range kv.values {
+ v = headerNewlineToSpace.Replace(v)
+ v = textproto.TrimString(v)
+ for _, s := range []string{kv.key, ": ", v, "\r\n"} {
+ if _, err := ws.WriteString(s); err != nil {
+ headerSorterPool.Put(sorter)
+ return err
+ }
+ }
+ if trace != nil && trace.WroteHeaderField != nil {
+ formattedVals = append(formattedVals, v)
+ }
+ }
+ if trace != nil && trace.WroteHeaderField != nil {
+ trace.WroteHeaderField(kv.key, formattedVals)
+ formattedVals = nil
+ }
+ }
+ headerSorterPool.Put(sorter)
+ return nil
+}
+
+// CanonicalHeaderKey returns the canonical format of the
+// header key s. The canonicalization converts the first
+// letter and any letter following a hyphen to upper case;
+// the rest are converted to lowercase. For example, the
+// canonical key for "accept-encoding" is "Accept-Encoding".
+// If s contains a space or invalid header field bytes, it is
+// returned without modifications.
+func CanonicalHeaderKey(s string) string { return textproto.CanonicalMIMEHeaderKey(s) }
+
+// hasToken reports whether token appears with v, ASCII
+// case-insensitive, with space or comma boundaries.
+// token must be all lowercase.
+// v may contain mixed cased.
+func hasToken(v, token string) bool {
+ if len(token) > len(v) || token == "" {
+ return false
+ }
+ if v == token {
+ return true
+ }
+ for sp := 0; sp <= len(v)-len(token); sp++ {
+ // Check that first character is good.
+ // The token is ASCII, so checking only a single byte
+ // is sufficient. We skip this potential starting
+ // position if both the first byte and its potential
+ // ASCII uppercase equivalent (b|0x20) don't match.
+ // False positives ('^' => '~') are caught by EqualFold.
+ if b := v[sp]; b != token[0] && b|0x20 != token[0] {
+ continue
+ }
+ // Check that start pos is on a valid token boundary.
+ if sp > 0 && !isTokenBoundary(v[sp-1]) {
+ continue
+ }
+ // Check that end pos is on a valid token boundary.
+ if endPos := sp + len(token); endPos != len(v) && !isTokenBoundary(v[endPos]) {
+ continue
+ }
+ if ascii.EqualFold(v[sp:sp+len(token)], token) {
+ return true
+ }
+ }
+ return false
+}
+
+func isTokenBoundary(b byte) bool {
+ return b == ' ' || b == ',' || b == '\t'
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/header_test.go b/platform/dbops/binaries/go/go/src/net/http/header_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e98cc5c760b2b0ba63db7100dbaf92bee9a7705e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/header_test.go
@@ -0,0 +1,272 @@
+// 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 http
+
+import (
+ "bytes"
+ "internal/race"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+var headerWriteTests = []struct {
+ h Header
+ exclude map[string]bool
+ expected string
+}{
+ {Header{}, nil, ""},
+ {
+ Header{
+ "Content-Type": {"text/html; charset=UTF-8"},
+ "Content-Length": {"0"},
+ },
+ nil,
+ "Content-Length: 0\r\nContent-Type: text/html; charset=UTF-8\r\n",
+ },
+ {
+ Header{
+ "Content-Length": {"0", "1", "2"},
+ },
+ nil,
+ "Content-Length: 0\r\nContent-Length: 1\r\nContent-Length: 2\r\n",
+ },
+ {
+ Header{
+ "Expires": {"-1"},
+ "Content-Length": {"0"},
+ "Content-Encoding": {"gzip"},
+ },
+ map[string]bool{"Content-Length": true},
+ "Content-Encoding: gzip\r\nExpires: -1\r\n",
+ },
+ {
+ Header{
+ "Expires": {"-1"},
+ "Content-Length": {"0", "1", "2"},
+ "Content-Encoding": {"gzip"},
+ },
+ map[string]bool{"Content-Length": true},
+ "Content-Encoding: gzip\r\nExpires: -1\r\n",
+ },
+ {
+ Header{
+ "Expires": {"-1"},
+ "Content-Length": {"0"},
+ "Content-Encoding": {"gzip"},
+ },
+ map[string]bool{"Content-Length": true, "Expires": true, "Content-Encoding": true},
+ "",
+ },
+ {
+ Header{
+ "Nil": nil,
+ "Empty": {},
+ "Blank": {""},
+ "Double-Blank": {"", ""},
+ },
+ nil,
+ "Blank: \r\nDouble-Blank: \r\nDouble-Blank: \r\n",
+ },
+ // Tests header sorting when over the insertion sort threshold side:
+ {
+ Header{
+ "k1": {"1a", "1b"},
+ "k2": {"2a", "2b"},
+ "k3": {"3a", "3b"},
+ "k4": {"4a", "4b"},
+ "k5": {"5a", "5b"},
+ "k6": {"6a", "6b"},
+ "k7": {"7a", "7b"},
+ "k8": {"8a", "8b"},
+ "k9": {"9a", "9b"},
+ },
+ map[string]bool{"k5": true},
+ "k1: 1a\r\nk1: 1b\r\nk2: 2a\r\nk2: 2b\r\nk3: 3a\r\nk3: 3b\r\n" +
+ "k4: 4a\r\nk4: 4b\r\nk6: 6a\r\nk6: 6b\r\n" +
+ "k7: 7a\r\nk7: 7b\r\nk8: 8a\r\nk8: 8b\r\nk9: 9a\r\nk9: 9b\r\n",
+ },
+ // Tests invalid characters in headers.
+ {
+ Header{
+ "Content-Type": {"text/html; charset=UTF-8"},
+ "NewlineInValue": {"1\r\nBar: 2"},
+ "NewlineInKey\r\n": {"1"},
+ "Colon:InKey": {"1"},
+ "Evil: 1\r\nSmuggledValue": {"1"},
+ },
+ nil,
+ "Content-Type: text/html; charset=UTF-8\r\n" +
+ "NewlineInValue: 1 Bar: 2\r\n",
+ },
+}
+
+func TestHeaderWrite(t *testing.T) {
+ var buf strings.Builder
+ for i, test := range headerWriteTests {
+ test.h.WriteSubset(&buf, test.exclude)
+ if buf.String() != test.expected {
+ t.Errorf("#%d:\n got: %q\nwant: %q", i, buf.String(), test.expected)
+ }
+ buf.Reset()
+ }
+}
+
+var parseTimeTests = []struct {
+ h Header
+ err bool
+}{
+ {Header{"Date": {""}}, true},
+ {Header{"Date": {"invalid"}}, true},
+ {Header{"Date": {"1994-11-06T08:49:37Z00:00"}}, true},
+ {Header{"Date": {"Sun, 06 Nov 1994 08:49:37 GMT"}}, false},
+ {Header{"Date": {"Sunday, 06-Nov-94 08:49:37 GMT"}}, false},
+ {Header{"Date": {"Sun Nov 6 08:49:37 1994"}}, false},
+}
+
+func TestParseTime(t *testing.T) {
+ expect := time.Date(1994, 11, 6, 8, 49, 37, 0, time.UTC)
+ for i, test := range parseTimeTests {
+ d, err := ParseTime(test.h.Get("Date"))
+ if err != nil {
+ if !test.err {
+ t.Errorf("#%d:\n got err: %v", i, err)
+ }
+ continue
+ }
+ if test.err {
+ t.Errorf("#%d:\n should err", i)
+ continue
+ }
+ if !expect.Equal(d) {
+ t.Errorf("#%d:\n got: %v\nwant: %v", i, d, expect)
+ }
+ }
+}
+
+type hasTokenTest struct {
+ header string
+ token string
+ want bool
+}
+
+var hasTokenTests = []hasTokenTest{
+ {"", "", false},
+ {"", "foo", false},
+ {"foo", "foo", true},
+ {"foo ", "foo", true},
+ {" foo", "foo", true},
+ {" foo ", "foo", true},
+ {"foo,bar", "foo", true},
+ {"bar,foo", "foo", true},
+ {"bar, foo", "foo", true},
+ {"bar,foo, baz", "foo", true},
+ {"bar, foo,baz", "foo", true},
+ {"bar,foo, baz", "foo", true},
+ {"bar, foo, baz", "foo", true},
+ {"FOO", "foo", true},
+ {"FOO ", "foo", true},
+ {" FOO", "foo", true},
+ {" FOO ", "foo", true},
+ {"FOO,BAR", "foo", true},
+ {"BAR,FOO", "foo", true},
+ {"BAR, FOO", "foo", true},
+ {"BAR,FOO, baz", "foo", true},
+ {"BAR, FOO,BAZ", "foo", true},
+ {"BAR,FOO, BAZ", "foo", true},
+ {"BAR, FOO, BAZ", "foo", true},
+ {"foobar", "foo", false},
+ {"barfoo ", "foo", false},
+}
+
+func TestHasToken(t *testing.T) {
+ for _, tt := range hasTokenTests {
+ if hasToken(tt.header, tt.token) != tt.want {
+ t.Errorf("hasToken(%q, %q) = %v; want %v", tt.header, tt.token, !tt.want, tt.want)
+ }
+ }
+}
+
+func TestNilHeaderClone(t *testing.T) {
+ t1 := Header(nil)
+ t2 := t1.Clone()
+ if t2 != nil {
+ t.Errorf("cloned header does not match original: got: %+v; want: %+v", t2, nil)
+ }
+}
+
+var testHeader = Header{
+ "Content-Length": {"123"},
+ "Content-Type": {"text/plain"},
+ "Date": {"some date at some time Z"},
+ "Server": {DefaultUserAgent},
+}
+
+var buf bytes.Buffer
+
+func BenchmarkHeaderWriteSubset(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ testHeader.WriteSubset(&buf, nil)
+ }
+}
+
+func TestHeaderWriteSubsetAllocs(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping alloc test in short mode")
+ }
+ if race.Enabled {
+ t.Skip("skipping test under race detector")
+ }
+ if runtime.GOMAXPROCS(0) > 1 {
+ t.Skip("skipping; GOMAXPROCS>1")
+ }
+ n := testing.AllocsPerRun(100, func() {
+ buf.Reset()
+ testHeader.WriteSubset(&buf, nil)
+ })
+ if n > 0 {
+ t.Errorf("allocs = %g; want 0", n)
+ }
+}
+
+// Issue 34878: test that every call to
+// cloneOrMakeHeader never returns a nil Header.
+func TestCloneOrMakeHeader(t *testing.T) {
+ tests := []struct {
+ name string
+ in, want Header
+ }{
+ {"nil", nil, Header{}},
+ {"empty", Header{}, Header{}},
+ {
+ name: "non-empty",
+ in: Header{"foo": {"bar"}},
+ want: Header{"foo": {"bar"}},
+ },
+ {
+ name: "nil value",
+ in: Header{"foo": nil},
+ want: Header{"foo": nil},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := cloneOrMakeHeader(tt.in)
+ if got == nil {
+ t.Fatal("unexpected nil Header")
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Fatalf("Got: %#v\nWant: %#v", got, tt.want)
+ }
+ got.Add("A", "B")
+ got.Get("A")
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/http.go b/platform/dbops/binaries/go/go/src/net/http/http.go
new file mode 100644
index 0000000000000000000000000000000000000000..6e2259adbf3529ce8bc8c48fd90c6c7e3a7d90d5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/http.go
@@ -0,0 +1,165 @@
+// 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:generate bundle -o=h2_bundle.go -prefix=http2 -tags=!nethttpomithttp2 golang.org/x/net/http2
+
+package http
+
+import (
+ "io"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+// incomparable is a zero-width, non-comparable type. Adding it to a struct
+// makes that struct also non-comparable, and generally doesn't add
+// any size (as long as it's first).
+type incomparable [0]func()
+
+// maxInt64 is the effective "infinite" value for the Server and
+// Transport's byte-limiting readers.
+const maxInt64 = 1<<63 - 1
+
+// aLongTimeAgo is a non-zero time, far in the past, used for
+// immediate cancellation of network operations.
+var aLongTimeAgo = time.Unix(1, 0)
+
+// omitBundledHTTP2 is set by omithttp2.go when the nethttpomithttp2
+// build tag is set. That means h2_bundle.go isn't compiled in and we
+// shouldn't try to use it.
+var omitBundledHTTP2 bool
+
+// TODO(bradfitz): move common stuff here. The other files have accumulated
+// generic http stuff in random places.
+
+// contextKey is a value for use with context.WithValue. It's used as
+// a pointer so it fits in an interface{} without allocation.
+type contextKey struct {
+ name string
+}
+
+func (k *contextKey) String() string { return "net/http context value " + k.name }
+
+// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
+// return true if the string includes a port.
+func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
+
+// removeEmptyPort strips the empty port in ":port" to ""
+// as mandated by RFC 3986 Section 6.2.3.
+func removeEmptyPort(host string) string {
+ if hasPort(host) {
+ return strings.TrimSuffix(host, ":")
+ }
+ return host
+}
+
+func isNotToken(r rune) bool {
+ return !httpguts.IsTokenRune(r)
+}
+
+// stringContainsCTLByte reports whether s contains any ASCII control character.
+func stringContainsCTLByte(s string) bool {
+ for i := 0; i < len(s); i++ {
+ b := s[i]
+ if b < ' ' || b == 0x7f {
+ return true
+ }
+ }
+ return false
+}
+
+func hexEscapeNonASCII(s string) string {
+ newLen := 0
+ for i := 0; i < len(s); i++ {
+ if s[i] >= utf8.RuneSelf {
+ newLen += 3
+ } else {
+ newLen++
+ }
+ }
+ if newLen == len(s) {
+ return s
+ }
+ b := make([]byte, 0, newLen)
+ var pos int
+ for i := 0; i < len(s); i++ {
+ if s[i] >= utf8.RuneSelf {
+ if pos < i {
+ b = append(b, s[pos:i]...)
+ }
+ b = append(b, '%')
+ b = strconv.AppendInt(b, int64(s[i]), 16)
+ pos = i + 1
+ }
+ }
+ if pos < len(s) {
+ b = append(b, s[pos:]...)
+ }
+ return string(b)
+}
+
+// NoBody is an [io.ReadCloser] with no bytes. Read always returns EOF
+// and Close always returns nil. It can be used in an outgoing client
+// request to explicitly signal that a request has zero bytes.
+// An alternative, however, is to simply set [Request.Body] to nil.
+var NoBody = noBody{}
+
+type noBody struct{}
+
+func (noBody) Read([]byte) (int, error) { return 0, io.EOF }
+func (noBody) Close() error { return nil }
+func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil }
+
+var (
+ // verify that an io.Copy from NoBody won't require a buffer:
+ _ io.WriterTo = NoBody
+ _ io.ReadCloser = NoBody
+)
+
+// PushOptions describes options for [Pusher.Push].
+type PushOptions struct {
+ // Method specifies the HTTP method for the promised request.
+ // If set, it must be "GET" or "HEAD". Empty means "GET".
+ Method string
+
+ // Header specifies additional promised request headers. This cannot
+ // include HTTP/2 pseudo header fields like ":path" and ":scheme",
+ // which will be added automatically.
+ Header Header
+}
+
+// Pusher is the interface implemented by ResponseWriters that support
+// HTTP/2 server push. For more background, see
+// https://tools.ietf.org/html/rfc7540#section-8.2.
+type Pusher interface {
+ // Push initiates an HTTP/2 server push. This constructs a synthetic
+ // request using the given target and options, serializes that request
+ // into a PUSH_PROMISE frame, then dispatches that request using the
+ // server's request handler. If opts is nil, default options are used.
+ //
+ // The target must either be an absolute path (like "/path") or an absolute
+ // URL that contains a valid host and the same scheme as the parent request.
+ // If the target is a path, it will inherit the scheme and host of the
+ // parent request.
+ //
+ // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
+ // Push may or may not detect these invalid pushes; however, invalid
+ // pushes will be detected and canceled by conforming clients.
+ //
+ // Handlers that wish to push URL X should call Push before sending any
+ // data that may trigger a request for URL X. This avoids a race where the
+ // client issues requests for X before receiving the PUSH_PROMISE for X.
+ //
+ // Push will run in a separate goroutine making the order of arrival
+ // non-deterministic. Any required synchronization needs to be implemented
+ // by the caller.
+ //
+ // Push returns ErrNotSupported if the client has disabled push or if push
+ // is not supported on the underlying connection.
+ Push(target string, opts *PushOptions) error
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/http_test.go b/platform/dbops/binaries/go/go/src/net/http/http_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e7e024e2057f39ada5778752ce4ae78d96fa043
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/http_test.go
@@ -0,0 +1,200 @@
+// Copyright 2014 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 of internal functions and things with no better homes.
+
+package http
+
+import (
+ "bytes"
+ "internal/testenv"
+ "io/fs"
+ "net/url"
+ "os"
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestForeachHeaderElement(t *testing.T) {
+ tests := []struct {
+ in string
+ want []string
+ }{
+ {"Foo", []string{"Foo"}},
+ {" Foo", []string{"Foo"}},
+ {"Foo ", []string{"Foo"}},
+ {" Foo ", []string{"Foo"}},
+
+ {"foo", []string{"foo"}},
+ {"anY-cAsE", []string{"anY-cAsE"}},
+
+ {"", nil},
+ {",,,, , ,, ,,, ,", nil},
+
+ {" Foo,Bar, Baz,lower,,Quux ", []string{"Foo", "Bar", "Baz", "lower", "Quux"}},
+ }
+ for _, tt := range tests {
+ var got []string
+ foreachHeaderElement(tt.in, func(v string) {
+ got = append(got, v)
+ })
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("foreachHeaderElement(%q) = %q; want %q", tt.in, got, tt.want)
+ }
+ }
+}
+
+// Test that cmd/go doesn't link in the HTTP server.
+//
+// This catches accidental dependencies between the HTTP transport and
+// server code.
+func TestCmdGoNoHTTPServer(t *testing.T) {
+ t.Parallel()
+ goBin := testenv.GoToolPath(t)
+ out, err := testenv.Command(t, goBin, "tool", "nm", goBin).CombinedOutput()
+ if err != nil {
+ t.Fatalf("go tool nm: %v: %s", err, out)
+ }
+ wantSym := map[string]bool{
+ // Verify these exist: (sanity checking this test)
+ "net/http.(*Client).do": true,
+ "net/http.(*Transport).RoundTrip": true,
+
+ // Verify these don't exist:
+ "net/http.http2Server": false,
+ "net/http.(*Server).Serve": false,
+ "net/http.(*ServeMux).ServeHTTP": false,
+ "net/http.DefaultServeMux": false,
+ }
+ for sym, want := range wantSym {
+ got := bytes.Contains(out, []byte(sym))
+ if !want && got {
+ t.Errorf("cmd/go unexpectedly links in HTTP server code; found symbol %q in cmd/go", sym)
+ }
+ if want && !got {
+ t.Errorf("expected to find symbol %q in cmd/go; not found", sym)
+ }
+ }
+}
+
+// Tests that the nethttpomithttp2 build tag doesn't rot too much,
+// even if there's not a regular builder on it.
+func TestOmitHTTP2(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping in short mode")
+ }
+ t.Parallel()
+ goTool := testenv.GoToolPath(t)
+ out, err := testenv.Command(t, goTool, "test", "-short", "-tags=nethttpomithttp2", "net/http").CombinedOutput()
+ if err != nil {
+ t.Fatalf("go test -short failed: %v, %s", err, out)
+ }
+}
+
+// Tests that the nethttpomithttp2 build tag at least type checks
+// in short mode.
+// The TestOmitHTTP2 test above actually runs tests (in long mode).
+func TestOmitHTTP2Vet(t *testing.T) {
+ t.Parallel()
+ goTool := testenv.GoToolPath(t)
+ out, err := testenv.Command(t, goTool, "vet", "-tags=nethttpomithttp2", "net/http").CombinedOutput()
+ if err != nil {
+ t.Fatalf("go vet failed: %v, %s", err, out)
+ }
+}
+
+var valuesCount int
+
+func BenchmarkCopyValues(b *testing.B) {
+ b.ReportAllocs()
+ src := url.Values{
+ "a": {"1", "2", "3", "4", "5"},
+ "b": {"2", "2", "3", "4", "5"},
+ "c": {"3", "2", "3", "4", "5"},
+ "d": {"4", "2", "3", "4", "5"},
+ "e": {"1", "1", "2", "3", "4", "5", "6", "7", "abcdef", "l", "a", "b", "c", "d", "z"},
+ "j": {"1", "2"},
+ "m": nil,
+ }
+ for i := 0; i < b.N; i++ {
+ dst := url.Values{"a": {"b"}, "b": {"2"}, "c": {"3"}, "d": {"4"}, "j": nil, "m": {"x"}}
+ copyValues(dst, src)
+ if valuesCount = len(dst["a"]); valuesCount != 6 {
+ b.Fatalf(`%d items in dst["a"] but expected 6`, valuesCount)
+ }
+ }
+ if valuesCount == 0 {
+ b.Fatal("Benchmark wasn't run")
+ }
+}
+
+var forbiddenStringsFunctions = map[string]bool{
+ // Functions that use Unicode-aware case folding.
+ "EqualFold": true,
+ "Title": true,
+ "ToLower": true,
+ "ToLowerSpecial": true,
+ "ToTitle": true,
+ "ToTitleSpecial": true,
+ "ToUpper": true,
+ "ToUpperSpecial": true,
+
+ // Functions that use Unicode-aware spaces.
+ "Fields": true,
+ "TrimSpace": true,
+}
+
+// TestNoUnicodeStrings checks that nothing in net/http uses the Unicode-aware
+// strings and bytes package functions. HTTP is mostly ASCII based, and doing
+// Unicode-aware case folding or space stripping can introduce vulnerabilities.
+func TestNoUnicodeStrings(t *testing.T) {
+ if !testenv.HasSrc() {
+ t.Skip("source code not available")
+ }
+
+ re := regexp.MustCompile(`(strings|bytes).([A-Za-z]+)`)
+ if err := fs.WalkDir(os.DirFS("."), ".", func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if path == "internal/ascii" {
+ return fs.SkipDir
+ }
+ if !strings.HasSuffix(path, ".go") ||
+ strings.HasSuffix(path, "_test.go") ||
+ path == "h2_bundle.go" || d.IsDir() {
+ return nil
+ }
+
+ contents, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for lineNum, line := range strings.Split(string(contents), "\n") {
+ for _, match := range re.FindAllStringSubmatch(line, -1) {
+ if !forbiddenStringsFunctions[match[2]] {
+ continue
+ }
+ t.Errorf("disallowed call to %s at %s:%d", match[0], path, lineNum+1)
+ }
+ }
+
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+}
+
+const redirectURL = "/thisaredirect细雪withasciilettersのけぶabcdefghijk.html"
+
+func BenchmarkHexEscapeNonASCII(b *testing.B) {
+ b.ReportAllocs()
+
+ for i := 0; i < b.N; i++ {
+ hexEscapeNonASCII(redirectURL)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/example_test.go b/platform/dbops/binaries/go/go/src/net/http/httptest/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a6738432ebf306bf39d444a3fabafdd9d02130e2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/example_test.go
@@ -0,0 +1,99 @@
+// 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 httptest_test
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+)
+
+func ExampleResponseRecorder() {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "Hello World!")
+ }
+
+ req := httptest.NewRequest("GET", "http://example.com/foo", nil)
+ w := httptest.NewRecorder()
+ handler(w, req)
+
+ resp := w.Result()
+ body, _ := io.ReadAll(resp.Body)
+
+ fmt.Println(resp.StatusCode)
+ fmt.Println(resp.Header.Get("Content-Type"))
+ fmt.Println(string(body))
+
+ // Output:
+ // 200
+ // text/html; charset=utf-8
+ // Hello World!
+}
+
+func ExampleServer() {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "Hello, client")
+ }))
+ defer ts.Close()
+
+ res, err := http.Get(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ greeting, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s", greeting)
+ // Output: Hello, client
+}
+
+func ExampleServer_hTTP2() {
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "Hello, %s", r.Proto)
+ }))
+ ts.EnableHTTP2 = true
+ ts.StartTLS()
+ defer ts.Close()
+
+ res, err := ts.Client().Get(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ greeting, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Printf("%s", greeting)
+
+ // Output: Hello, HTTP/2.0
+}
+
+func ExampleNewTLSServer() {
+ ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "Hello, client")
+ }))
+ defer ts.Close()
+
+ client := ts.Client()
+ res, err := client.Get(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ greeting, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s", greeting)
+ // Output: Hello, client
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/httptest.go b/platform/dbops/binaries/go/go/src/net/http/httptest/httptest.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0ca64362d7fbd8e25719b64132c423c7313bda2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/httptest.go
@@ -0,0 +1,90 @@
+// 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 httptest provides utilities for HTTP testing.
+package httptest
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/tls"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// NewRequest returns a new incoming server Request, suitable
+// for passing to an [http.Handler] for testing.
+//
+// The target is the RFC 7230 "request-target": it may be either a
+// path or an absolute URL. If target is an absolute URL, the host name
+// from the URL is used. Otherwise, "example.com" is used.
+//
+// The TLS field is set to a non-nil dummy value if target has scheme
+// "https".
+//
+// The Request.Proto is always HTTP/1.1.
+//
+// An empty method means "GET".
+//
+// The provided body may be nil. If the body is of type *bytes.Reader,
+// *strings.Reader, or *bytes.Buffer, the Request.ContentLength is
+// set.
+//
+// NewRequest panics on error for ease of use in testing, where a
+// panic is acceptable.
+//
+// To generate a client HTTP request instead of a server request, see
+// the NewRequest function in the net/http package.
+func NewRequest(method, target string, body io.Reader) *http.Request {
+ if method == "" {
+ method = "GET"
+ }
+ req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(method + " " + target + " HTTP/1.0\r\n\r\n")))
+ if err != nil {
+ panic("invalid NewRequest arguments; " + err.Error())
+ }
+
+ // HTTP/1.0 was used above to avoid needing a Host field. Change it to 1.1 here.
+ req.Proto = "HTTP/1.1"
+ req.ProtoMinor = 1
+ req.Close = false
+
+ if body != nil {
+ switch v := body.(type) {
+ case *bytes.Buffer:
+ req.ContentLength = int64(v.Len())
+ case *bytes.Reader:
+ req.ContentLength = int64(v.Len())
+ case *strings.Reader:
+ req.ContentLength = int64(v.Len())
+ default:
+ req.ContentLength = -1
+ }
+ if rc, ok := body.(io.ReadCloser); ok {
+ req.Body = rc
+ } else {
+ req.Body = io.NopCloser(body)
+ }
+ }
+
+ // 192.0.2.0/24 is "TEST-NET" in RFC 5737 for use solely in
+ // documentation and example source code and should not be
+ // used publicly.
+ req.RemoteAddr = "192.0.2.1:1234"
+
+ if req.Host == "" {
+ req.Host = "example.com"
+ }
+
+ if strings.HasPrefix(target, "https://") {
+ req.TLS = &tls.ConnectionState{
+ Version: tls.VersionTLS12,
+ HandshakeComplete: true,
+ ServerName: req.Host,
+ }
+ }
+
+ return req
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/httptest_test.go b/platform/dbops/binaries/go/go/src/net/http/httptest/httptest_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..071add67ea6dbcf7a357a9a1ff63517187a31ee3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/httptest_test.go
@@ -0,0 +1,179 @@
+// 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 httptest
+
+import (
+ "crypto/tls"
+ "io"
+ "net/http"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestNewRequest(t *testing.T) {
+ for _, tt := range [...]struct {
+ name string
+
+ method, uri string
+ body io.Reader
+
+ want *http.Request
+ wantBody string
+ }{
+ {
+ name: "Empty method means GET",
+ method: "",
+ uri: "/",
+ body: nil,
+ want: &http.Request{
+ Method: "GET",
+ Host: "example.com",
+ URL: &url.URL{Path: "/"},
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "/",
+ },
+ wantBody: "",
+ },
+
+ {
+ name: "GET with full URL",
+ method: "GET",
+ uri: "http://foo.com/path/%2f/bar/",
+ body: nil,
+ want: &http.Request{
+ Method: "GET",
+ Host: "foo.com",
+ URL: &url.URL{
+ Scheme: "http",
+ Path: "/path///bar/",
+ RawPath: "/path/%2f/bar/",
+ Host: "foo.com",
+ },
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "http://foo.com/path/%2f/bar/",
+ },
+ wantBody: "",
+ },
+
+ {
+ name: "GET with full https URL",
+ method: "GET",
+ uri: "https://foo.com/path/",
+ body: nil,
+ want: &http.Request{
+ Method: "GET",
+ Host: "foo.com",
+ URL: &url.URL{
+ Scheme: "https",
+ Path: "/path/",
+ Host: "foo.com",
+ },
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "https://foo.com/path/",
+ TLS: &tls.ConnectionState{
+ Version: tls.VersionTLS12,
+ HandshakeComplete: true,
+ ServerName: "foo.com",
+ },
+ },
+ wantBody: "",
+ },
+
+ {
+ name: "Post with known length",
+ method: "POST",
+ uri: "/",
+ body: strings.NewReader("foo"),
+ want: &http.Request{
+ Method: "POST",
+ Host: "example.com",
+ URL: &url.URL{Path: "/"},
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ContentLength: 3,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "/",
+ },
+ wantBody: "foo",
+ },
+
+ {
+ name: "Post with unknown length",
+ method: "POST",
+ uri: "/",
+ body: struct{ io.Reader }{strings.NewReader("foo")},
+ want: &http.Request{
+ Method: "POST",
+ Host: "example.com",
+ URL: &url.URL{Path: "/"},
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ContentLength: -1,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "/",
+ },
+ wantBody: "foo",
+ },
+
+ {
+ name: "OPTIONS *",
+ method: "OPTIONS",
+ uri: "*",
+ want: &http.Request{
+ Method: "OPTIONS",
+ Host: "example.com",
+ URL: &url.URL{Path: "*"},
+ Header: http.Header{},
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ RemoteAddr: "192.0.2.1:1234",
+ RequestURI: "*",
+ },
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got := NewRequest(tt.method, tt.uri, tt.body)
+ slurp, err := io.ReadAll(got.Body)
+ if err != nil {
+ t.Errorf("ReadAll: %v", err)
+ }
+ if string(slurp) != tt.wantBody {
+ t.Errorf("Body = %q; want %q", slurp, tt.wantBody)
+ }
+ got.Body = nil // before DeepEqual
+ if !reflect.DeepEqual(got.URL, tt.want.URL) {
+ t.Errorf("Request.URL mismatch:\n got: %#v\nwant: %#v", got.URL, tt.want.URL)
+ }
+ if !reflect.DeepEqual(got.Header, tt.want.Header) {
+ t.Errorf("Request.Header mismatch:\n got: %#v\nwant: %#v", got.Header, tt.want.Header)
+ }
+ if !reflect.DeepEqual(got.TLS, tt.want.TLS) {
+ t.Errorf("Request.TLS mismatch:\n got: %#v\nwant: %#v", got.TLS, tt.want.TLS)
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("Request mismatch:\n got: %#v\nwant: %#v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/recorder.go b/platform/dbops/binaries/go/go/src/net/http/httptest/recorder.go
new file mode 100644
index 0000000000000000000000000000000000000000..dd51901b0d3b948c5fc0519127a4cdb0009748f2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/recorder.go
@@ -0,0 +1,255 @@
+// 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 httptest
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "net/textproto"
+ "strconv"
+ "strings"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+// ResponseRecorder is an implementation of [http.ResponseWriter] that
+// records its mutations for later inspection in tests.
+type ResponseRecorder struct {
+ // Code is the HTTP response code set by WriteHeader.
+ //
+ // Note that if a Handler never calls WriteHeader or Write,
+ // this might end up being 0, rather than the implicit
+ // http.StatusOK. To get the implicit value, use the Result
+ // method.
+ Code int
+
+ // HeaderMap contains the headers explicitly set by the Handler.
+ // It is an internal detail.
+ //
+ // Deprecated: HeaderMap exists for historical compatibility
+ // and should not be used. To access the headers returned by a handler,
+ // use the Response.Header map as returned by the Result method.
+ HeaderMap http.Header
+
+ // Body is the buffer to which the Handler's Write calls are sent.
+ // If nil, the Writes are silently discarded.
+ Body *bytes.Buffer
+
+ // Flushed is whether the Handler called Flush.
+ Flushed bool
+
+ result *http.Response // cache of Result's return value
+ snapHeader http.Header // snapshot of HeaderMap at first Write
+ wroteHeader bool
+}
+
+// NewRecorder returns an initialized [ResponseRecorder].
+func NewRecorder() *ResponseRecorder {
+ return &ResponseRecorder{
+ HeaderMap: make(http.Header),
+ Body: new(bytes.Buffer),
+ Code: 200,
+ }
+}
+
+// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
+// an explicit DefaultRemoteAddr isn't set on [ResponseRecorder].
+const DefaultRemoteAddr = "1.2.3.4"
+
+// Header implements [http.ResponseWriter]. It returns the response
+// headers to mutate within a handler. To test the headers that were
+// written after a handler completes, use the [ResponseRecorder.Result] method and see
+// the returned Response value's Header.
+func (rw *ResponseRecorder) Header() http.Header {
+ m := rw.HeaderMap
+ if m == nil {
+ m = make(http.Header)
+ rw.HeaderMap = m
+ }
+ return m
+}
+
+// writeHeader writes a header if it was not written yet and
+// detects Content-Type if needed.
+//
+// bytes or str are the beginning of the response body.
+// We pass both to avoid unnecessarily generate garbage
+// in rw.WriteString which was created for performance reasons.
+// Non-nil bytes win.
+func (rw *ResponseRecorder) writeHeader(b []byte, str string) {
+ if rw.wroteHeader {
+ return
+ }
+ if len(str) > 512 {
+ str = str[:512]
+ }
+
+ m := rw.Header()
+
+ _, hasType := m["Content-Type"]
+ hasTE := m.Get("Transfer-Encoding") != ""
+ if !hasType && !hasTE {
+ if b == nil {
+ b = []byte(str)
+ }
+ m.Set("Content-Type", http.DetectContentType(b))
+ }
+
+ rw.WriteHeader(200)
+}
+
+// Write implements http.ResponseWriter. The data in buf is written to
+// rw.Body, if not nil.
+func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
+ rw.writeHeader(buf, "")
+ if rw.Body != nil {
+ rw.Body.Write(buf)
+ }
+ return len(buf), nil
+}
+
+// WriteString implements [io.StringWriter]. The data in str is written
+// to rw.Body, if not nil.
+func (rw *ResponseRecorder) WriteString(str string) (int, error) {
+ rw.writeHeader(nil, str)
+ if rw.Body != nil {
+ rw.Body.WriteString(str)
+ }
+ return len(str), nil
+}
+
+func checkWriteHeaderCode(code int) {
+ // Issue 22880: require valid WriteHeader status codes.
+ // For now we only enforce that it's three digits.
+ // In the future we might block things over 599 (600 and above aren't defined
+ // at https://httpwg.org/specs/rfc7231.html#status.codes)
+ // and we might block under 200 (once we have more mature 1xx support).
+ // But for now any three digits.
+ //
+ // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
+ // no equivalent bogus thing we can realistically send in HTTP/2,
+ // so we'll consistently panic instead and help people find their bugs
+ // early. (We can't return an error from WriteHeader even if we wanted to.)
+ if code < 100 || code > 999 {
+ panic(fmt.Sprintf("invalid WriteHeader code %v", code))
+ }
+}
+
+// WriteHeader implements [http.ResponseWriter].
+func (rw *ResponseRecorder) WriteHeader(code int) {
+ if rw.wroteHeader {
+ return
+ }
+
+ checkWriteHeaderCode(code)
+ rw.Code = code
+ rw.wroteHeader = true
+ if rw.HeaderMap == nil {
+ rw.HeaderMap = make(http.Header)
+ }
+ rw.snapHeader = rw.HeaderMap.Clone()
+}
+
+// Flush implements [http.Flusher]. To test whether Flush was
+// called, see rw.Flushed.
+func (rw *ResponseRecorder) Flush() {
+ if !rw.wroteHeader {
+ rw.WriteHeader(200)
+ }
+ rw.Flushed = true
+}
+
+// Result returns the response generated by the handler.
+//
+// The returned Response will have at least its StatusCode,
+// Header, Body, and optionally Trailer populated.
+// More fields may be populated in the future, so callers should
+// not DeepEqual the result in tests.
+//
+// The Response.Header is a snapshot of the headers at the time of the
+// first write call, or at the time of this call, if the handler never
+// did a write.
+//
+// The Response.Body is guaranteed to be non-nil and Body.Read call is
+// guaranteed to not return any error other than [io.EOF].
+//
+// Result must only be called after the handler has finished running.
+func (rw *ResponseRecorder) Result() *http.Response {
+ if rw.result != nil {
+ return rw.result
+ }
+ if rw.snapHeader == nil {
+ rw.snapHeader = rw.HeaderMap.Clone()
+ }
+ res := &http.Response{
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ StatusCode: rw.Code,
+ Header: rw.snapHeader,
+ }
+ rw.result = res
+ if res.StatusCode == 0 {
+ res.StatusCode = 200
+ }
+ res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
+ if rw.Body != nil {
+ res.Body = io.NopCloser(bytes.NewReader(rw.Body.Bytes()))
+ } else {
+ res.Body = http.NoBody
+ }
+ res.ContentLength = parseContentLength(res.Header.Get("Content-Length"))
+
+ if trailers, ok := rw.snapHeader["Trailer"]; ok {
+ res.Trailer = make(http.Header, len(trailers))
+ for _, k := range trailers {
+ for _, k := range strings.Split(k, ",") {
+ k = http.CanonicalHeaderKey(textproto.TrimString(k))
+ if !httpguts.ValidTrailerHeader(k) {
+ // Ignore since forbidden by RFC 7230, section 4.1.2.
+ continue
+ }
+ vv, ok := rw.HeaderMap[k]
+ if !ok {
+ continue
+ }
+ vv2 := make([]string, len(vv))
+ copy(vv2, vv)
+ res.Trailer[k] = vv2
+ }
+ }
+ }
+ for k, vv := range rw.HeaderMap {
+ if !strings.HasPrefix(k, http.TrailerPrefix) {
+ continue
+ }
+ if res.Trailer == nil {
+ res.Trailer = make(http.Header)
+ }
+ for _, v := range vv {
+ res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v)
+ }
+ }
+ return res
+}
+
+// parseContentLength trims whitespace from s and returns -1 if no value
+// is set, or the value if it's >= 0.
+//
+// This a modified version of same function found in net/http/transfer.go. This
+// one just ignores an invalid header.
+func parseContentLength(cl string) int64 {
+ cl = textproto.TrimString(cl)
+ if cl == "" {
+ return -1
+ }
+ n, err := strconv.ParseUint(cl, 10, 63)
+ if err != nil {
+ return -1
+ }
+ return int64(n)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/recorder_test.go b/platform/dbops/binaries/go/go/src/net/http/httptest/recorder_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4782eced43e6ce61c2dcab57b827048224be7f93
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/recorder_test.go
@@ -0,0 +1,371 @@
+// 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 httptest
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "testing"
+)
+
+func TestRecorder(t *testing.T) {
+ type checkFunc func(*ResponseRecorder) error
+ check := func(fns ...checkFunc) []checkFunc { return fns }
+
+ hasStatus := func(wantCode int) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if rec.Code != wantCode {
+ return fmt.Errorf("Status = %d; want %d", rec.Code, wantCode)
+ }
+ return nil
+ }
+ }
+ hasResultStatus := func(want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if rec.Result().Status != want {
+ return fmt.Errorf("Result().Status = %q; want %q", rec.Result().Status, want)
+ }
+ return nil
+ }
+ }
+ hasResultStatusCode := func(wantCode int) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if rec.Result().StatusCode != wantCode {
+ return fmt.Errorf("Result().StatusCode = %d; want %d", rec.Result().StatusCode, wantCode)
+ }
+ return nil
+ }
+ }
+ hasResultContents := func(want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ contentBytes, err := io.ReadAll(rec.Result().Body)
+ if err != nil {
+ return err
+ }
+ contents := string(contentBytes)
+ if contents != want {
+ return fmt.Errorf("Result().Body = %s; want %s", contents, want)
+ }
+ return nil
+ }
+ }
+ hasContents := func(want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if rec.Body.String() != want {
+ return fmt.Errorf("wrote = %q; want %q", rec.Body.String(), want)
+ }
+ return nil
+ }
+ }
+ hasFlush := func(want bool) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if rec.Flushed != want {
+ return fmt.Errorf("Flushed = %v; want %v", rec.Flushed, want)
+ }
+ return nil
+ }
+ }
+ hasOldHeader := func(key, want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if got := rec.HeaderMap.Get(key); got != want {
+ return fmt.Errorf("HeaderMap header %s = %q; want %q", key, got, want)
+ }
+ return nil
+ }
+ }
+ hasHeader := func(key, want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if got := rec.Result().Header.Get(key); got != want {
+ return fmt.Errorf("final header %s = %q; want %q", key, got, want)
+ }
+ return nil
+ }
+ }
+ hasNotHeaders := func(keys ...string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ for _, k := range keys {
+ v, ok := rec.Result().Header[http.CanonicalHeaderKey(k)]
+ if ok {
+ return fmt.Errorf("unexpected header %s with value %q", k, v)
+ }
+ }
+ return nil
+ }
+ }
+ hasTrailer := func(key, want string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if got := rec.Result().Trailer.Get(key); got != want {
+ return fmt.Errorf("trailer %s = %q; want %q", key, got, want)
+ }
+ return nil
+ }
+ }
+ hasNotTrailers := func(keys ...string) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ trailers := rec.Result().Trailer
+ for _, k := range keys {
+ _, ok := trailers[http.CanonicalHeaderKey(k)]
+ if ok {
+ return fmt.Errorf("unexpected trailer %s", k)
+ }
+ }
+ return nil
+ }
+ }
+ hasContentLength := func(length int64) checkFunc {
+ return func(rec *ResponseRecorder) error {
+ if got := rec.Result().ContentLength; got != length {
+ return fmt.Errorf("ContentLength = %d; want %d", got, length)
+ }
+ return nil
+ }
+ }
+
+ for _, tt := range [...]struct {
+ name string
+ h func(w http.ResponseWriter, r *http.Request)
+ checks []checkFunc
+ }{
+ {
+ "200 default",
+ func(w http.ResponseWriter, r *http.Request) {},
+ check(hasStatus(200), hasContents("")),
+ },
+ {
+ "first code only",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(201)
+ w.WriteHeader(202)
+ w.Write([]byte("hi"))
+ },
+ check(hasStatus(201), hasContents("hi")),
+ },
+ {
+ "write sends 200",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hi first"))
+ w.WriteHeader(201)
+ w.WriteHeader(202)
+ },
+ check(hasStatus(200), hasContents("hi first"), hasFlush(false)),
+ },
+ {
+ "write string",
+ func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "hi first")
+ },
+ check(
+ hasStatus(200),
+ hasContents("hi first"),
+ hasFlush(false),
+ hasHeader("Content-Type", "text/plain; charset=utf-8"),
+ ),
+ },
+ {
+ "flush",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.(http.Flusher).Flush() // also sends a 200
+ w.WriteHeader(201)
+ },
+ check(hasStatus(200), hasFlush(true), hasContentLength(-1)),
+ },
+ {
+ "Content-Type detection",
+ func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "")
+ },
+ check(hasHeader("Content-Type", "text/html; charset=utf-8")),
+ },
+ {
+ "no Content-Type detection with Transfer-Encoding",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Transfer-Encoding", "some encoding")
+ io.WriteString(w, "")
+ },
+ check(hasHeader("Content-Type", "")), // no header
+ },
+ {
+ "no Content-Type detection if set explicitly",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "some/type")
+ io.WriteString(w, "")
+ },
+ check(hasHeader("Content-Type", "some/type")),
+ },
+ {
+ "Content-Type detection doesn't crash if HeaderMap is nil",
+ func(w http.ResponseWriter, r *http.Request) {
+ // Act as if the user wrote new(httptest.ResponseRecorder)
+ // rather than using NewRecorder (which initializes
+ // HeaderMap)
+ w.(*ResponseRecorder).HeaderMap = nil
+ io.WriteString(w, "")
+ },
+ check(hasHeader("Content-Type", "text/html; charset=utf-8")),
+ },
+ {
+ "Header is not changed after write",
+ func(w http.ResponseWriter, r *http.Request) {
+ hdr := w.Header()
+ hdr.Set("Key", "correct")
+ w.WriteHeader(200)
+ hdr.Set("Key", "incorrect")
+ },
+ check(hasHeader("Key", "correct")),
+ },
+ {
+ "Trailer headers are correctly recorded",
+ func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Non-Trailer", "correct")
+ w.Header().Set("Trailer", "Trailer-A, Trailer-B")
+ w.Header().Add("Trailer", "Trailer-C")
+ io.WriteString(w, "")
+ w.Header().Set("Non-Trailer", "incorrect")
+ w.Header().Set("Trailer-A", "valuea")
+ w.Header().Set("Trailer-C", "valuec")
+ w.Header().Set("Trailer-NotDeclared", "should be omitted")
+ w.Header().Set("Trailer:Trailer-D", "with prefix")
+ },
+ check(
+ hasStatus(200),
+ hasHeader("Content-Type", "text/html; charset=utf-8"),
+ hasHeader("Non-Trailer", "correct"),
+ hasNotHeaders("Trailer-A", "Trailer-B", "Trailer-C", "Trailer-NotDeclared"),
+ hasTrailer("Trailer-A", "valuea"),
+ hasTrailer("Trailer-C", "valuec"),
+ hasNotTrailers("Non-Trailer", "Trailer-B", "Trailer-NotDeclared"),
+ hasTrailer("Trailer-D", "with prefix"),
+ ),
+ },
+ {
+ "Header set without any write", // Issue 15560
+ func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Foo", "1")
+
+ // Simulate somebody using
+ // new(ResponseRecorder) instead of
+ // using the constructor which sets
+ // this to 200
+ w.(*ResponseRecorder).Code = 0
+ },
+ check(
+ hasOldHeader("X-Foo", "1"),
+ hasStatus(0),
+ hasHeader("X-Foo", "1"),
+ hasResultStatus("200 OK"),
+ hasResultStatusCode(200),
+ ),
+ },
+ {
+ "HeaderMap vs FinalHeaders", // more for Issue 15560
+ func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("X-Foo", "1")
+ w.Write([]byte("hi"))
+ h.Set("X-Foo", "2")
+ h.Set("X-Bar", "2")
+ },
+ check(
+ hasOldHeader("X-Foo", "2"),
+ hasOldHeader("X-Bar", "2"),
+ hasHeader("X-Foo", "1"),
+ hasNotHeaders("X-Bar"),
+ ),
+ },
+ {
+ "setting Content-Length header",
+ func(w http.ResponseWriter, r *http.Request) {
+ body := "Some body"
+ contentLength := fmt.Sprintf("%d", len(body))
+ w.Header().Set("Content-Length", contentLength)
+ io.WriteString(w, body)
+ },
+ check(hasStatus(200), hasContents("Some body"), hasContentLength(9)),
+ },
+ {
+ "nil ResponseRecorder.Body", // Issue 26642
+ func(w http.ResponseWriter, r *http.Request) {
+ w.(*ResponseRecorder).Body = nil
+ io.WriteString(w, "hi")
+ },
+ check(hasResultContents("")), // check we don't crash reading the body
+
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ r, _ := http.NewRequest("GET", "http://foo.com/", nil)
+ h := http.HandlerFunc(tt.h)
+ rec := NewRecorder()
+ h.ServeHTTP(rec, r)
+ for _, check := range tt.checks {
+ if err := check(rec); err != nil {
+ t.Error(err)
+ }
+ }
+ })
+ }
+}
+
+// issue 39017 - disallow Content-Length values such as "+3"
+func TestParseContentLength(t *testing.T) {
+ tests := []struct {
+ cl string
+ want int64
+ }{
+ {
+ cl: "3",
+ want: 3,
+ },
+ {
+ cl: "+3",
+ want: -1,
+ },
+ {
+ cl: "-3",
+ want: -1,
+ },
+ {
+ // max int64, for safe conversion before returning
+ cl: "9223372036854775807",
+ want: 9223372036854775807,
+ },
+ {
+ cl: "9223372036854775808",
+ want: -1,
+ },
+ }
+
+ for _, tt := range tests {
+ if got := parseContentLength(tt.cl); got != tt.want {
+ t.Errorf("%q:\n\tgot=%d\n\twant=%d", tt.cl, got, tt.want)
+ }
+ }
+}
+
+// Ensure that httptest.Recorder panics when given a non-3 digit (XXX)
+// status HTTP code. See https://golang.org/issues/45353
+func TestRecorderPanicsOnNonXXXStatusCode(t *testing.T) {
+ badCodes := []int{
+ -100, 0, 99, 1000, 20000,
+ }
+ for _, badCode := range badCodes {
+ badCode := badCode
+ t.Run(fmt.Sprintf("Code=%d", badCode), func(t *testing.T) {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Fatal("Expected a panic")
+ }
+ }()
+
+ handler := func(rw http.ResponseWriter, _ *http.Request) {
+ rw.WriteHeader(badCode)
+ }
+ r, _ := http.NewRequest("GET", "http://example.org/", nil)
+ rw := NewRecorder()
+ handler(rw, r)
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/server.go b/platform/dbops/binaries/go/go/src/net/http/httptest/server.go
new file mode 100644
index 0000000000000000000000000000000000000000..5095b438ec9487d214e7e84b2ade092700b788bb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/server.go
@@ -0,0 +1,385 @@
+// 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.
+
+// Implementation of Server
+
+package httptest
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "flag"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/http/internal/testcert"
+ "os"
+ "strings"
+ "sync"
+ "time"
+)
+
+// A Server is an HTTP server listening on a system-chosen port on the
+// local loopback interface, for use in end-to-end HTTP tests.
+type Server struct {
+ URL string // base URL of form http://ipaddr:port with no trailing slash
+ Listener net.Listener
+
+ // EnableHTTP2 controls whether HTTP/2 is enabled
+ // on the server. It must be set between calling
+ // NewUnstartedServer and calling Server.StartTLS.
+ EnableHTTP2 bool
+
+ // TLS is the optional TLS configuration, populated with a new config
+ // after TLS is started. If set on an unstarted server before StartTLS
+ // is called, existing fields are copied into the new config.
+ TLS *tls.Config
+
+ // Config may be changed after calling NewUnstartedServer and
+ // before Start or StartTLS.
+ Config *http.Server
+
+ // certificate is a parsed version of the TLS config certificate, if present.
+ certificate *x509.Certificate
+
+ // wg counts the number of outstanding HTTP requests on this server.
+ // Close blocks until all requests are finished.
+ wg sync.WaitGroup
+
+ mu sync.Mutex // guards closed and conns
+ closed bool
+ conns map[net.Conn]http.ConnState // except terminal states
+
+ // client is configured for use with the server.
+ // Its transport is automatically closed when Close is called.
+ client *http.Client
+}
+
+func newLocalListener() net.Listener {
+ if serveFlag != "" {
+ l, err := net.Listen("tcp", serveFlag)
+ if err != nil {
+ panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err))
+ }
+ return l
+ }
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ if l, err = net.Listen("tcp6", "[::1]:0"); err != nil {
+ panic(fmt.Sprintf("httptest: failed to listen on a port: %v", err))
+ }
+ }
+ return l
+}
+
+// When debugging a particular http server-based test,
+// this flag lets you run
+//
+// go test -run='^BrokenTest$' -httptest.serve=127.0.0.1:8000
+//
+// to start the broken server so you can interact with it manually.
+// We only register this flag if it looks like the caller knows about it
+// and is trying to use it as we don't want to pollute flags and this
+// isn't really part of our API. Don't depend on this.
+var serveFlag string
+
+func init() {
+ if strSliceContainsPrefix(os.Args, "-httptest.serve=") || strSliceContainsPrefix(os.Args, "--httptest.serve=") {
+ flag.StringVar(&serveFlag, "httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks.")
+ }
+}
+
+func strSliceContainsPrefix(v []string, pre string) bool {
+ for _, s := range v {
+ if strings.HasPrefix(s, pre) {
+ return true
+ }
+ }
+ return false
+}
+
+// NewServer starts and returns a new [Server].
+// The caller should call Close when finished, to shut it down.
+func NewServer(handler http.Handler) *Server {
+ ts := NewUnstartedServer(handler)
+ ts.Start()
+ return ts
+}
+
+// NewUnstartedServer returns a new [Server] but doesn't start it.
+//
+// After changing its configuration, the caller should call Start or
+// StartTLS.
+//
+// The caller should call Close when finished, to shut it down.
+func NewUnstartedServer(handler http.Handler) *Server {
+ return &Server{
+ Listener: newLocalListener(),
+ Config: &http.Server{Handler: handler},
+ }
+}
+
+// Start starts a server from NewUnstartedServer.
+func (s *Server) Start() {
+ if s.URL != "" {
+ panic("Server already started")
+ }
+ if s.client == nil {
+ s.client = &http.Client{Transport: &http.Transport{}}
+ }
+ s.URL = "http://" + s.Listener.Addr().String()
+ s.wrap()
+ s.goServe()
+ if serveFlag != "" {
+ fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL)
+ select {}
+ }
+}
+
+// StartTLS starts TLS on a server from NewUnstartedServer.
+func (s *Server) StartTLS() {
+ if s.URL != "" {
+ panic("Server already started")
+ }
+ if s.client == nil {
+ s.client = &http.Client{}
+ }
+ cert, err := tls.X509KeyPair(testcert.LocalhostCert, testcert.LocalhostKey)
+ if err != nil {
+ panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
+ }
+
+ existingConfig := s.TLS
+ if existingConfig != nil {
+ s.TLS = existingConfig.Clone()
+ } else {
+ s.TLS = new(tls.Config)
+ }
+ if s.TLS.NextProtos == nil {
+ nextProtos := []string{"http/1.1"}
+ if s.EnableHTTP2 {
+ nextProtos = []string{"h2"}
+ }
+ s.TLS.NextProtos = nextProtos
+ }
+ if len(s.TLS.Certificates) == 0 {
+ s.TLS.Certificates = []tls.Certificate{cert}
+ }
+ s.certificate, err = x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0])
+ if err != nil {
+ panic(fmt.Sprintf("httptest: NewTLSServer: %v", err))
+ }
+ certpool := x509.NewCertPool()
+ certpool.AddCert(s.certificate)
+ s.client.Transport = &http.Transport{
+ TLSClientConfig: &tls.Config{
+ RootCAs: certpool,
+ },
+ ForceAttemptHTTP2: s.EnableHTTP2,
+ }
+ s.Listener = tls.NewListener(s.Listener, s.TLS)
+ s.URL = "https://" + s.Listener.Addr().String()
+ s.wrap()
+ s.goServe()
+}
+
+// NewTLSServer starts and returns a new [Server] using TLS.
+// The caller should call Close when finished, to shut it down.
+func NewTLSServer(handler http.Handler) *Server {
+ ts := NewUnstartedServer(handler)
+ ts.StartTLS()
+ return ts
+}
+
+type closeIdleTransport interface {
+ CloseIdleConnections()
+}
+
+// Close shuts down the server and blocks until all outstanding
+// requests on this server have completed.
+func (s *Server) Close() {
+ s.mu.Lock()
+ if !s.closed {
+ s.closed = true
+ s.Listener.Close()
+ s.Config.SetKeepAlivesEnabled(false)
+ for c, st := range s.conns {
+ // Force-close any idle connections (those between
+ // requests) and new connections (those which connected
+ // but never sent a request). StateNew connections are
+ // super rare and have only been seen (in
+ // previously-flaky tests) in the case of
+ // socket-late-binding races from the http Client
+ // dialing this server and then getting an idle
+ // connection before the dial completed. There is thus
+ // a connected connection in StateNew with no
+ // associated Request. We only close StateIdle and
+ // StateNew because they're not doing anything. It's
+ // possible StateNew is about to do something in a few
+ // milliseconds, but a previous CL to check again in a
+ // few milliseconds wasn't liked (early versions of
+ // https://golang.org/cl/15151) so now we just
+ // forcefully close StateNew. The docs for Server.Close say
+ // we wait for "outstanding requests", so we don't close things
+ // in StateActive.
+ if st == http.StateIdle || st == http.StateNew {
+ s.closeConn(c)
+ }
+ }
+ // If this server doesn't shut down in 5 seconds, tell the user why.
+ t := time.AfterFunc(5*time.Second, s.logCloseHangDebugInfo)
+ defer t.Stop()
+ }
+ s.mu.Unlock()
+
+ // Not part of httptest.Server's correctness, but assume most
+ // users of httptest.Server will be using the standard
+ // transport, so help them out and close any idle connections for them.
+ if t, ok := http.DefaultTransport.(closeIdleTransport); ok {
+ t.CloseIdleConnections()
+ }
+
+ // Also close the client idle connections.
+ if s.client != nil {
+ if t, ok := s.client.Transport.(closeIdleTransport); ok {
+ t.CloseIdleConnections()
+ }
+ }
+
+ s.wg.Wait()
+}
+
+func (s *Server) logCloseHangDebugInfo() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ var buf strings.Builder
+ buf.WriteString("httptest.Server blocked in Close after 5 seconds, waiting for connections:\n")
+ for c, st := range s.conns {
+ fmt.Fprintf(&buf, " %T %p %v in state %v\n", c, c, c.RemoteAddr(), st)
+ }
+ log.Print(buf.String())
+}
+
+// CloseClientConnections closes any open HTTP connections to the test Server.
+func (s *Server) CloseClientConnections() {
+ s.mu.Lock()
+ nconn := len(s.conns)
+ ch := make(chan struct{}, nconn)
+ for c := range s.conns {
+ go s.closeConnChan(c, ch)
+ }
+ s.mu.Unlock()
+
+ // Wait for outstanding closes to finish.
+ //
+ // Out of paranoia for making a late change in Go 1.6, we
+ // bound how long this can wait, since golang.org/issue/14291
+ // isn't fully understood yet. At least this should only be used
+ // in tests.
+ timer := time.NewTimer(5 * time.Second)
+ defer timer.Stop()
+ for i := 0; i < nconn; i++ {
+ select {
+ case <-ch:
+ case <-timer.C:
+ // Too slow. Give up.
+ return
+ }
+ }
+}
+
+// Certificate returns the certificate used by the server, or nil if
+// the server doesn't use TLS.
+func (s *Server) Certificate() *x509.Certificate {
+ return s.certificate
+}
+
+// Client returns an HTTP client configured for making requests to the server.
+// It is configured to trust the server's TLS test certificate and will
+// close its idle connections on [Server.Close].
+func (s *Server) Client() *http.Client {
+ return s.client
+}
+
+func (s *Server) goServe() {
+ s.wg.Add(1)
+ go func() {
+ defer s.wg.Done()
+ s.Config.Serve(s.Listener)
+ }()
+}
+
+// wrap installs the connection state-tracking hook to know which
+// connections are idle.
+func (s *Server) wrap() {
+ oldHook := s.Config.ConnState
+ s.Config.ConnState = func(c net.Conn, cs http.ConnState) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ switch cs {
+ case http.StateNew:
+ if _, exists := s.conns[c]; exists {
+ panic("invalid state transition")
+ }
+ if s.conns == nil {
+ s.conns = make(map[net.Conn]http.ConnState)
+ }
+ // Add c to the set of tracked conns and increment it to the
+ // waitgroup.
+ s.wg.Add(1)
+ s.conns[c] = cs
+ if s.closed {
+ // Probably just a socket-late-binding dial from
+ // the default transport that lost the race (and
+ // thus this connection is now idle and will
+ // never be used).
+ s.closeConn(c)
+ }
+ case http.StateActive:
+ if oldState, ok := s.conns[c]; ok {
+ if oldState != http.StateNew && oldState != http.StateIdle {
+ panic("invalid state transition")
+ }
+ s.conns[c] = cs
+ }
+ case http.StateIdle:
+ if oldState, ok := s.conns[c]; ok {
+ if oldState != http.StateActive {
+ panic("invalid state transition")
+ }
+ s.conns[c] = cs
+ }
+ if s.closed {
+ s.closeConn(c)
+ }
+ case http.StateHijacked, http.StateClosed:
+ // Remove c from the set of tracked conns and decrement it from the
+ // waitgroup, unless it was previously removed.
+ if _, ok := s.conns[c]; ok {
+ delete(s.conns, c)
+ // Keep Close from returning until the user's ConnState hook
+ // (if any) finishes.
+ defer s.wg.Done()
+ }
+ }
+ if oldHook != nil {
+ oldHook(c, cs)
+ }
+ }
+}
+
+// closeConn closes c.
+// s.mu must be held.
+func (s *Server) closeConn(c net.Conn) { s.closeConnChan(c, nil) }
+
+// closeConnChan is like closeConn, but takes an optional channel to receive a value
+// when the goroutine closing c is done.
+func (s *Server) closeConnChan(c net.Conn, done chan<- struct{}) {
+ c.Close()
+ if done != nil {
+ done <- struct{}{}
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptest/server_test.go b/platform/dbops/binaries/go/go/src/net/http/httptest/server_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5313f65456c350e9f74b94b2070a0a36b46506f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptest/server_test.go
@@ -0,0 +1,294 @@
+// 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 httptest
+
+import (
+ "bufio"
+ "io"
+ "net"
+ "net/http"
+ "sync"
+ "testing"
+)
+
+type newServerFunc func(http.Handler) *Server
+
+var newServers = map[string]newServerFunc{
+ "NewServer": NewServer,
+ "NewTLSServer": NewTLSServer,
+
+ // The manual variants of newServer create a Server manually by only filling
+ // in the exported fields of Server.
+ "NewServerManual": func(h http.Handler) *Server {
+ ts := &Server{Listener: newLocalListener(), Config: &http.Server{Handler: h}}
+ ts.Start()
+ return ts
+ },
+ "NewTLSServerManual": func(h http.Handler) *Server {
+ ts := &Server{Listener: newLocalListener(), Config: &http.Server{Handler: h}}
+ ts.StartTLS()
+ return ts
+ },
+}
+
+func TestServer(t *testing.T) {
+ for _, name := range []string{"NewServer", "NewServerManual"} {
+ t.Run(name, func(t *testing.T) {
+ newServer := newServers[name]
+ t.Run("Server", func(t *testing.T) { testServer(t, newServer) })
+ t.Run("GetAfterClose", func(t *testing.T) { testGetAfterClose(t, newServer) })
+ t.Run("ServerCloseBlocking", func(t *testing.T) { testServerCloseBlocking(t, newServer) })
+ t.Run("ServerCloseClientConnections", func(t *testing.T) { testServerCloseClientConnections(t, newServer) })
+ t.Run("ServerClientTransportType", func(t *testing.T) { testServerClientTransportType(t, newServer) })
+ })
+ }
+ for _, name := range []string{"NewTLSServer", "NewTLSServerManual"} {
+ t.Run(name, func(t *testing.T) {
+ newServer := newServers[name]
+ t.Run("ServerClient", func(t *testing.T) { testServerClient(t, newServer) })
+ t.Run("TLSServerClientTransportType", func(t *testing.T) { testTLSServerClientTransportType(t, newServer) })
+ })
+ }
+}
+
+func testServer(t *testing.T, newServer newServerFunc) {
+ ts := newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hello"))
+ }))
+ defer ts.Close()
+ res, err := http.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != "hello" {
+ t.Errorf("got %q, want hello", string(got))
+ }
+}
+
+// Issue 12781
+func testGetAfterClose(t *testing.T, newServer newServerFunc) {
+ ts := newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hello"))
+ }))
+
+ res, err := http.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != "hello" {
+ t.Fatalf("got %q, want hello", string(got))
+ }
+
+ ts.Close()
+
+ res, err = http.Get(ts.URL)
+ if err == nil {
+ body, _ := io.ReadAll(res.Body)
+ t.Fatalf("Unexpected response after close: %v, %v, %s", res.Status, res.Header, body)
+ }
+}
+
+func testServerCloseBlocking(t *testing.T, newServer newServerFunc) {
+ ts := newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hello"))
+ }))
+ dial := func() net.Conn {
+ c, err := net.Dial("tcp", ts.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+ }
+
+ // Keep one connection in StateNew (connected, but not sending anything)
+ cnew := dial()
+ defer cnew.Close()
+
+ // Keep one connection in StateIdle (idle after a request)
+ cidle := dial()
+ defer cidle.Close()
+ cidle.Write([]byte("HEAD / HTTP/1.1\r\nHost: foo\r\n\r\n"))
+ _, err := http.ReadResponse(bufio.NewReader(cidle), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ts.Close() // test we don't hang here forever.
+}
+
+// Issue 14290
+func testServerCloseClientConnections(t *testing.T, newServer newServerFunc) {
+ var s *Server
+ s = newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ s.CloseClientConnections()
+ }))
+ defer s.Close()
+ res, err := http.Get(s.URL)
+ if err == nil {
+ res.Body.Close()
+ t.Fatalf("Unexpected response: %#v", res)
+ }
+}
+
+// Tests that the Server.Client method works and returns an http.Client that can hit
+// NewTLSServer without cert warnings.
+func testServerClient(t *testing.T, newTLSServer newServerFunc) {
+ ts := newTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hello"))
+ }))
+ defer ts.Close()
+ client := ts.Client()
+ res, err := client.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != "hello" {
+ t.Errorf("got %q, want hello", string(got))
+ }
+}
+
+// Tests that the Server.Client.Transport interface is implemented
+// by a *http.Transport.
+func testServerClientTransportType(t *testing.T, newServer newServerFunc) {
+ ts := newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ }))
+ defer ts.Close()
+ client := ts.Client()
+ if _, ok := client.Transport.(*http.Transport); !ok {
+ t.Errorf("got %T, want *http.Transport", client.Transport)
+ }
+}
+
+// Tests that the TLS Server.Client.Transport interface is implemented
+// by a *http.Transport.
+func testTLSServerClientTransportType(t *testing.T, newTLSServer newServerFunc) {
+ ts := newTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ }))
+ defer ts.Close()
+ client := ts.Client()
+ if _, ok := client.Transport.(*http.Transport); !ok {
+ t.Errorf("got %T, want *http.Transport", client.Transport)
+ }
+}
+
+type onlyCloseListener struct {
+ net.Listener
+}
+
+func (onlyCloseListener) Close() error { return nil }
+
+// Issue 19729: panic in Server.Close for values created directly
+// without a constructor (so the unexported client field is nil).
+func TestServerZeroValueClose(t *testing.T) {
+ ts := &Server{
+ Listener: onlyCloseListener{},
+ Config: &http.Server{},
+ }
+
+ ts.Close() // tests that it doesn't panic
+}
+
+// Issue 51799: test hijacking a connection and then closing it
+// concurrently with closing the server.
+func TestCloseHijackedConnection(t *testing.T) {
+ hijacked := make(chan net.Conn)
+ ts := NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(hijacked)
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ t.Fatal("failed to hijack")
+ }
+ c, _, err := hj.Hijack()
+ if err != nil {
+ t.Fatal(err)
+ }
+ hijacked <- c
+ }))
+
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ req, err := http.NewRequest("GET", ts.URL, nil)
+ if err != nil {
+ t.Log(err)
+ }
+ // Use a client not associated with the Server.
+ var c http.Client
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Log(err)
+ return
+ }
+ resp.Body.Close()
+ }()
+
+ wg.Add(1)
+ conn := <-hijacked
+ go func(conn net.Conn) {
+ defer wg.Done()
+ // Close the connection and then inform the Server that
+ // we closed it.
+ conn.Close()
+ ts.Config.ConnState(conn, http.StateClosed)
+ }(conn)
+
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ts.Close()
+ }()
+ wg.Wait()
+}
+
+func TestTLSServerWithHTTP2(t *testing.T) {
+ modes := []struct {
+ name string
+ wantProto string
+ }{
+ {"http1", "HTTP/1.1"},
+ {"http2", "HTTP/2.0"},
+ }
+
+ for _, tt := range modes {
+ t.Run(tt.name, func(t *testing.T) {
+ cst := NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Proto", r.Proto)
+ }))
+
+ switch tt.name {
+ case "http2":
+ cst.EnableHTTP2 = true
+ cst.StartTLS()
+ default:
+ cst.Start()
+ }
+
+ defer cst.Close()
+
+ res, err := cst.Client().Get(cst.URL)
+ if err != nil {
+ t.Fatalf("Failed to make request: %v", err)
+ }
+ if g, w := res.Header.Get("X-Proto"), tt.wantProto; g != w {
+ t.Fatalf("X-Proto header mismatch:\n\tgot: %q\n\twant: %q", g, w)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptrace/example_test.go b/platform/dbops/binaries/go/go/src/net/http/httptrace/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..07fdc0a4726fc35e9f1b776171eb10e404e0e096
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptrace/example_test.go
@@ -0,0 +1,29 @@
+// 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 httptrace_test
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "net/http/httptrace"
+)
+
+func Example() {
+ req, _ := http.NewRequest("GET", "http://example.com", nil)
+ trace := &httptrace.ClientTrace{
+ GotConn: func(connInfo httptrace.GotConnInfo) {
+ fmt.Printf("Got Conn: %+v\n", connInfo)
+ },
+ DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
+ fmt.Printf("DNS Info: %+v\n", dnsInfo)
+ },
+ }
+ req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
+ _, err := http.DefaultTransport.RoundTrip(req)
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptrace/trace.go b/platform/dbops/binaries/go/go/src/net/http/httptrace/trace.go
new file mode 100644
index 0000000000000000000000000000000000000000..706a4329578ef79e6522c5c6608439bedf84e4fb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptrace/trace.go
@@ -0,0 +1,255 @@
+// 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 httptrace provides mechanisms to trace the events within
+// HTTP client requests.
+package httptrace
+
+import (
+ "context"
+ "crypto/tls"
+ "internal/nettrace"
+ "net"
+ "net/textproto"
+ "reflect"
+ "time"
+)
+
+// unique type to prevent assignment.
+type clientEventContextKey struct{}
+
+// ContextClientTrace returns the [ClientTrace] associated with the
+// provided context. If none, it returns nil.
+func ContextClientTrace(ctx context.Context) *ClientTrace {
+ trace, _ := ctx.Value(clientEventContextKey{}).(*ClientTrace)
+ return trace
+}
+
+// WithClientTrace returns a new context based on the provided parent
+// ctx. HTTP client requests made with the returned context will use
+// the provided trace hooks, in addition to any previous hooks
+// registered with ctx. Any hooks defined in the provided trace will
+// be called first.
+func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context {
+ if trace == nil {
+ panic("nil trace")
+ }
+ old := ContextClientTrace(ctx)
+ trace.compose(old)
+
+ ctx = context.WithValue(ctx, clientEventContextKey{}, trace)
+ if trace.hasNetHooks() {
+ nt := &nettrace.Trace{
+ ConnectStart: trace.ConnectStart,
+ ConnectDone: trace.ConnectDone,
+ }
+ if trace.DNSStart != nil {
+ nt.DNSStart = func(name string) {
+ trace.DNSStart(DNSStartInfo{Host: name})
+ }
+ }
+ if trace.DNSDone != nil {
+ nt.DNSDone = func(netIPs []any, coalesced bool, err error) {
+ addrs := make([]net.IPAddr, len(netIPs))
+ for i, ip := range netIPs {
+ addrs[i] = ip.(net.IPAddr)
+ }
+ trace.DNSDone(DNSDoneInfo{
+ Addrs: addrs,
+ Coalesced: coalesced,
+ Err: err,
+ })
+ }
+ }
+ ctx = context.WithValue(ctx, nettrace.TraceKey{}, nt)
+ }
+ return ctx
+}
+
+// ClientTrace is a set of hooks to run at various stages of an outgoing
+// HTTP request. Any particular hook may be nil. Functions may be
+// called concurrently from different goroutines and some may be called
+// after the request has completed or failed.
+//
+// ClientTrace currently traces a single HTTP request & response
+// during a single round trip and has no hooks that span a series
+// of redirected requests.
+//
+// See https://blog.golang.org/http-tracing for more.
+type ClientTrace struct {
+ // GetConn is called before a connection is created or
+ // retrieved from an idle pool. The hostPort is the
+ // "host:port" of the target or proxy. GetConn is called even
+ // if there's already an idle cached connection available.
+ GetConn func(hostPort string)
+
+ // GotConn is called after a successful connection is
+ // obtained. There is no hook for failure to obtain a
+ // connection; instead, use the error from
+ // Transport.RoundTrip.
+ GotConn func(GotConnInfo)
+
+ // PutIdleConn is called when the connection is returned to
+ // the idle pool. If err is nil, the connection was
+ // successfully returned to the idle pool. If err is non-nil,
+ // it describes why not. PutIdleConn is not called if
+ // connection reuse is disabled via Transport.DisableKeepAlives.
+ // PutIdleConn is called before the caller's Response.Body.Close
+ // call returns.
+ // For HTTP/2, this hook is not currently used.
+ PutIdleConn func(err error)
+
+ // GotFirstResponseByte is called when the first byte of the response
+ // headers is available.
+ GotFirstResponseByte func()
+
+ // Got100Continue is called if the server replies with a "100
+ // Continue" response.
+ Got100Continue func()
+
+ // Got1xxResponse is called for each 1xx informational response header
+ // returned before the final non-1xx response. Got1xxResponse is called
+ // for "100 Continue" responses, even if Got100Continue is also defined.
+ // If it returns an error, the client request is aborted with that error value.
+ Got1xxResponse func(code int, header textproto.MIMEHeader) error
+
+ // DNSStart is called when a DNS lookup begins.
+ DNSStart func(DNSStartInfo)
+
+ // DNSDone is called when a DNS lookup ends.
+ DNSDone func(DNSDoneInfo)
+
+ // ConnectStart is called when a new connection's Dial begins.
+ // If net.Dialer.DualStack (IPv6 "Happy Eyeballs") support is
+ // enabled, this may be called multiple times.
+ ConnectStart func(network, addr string)
+
+ // ConnectDone is called when a new connection's Dial
+ // completes. The provided err indicates whether the
+ // connection completed successfully.
+ // If net.Dialer.DualStack ("Happy Eyeballs") support is
+ // enabled, this may be called multiple times.
+ ConnectDone func(network, addr string, err error)
+
+ // TLSHandshakeStart is called when the TLS handshake is started. When
+ // connecting to an HTTPS site via an HTTP proxy, the handshake happens
+ // after the CONNECT request is processed by the proxy.
+ TLSHandshakeStart func()
+
+ // TLSHandshakeDone is called after the TLS handshake with either the
+ // successful handshake's connection state, or a non-nil error on handshake
+ // failure.
+ TLSHandshakeDone func(tls.ConnectionState, error)
+
+ // WroteHeaderField is called after the Transport has written
+ // each request header. At the time of this call the values
+ // might be buffered and not yet written to the network.
+ WroteHeaderField func(key string, value []string)
+
+ // WroteHeaders is called after the Transport has written
+ // all request headers.
+ WroteHeaders func()
+
+ // Wait100Continue is called if the Request specified
+ // "Expect: 100-continue" and the Transport has written the
+ // request headers but is waiting for "100 Continue" from the
+ // server before writing the request body.
+ Wait100Continue func()
+
+ // WroteRequest is called with the result of writing the
+ // request and any body. It may be called multiple times
+ // in the case of retried requests.
+ WroteRequest func(WroteRequestInfo)
+}
+
+// WroteRequestInfo contains information provided to the WroteRequest
+// hook.
+type WroteRequestInfo struct {
+ // Err is any error encountered while writing the Request.
+ Err error
+}
+
+// compose modifies t such that it respects the previously-registered hooks in old,
+// subject to the composition policy requested in t.Compose.
+func (t *ClientTrace) compose(old *ClientTrace) {
+ if old == nil {
+ return
+ }
+ tv := reflect.ValueOf(t).Elem()
+ ov := reflect.ValueOf(old).Elem()
+ structType := tv.Type()
+ for i := 0; i < structType.NumField(); i++ {
+ tf := tv.Field(i)
+ hookType := tf.Type()
+ if hookType.Kind() != reflect.Func {
+ continue
+ }
+ of := ov.Field(i)
+ if of.IsNil() {
+ continue
+ }
+ if tf.IsNil() {
+ tf.Set(of)
+ continue
+ }
+
+ // Make a copy of tf for tf to call. (Otherwise it
+ // creates a recursive call cycle and stack overflows)
+ tfCopy := reflect.ValueOf(tf.Interface())
+
+ // We need to call both tf and of in some order.
+ newFunc := reflect.MakeFunc(hookType, func(args []reflect.Value) []reflect.Value {
+ tfCopy.Call(args)
+ return of.Call(args)
+ })
+ tv.Field(i).Set(newFunc)
+ }
+}
+
+// DNSStartInfo contains information about a DNS request.
+type DNSStartInfo struct {
+ Host string
+}
+
+// DNSDoneInfo contains information about the results of a DNS lookup.
+type DNSDoneInfo struct {
+ // Addrs are the IPv4 and/or IPv6 addresses found in the DNS
+ // lookup. The contents of the slice should not be mutated.
+ Addrs []net.IPAddr
+
+ // Err is any error that occurred during the DNS lookup.
+ Err error
+
+ // Coalesced is whether the Addrs were shared with another
+ // caller who was doing the same DNS lookup concurrently.
+ Coalesced bool
+}
+
+func (t *ClientTrace) hasNetHooks() bool {
+ if t == nil {
+ return false
+ }
+ return t.DNSStart != nil || t.DNSDone != nil || t.ConnectStart != nil || t.ConnectDone != nil
+}
+
+// GotConnInfo is the argument to the [ClientTrace.GotConn] function and
+// contains information about the obtained connection.
+type GotConnInfo struct {
+ // Conn is the connection that was obtained. It is owned by
+ // the http.Transport and should not be read, written or
+ // closed by users of ClientTrace.
+ Conn net.Conn
+
+ // Reused is whether this connection has been previously
+ // used for another HTTP request.
+ Reused bool
+
+ // WasIdle is whether this connection was obtained from an
+ // idle pool.
+ WasIdle bool
+
+ // IdleTime reports how long the connection was previously
+ // idle, if WasIdle is true.
+ IdleTime time.Duration
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httptrace/trace_test.go b/platform/dbops/binaries/go/go/src/net/http/httptrace/trace_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6efa1f79401b95f536dbe51f6040935f820077cc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httptrace/trace_test.go
@@ -0,0 +1,89 @@
+// 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 httptrace
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+func TestWithClientTrace(t *testing.T) {
+ var buf strings.Builder
+ connectStart := func(b byte) func(network, addr string) {
+ return func(network, addr string) {
+ buf.WriteByte(b)
+ }
+ }
+
+ ctx := context.Background()
+ oldtrace := &ClientTrace{
+ ConnectStart: connectStart('O'),
+ }
+ ctx = WithClientTrace(ctx, oldtrace)
+ newtrace := &ClientTrace{
+ ConnectStart: connectStart('N'),
+ }
+ ctx = WithClientTrace(ctx, newtrace)
+ trace := ContextClientTrace(ctx)
+
+ buf.Reset()
+ trace.ConnectStart("net", "addr")
+ if got, want := buf.String(), "NO"; got != want {
+ t.Errorf("got %q; want %q", got, want)
+ }
+}
+
+func TestCompose(t *testing.T) {
+ var buf strings.Builder
+ var testNum int
+
+ connectStart := func(b byte) func(network, addr string) {
+ return func(network, addr string) {
+ if addr != "addr" {
+ t.Errorf(`%d. args for %q case = %q, %q; want addr of "addr"`, testNum, b, network, addr)
+ }
+ buf.WriteByte(b)
+ }
+ }
+
+ tests := [...]struct {
+ trace, old *ClientTrace
+ want string
+ }{
+ 0: {
+ want: "T",
+ trace: &ClientTrace{
+ ConnectStart: connectStart('T'),
+ },
+ },
+ 1: {
+ want: "TO",
+ trace: &ClientTrace{
+ ConnectStart: connectStart('T'),
+ },
+ old: &ClientTrace{ConnectStart: connectStart('O')},
+ },
+ 2: {
+ want: "O",
+ trace: &ClientTrace{},
+ old: &ClientTrace{ConnectStart: connectStart('O')},
+ },
+ }
+ for i, tt := range tests {
+ testNum = i
+ buf.Reset()
+
+ tr := *tt.trace
+ tr.compose(tt.old)
+ if tr.ConnectStart != nil {
+ tr.ConnectStart("net", "addr")
+ }
+ if got := buf.String(); got != tt.want {
+ t.Errorf("%d. got = %q; want %q", i, got, tt.want)
+ }
+ }
+
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/dump.go b/platform/dbops/binaries/go/go/src/net/http/httputil/dump.go
new file mode 100644
index 0000000000000000000000000000000000000000..2edb9bc98d3bc859d0d64f33097d941c3c5f5d7a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/dump.go
@@ -0,0 +1,337 @@
+// 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 httputil
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// drainBody reads all of b to memory and then returns two equivalent
+// ReadClosers yielding the same bytes.
+//
+// It returns an error if the initial slurp of all bytes fails. It does not attempt
+// to make the returned ReadClosers have identical error-matching behavior.
+func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
+ if b == nil || b == http.NoBody {
+ // No copying needed. Preserve the magic sentinel meaning of NoBody.
+ return http.NoBody, http.NoBody, nil
+ }
+ var buf bytes.Buffer
+ if _, err = buf.ReadFrom(b); err != nil {
+ return nil, b, err
+ }
+ if err = b.Close(); err != nil {
+ return nil, b, err
+ }
+ return io.NopCloser(&buf), io.NopCloser(bytes.NewReader(buf.Bytes())), nil
+}
+
+// dumpConn is a net.Conn which writes to Writer and reads from Reader
+type dumpConn struct {
+ io.Writer
+ io.Reader
+}
+
+func (c *dumpConn) Close() error { return nil }
+func (c *dumpConn) LocalAddr() net.Addr { return nil }
+func (c *dumpConn) RemoteAddr() net.Addr { return nil }
+func (c *dumpConn) SetDeadline(t time.Time) error { return nil }
+func (c *dumpConn) SetReadDeadline(t time.Time) error { return nil }
+func (c *dumpConn) SetWriteDeadline(t time.Time) error { return nil }
+
+type neverEnding byte
+
+func (b neverEnding) Read(p []byte) (n int, err error) {
+ for i := range p {
+ p[i] = byte(b)
+ }
+ return len(p), nil
+}
+
+// outgoingLength is a copy of the unexported
+// (*http.Request).outgoingLength method.
+func outgoingLength(req *http.Request) int64 {
+ if req.Body == nil || req.Body == http.NoBody {
+ return 0
+ }
+ if req.ContentLength != 0 {
+ return req.ContentLength
+ }
+ return -1
+}
+
+// DumpRequestOut is like [DumpRequest] but for outgoing client requests. It
+// includes any headers that the standard [http.Transport] adds, such as
+// User-Agent.
+func DumpRequestOut(req *http.Request, body bool) ([]byte, error) {
+ save := req.Body
+ dummyBody := false
+ if !body {
+ contentLength := outgoingLength(req)
+ if contentLength != 0 {
+ req.Body = io.NopCloser(io.LimitReader(neverEnding('x'), contentLength))
+ dummyBody = true
+ }
+ } else {
+ var err error
+ save, req.Body, err = drainBody(req.Body)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // Since we're using the actual Transport code to write the request,
+ // switch to http so the Transport doesn't try to do an SSL
+ // negotiation with our dumpConn and its bytes.Buffer & pipe.
+ // The wire format for https and http are the same, anyway.
+ reqSend := req
+ if req.URL.Scheme == "https" {
+ reqSend = new(http.Request)
+ *reqSend = *req
+ reqSend.URL = new(url.URL)
+ *reqSend.URL = *req.URL
+ reqSend.URL.Scheme = "http"
+ }
+
+ // Use the actual Transport code to record what we would send
+ // on the wire, but not using TCP. Use a Transport with a
+ // custom dialer that returns a fake net.Conn that waits
+ // for the full input (and recording it), and then responds
+ // with a dummy response.
+ var buf bytes.Buffer // records the output
+ pr, pw := io.Pipe()
+ defer pr.Close()
+ defer pw.Close()
+ dr := &delegateReader{c: make(chan io.Reader)}
+
+ t := &http.Transport{
+ Dial: func(net, addr string) (net.Conn, error) {
+ return &dumpConn{io.MultiWriter(&buf, pw), dr}, nil
+ },
+ }
+ defer t.CloseIdleConnections()
+
+ // We need this channel to ensure that the reader
+ // goroutine exits if t.RoundTrip returns an error.
+ // See golang.org/issue/32571.
+ quitReadCh := make(chan struct{})
+ // Wait for the request before replying with a dummy response:
+ go func() {
+ req, err := http.ReadRequest(bufio.NewReader(pr))
+ if err == nil {
+ // Ensure all the body is read; otherwise
+ // we'll get a partial dump.
+ io.Copy(io.Discard, req.Body)
+ req.Body.Close()
+ }
+ select {
+ case dr.c <- strings.NewReader("HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"):
+ case <-quitReadCh:
+ // Ensure delegateReader.Read doesn't block forever if we get an error.
+ close(dr.c)
+ }
+ }()
+
+ _, err := t.RoundTrip(reqSend)
+
+ req.Body = save
+ if err != nil {
+ pw.Close()
+ dr.err = err
+ close(quitReadCh)
+ return nil, err
+ }
+ dump := buf.Bytes()
+
+ // If we used a dummy body above, remove it now.
+ // TODO: if the req.ContentLength is large, we allocate memory
+ // unnecessarily just to slice it off here. But this is just
+ // a debug function, so this is acceptable for now. We could
+ // discard the body earlier if this matters.
+ if dummyBody {
+ if i := bytes.Index(dump, []byte("\r\n\r\n")); i >= 0 {
+ dump = dump[:i+4]
+ }
+ }
+ return dump, nil
+}
+
+// delegateReader is a reader that delegates to another reader,
+// once it arrives on a channel.
+type delegateReader struct {
+ c chan io.Reader
+ err error // only used if r is nil and c is closed.
+ r io.Reader // nil until received from c
+}
+
+func (r *delegateReader) Read(p []byte) (int, error) {
+ if r.r == nil {
+ var ok bool
+ if r.r, ok = <-r.c; !ok {
+ return 0, r.err
+ }
+ }
+ return r.r.Read(p)
+}
+
+// Return value if nonempty, def otherwise.
+func valueOrDefault(value, def string) string {
+ if value != "" {
+ return value
+ }
+ return def
+}
+
+var reqWriteExcludeHeaderDump = map[string]bool{
+ "Host": true, // not in Header map anyway
+ "Transfer-Encoding": true,
+ "Trailer": true,
+}
+
+// DumpRequest returns the given request in its HTTP/1.x wire
+// representation. It should only be used by servers to debug client
+// requests. The returned representation is an approximation only;
+// some details of the initial request are lost while parsing it into
+// an [http.Request]. In particular, the order and case of header field
+// names are lost. The order of values in multi-valued headers is kept
+// intact. HTTP/2 requests are dumped in HTTP/1.x form, not in their
+// original binary representations.
+//
+// If body is true, DumpRequest also returns the body. To do so, it
+// consumes req.Body and then replaces it with a new [io.ReadCloser]
+// that yields the same bytes. If DumpRequest returns an error,
+// the state of req is undefined.
+//
+// The documentation for [http.Request.Write] details which fields
+// of req are included in the dump.
+func DumpRequest(req *http.Request, body bool) ([]byte, error) {
+ var err error
+ save := req.Body
+ if !body || req.Body == nil {
+ req.Body = nil
+ } else {
+ save, req.Body, err = drainBody(req.Body)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var b bytes.Buffer
+
+ // By default, print out the unmodified req.RequestURI, which
+ // is always set for incoming server requests. But because we
+ // previously used req.URL.RequestURI and the docs weren't
+ // always so clear about when to use DumpRequest vs
+ // DumpRequestOut, fall back to the old way if the caller
+ // provides a non-server Request.
+ reqURI := req.RequestURI
+ if reqURI == "" {
+ reqURI = req.URL.RequestURI()
+ }
+
+ fmt.Fprintf(&b, "%s %s HTTP/%d.%d\r\n", valueOrDefault(req.Method, "GET"),
+ reqURI, req.ProtoMajor, req.ProtoMinor)
+
+ absRequestURI := strings.HasPrefix(req.RequestURI, "http://") || strings.HasPrefix(req.RequestURI, "https://")
+ if !absRequestURI {
+ host := req.Host
+ if host == "" && req.URL != nil {
+ host = req.URL.Host
+ }
+ if host != "" {
+ fmt.Fprintf(&b, "Host: %s\r\n", host)
+ }
+ }
+
+ chunked := len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked"
+ if len(req.TransferEncoding) > 0 {
+ fmt.Fprintf(&b, "Transfer-Encoding: %s\r\n", strings.Join(req.TransferEncoding, ","))
+ }
+
+ err = req.Header.WriteSubset(&b, reqWriteExcludeHeaderDump)
+ if err != nil {
+ return nil, err
+ }
+
+ io.WriteString(&b, "\r\n")
+
+ if req.Body != nil {
+ var dest io.Writer = &b
+ if chunked {
+ dest = NewChunkedWriter(dest)
+ }
+ _, err = io.Copy(dest, req.Body)
+ if chunked {
+ dest.(io.Closer).Close()
+ io.WriteString(&b, "\r\n")
+ }
+ }
+
+ req.Body = save
+ if err != nil {
+ return nil, err
+ }
+ return b.Bytes(), nil
+}
+
+// errNoBody is a sentinel error value used by failureToReadBody so we
+// can detect that the lack of body was intentional.
+var errNoBody = errors.New("sentinel error value")
+
+// failureToReadBody is an io.ReadCloser that just returns errNoBody on
+// Read. It's swapped in when we don't actually want to consume
+// the body, but need a non-nil one, and want to distinguish the
+// error from reading the dummy body.
+type failureToReadBody struct{}
+
+func (failureToReadBody) Read([]byte) (int, error) { return 0, errNoBody }
+func (failureToReadBody) Close() error { return nil }
+
+// emptyBody is an instance of empty reader.
+var emptyBody = io.NopCloser(strings.NewReader(""))
+
+// DumpResponse is like DumpRequest but dumps a response.
+func DumpResponse(resp *http.Response, body bool) ([]byte, error) {
+ var b bytes.Buffer
+ var err error
+ save := resp.Body
+ savecl := resp.ContentLength
+
+ if !body {
+ // For content length of zero. Make sure the body is an empty
+ // reader, instead of returning error through failureToReadBody{}.
+ if resp.ContentLength == 0 {
+ resp.Body = emptyBody
+ } else {
+ resp.Body = failureToReadBody{}
+ }
+ } else if resp.Body == nil {
+ resp.Body = emptyBody
+ } else {
+ save, resp.Body, err = drainBody(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ }
+ err = resp.Write(&b)
+ if err == errNoBody {
+ err = nil
+ }
+ resp.Body = save
+ resp.ContentLength = savecl
+ if err != nil {
+ return nil, err
+ }
+ return b.Bytes(), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/dump_test.go b/platform/dbops/binaries/go/go/src/net/http/httputil/dump_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c20c054865fa32b12123d860489a63e20496db1d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/dump_test.go
@@ -0,0 +1,532 @@
+// 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 httputil
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "math/rand"
+ "net/http"
+ "net/url"
+ "runtime"
+ "runtime/pprof"
+ "strings"
+ "testing"
+ "time"
+)
+
+type eofReader struct{}
+
+func (n eofReader) Close() error { return nil }
+
+func (n eofReader) Read([]byte) (int, error) { return 0, io.EOF }
+
+type dumpTest struct {
+ // Either Req or GetReq can be set/nil but not both.
+ Req *http.Request
+ GetReq func() *http.Request
+
+ Body any // optional []byte or func() io.ReadCloser to populate Req.Body
+
+ WantDump string
+ WantDumpOut string
+ MustError bool // if true, the test is expected to throw an error
+ NoBody bool // if true, set DumpRequest{,Out} body to false
+}
+
+var dumpTests = []dumpTest{
+ // HTTP/1.1 => chunked coding; body; empty trailer
+ {
+ Req: &http.Request{
+ Method: "GET",
+ URL: &url.URL{
+ Scheme: "http",
+ Host: "www.google.com",
+ Path: "/search",
+ },
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ TransferEncoding: []string{"chunked"},
+ },
+
+ Body: []byte("abcdef"),
+
+ WantDump: "GET /search HTTP/1.1\r\n" +
+ "Host: www.google.com\r\n" +
+ "Transfer-Encoding: chunked\r\n\r\n" +
+ chunk("abcdef") + chunk(""),
+ },
+
+ // Verify that DumpRequest preserves the HTTP version number, doesn't add a Host,
+ // and doesn't add a User-Agent.
+ {
+ Req: &http.Request{
+ Method: "GET",
+ URL: mustParseURL("/foo"),
+ ProtoMajor: 1,
+ ProtoMinor: 0,
+ Header: http.Header{
+ "X-Foo": []string{"X-Bar"},
+ },
+ },
+
+ WantDump: "GET /foo HTTP/1.0\r\n" +
+ "X-Foo: X-Bar\r\n\r\n",
+ },
+
+ {
+ Req: mustNewRequest("GET", "http://example.com/foo", nil),
+
+ WantDumpOut: "GET /foo HTTP/1.1\r\n" +
+ "Host: example.com\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n",
+ },
+
+ // Test that an https URL doesn't try to do an SSL negotiation
+ // with a bytes.Buffer and hang with all goroutines not
+ // runnable.
+ {
+ Req: mustNewRequest("GET", "https://example.com/foo", nil),
+ WantDumpOut: "GET /foo HTTP/1.1\r\n" +
+ "Host: example.com\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n",
+ },
+
+ // Request with Body, but Dump requested without it.
+ {
+ Req: &http.Request{
+ Method: "POST",
+ URL: &url.URL{
+ Scheme: "http",
+ Host: "post.tld",
+ Path: "/",
+ },
+ ContentLength: 6,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ },
+
+ Body: []byte("abcdef"),
+
+ WantDumpOut: "POST / HTTP/1.1\r\n" +
+ "Host: post.tld\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Content-Length: 6\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n",
+
+ NoBody: true,
+ },
+
+ // Request with Body > 8196 (default buffer size)
+ {
+ Req: &http.Request{
+ Method: "POST",
+ URL: &url.URL{
+ Scheme: "http",
+ Host: "post.tld",
+ Path: "/",
+ },
+ Header: http.Header{
+ "Content-Length": []string{"8193"},
+ },
+
+ ContentLength: 8193,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ },
+
+ Body: bytes.Repeat([]byte("a"), 8193),
+
+ WantDumpOut: "POST / HTTP/1.1\r\n" +
+ "Host: post.tld\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Content-Length: 8193\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n" +
+ strings.Repeat("a", 8193),
+ WantDump: "POST / HTTP/1.1\r\n" +
+ "Host: post.tld\r\n" +
+ "Content-Length: 8193\r\n\r\n" +
+ strings.Repeat("a", 8193),
+ },
+
+ {
+ GetReq: func() *http.Request {
+ return mustReadRequest("GET http://foo.com/ HTTP/1.1\r\n" +
+ "User-Agent: blah\r\n\r\n")
+ },
+ NoBody: true,
+ WantDump: "GET http://foo.com/ HTTP/1.1\r\n" +
+ "User-Agent: blah\r\n\r\n",
+ },
+
+ // Issue #7215. DumpRequest should return the "Content-Length" when set
+ {
+ GetReq: func() *http.Request {
+ return mustReadRequest("POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n" +
+ "Content-Length: 3\r\n" +
+ "\r\nkey1=name1&key2=name2")
+ },
+ WantDump: "POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n" +
+ "Content-Length: 3\r\n" +
+ "\r\nkey",
+ },
+ // Issue #7215. DumpRequest should return the "Content-Length" in ReadRequest
+ {
+ GetReq: func() *http.Request {
+ return mustReadRequest("POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n" +
+ "Content-Length: 0\r\n" +
+ "\r\nkey1=name1&key2=name2")
+ },
+ WantDump: "POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n" +
+ "Content-Length: 0\r\n\r\n",
+ },
+
+ // Issue #7215. DumpRequest should not return the "Content-Length" if unset
+ {
+ GetReq: func() *http.Request {
+ return mustReadRequest("POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n" +
+ "\r\nkey1=name1&key2=name2")
+ },
+ WantDump: "POST /v2/api/?login HTTP/1.1\r\n" +
+ "Host: passport.myhost.com\r\n\r\n",
+ },
+
+ // Issue 18506: make drainBody recognize NoBody. Otherwise
+ // this was turning into a chunked request.
+ {
+ Req: mustNewRequest("POST", "http://example.com/foo", http.NoBody),
+ WantDumpOut: "POST /foo HTTP/1.1\r\n" +
+ "Host: example.com\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Content-Length: 0\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n",
+ },
+
+ // Issue 34504: a non-nil Body without ContentLength set should be chunked
+ {
+ Req: &http.Request{
+ Method: "PUT",
+ URL: &url.URL{
+ Scheme: "http",
+ Host: "post.tld",
+ Path: "/test",
+ },
+ ContentLength: 0,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Body: &eofReader{},
+ },
+ NoBody: true,
+ WantDumpOut: "PUT /test HTTP/1.1\r\n" +
+ "Host: post.tld\r\n" +
+ "User-Agent: Go-http-client/1.1\r\n" +
+ "Transfer-Encoding: chunked\r\n" +
+ "Accept-Encoding: gzip\r\n\r\n",
+ },
+
+ // Issue 54616: request with Connection header doesn't result in duplicate header.
+ {
+ GetReq: func() *http.Request {
+ return mustReadRequest("GET / HTTP/1.1\r\n" +
+ "Host: example.com\r\n" +
+ "Connection: close\r\n\r\n")
+ },
+ NoBody: true,
+ WantDump: "GET / HTTP/1.1\r\n" +
+ "Host: example.com\r\n" +
+ "Connection: close\r\n\r\n",
+ },
+}
+
+func TestDumpRequest(t *testing.T) {
+ // Make a copy of dumpTests and add 10 new cases with an empty URL
+ // to test that no goroutines are leaked. See golang.org/issue/32571.
+ // 10 seems to be a decent number which always triggers the failure.
+ dumpTests := dumpTests[:]
+ for i := 0; i < 10; i++ {
+ dumpTests = append(dumpTests, dumpTest{
+ Req: mustNewRequest("GET", "", nil),
+ MustError: true,
+ })
+ }
+ numg0 := runtime.NumGoroutine()
+ for i, tt := range dumpTests {
+ if tt.Req != nil && tt.GetReq != nil || tt.Req == nil && tt.GetReq == nil {
+ t.Errorf("#%d: either .Req(%p) or .GetReq(%p) can be set/nil but not both", i, tt.Req, tt.GetReq)
+ continue
+ }
+
+ freshReq := func(ti dumpTest) *http.Request {
+ req := ti.Req
+ if req == nil {
+ req = ti.GetReq()
+ }
+
+ if req.Header == nil {
+ req.Header = make(http.Header)
+ }
+
+ if ti.Body == nil {
+ return req
+ }
+ switch b := ti.Body.(type) {
+ case []byte:
+ req.Body = io.NopCloser(bytes.NewReader(b))
+ case func() io.ReadCloser:
+ req.Body = b()
+ default:
+ t.Fatalf("Test %d: unsupported Body of %T", i, ti.Body)
+ }
+ return req
+ }
+
+ if tt.WantDump != "" {
+ req := freshReq(tt)
+ dump, err := DumpRequest(req, !tt.NoBody)
+ if err != nil {
+ t.Errorf("DumpRequest #%d: %s\nWantDump:\n%s", i, err, tt.WantDump)
+ continue
+ }
+ if string(dump) != tt.WantDump {
+ t.Errorf("DumpRequest %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDump, string(dump))
+ continue
+ }
+ }
+
+ if tt.MustError {
+ req := freshReq(tt)
+ _, err := DumpRequestOut(req, !tt.NoBody)
+ if err == nil {
+ t.Errorf("DumpRequestOut #%d: expected an error, got nil", i)
+ }
+ continue
+ }
+
+ if tt.WantDumpOut != "" {
+ req := freshReq(tt)
+ dump, err := DumpRequestOut(req, !tt.NoBody)
+ if err != nil {
+ t.Errorf("DumpRequestOut #%d: %s", i, err)
+ continue
+ }
+ if string(dump) != tt.WantDumpOut {
+ t.Errorf("DumpRequestOut %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDumpOut, string(dump))
+ continue
+ }
+ }
+ }
+
+ // Validate we haven't leaked any goroutines.
+ var dg int
+ dl := deadline(t, 5*time.Second, time.Second)
+ for time.Now().Before(dl) {
+ if dg = runtime.NumGoroutine() - numg0; dg <= 4 {
+ // No unexpected goroutines.
+ return
+ }
+
+ // Allow goroutines to schedule and die off.
+ runtime.Gosched()
+ }
+
+ buf := make([]byte, 4096)
+ buf = buf[:runtime.Stack(buf, true)]
+ t.Errorf("Unexpectedly large number of new goroutines: %d new: %s", dg, buf)
+}
+
+// deadline returns the time which is needed before t.Deadline()
+// if one is configured and it is s greater than needed in the future,
+// otherwise defaultDelay from the current time.
+func deadline(t *testing.T, defaultDelay, needed time.Duration) time.Time {
+ if dl, ok := t.Deadline(); ok {
+ if dl = dl.Add(-needed); dl.After(time.Now()) {
+ // Allow an arbitrarily long delay.
+ return dl
+ }
+ }
+
+ // No deadline configured or its closer than needed from now
+ // so just use the default.
+ return time.Now().Add(defaultDelay)
+}
+
+func chunk(s string) string {
+ return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
+}
+
+func mustParseURL(s string) *url.URL {
+ u, err := url.Parse(s)
+ if err != nil {
+ panic(fmt.Sprintf("Error parsing URL %q: %v", s, err))
+ }
+ return u
+}
+
+func mustNewRequest(method, url string, body io.Reader) *http.Request {
+ req, err := http.NewRequest(method, url, body)
+ if err != nil {
+ panic(fmt.Sprintf("NewRequest(%q, %q, %p) err = %v", method, url, body, err))
+ }
+ return req
+}
+
+func mustReadRequest(s string) *http.Request {
+ req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(s)))
+ if err != nil {
+ panic(err)
+ }
+ return req
+}
+
+var dumpResTests = []struct {
+ res *http.Response
+ body bool
+ want string
+}{
+ {
+ res: &http.Response{
+ Status: "200 OK",
+ StatusCode: 200,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: 50,
+ Header: http.Header{
+ "Foo": []string{"Bar"},
+ },
+ Body: io.NopCloser(strings.NewReader("foo")), // shouldn't be used
+ },
+ body: false, // to verify we see 50, not empty or 3.
+ want: `HTTP/1.1 200 OK
+Content-Length: 50
+Foo: Bar`,
+ },
+
+ {
+ res: &http.Response{
+ Status: "200 OK",
+ StatusCode: 200,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: 3,
+ Body: io.NopCloser(strings.NewReader("foo")),
+ },
+ body: true,
+ want: `HTTP/1.1 200 OK
+Content-Length: 3
+
+foo`,
+ },
+
+ {
+ res: &http.Response{
+ Status: "200 OK",
+ StatusCode: 200,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: -1,
+ Body: io.NopCloser(strings.NewReader("foo")),
+ TransferEncoding: []string{"chunked"},
+ },
+ body: true,
+ want: `HTTP/1.1 200 OK
+Transfer-Encoding: chunked
+
+3
+foo
+0`,
+ },
+ {
+ res: &http.Response{
+ Status: "200 OK",
+ StatusCode: 200,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: 0,
+ Header: http.Header{
+ // To verify if headers are not filtered out.
+ "Foo1": []string{"Bar1"},
+ "Foo2": []string{"Bar2"},
+ },
+ Body: nil,
+ },
+ body: false, // to verify we see 0, not empty.
+ want: `HTTP/1.1 200 OK
+Foo1: Bar1
+Foo2: Bar2
+Content-Length: 0`,
+ },
+}
+
+func TestDumpResponse(t *testing.T) {
+ for i, tt := range dumpResTests {
+ gotb, err := DumpResponse(tt.res, tt.body)
+ if err != nil {
+ t.Errorf("%d. DumpResponse = %v", i, err)
+ continue
+ }
+ got := string(gotb)
+ got = strings.TrimSpace(got)
+ got = strings.ReplaceAll(got, "\r", "")
+
+ if got != tt.want {
+ t.Errorf("%d.\nDumpResponse got:\n%s\n\nWant:\n%s\n", i, got, tt.want)
+ }
+ }
+}
+
+// Issue 38352: Check for deadlock on canceled requests.
+func TestDumpRequestOutIssue38352(t *testing.T) {
+ if testing.Short() {
+ return
+ }
+ t.Parallel()
+
+ timeout := 10 * time.Second
+ if deadline, ok := t.Deadline(); ok {
+ timeout = time.Until(deadline)
+ timeout -= time.Second * 2 // Leave 2 seconds to report failures.
+ }
+ for i := 0; i < 1000; i++ {
+ delay := time.Duration(rand.Intn(5)) * time.Millisecond
+ ctx, cancel := context.WithTimeout(context.Background(), delay)
+ defer cancel()
+
+ r := bytes.NewBuffer(make([]byte, 10000))
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://example.com", r)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ out := make(chan error)
+ go func() {
+ _, err = DumpRequestOut(req, true)
+ out <- err
+ }()
+
+ select {
+ case <-out:
+ case <-time.After(timeout):
+ b := &strings.Builder{}
+ fmt.Fprintf(b, "deadlock detected on iteration %d after %s with delay: %v\n", i, timeout, delay)
+ pprof.Lookup("goroutine").WriteTo(b, 1)
+ t.Fatal(b.String())
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/example_test.go b/platform/dbops/binaries/go/go/src/net/http/httputil/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6c107f839001b1c3379d4ee6a5fcc2f8f6dffebb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/example_test.go
@@ -0,0 +1,128 @@
+// 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.
+
+package httputil_test
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+)
+
+func ExampleDumpRequest() {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ dump, err := httputil.DumpRequest(r, true)
+ if err != nil {
+ http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
+ return
+ }
+
+ fmt.Fprintf(w, "%q", dump)
+ }))
+ defer ts.Close()
+
+ const body = "Go is a general-purpose language designed with systems programming in mind."
+ req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body))
+ if err != nil {
+ log.Fatal(err)
+ }
+ req.Host = "www.example.org"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer resp.Body.Close()
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s", b)
+
+ // Output:
+ // "POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nContent-Length: 75\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
+}
+
+func ExampleDumpRequestOut() {
+ const body = "Go is a general-purpose language designed with systems programming in mind."
+ req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body))
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ dump, err := httputil.DumpRequestOut(req, true)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%q", dump)
+
+ // Output:
+ // "PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
+}
+
+func ExampleDumpResponse() {
+ const body = "Go is a general-purpose language designed with systems programming in mind."
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
+ fmt.Fprintln(w, body)
+ }))
+ defer ts.Close()
+
+ resp, err := http.Get(ts.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer resp.Body.Close()
+
+ dump, err := httputil.DumpResponse(resp, true)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%q", dump)
+
+ // Output:
+ // "HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n"
+}
+
+func ExampleReverseProxy() {
+ backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, "this call was relayed by the reverse proxy")
+ }))
+ defer backendServer.Close()
+
+ rpURL, err := url.Parse(backendServer.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+ frontendProxy := httptest.NewServer(&httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) {
+ r.SetXForwarded()
+ r.SetURL(rpURL)
+ },
+ })
+ defer frontendProxy.Close()
+
+ resp, err := http.Get(frontendProxy.URL)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s", b)
+
+ // Output:
+ // this call was relayed by the reverse proxy
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/httputil.go b/platform/dbops/binaries/go/go/src/net/http/httputil/httputil.go
new file mode 100644
index 0000000000000000000000000000000000000000..431930ea65ccf58aecb05c220a475a8767f5c343
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/httputil.go
@@ -0,0 +1,41 @@
+// Copyright 2014 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 httputil provides HTTP utility functions, complementing the
+// more common ones in the net/http package.
+package httputil
+
+import (
+ "io"
+ "net/http/internal"
+)
+
+// NewChunkedReader returns a new chunkedReader that translates the data read from r
+// out of HTTP "chunked" format before returning it.
+// The chunkedReader returns [io.EOF] when the final 0-length chunk is read.
+//
+// NewChunkedReader is not needed by normal applications. The http package
+// automatically decodes chunking when reading response bodies.
+func NewChunkedReader(r io.Reader) io.Reader {
+ return internal.NewChunkedReader(r)
+}
+
+// NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP
+// "chunked" format before writing them to w. Closing the returned chunkedWriter
+// sends the final 0-length chunk that marks the end of the stream but does
+// not send the final CRLF that appears after trailers; trailers and the last
+// CRLF must be written separately.
+//
+// NewChunkedWriter is not needed by normal applications. The http
+// package adds chunking automatically if handlers don't set a
+// Content-Length header. Using NewChunkedWriter inside a handler
+// would result in double chunking or chunking with a Content-Length
+// length, both of which are wrong.
+func NewChunkedWriter(w io.Writer) io.WriteCloser {
+ return internal.NewChunkedWriter(w)
+}
+
+// ErrLineTooLong is returned when reading malformed chunked data
+// with lines that are too long.
+var ErrLineTooLong = internal.ErrLineTooLong
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/persist.go b/platform/dbops/binaries/go/go/src/net/http/httputil/persist.go
new file mode 100644
index 0000000000000000000000000000000000000000..0cbe3ebf10eef0f0b10bb3febb98829b50c17a51
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/persist.go
@@ -0,0 +1,431 @@
+// 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 httputil
+
+import (
+ "bufio"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/textproto"
+ "sync"
+)
+
+var (
+ // Deprecated: No longer used.
+ ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"}
+
+ // Deprecated: No longer used.
+ ErrClosed = &http.ProtocolError{ErrorString: "connection closed by user"}
+
+ // Deprecated: No longer used.
+ ErrPipeline = &http.ProtocolError{ErrorString: "pipeline error"}
+)
+
+// This is an API usage error - the local side is closed.
+// ErrPersistEOF (above) reports that the remote side is closed.
+var errClosed = errors.New("i/o operation on closed connection")
+
+// ServerConn is an artifact of Go's early HTTP implementation.
+// It is low-level, old, and unused by Go's current HTTP stack.
+// We should have deleted it before Go 1.
+//
+// Deprecated: Use the Server in package [net/http] instead.
+type ServerConn struct {
+ mu sync.Mutex // read-write protects the following fields
+ c net.Conn
+ r *bufio.Reader
+ re, we error // read/write errors
+ lastbody io.ReadCloser
+ nread, nwritten int
+ pipereq map[*http.Request]uint
+
+ pipe textproto.Pipeline
+}
+
+// NewServerConn is an artifact of Go's early HTTP implementation.
+// It is low-level, old, and unused by Go's current HTTP stack.
+// We should have deleted it before Go 1.
+//
+// Deprecated: Use the Server in package [net/http] instead.
+func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn {
+ if r == nil {
+ r = bufio.NewReader(c)
+ }
+ return &ServerConn{c: c, r: r, pipereq: make(map[*http.Request]uint)}
+}
+
+// Hijack detaches the [ServerConn] and returns the underlying connection as well
+// as the read-side bufio which may have some left over data. Hijack may be
+// called before Read has signaled the end of the keep-alive logic. The user
+// should not call Hijack while [ServerConn.Read] or [ServerConn.Write] is in progress.
+func (sc *ServerConn) Hijack() (net.Conn, *bufio.Reader) {
+ sc.mu.Lock()
+ defer sc.mu.Unlock()
+ c := sc.c
+ r := sc.r
+ sc.c = nil
+ sc.r = nil
+ return c, r
+}
+
+// Close calls [ServerConn.Hijack] and then also closes the underlying connection.
+func (sc *ServerConn) Close() error {
+ c, _ := sc.Hijack()
+ if c != nil {
+ return c.Close()
+ }
+ return nil
+}
+
+// Read returns the next request on the wire. An [ErrPersistEOF] is returned if
+// it is gracefully determined that there are no more requests (e.g. after the
+// first request on an HTTP/1.0 connection, or after a Connection:close on a
+// HTTP/1.1 connection).
+func (sc *ServerConn) Read() (*http.Request, error) {
+ var req *http.Request
+ var err error
+
+ // Ensure ordered execution of Reads and Writes
+ id := sc.pipe.Next()
+ sc.pipe.StartRequest(id)
+ defer func() {
+ sc.pipe.EndRequest(id)
+ if req == nil {
+ sc.pipe.StartResponse(id)
+ sc.pipe.EndResponse(id)
+ } else {
+ // Remember the pipeline id of this request
+ sc.mu.Lock()
+ sc.pipereq[req] = id
+ sc.mu.Unlock()
+ }
+ }()
+
+ sc.mu.Lock()
+ if sc.we != nil { // no point receiving if write-side broken or closed
+ defer sc.mu.Unlock()
+ return nil, sc.we
+ }
+ if sc.re != nil {
+ defer sc.mu.Unlock()
+ return nil, sc.re
+ }
+ if sc.r == nil { // connection closed by user in the meantime
+ defer sc.mu.Unlock()
+ return nil, errClosed
+ }
+ r := sc.r
+ lastbody := sc.lastbody
+ sc.lastbody = nil
+ sc.mu.Unlock()
+
+ // Make sure body is fully consumed, even if user does not call body.Close
+ if lastbody != nil {
+ // body.Close is assumed to be idempotent and multiple calls to
+ // it should return the error that its first invocation
+ // returned.
+ err = lastbody.Close()
+ if err != nil {
+ sc.mu.Lock()
+ defer sc.mu.Unlock()
+ sc.re = err
+ return nil, err
+ }
+ }
+
+ req, err = http.ReadRequest(r)
+ sc.mu.Lock()
+ defer sc.mu.Unlock()
+ if err != nil {
+ if err == io.ErrUnexpectedEOF {
+ // A close from the opposing client is treated as a
+ // graceful close, even if there was some unparse-able
+ // data before the close.
+ sc.re = ErrPersistEOF
+ return nil, sc.re
+ } else {
+ sc.re = err
+ return req, err
+ }
+ }
+ sc.lastbody = req.Body
+ sc.nread++
+ if req.Close {
+ sc.re = ErrPersistEOF
+ return req, sc.re
+ }
+ return req, err
+}
+
+// Pending returns the number of unanswered requests
+// that have been received on the connection.
+func (sc *ServerConn) Pending() int {
+ sc.mu.Lock()
+ defer sc.mu.Unlock()
+ return sc.nread - sc.nwritten
+}
+
+// Write writes resp in response to req. To close the connection gracefully, set the
+// Response.Close field to true. Write should be considered operational until
+// it returns an error, regardless of any errors returned on the [ServerConn.Read] side.
+func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error {
+
+ // Retrieve the pipeline ID of this request/response pair
+ sc.mu.Lock()
+ id, ok := sc.pipereq[req]
+ delete(sc.pipereq, req)
+ if !ok {
+ sc.mu.Unlock()
+ return ErrPipeline
+ }
+ sc.mu.Unlock()
+
+ // Ensure pipeline order
+ sc.pipe.StartResponse(id)
+ defer sc.pipe.EndResponse(id)
+
+ sc.mu.Lock()
+ if sc.we != nil {
+ defer sc.mu.Unlock()
+ return sc.we
+ }
+ if sc.c == nil { // connection closed by user in the meantime
+ defer sc.mu.Unlock()
+ return ErrClosed
+ }
+ c := sc.c
+ if sc.nread <= sc.nwritten {
+ defer sc.mu.Unlock()
+ return errors.New("persist server pipe count")
+ }
+ if resp.Close {
+ // After signaling a keep-alive close, any pipelined unread
+ // requests will be lost. It is up to the user to drain them
+ // before signaling.
+ sc.re = ErrPersistEOF
+ }
+ sc.mu.Unlock()
+
+ err := resp.Write(c)
+ sc.mu.Lock()
+ defer sc.mu.Unlock()
+ if err != nil {
+ sc.we = err
+ return err
+ }
+ sc.nwritten++
+
+ return nil
+}
+
+// ClientConn is an artifact of Go's early HTTP implementation.
+// It is low-level, old, and unused by Go's current HTTP stack.
+// We should have deleted it before Go 1.
+//
+// Deprecated: Use Client or Transport in package [net/http] instead.
+type ClientConn struct {
+ mu sync.Mutex // read-write protects the following fields
+ c net.Conn
+ r *bufio.Reader
+ re, we error // read/write errors
+ lastbody io.ReadCloser
+ nread, nwritten int
+ pipereq map[*http.Request]uint
+
+ pipe textproto.Pipeline
+ writeReq func(*http.Request, io.Writer) error
+}
+
+// NewClientConn is an artifact of Go's early HTTP implementation.
+// It is low-level, old, and unused by Go's current HTTP stack.
+// We should have deleted it before Go 1.
+//
+// Deprecated: Use the Client or Transport in package [net/http] instead.
+func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn {
+ if r == nil {
+ r = bufio.NewReader(c)
+ }
+ return &ClientConn{
+ c: c,
+ r: r,
+ pipereq: make(map[*http.Request]uint),
+ writeReq: (*http.Request).Write,
+ }
+}
+
+// NewProxyClientConn is an artifact of Go's early HTTP implementation.
+// It is low-level, old, and unused by Go's current HTTP stack.
+// We should have deleted it before Go 1.
+//
+// Deprecated: Use the Client or Transport in package [net/http] instead.
+func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn {
+ cc := NewClientConn(c, r)
+ cc.writeReq = (*http.Request).WriteProxy
+ return cc
+}
+
+// Hijack detaches the [ClientConn] and returns the underlying connection as well
+// as the read-side bufio which may have some left over data. Hijack may be
+// called before the user or Read have signaled the end of the keep-alive
+// logic. The user should not call Hijack while [ClientConn.Read] or ClientConn.Write is in progress.
+func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader) {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ c = cc.c
+ r = cc.r
+ cc.c = nil
+ cc.r = nil
+ return
+}
+
+// Close calls [ClientConn.Hijack] and then also closes the underlying connection.
+func (cc *ClientConn) Close() error {
+ c, _ := cc.Hijack()
+ if c != nil {
+ return c.Close()
+ }
+ return nil
+}
+
+// Write writes a request. An [ErrPersistEOF] error is returned if the connection
+// has been closed in an HTTP keep-alive sense. If req.Close equals true, the
+// keep-alive connection is logically closed after this request and the opposing
+// server is informed. An ErrUnexpectedEOF indicates the remote closed the
+// underlying TCP connection, which is usually considered as graceful close.
+func (cc *ClientConn) Write(req *http.Request) error {
+ var err error
+
+ // Ensure ordered execution of Writes
+ id := cc.pipe.Next()
+ cc.pipe.StartRequest(id)
+ defer func() {
+ cc.pipe.EndRequest(id)
+ if err != nil {
+ cc.pipe.StartResponse(id)
+ cc.pipe.EndResponse(id)
+ } else {
+ // Remember the pipeline id of this request
+ cc.mu.Lock()
+ cc.pipereq[req] = id
+ cc.mu.Unlock()
+ }
+ }()
+
+ cc.mu.Lock()
+ if cc.re != nil { // no point sending if read-side closed or broken
+ defer cc.mu.Unlock()
+ return cc.re
+ }
+ if cc.we != nil {
+ defer cc.mu.Unlock()
+ return cc.we
+ }
+ if cc.c == nil { // connection closed by user in the meantime
+ defer cc.mu.Unlock()
+ return errClosed
+ }
+ c := cc.c
+ if req.Close {
+ // We write the EOF to the write-side error, because there
+ // still might be some pipelined reads
+ cc.we = ErrPersistEOF
+ }
+ cc.mu.Unlock()
+
+ err = cc.writeReq(req, c)
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ if err != nil {
+ cc.we = err
+ return err
+ }
+ cc.nwritten++
+
+ return nil
+}
+
+// Pending returns the number of unanswered requests
+// that have been sent on the connection.
+func (cc *ClientConn) Pending() int {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.nwritten - cc.nread
+}
+
+// Read reads the next response from the wire. A valid response might be
+// returned together with an [ErrPersistEOF], which means that the remote
+// requested that this be the last request serviced. Read can be called
+// concurrently with [ClientConn.Write], but not with another Read.
+func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error) {
+ // Retrieve the pipeline ID of this request/response pair
+ cc.mu.Lock()
+ id, ok := cc.pipereq[req]
+ delete(cc.pipereq, req)
+ if !ok {
+ cc.mu.Unlock()
+ return nil, ErrPipeline
+ }
+ cc.mu.Unlock()
+
+ // Ensure pipeline order
+ cc.pipe.StartResponse(id)
+ defer cc.pipe.EndResponse(id)
+
+ cc.mu.Lock()
+ if cc.re != nil {
+ defer cc.mu.Unlock()
+ return nil, cc.re
+ }
+ if cc.r == nil { // connection closed by user in the meantime
+ defer cc.mu.Unlock()
+ return nil, errClosed
+ }
+ r := cc.r
+ lastbody := cc.lastbody
+ cc.lastbody = nil
+ cc.mu.Unlock()
+
+ // Make sure body is fully consumed, even if user does not call body.Close
+ if lastbody != nil {
+ // body.Close is assumed to be idempotent and multiple calls to
+ // it should return the error that its first invocation
+ // returned.
+ err = lastbody.Close()
+ if err != nil {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ cc.re = err
+ return nil, err
+ }
+ }
+
+ resp, err = http.ReadResponse(r, req)
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ if err != nil {
+ cc.re = err
+ return resp, err
+ }
+ cc.lastbody = resp.Body
+
+ cc.nread++
+
+ if resp.Close {
+ cc.re = ErrPersistEOF // don't send any more requests
+ return resp, cc.re
+ }
+ return resp, err
+}
+
+// Do is convenience method that writes a request and reads a response.
+func (cc *ClientConn) Do(req *http.Request) (*http.Response, error) {
+ err := cc.Write(req)
+ if err != nil {
+ return nil, err
+ }
+ return cc.Read(req)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy.go b/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy.go
new file mode 100644
index 0000000000000000000000000000000000000000..5c70f0d27bb1f7f630c29b7b134d2d2e213dfff7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy.go
@@ -0,0 +1,831 @@
+// 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.
+
+// HTTP reverse proxy handler
+
+package httputil
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "mime"
+ "net"
+ "net/http"
+ "net/http/httptrace"
+ "net/http/internal/ascii"
+ "net/textproto"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+// A ProxyRequest contains a request to be rewritten by a [ReverseProxy].
+type ProxyRequest struct {
+ // In is the request received by the proxy.
+ // The Rewrite function must not modify In.
+ In *http.Request
+
+ // Out is the request which will be sent by the proxy.
+ // The Rewrite function may modify or replace this request.
+ // Hop-by-hop headers are removed from this request
+ // before Rewrite is called.
+ Out *http.Request
+}
+
+// SetURL routes the outbound request to the scheme, host, and base path
+// provided in target. If the target's path is "/base" and the incoming
+// request was for "/dir", the target request will be for "/base/dir".
+//
+// SetURL rewrites the outbound Host header to match the target's host.
+// To preserve the inbound request's Host header (the default behavior
+// of [NewSingleHostReverseProxy]):
+//
+// rewriteFunc := func(r *httputil.ProxyRequest) {
+// r.SetURL(url)
+// r.Out.Host = r.In.Host
+// }
+func (r *ProxyRequest) SetURL(target *url.URL) {
+ rewriteRequestURL(r.Out, target)
+ r.Out.Host = ""
+}
+
+// SetXForwarded sets the X-Forwarded-For, X-Forwarded-Host, and
+// X-Forwarded-Proto headers of the outbound request.
+//
+// - The X-Forwarded-For header is set to the client IP address.
+// - The X-Forwarded-Host header is set to the host name requested
+// by the client.
+// - The X-Forwarded-Proto header is set to "http" or "https", depending
+// on whether the inbound request was made on a TLS-enabled connection.
+//
+// If the outbound request contains an existing X-Forwarded-For header,
+// SetXForwarded appends the client IP address to it. To append to the
+// inbound request's X-Forwarded-For header (the default behavior of
+// [ReverseProxy] when using a Director function), copy the header
+// from the inbound request before calling SetXForwarded:
+//
+// rewriteFunc := func(r *httputil.ProxyRequest) {
+// r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
+// r.SetXForwarded()
+// }
+func (r *ProxyRequest) SetXForwarded() {
+ clientIP, _, err := net.SplitHostPort(r.In.RemoteAddr)
+ if err == nil {
+ prior := r.Out.Header["X-Forwarded-For"]
+ if len(prior) > 0 {
+ clientIP = strings.Join(prior, ", ") + ", " + clientIP
+ }
+ r.Out.Header.Set("X-Forwarded-For", clientIP)
+ } else {
+ r.Out.Header.Del("X-Forwarded-For")
+ }
+ r.Out.Header.Set("X-Forwarded-Host", r.In.Host)
+ if r.In.TLS == nil {
+ r.Out.Header.Set("X-Forwarded-Proto", "http")
+ } else {
+ r.Out.Header.Set("X-Forwarded-Proto", "https")
+ }
+}
+
+// ReverseProxy is an HTTP Handler that takes an incoming request and
+// sends it to another server, proxying the response back to the
+// client.
+//
+// 1xx responses are forwarded to the client if the underlying
+// transport supports ClientTrace.Got1xxResponse.
+type ReverseProxy struct {
+ // Rewrite must be a function which modifies
+ // the request into a new request to be sent
+ // using Transport. Its response is then copied
+ // back to the original client unmodified.
+ // Rewrite must not access the provided ProxyRequest
+ // or its contents after returning.
+ //
+ // The Forwarded, X-Forwarded, X-Forwarded-Host,
+ // and X-Forwarded-Proto headers are removed from the
+ // outbound request before Rewrite is called. See also
+ // the ProxyRequest.SetXForwarded method.
+ //
+ // Unparsable query parameters are removed from the
+ // outbound request before Rewrite is called.
+ // The Rewrite function may copy the inbound URL's
+ // RawQuery to the outbound URL to preserve the original
+ // parameter string. Note that this can lead to security
+ // issues if the proxy's interpretation of query parameters
+ // does not match that of the downstream server.
+ //
+ // At most one of Rewrite or Director may be set.
+ Rewrite func(*ProxyRequest)
+
+ // Director is a function which modifies
+ // the request into a new request to be sent
+ // using Transport. Its response is then copied
+ // back to the original client unmodified.
+ // Director must not access the provided Request
+ // after returning.
+ //
+ // By default, the X-Forwarded-For header is set to the
+ // value of the client IP address. If an X-Forwarded-For
+ // header already exists, the client IP is appended to the
+ // existing values. As a special case, if the header
+ // exists in the Request.Header map but has a nil value
+ // (such as when set by the Director func), the X-Forwarded-For
+ // header is not modified.
+ //
+ // To prevent IP spoofing, be sure to delete any pre-existing
+ // X-Forwarded-For header coming from the client or
+ // an untrusted proxy.
+ //
+ // Hop-by-hop headers are removed from the request after
+ // Director returns, which can remove headers added by
+ // Director. Use a Rewrite function instead to ensure
+ // modifications to the request are preserved.
+ //
+ // Unparsable query parameters are removed from the outbound
+ // request if Request.Form is set after Director returns.
+ //
+ // At most one of Rewrite or Director may be set.
+ Director func(*http.Request)
+
+ // The transport used to perform proxy requests.
+ // If nil, http.DefaultTransport is used.
+ Transport http.RoundTripper
+
+ // FlushInterval specifies the flush interval
+ // to flush to the client while copying the
+ // response body.
+ // If zero, no periodic flushing is done.
+ // A negative value means to flush immediately
+ // after each write to the client.
+ // The FlushInterval is ignored when ReverseProxy
+ // recognizes a response as a streaming response, or
+ // if its ContentLength is -1; for such responses, writes
+ // are flushed to the client immediately.
+ FlushInterval time.Duration
+
+ // ErrorLog specifies an optional logger for errors
+ // that occur when attempting to proxy the request.
+ // If nil, logging is done via the log package's standard logger.
+ ErrorLog *log.Logger
+
+ // BufferPool optionally specifies a buffer pool to
+ // get byte slices for use by io.CopyBuffer when
+ // copying HTTP response bodies.
+ BufferPool BufferPool
+
+ // ModifyResponse is an optional function that modifies the
+ // Response from the backend. It is called if the backend
+ // returns a response at all, with any HTTP status code.
+ // If the backend is unreachable, the optional ErrorHandler is
+ // called without any call to ModifyResponse.
+ //
+ // If ModifyResponse returns an error, ErrorHandler is called
+ // with its error value. If ErrorHandler is nil, its default
+ // implementation is used.
+ ModifyResponse func(*http.Response) error
+
+ // ErrorHandler is an optional function that handles errors
+ // reaching the backend or errors from ModifyResponse.
+ //
+ // If nil, the default is to log the provided error and return
+ // a 502 Status Bad Gateway response.
+ ErrorHandler func(http.ResponseWriter, *http.Request, error)
+}
+
+// A BufferPool is an interface for getting and returning temporary
+// byte slices for use by [io.CopyBuffer].
+type BufferPool interface {
+ Get() []byte
+ Put([]byte)
+}
+
+func singleJoiningSlash(a, b string) string {
+ aslash := strings.HasSuffix(a, "/")
+ bslash := strings.HasPrefix(b, "/")
+ switch {
+ case aslash && bslash:
+ return a + b[1:]
+ case !aslash && !bslash:
+ return a + "/" + b
+ }
+ return a + b
+}
+
+func joinURLPath(a, b *url.URL) (path, rawpath string) {
+ if a.RawPath == "" && b.RawPath == "" {
+ return singleJoiningSlash(a.Path, b.Path), ""
+ }
+ // Same as singleJoiningSlash, but uses EscapedPath to determine
+ // whether a slash should be added
+ apath := a.EscapedPath()
+ bpath := b.EscapedPath()
+
+ aslash := strings.HasSuffix(apath, "/")
+ bslash := strings.HasPrefix(bpath, "/")
+
+ switch {
+ case aslash && bslash:
+ return a.Path + b.Path[1:], apath + bpath[1:]
+ case !aslash && !bslash:
+ return a.Path + "/" + b.Path, apath + "/" + bpath
+ }
+ return a.Path + b.Path, apath + bpath
+}
+
+// NewSingleHostReverseProxy returns a new [ReverseProxy] that routes
+// URLs to the scheme, host, and base path provided in target. If the
+// target's path is "/base" and the incoming request was for "/dir",
+// the target request will be for /base/dir.
+//
+// NewSingleHostReverseProxy does not rewrite the Host header.
+//
+// To customize the ReverseProxy behavior beyond what
+// NewSingleHostReverseProxy provides, use ReverseProxy directly
+// with a Rewrite function. The ProxyRequest SetURL method
+// may be used to route the outbound request. (Note that SetURL,
+// unlike NewSingleHostReverseProxy, rewrites the Host header
+// of the outbound request by default.)
+//
+// proxy := &ReverseProxy{
+// Rewrite: func(r *ProxyRequest) {
+// r.SetURL(target)
+// r.Out.Host = r.In.Host // if desired
+// },
+// }
+func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
+ director := func(req *http.Request) {
+ rewriteRequestURL(req, target)
+ }
+ return &ReverseProxy{Director: director}
+}
+
+func rewriteRequestURL(req *http.Request, target *url.URL) {
+ targetQuery := target.RawQuery
+ req.URL.Scheme = target.Scheme
+ req.URL.Host = target.Host
+ req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
+ if targetQuery == "" || req.URL.RawQuery == "" {
+ req.URL.RawQuery = targetQuery + req.URL.RawQuery
+ } else {
+ req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
+ }
+}
+
+func copyHeader(dst, src http.Header) {
+ for k, vv := range src {
+ for _, v := range vv {
+ dst.Add(k, v)
+ }
+ }
+}
+
+// Hop-by-hop headers. These are removed when sent to the backend.
+// As of RFC 7230, hop-by-hop headers are required to appear in the
+// Connection header field. These are the headers defined by the
+// obsoleted RFC 2616 (section 13.5.1) and are used for backward
+// compatibility.
+var hopHeaders = []string{
+ "Connection",
+ "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
+ "Keep-Alive",
+ "Proxy-Authenticate",
+ "Proxy-Authorization",
+ "Te", // canonicalized version of "TE"
+ "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
+ "Transfer-Encoding",
+ "Upgrade",
+}
+
+func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
+ p.logf("http: proxy error: %v", err)
+ rw.WriteHeader(http.StatusBadGateway)
+}
+
+func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
+ if p.ErrorHandler != nil {
+ return p.ErrorHandler
+ }
+ return p.defaultErrorHandler
+}
+
+// modifyResponse conditionally runs the optional ModifyResponse hook
+// and reports whether the request should proceed.
+func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
+ if p.ModifyResponse == nil {
+ return true
+ }
+ if err := p.ModifyResponse(res); err != nil {
+ res.Body.Close()
+ p.getErrorHandler()(rw, req, err)
+ return false
+ }
+ return true
+}
+
+func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
+ transport := p.Transport
+ if transport == nil {
+ transport = http.DefaultTransport
+ }
+
+ ctx := req.Context()
+ if ctx.Done() != nil {
+ // CloseNotifier predates context.Context, and has been
+ // entirely superseded by it. If the request contains
+ // a Context that carries a cancellation signal, don't
+ // bother spinning up a goroutine to watch the CloseNotify
+ // channel (if any).
+ //
+ // If the request Context has a nil Done channel (which
+ // means it is either context.Background, or a custom
+ // Context implementation with no cancellation signal),
+ // then consult the CloseNotifier if available.
+ } else if cn, ok := rw.(http.CloseNotifier); ok {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithCancel(ctx)
+ defer cancel()
+ notifyChan := cn.CloseNotify()
+ go func() {
+ select {
+ case <-notifyChan:
+ cancel()
+ case <-ctx.Done():
+ }
+ }()
+ }
+
+ outreq := req.Clone(ctx)
+ if req.ContentLength == 0 {
+ outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
+ }
+ if outreq.Body != nil {
+ // Reading from the request body after returning from a handler is not
+ // allowed, and the RoundTrip goroutine that reads the Body can outlive
+ // this handler. This can lead to a crash if the handler panics (see
+ // Issue 46866). Although calling Close doesn't guarantee there isn't
+ // any Read in flight after the handle returns, in practice it's safe to
+ // read after closing it.
+ defer outreq.Body.Close()
+ }
+ if outreq.Header == nil {
+ outreq.Header = make(http.Header) // Issue 33142: historical behavior was to always allocate
+ }
+
+ if (p.Director != nil) == (p.Rewrite != nil) {
+ p.getErrorHandler()(rw, req, errors.New("ReverseProxy must have exactly one of Director or Rewrite set"))
+ return
+ }
+
+ if p.Director != nil {
+ p.Director(outreq)
+ if outreq.Form != nil {
+ outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
+ }
+ }
+ outreq.Close = false
+
+ reqUpType := upgradeType(outreq.Header)
+ if !ascii.IsPrint(reqUpType) {
+ p.getErrorHandler()(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType))
+ return
+ }
+ removeHopByHopHeaders(outreq.Header)
+
+ // Issue 21096: tell backend applications that care about trailer support
+ // that we support trailers. (We do, but we don't go out of our way to
+ // advertise that unless the incoming client request thought it was worth
+ // mentioning.) Note that we look at req.Header, not outreq.Header, since
+ // the latter has passed through removeHopByHopHeaders.
+ if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
+ outreq.Header.Set("Te", "trailers")
+ }
+
+ // After stripping all the hop-by-hop connection headers above, add back any
+ // necessary for protocol upgrades, such as for websockets.
+ if reqUpType != "" {
+ outreq.Header.Set("Connection", "Upgrade")
+ outreq.Header.Set("Upgrade", reqUpType)
+ }
+
+ if p.Rewrite != nil {
+ // Strip client-provided forwarding headers.
+ // The Rewrite func may use SetXForwarded to set new values
+ // for these or copy the previous values from the inbound request.
+ outreq.Header.Del("Forwarded")
+ outreq.Header.Del("X-Forwarded-For")
+ outreq.Header.Del("X-Forwarded-Host")
+ outreq.Header.Del("X-Forwarded-Proto")
+
+ // Remove unparsable query parameters from the outbound request.
+ outreq.URL.RawQuery = cleanQueryParams(outreq.URL.RawQuery)
+
+ pr := &ProxyRequest{
+ In: req,
+ Out: outreq,
+ }
+ p.Rewrite(pr)
+ outreq = pr.Out
+ } else {
+ if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
+ // If we aren't the first proxy retain prior
+ // X-Forwarded-For information as a comma+space
+ // separated list and fold multiple headers into one.
+ prior, ok := outreq.Header["X-Forwarded-For"]
+ omit := ok && prior == nil // Issue 38079: nil now means don't populate the header
+ if len(prior) > 0 {
+ clientIP = strings.Join(prior, ", ") + ", " + clientIP
+ }
+ if !omit {
+ outreq.Header.Set("X-Forwarded-For", clientIP)
+ }
+ }
+ }
+
+ if _, ok := outreq.Header["User-Agent"]; !ok {
+ // If the outbound request doesn't have a User-Agent header set,
+ // don't send the default Go HTTP client User-Agent.
+ outreq.Header.Set("User-Agent", "")
+ }
+
+ trace := &httptrace.ClientTrace{
+ Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
+ h := rw.Header()
+ copyHeader(h, http.Header(header))
+ rw.WriteHeader(code)
+
+ // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
+ clear(h)
+ return nil
+ },
+ }
+ outreq = outreq.WithContext(httptrace.WithClientTrace(outreq.Context(), trace))
+
+ res, err := transport.RoundTrip(outreq)
+ if err != nil {
+ p.getErrorHandler()(rw, outreq, err)
+ return
+ }
+
+ // Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
+ if res.StatusCode == http.StatusSwitchingProtocols {
+ if !p.modifyResponse(rw, res, outreq) {
+ return
+ }
+ p.handleUpgradeResponse(rw, outreq, res)
+ return
+ }
+
+ removeHopByHopHeaders(res.Header)
+
+ if !p.modifyResponse(rw, res, outreq) {
+ return
+ }
+
+ copyHeader(rw.Header(), res.Header)
+
+ // The "Trailer" header isn't included in the Transport's response,
+ // at least for *http.Transport. Build it up from Trailer.
+ announcedTrailers := len(res.Trailer)
+ if announcedTrailers > 0 {
+ trailerKeys := make([]string, 0, len(res.Trailer))
+ for k := range res.Trailer {
+ trailerKeys = append(trailerKeys, k)
+ }
+ rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
+ }
+
+ rw.WriteHeader(res.StatusCode)
+
+ err = p.copyResponse(rw, res.Body, p.flushInterval(res))
+ if err != nil {
+ defer res.Body.Close()
+ // Since we're streaming the response, if we run into an error all we can do
+ // is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
+ // on read error while copying body.
+ if !shouldPanicOnCopyError(req) {
+ p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
+ return
+ }
+ panic(http.ErrAbortHandler)
+ }
+ res.Body.Close() // close now, instead of defer, to populate res.Trailer
+
+ if len(res.Trailer) > 0 {
+ // Force chunking if we saw a response trailer.
+ // This prevents net/http from calculating the length for short
+ // bodies and adding a Content-Length.
+ http.NewResponseController(rw).Flush()
+ }
+
+ if len(res.Trailer) == announcedTrailers {
+ copyHeader(rw.Header(), res.Trailer)
+ return
+ }
+
+ for k, vv := range res.Trailer {
+ k = http.TrailerPrefix + k
+ for _, v := range vv {
+ rw.Header().Add(k, v)
+ }
+ }
+}
+
+var inOurTests bool // whether we're in our own tests
+
+// shouldPanicOnCopyError reports whether the reverse proxy should
+// panic with http.ErrAbortHandler. This is the right thing to do by
+// default, but Go 1.10 and earlier did not, so existing unit tests
+// weren't expecting panics. Only panic in our own tests, or when
+// running under the HTTP server.
+func shouldPanicOnCopyError(req *http.Request) bool {
+ if inOurTests {
+ // Our tests know to handle this panic.
+ return true
+ }
+ if req.Context().Value(http.ServerContextKey) != nil {
+ // We seem to be running under an HTTP server, so
+ // it'll recover the panic.
+ return true
+ }
+ // Otherwise act like Go 1.10 and earlier to not break
+ // existing tests.
+ return false
+}
+
+// removeHopByHopHeaders removes hop-by-hop headers.
+func removeHopByHopHeaders(h http.Header) {
+ // RFC 7230, section 6.1: Remove headers listed in the "Connection" header.
+ for _, f := range h["Connection"] {
+ for _, sf := range strings.Split(f, ",") {
+ if sf = textproto.TrimString(sf); sf != "" {
+ h.Del(sf)
+ }
+ }
+ }
+ // RFC 2616, section 13.5.1: Remove a set of known hop-by-hop headers.
+ // This behavior is superseded by the RFC 7230 Connection header, but
+ // preserve it for backwards compatibility.
+ for _, f := range hopHeaders {
+ h.Del(f)
+ }
+}
+
+// flushInterval returns the p.FlushInterval value, conditionally
+// overriding its value for a specific request/response.
+func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
+ resCT := res.Header.Get("Content-Type")
+
+ // For Server-Sent Events responses, flush immediately.
+ // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
+ if baseCT, _, _ := mime.ParseMediaType(resCT); baseCT == "text/event-stream" {
+ return -1 // negative means immediately
+ }
+
+ // We might have the case of streaming for which Content-Length might be unset.
+ if res.ContentLength == -1 {
+ return -1
+ }
+
+ return p.FlushInterval
+}
+
+func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
+ var w io.Writer = dst
+
+ if flushInterval != 0 {
+ mlw := &maxLatencyWriter{
+ dst: dst,
+ flush: http.NewResponseController(dst).Flush,
+ latency: flushInterval,
+ }
+ defer mlw.stop()
+
+ // set up initial timer so headers get flushed even if body writes are delayed
+ mlw.flushPending = true
+ mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
+
+ w = mlw
+ }
+
+ var buf []byte
+ if p.BufferPool != nil {
+ buf = p.BufferPool.Get()
+ defer p.BufferPool.Put(buf)
+ }
+ _, err := p.copyBuffer(w, src, buf)
+ return err
+}
+
+// copyBuffer returns any write errors or non-EOF read errors, and the amount
+// of bytes written.
+func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
+ if len(buf) == 0 {
+ buf = make([]byte, 32*1024)
+ }
+ var written int64
+ for {
+ nr, rerr := src.Read(buf)
+ if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
+ p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
+ }
+ if nr > 0 {
+ nw, werr := dst.Write(buf[:nr])
+ if nw > 0 {
+ written += int64(nw)
+ }
+ if werr != nil {
+ return written, werr
+ }
+ if nr != nw {
+ return written, io.ErrShortWrite
+ }
+ }
+ if rerr != nil {
+ if rerr == io.EOF {
+ rerr = nil
+ }
+ return written, rerr
+ }
+ }
+}
+
+func (p *ReverseProxy) logf(format string, args ...any) {
+ if p.ErrorLog != nil {
+ p.ErrorLog.Printf(format, args...)
+ } else {
+ log.Printf(format, args...)
+ }
+}
+
+type maxLatencyWriter struct {
+ dst io.Writer
+ flush func() error
+ latency time.Duration // non-zero; negative means to flush immediately
+
+ mu sync.Mutex // protects t, flushPending, and dst.Flush
+ t *time.Timer
+ flushPending bool
+}
+
+func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ n, err = m.dst.Write(p)
+ if m.latency < 0 {
+ m.flush()
+ return
+ }
+ if m.flushPending {
+ return
+ }
+ if m.t == nil {
+ m.t = time.AfterFunc(m.latency, m.delayedFlush)
+ } else {
+ m.t.Reset(m.latency)
+ }
+ m.flushPending = true
+ return
+}
+
+func (m *maxLatencyWriter) delayedFlush() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
+ return
+ }
+ m.flush()
+ m.flushPending = false
+}
+
+func (m *maxLatencyWriter) stop() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.flushPending = false
+ if m.t != nil {
+ m.t.Stop()
+ }
+}
+
+func upgradeType(h http.Header) string {
+ if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
+ return ""
+ }
+ return h.Get("Upgrade")
+}
+
+func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
+ reqUpType := upgradeType(req.Header)
+ resUpType := upgradeType(res.Header)
+ if !ascii.IsPrint(resUpType) { // We know reqUpType is ASCII, it's checked by the caller.
+ p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch to invalid protocol %q", resUpType))
+ }
+ if !ascii.EqualFold(reqUpType, resUpType) {
+ p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
+ return
+ }
+
+ backConn, ok := res.Body.(io.ReadWriteCloser)
+ if !ok {
+ p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
+ return
+ }
+
+ rc := http.NewResponseController(rw)
+ conn, brw, hijackErr := rc.Hijack()
+ if errors.Is(hijackErr, http.ErrNotSupported) {
+ p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
+ return
+ }
+
+ backConnCloseCh := make(chan bool)
+ go func() {
+ // Ensure that the cancellation of a request closes the backend.
+ // See issue https://golang.org/issue/35559.
+ select {
+ case <-req.Context().Done():
+ case <-backConnCloseCh:
+ }
+ backConn.Close()
+ }()
+ defer close(backConnCloseCh)
+
+ if hijackErr != nil {
+ p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", hijackErr))
+ return
+ }
+ defer conn.Close()
+
+ copyHeader(rw.Header(), res.Header)
+
+ res.Header = rw.Header()
+ res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above
+ if err := res.Write(brw); err != nil {
+ p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
+ return
+ }
+ if err := brw.Flush(); err != nil {
+ p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
+ return
+ }
+ errc := make(chan error, 1)
+ spc := switchProtocolCopier{user: conn, backend: backConn}
+ go spc.copyToBackend(errc)
+ go spc.copyFromBackend(errc)
+ <-errc
+}
+
+// switchProtocolCopier exists so goroutines proxying data back and
+// forth have nice names in stacks.
+type switchProtocolCopier struct {
+ user, backend io.ReadWriter
+}
+
+func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
+ _, err := io.Copy(c.user, c.backend)
+ errc <- err
+}
+
+func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
+ _, err := io.Copy(c.backend, c.user)
+ errc <- err
+}
+
+func cleanQueryParams(s string) string {
+ reencode := func(s string) string {
+ v, _ := url.ParseQuery(s)
+ return v.Encode()
+ }
+ for i := 0; i < len(s); {
+ switch s[i] {
+ case ';':
+ return reencode(s)
+ case '%':
+ if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
+ return reencode(s)
+ }
+ i += 3
+ default:
+ i++
+ }
+ }
+ return s
+}
+
+func ishex(c byte) bool {
+ switch {
+ case '0' <= c && c <= '9':
+ return true
+ case 'a' <= c && c <= 'f':
+ return true
+ case 'A' <= c && c <= 'F':
+ return true
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy_test.go b/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..dd3330b615dbaecd4150e54abf14f23d224db18f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/httputil/reverseproxy_test.go
@@ -0,0 +1,1863 @@
+// 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.
+
+// Reverse proxy tests.
+
+package httputil
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httptrace"
+ "net/http/internal/ascii"
+ "net/textproto"
+ "net/url"
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+const fakeHopHeader = "X-Fake-Hop-Header-For-Test"
+
+func init() {
+ inOurTests = true
+ hopHeaders = append(hopHeaders, fakeHopHeader)
+}
+
+func TestReverseProxy(t *testing.T) {
+ const backendResponse = "I am the backend"
+ const backendStatus = 404
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "GET" && r.FormValue("mode") == "hangup" {
+ c, _, _ := w.(http.Hijacker).Hijack()
+ c.Close()
+ return
+ }
+ if len(r.TransferEncoding) > 0 {
+ t.Errorf("backend got unexpected TransferEncoding: %v", r.TransferEncoding)
+ }
+ if r.Header.Get("X-Forwarded-For") == "" {
+ t.Errorf("didn't get X-Forwarded-For header")
+ }
+ if c := r.Header.Get("Connection"); c != "" {
+ t.Errorf("handler got Connection header value %q", c)
+ }
+ if c := r.Header.Get("Te"); c != "trailers" {
+ t.Errorf("handler got Te header value %q; want 'trailers'", c)
+ }
+ if c := r.Header.Get("Upgrade"); c != "" {
+ t.Errorf("handler got Upgrade header value %q", c)
+ }
+ if c := r.Header.Get("Proxy-Connection"); c != "" {
+ t.Errorf("handler got Proxy-Connection header value %q", c)
+ }
+ if g, e := r.Host, "some-name"; g != e {
+ t.Errorf("backend got Host header %q, want %q", g, e)
+ }
+ w.Header().Set("Trailers", "not a special header field name")
+ w.Header().Set("Trailer", "X-Trailer")
+ w.Header().Set("X-Foo", "bar")
+ w.Header().Set("Upgrade", "foo")
+ w.Header().Set(fakeHopHeader, "foo")
+ w.Header().Add("X-Multi-Value", "foo")
+ w.Header().Add("X-Multi-Value", "bar")
+ http.SetCookie(w, &http.Cookie{Name: "flavor", Value: "chocolateChip"})
+ w.WriteHeader(backendStatus)
+ w.Write([]byte(backendResponse))
+ w.Header().Set("X-Trailer", "trailer_value")
+ w.Header().Set(http.TrailerPrefix+"X-Unannounced-Trailer", "unannounced_trailer_value")
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Host = "some-name"
+ getReq.Header.Set("Connection", "close, TE")
+ getReq.Header.Add("Te", "foo")
+ getReq.Header.Add("Te", "bar, trailers")
+ getReq.Header.Set("Proxy-Connection", "should be deleted")
+ getReq.Header.Set("Upgrade", "foo")
+ getReq.Close = true
+ res, err := frontendClient.Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ if g, e := res.StatusCode, backendStatus; g != e {
+ t.Errorf("got res.StatusCode %d; expected %d", g, e)
+ }
+ if g, e := res.Header.Get("X-Foo"), "bar"; g != e {
+ t.Errorf("got X-Foo %q; expected %q", g, e)
+ }
+ if c := res.Header.Get(fakeHopHeader); c != "" {
+ t.Errorf("got %s header value %q", fakeHopHeader, c)
+ }
+ if g, e := res.Header.Get("Trailers"), "not a special header field name"; g != e {
+ t.Errorf("header Trailers = %q; want %q", g, e)
+ }
+ if g, e := len(res.Header["X-Multi-Value"]), 2; g != e {
+ t.Errorf("got %d X-Multi-Value header values; expected %d", g, e)
+ }
+ if g, e := len(res.Header["Set-Cookie"]), 1; g != e {
+ t.Fatalf("got %d SetCookies, want %d", g, e)
+ }
+ if g, e := res.Trailer, (http.Header{"X-Trailer": nil}); !reflect.DeepEqual(g, e) {
+ t.Errorf("before reading body, Trailer = %#v; want %#v", g, e)
+ }
+ if cookie := res.Cookies()[0]; cookie.Name != "flavor" {
+ t.Errorf("unexpected cookie %q", cookie.Name)
+ }
+ bodyBytes, _ := io.ReadAll(res.Body)
+ if g, e := string(bodyBytes), backendResponse; g != e {
+ t.Errorf("got body %q; expected %q", g, e)
+ }
+ if g, e := res.Trailer.Get("X-Trailer"), "trailer_value"; g != e {
+ t.Errorf("Trailer(X-Trailer) = %q ; want %q", g, e)
+ }
+ if g, e := res.Trailer.Get("X-Unannounced-Trailer"), "unannounced_trailer_value"; g != e {
+ t.Errorf("Trailer(X-Unannounced-Trailer) = %q ; want %q", g, e)
+ }
+
+ // Test that a backend failing to be reached or one which doesn't return
+ // a response results in a StatusBadGateway.
+ getReq, _ = http.NewRequest("GET", frontend.URL+"/?mode=hangup", nil)
+ getReq.Close = true
+ res, err = frontendClient.Do(getReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusBadGateway {
+ t.Errorf("request to bad proxy = %v; want 502 StatusBadGateway", res.Status)
+ }
+
+}
+
+// Issue 16875: remove any proxied headers mentioned in the "Connection"
+// header value.
+func TestReverseProxyStripHeadersPresentInConnection(t *testing.T) {
+ const fakeConnectionToken = "X-Fake-Connection-Token"
+ const backendResponse = "I am the backend"
+
+ // someConnHeader is some arbitrary header to be declared as a hop-by-hop header
+ // in the Request's Connection header.
+ const someConnHeader = "X-Some-Conn-Header"
+
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if c := r.Header.Get("Connection"); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", "Connection", c)
+ }
+ if c := r.Header.Get(fakeConnectionToken); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", fakeConnectionToken, c)
+ }
+ if c := r.Header.Get(someConnHeader); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", someConnHeader, c)
+ }
+ w.Header().Add("Connection", "Upgrade, "+fakeConnectionToken)
+ w.Header().Add("Connection", someConnHeader)
+ w.Header().Set(someConnHeader, "should be deleted")
+ w.Header().Set(fakeConnectionToken, "should be deleted")
+ io.WriteString(w, backendResponse)
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ proxyHandler.ServeHTTP(w, r)
+ if c := r.Header.Get(someConnHeader); c != "should be deleted" {
+ t.Errorf("handler modified header %q = %q; want %q", someConnHeader, c, "should be deleted")
+ }
+ if c := r.Header.Get(fakeConnectionToken); c != "should be deleted" {
+ t.Errorf("handler modified header %q = %q; want %q", fakeConnectionToken, c, "should be deleted")
+ }
+ c := r.Header["Connection"]
+ var cf []string
+ for _, f := range c {
+ for _, sf := range strings.Split(f, ",") {
+ if sf = strings.TrimSpace(sf); sf != "" {
+ cf = append(cf, sf)
+ }
+ }
+ }
+ sort.Strings(cf)
+ expectedValues := []string{"Upgrade", someConnHeader, fakeConnectionToken}
+ sort.Strings(expectedValues)
+ if !reflect.DeepEqual(cf, expectedValues) {
+ t.Errorf("handler modified header %q = %q; want %q", "Connection", cf, expectedValues)
+ }
+ }))
+ defer frontend.Close()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Header.Add("Connection", "Upgrade, "+fakeConnectionToken)
+ getReq.Header.Add("Connection", someConnHeader)
+ getReq.Header.Set(someConnHeader, "should be deleted")
+ getReq.Header.Set(fakeConnectionToken, "should be deleted")
+ res, err := frontend.Client().Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ bodyBytes, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("reading body: %v", err)
+ }
+ if got, want := string(bodyBytes), backendResponse; got != want {
+ t.Errorf("got body %q; want %q", got, want)
+ }
+ if c := res.Header.Get("Connection"); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", "Connection", c)
+ }
+ if c := res.Header.Get(someConnHeader); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", someConnHeader, c)
+ }
+ if c := res.Header.Get(fakeConnectionToken); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", fakeConnectionToken, c)
+ }
+}
+
+func TestReverseProxyStripEmptyConnection(t *testing.T) {
+ // See Issue 46313.
+ const backendResponse = "I am the backend"
+
+ // someConnHeader is some arbitrary header to be declared as a hop-by-hop header
+ // in the Request's Connection header.
+ const someConnHeader = "X-Some-Conn-Header"
+
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if c := r.Header.Values("Connection"); len(c) != 0 {
+ t.Errorf("handler got header %q = %v; want empty", "Connection", c)
+ }
+ if c := r.Header.Get(someConnHeader); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", someConnHeader, c)
+ }
+ w.Header().Add("Connection", "")
+ w.Header().Add("Connection", someConnHeader)
+ w.Header().Set(someConnHeader, "should be deleted")
+ io.WriteString(w, backendResponse)
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ proxyHandler.ServeHTTP(w, r)
+ if c := r.Header.Get(someConnHeader); c != "should be deleted" {
+ t.Errorf("handler modified header %q = %q; want %q", someConnHeader, c, "should be deleted")
+ }
+ }))
+ defer frontend.Close()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Header.Add("Connection", "")
+ getReq.Header.Add("Connection", someConnHeader)
+ getReq.Header.Set(someConnHeader, "should be deleted")
+ res, err := frontend.Client().Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ bodyBytes, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("reading body: %v", err)
+ }
+ if got, want := string(bodyBytes), backendResponse; got != want {
+ t.Errorf("got body %q; want %q", got, want)
+ }
+ if c := res.Header.Get("Connection"); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", "Connection", c)
+ }
+ if c := res.Header.Get(someConnHeader); c != "" {
+ t.Errorf("handler got header %q = %q; want empty", someConnHeader, c)
+ }
+}
+
+func TestXForwardedFor(t *testing.T) {
+ const prevForwardedFor = "client ip"
+ const backendResponse = "I am the backend"
+ const backendStatus = 404
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("X-Forwarded-For") == "" {
+ t.Errorf("didn't get X-Forwarded-For header")
+ }
+ if !strings.Contains(r.Header.Get("X-Forwarded-For"), prevForwardedFor) {
+ t.Errorf("X-Forwarded-For didn't contain prior data")
+ }
+ w.WriteHeader(backendStatus)
+ w.Write([]byte(backendResponse))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Header.Set("Connection", "close")
+ getReq.Header.Set("X-Forwarded-For", prevForwardedFor)
+ getReq.Close = true
+ res, err := frontend.Client().Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ if g, e := res.StatusCode, backendStatus; g != e {
+ t.Errorf("got res.StatusCode %d; expected %d", g, e)
+ }
+ bodyBytes, _ := io.ReadAll(res.Body)
+ if g, e := string(bodyBytes), backendResponse; g != e {
+ t.Errorf("got body %q; expected %q", g, e)
+ }
+}
+
+// Issue 38079: don't append to X-Forwarded-For if it's present but nil
+func TestXForwardedFor_Omit(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if v := r.Header.Get("X-Forwarded-For"); v != "" {
+ t.Errorf("got X-Forwarded-For header: %q", v)
+ }
+ w.Write([]byte("hi"))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ oldDirector := proxyHandler.Director
+ proxyHandler.Director = func(r *http.Request) {
+ r.Header["X-Forwarded-For"] = nil
+ oldDirector(r)
+ }
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Host = "some-name"
+ getReq.Close = true
+ res, err := frontend.Client().Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ res.Body.Close()
+}
+
+func TestReverseProxyRewriteStripsForwarded(t *testing.T) {
+ headers := []string{
+ "Forwarded",
+ "X-Forwarded-For",
+ "X-Forwarded-Host",
+ "X-Forwarded-Proto",
+ }
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ for _, h := range headers {
+ if v := r.Header.Get(h); v != "" {
+ t.Errorf("got %v header: %q", h, v)
+ }
+ }
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := &ReverseProxy{
+ Rewrite: func(r *ProxyRequest) {
+ r.SetURL(backendURL)
+ },
+ }
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Host = "some-name"
+ getReq.Close = true
+ for _, h := range headers {
+ getReq.Header.Set(h, "x")
+ }
+ res, err := frontend.Client().Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ res.Body.Close()
+}
+
+var proxyQueryTests = []struct {
+ baseSuffix string // suffix to add to backend URL
+ reqSuffix string // suffix to add to frontend's request URL
+ want string // what backend should see for final request URL (without ?)
+}{
+ {"", "", ""},
+ {"?sta=tic", "?us=er", "sta=tic&us=er"},
+ {"", "?us=er", "us=er"},
+ {"?sta=tic", "", "sta=tic"},
+}
+
+func TestReverseProxyQuery(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Got-Query", r.URL.RawQuery)
+ w.Write([]byte("hi"))
+ }))
+ defer backend.Close()
+
+ for i, tt := range proxyQueryTests {
+ backendURL, err := url.Parse(backend.URL + tt.baseSuffix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL))
+ req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil)
+ req.Close = true
+ res, err := frontend.Client().Do(req)
+ if err != nil {
+ t.Fatalf("%d. Get: %v", i, err)
+ }
+ if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e {
+ t.Errorf("%d. got query %q; expected %q", i, g, e)
+ }
+ res.Body.Close()
+ frontend.Close()
+ }
+}
+
+func TestReverseProxyFlushInterval(t *testing.T) {
+ const expected = "hi"
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(expected))
+ }))
+ defer backend.Close()
+
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.FlushInterval = time.Microsecond
+
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ req, _ := http.NewRequest("GET", frontend.URL, nil)
+ req.Close = true
+ res, err := frontend.Client().Do(req)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ if bodyBytes, _ := io.ReadAll(res.Body); string(bodyBytes) != expected {
+ t.Errorf("got body %q; expected %q", bodyBytes, expected)
+ }
+}
+
+type mockFlusher struct {
+ http.ResponseWriter
+ flushed bool
+}
+
+func (m *mockFlusher) Flush() {
+ m.flushed = true
+}
+
+type wrappedRW struct {
+ http.ResponseWriter
+}
+
+func (w *wrappedRW) Unwrap() http.ResponseWriter {
+ return w.ResponseWriter
+}
+
+func TestReverseProxyResponseControllerFlushInterval(t *testing.T) {
+ const expected = "hi"
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(expected))
+ }))
+ defer backend.Close()
+
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mf := &mockFlusher{}
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.FlushInterval = -1 // flush immediately
+ proxyWithMiddleware := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mf.ResponseWriter = w
+ w = &wrappedRW{mf}
+ proxyHandler.ServeHTTP(w, r)
+ })
+
+ frontend := httptest.NewServer(proxyWithMiddleware)
+ defer frontend.Close()
+
+ req, _ := http.NewRequest("GET", frontend.URL, nil)
+ req.Close = true
+ res, err := frontend.Client().Do(req)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ if bodyBytes, _ := io.ReadAll(res.Body); string(bodyBytes) != expected {
+ t.Errorf("got body %q; expected %q", bodyBytes, expected)
+ }
+ if !mf.flushed {
+ t.Errorf("response writer was not flushed")
+ }
+}
+
+func TestReverseProxyFlushIntervalHeaders(t *testing.T) {
+ const expected = "hi"
+ stopCh := make(chan struct{})
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Add("MyHeader", expected)
+ w.WriteHeader(200)
+ w.(http.Flusher).Flush()
+ <-stopCh
+ }))
+ defer backend.Close()
+ defer close(stopCh)
+
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.FlushInterval = time.Microsecond
+
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ req, _ := http.NewRequest("GET", frontend.URL, nil)
+ req.Close = true
+
+ ctx, cancel := context.WithTimeout(req.Context(), 10*time.Second)
+ defer cancel()
+ req = req.WithContext(ctx)
+
+ res, err := frontend.Client().Do(req)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+
+ if res.Header.Get("MyHeader") != expected {
+ t.Errorf("got header %q; expected %q", res.Header.Get("MyHeader"), expected)
+ }
+}
+
+func TestReverseProxyCancellation(t *testing.T) {
+ const backendResponse = "I am the backend"
+
+ reqInFlight := make(chan struct{})
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ close(reqInFlight) // cause the client to cancel its request
+
+ select {
+ case <-time.After(10 * time.Second):
+ // Note: this should only happen in broken implementations, and the
+ // closenotify case should be instantaneous.
+ t.Error("Handler never saw CloseNotify")
+ return
+ case <-w.(http.CloseNotifier).CloseNotify():
+ }
+
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(backendResponse))
+ }))
+
+ defer backend.Close()
+
+ backend.Config.ErrorLog = log.New(io.Discard, "", 0)
+
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+
+ // Discards errors of the form:
+ // http: proxy error: read tcp 127.0.0.1:44643: use of closed network connection
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0)
+
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ go func() {
+ <-reqInFlight
+ frontendClient.Transport.(*http.Transport).CancelRequest(getReq)
+ }()
+ res, err := frontendClient.Do(getReq)
+ if res != nil {
+ t.Errorf("got response %v; want nil", res.Status)
+ }
+ if err == nil {
+ // This should be an error like:
+ // Get "http://127.0.0.1:58079": read tcp 127.0.0.1:58079:
+ // use of closed network connection
+ t.Error("Server.Client().Do() returned nil error; want non-nil error")
+ }
+}
+
+func req(t *testing.T, v string) *http.Request {
+ req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(v)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return req
+}
+
+// Issue 12344
+func TestNilBody(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("hi"))
+ }))
+ defer backend.Close()
+
+ frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ backURL, _ := url.Parse(backend.URL)
+ rp := NewSingleHostReverseProxy(backURL)
+ r := req(t, "GET / HTTP/1.0\r\n\r\n")
+ r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working
+ rp.ServeHTTP(w, r)
+ }))
+ defer frontend.Close()
+
+ res, err := http.Get(frontend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ slurp, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(slurp) != "hi" {
+ t.Errorf("Got %q; want %q", slurp, "hi")
+ }
+}
+
+// Issue 15524
+func TestUserAgentHeader(t *testing.T) {
+ var gotUA string
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotUA = r.Header.Get("User-Agent")
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ proxyHandler := new(ReverseProxy)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ proxyHandler.Director = func(req *http.Request) {
+ req.URL = backendURL
+ }
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ for _, sentUA := range []string{"explicit UA", ""} {
+ getReq, _ := http.NewRequest("GET", frontend.URL, nil)
+ getReq.Header.Set("User-Agent", sentUA)
+ getReq.Close = true
+ res, err := frontendClient.Do(getReq)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ res.Body.Close()
+ if got, want := gotUA, sentUA; got != want {
+ t.Errorf("got forwarded User-Agent %q, want %q", got, want)
+ }
+ }
+}
+
+type bufferPool struct {
+ get func() []byte
+ put func([]byte)
+}
+
+func (bp bufferPool) Get() []byte { return bp.get() }
+func (bp bufferPool) Put(v []byte) { bp.put(v) }
+
+func TestReverseProxyGetPutBuffer(t *testing.T) {
+ const msg = "hi"
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, msg)
+ }))
+ defer backend.Close()
+
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var (
+ mu sync.Mutex
+ log []string
+ )
+ addLog := func(event string) {
+ mu.Lock()
+ defer mu.Unlock()
+ log = append(log, event)
+ }
+ rp := NewSingleHostReverseProxy(backendURL)
+ const size = 1234
+ rp.BufferPool = bufferPool{
+ get: func() []byte {
+ addLog("getBuf")
+ return make([]byte, size)
+ },
+ put: func(p []byte) {
+ addLog("putBuf-" + strconv.Itoa(len(p)))
+ },
+ }
+ frontend := httptest.NewServer(rp)
+ defer frontend.Close()
+
+ req, _ := http.NewRequest("GET", frontend.URL, nil)
+ req.Close = true
+ res, err := frontend.Client().Do(req)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ t.Fatalf("reading body: %v", err)
+ }
+ if string(slurp) != msg {
+ t.Errorf("msg = %q; want %q", slurp, msg)
+ }
+ wantLog := []string{"getBuf", "putBuf-" + strconv.Itoa(size)}
+ mu.Lock()
+ defer mu.Unlock()
+ if !reflect.DeepEqual(log, wantLog) {
+ t.Errorf("Log events = %q; want %q", log, wantLog)
+ }
+}
+
+func TestReverseProxy_Post(t *testing.T) {
+ const backendResponse = "I am the backend"
+ const backendStatus = 200
+ var requestBody = bytes.Repeat([]byte("a"), 1<<20)
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ slurp, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("Backend body read = %v", err)
+ }
+ if len(slurp) != len(requestBody) {
+ t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
+ }
+ if !bytes.Equal(slurp, requestBody) {
+ t.Error("Backend read wrong request body.") // 1MB; omitting details
+ }
+ w.Write([]byte(backendResponse))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ postReq, _ := http.NewRequest("POST", frontend.URL, bytes.NewReader(requestBody))
+ res, err := frontend.Client().Do(postReq)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ if g, e := res.StatusCode, backendStatus; g != e {
+ t.Errorf("got res.StatusCode %d; expected %d", g, e)
+ }
+ bodyBytes, _ := io.ReadAll(res.Body)
+ if g, e := string(bodyBytes), backendResponse; g != e {
+ t.Errorf("got body %q; expected %q", g, e)
+ }
+}
+
+type RoundTripperFunc func(*http.Request) (*http.Response, error)
+
+func (fn RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return fn(req)
+}
+
+// Issue 16036: send a Request with a nil Body when possible
+func TestReverseProxy_NilBody(t *testing.T) {
+ backendURL, _ := url.Parse("http://fake.tld/")
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ proxyHandler.Transport = RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ if req.Body != nil {
+ t.Error("Body != nil; want a nil Body")
+ }
+ return nil, errors.New("done testing the interesting part; so force a 502 Gateway error")
+ })
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ res, err := frontend.Client().Get(frontend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 502 {
+ t.Errorf("status code = %v; want 502 (Gateway Error)", res.Status)
+ }
+}
+
+// Issue 33142: always allocate the request headers
+func TestReverseProxy_AllocatedHeader(t *testing.T) {
+ proxyHandler := new(ReverseProxy)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ proxyHandler.Director = func(*http.Request) {} // noop
+ proxyHandler.Transport = RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ if req.Header == nil {
+ t.Error("Header == nil; want a non-nil Header")
+ }
+ return nil, errors.New("done testing the interesting part; so force a 502 Gateway error")
+ })
+
+ proxyHandler.ServeHTTP(httptest.NewRecorder(), &http.Request{
+ Method: "GET",
+ URL: &url.URL{Scheme: "http", Host: "fake.tld", Path: "/"},
+ Proto: "HTTP/1.0",
+ ProtoMajor: 1,
+ })
+}
+
+// Issue 14237. Test ModifyResponse and that an error from it
+// causes the proxy to return StatusBadGateway, or StatusOK otherwise.
+func TestReverseProxyModifyResponse(t *testing.T) {
+ backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Add("X-Hit-Mod", fmt.Sprintf("%v", r.URL.Path == "/mod"))
+ }))
+ defer backendServer.Close()
+
+ rpURL, _ := url.Parse(backendServer.URL)
+ rproxy := NewSingleHostReverseProxy(rpURL)
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ rproxy.ModifyResponse = func(resp *http.Response) error {
+ if resp.Header.Get("X-Hit-Mod") != "true" {
+ return fmt.Errorf("tried to by-pass proxy")
+ }
+ return nil
+ }
+
+ frontendProxy := httptest.NewServer(rproxy)
+ defer frontendProxy.Close()
+
+ tests := []struct {
+ url string
+ wantCode int
+ }{
+ {frontendProxy.URL + "/mod", http.StatusOK},
+ {frontendProxy.URL + "/schedule", http.StatusBadGateway},
+ }
+
+ for i, tt := range tests {
+ resp, err := http.Get(tt.url)
+ if err != nil {
+ t.Fatalf("failed to reach proxy: %v", err)
+ }
+ if g, e := resp.StatusCode, tt.wantCode; g != e {
+ t.Errorf("#%d: got res.StatusCode %d; expected %d", i, g, e)
+ }
+ resp.Body.Close()
+ }
+}
+
+type failingRoundTripper struct{}
+
+func (failingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
+ return nil, errors.New("some error")
+}
+
+type staticResponseRoundTripper struct{ res *http.Response }
+
+func (rt staticResponseRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
+ return rt.res, nil
+}
+
+func TestReverseProxyErrorHandler(t *testing.T) {
+ tests := []struct {
+ name string
+ wantCode int
+ errorHandler func(http.ResponseWriter, *http.Request, error)
+ transport http.RoundTripper // defaults to failingRoundTripper
+ modifyResponse func(*http.Response) error
+ }{
+ {
+ name: "default",
+ wantCode: http.StatusBadGateway,
+ },
+ {
+ name: "errorhandler",
+ wantCode: http.StatusTeapot,
+ errorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { rw.WriteHeader(http.StatusTeapot) },
+ },
+ {
+ name: "modifyresponse_noerr",
+ transport: staticResponseRoundTripper{
+ &http.Response{StatusCode: 345, Body: http.NoBody},
+ },
+ modifyResponse: func(res *http.Response) error {
+ res.StatusCode++
+ return nil
+ },
+ errorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { rw.WriteHeader(http.StatusTeapot) },
+ wantCode: 346,
+ },
+ {
+ name: "modifyresponse_err",
+ transport: staticResponseRoundTripper{
+ &http.Response{StatusCode: 345, Body: http.NoBody},
+ },
+ modifyResponse: func(res *http.Response) error {
+ res.StatusCode++
+ return errors.New("some error to trigger errorHandler")
+ },
+ errorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { rw.WriteHeader(http.StatusTeapot) },
+ wantCode: http.StatusTeapot,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ target := &url.URL{
+ Scheme: "http",
+ Host: "dummy.tld",
+ Path: "/",
+ }
+ rproxy := NewSingleHostReverseProxy(target)
+ rproxy.Transport = tt.transport
+ rproxy.ModifyResponse = tt.modifyResponse
+ if rproxy.Transport == nil {
+ rproxy.Transport = failingRoundTripper{}
+ }
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ if tt.errorHandler != nil {
+ rproxy.ErrorHandler = tt.errorHandler
+ }
+ frontendProxy := httptest.NewServer(rproxy)
+ defer frontendProxy.Close()
+
+ resp, err := http.Get(frontendProxy.URL + "/test")
+ if err != nil {
+ t.Fatalf("failed to reach proxy: %v", err)
+ }
+ if g, e := resp.StatusCode, tt.wantCode; g != e {
+ t.Errorf("got res.StatusCode %d; expected %d", g, e)
+ }
+ resp.Body.Close()
+ })
+ }
+}
+
+// Issue 16659: log errors from short read
+func TestReverseProxy_CopyBuffer(t *testing.T) {
+ backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ out := "this call was relayed by the reverse proxy"
+ // Coerce a wrong content length to induce io.UnexpectedEOF
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(out)*2))
+ fmt.Fprintln(w, out)
+ }))
+ defer backendServer.Close()
+
+ rpURL, err := url.Parse(backendServer.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var proxyLog bytes.Buffer
+ rproxy := NewSingleHostReverseProxy(rpURL)
+ rproxy.ErrorLog = log.New(&proxyLog, "", log.Lshortfile)
+ donec := make(chan bool, 1)
+ frontendProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer func() { donec <- true }()
+ rproxy.ServeHTTP(w, r)
+ }))
+ defer frontendProxy.Close()
+
+ if _, err = frontendProxy.Client().Get(frontendProxy.URL); err == nil {
+ t.Fatalf("want non-nil error")
+ }
+ // The race detector complains about the proxyLog usage in logf in copyBuffer
+ // and our usage below with proxyLog.Bytes() so we're explicitly using a
+ // channel to ensure that the ReverseProxy's ServeHTTP is done before we
+ // continue after Get.
+ <-donec
+
+ expected := []string{
+ "EOF",
+ "read",
+ }
+ for _, phrase := range expected {
+ if !bytes.Contains(proxyLog.Bytes(), []byte(phrase)) {
+ t.Errorf("expected log to contain phrase %q", phrase)
+ }
+ }
+}
+
+type staticTransport struct {
+ res *http.Response
+}
+
+func (t *staticTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ return t.res, nil
+}
+
+func BenchmarkServeHTTP(b *testing.B) {
+ res := &http.Response{
+ StatusCode: 200,
+ Body: io.NopCloser(strings.NewReader("")),
+ }
+ proxy := &ReverseProxy{
+ Director: func(*http.Request) {},
+ Transport: &staticTransport{res},
+ }
+
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "/", nil)
+
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ proxy.ServeHTTP(w, r)
+ }
+}
+
+func TestServeHTTPDeepCopy(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("Hello Gopher!"))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ type result struct {
+ before, after string
+ }
+
+ resultChan := make(chan result, 1)
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ before := r.URL.String()
+ proxyHandler.ServeHTTP(w, r)
+ after := r.URL.String()
+ resultChan <- result{before: before, after: after}
+ }))
+ defer frontend.Close()
+
+ want := result{before: "/", after: "/"}
+
+ res, err := frontend.Client().Get(frontend.URL)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ res.Body.Close()
+
+ got := <-resultChan
+ if got != want {
+ t.Errorf("got = %+v; want = %+v", got, want)
+ }
+}
+
+// Issue 18327: verify we always do a deep copy of the Request.Header map
+// before any mutations.
+func TestClonesRequestHeaders(t *testing.T) {
+ log.SetOutput(io.Discard)
+ defer log.SetOutput(os.Stderr)
+ req, _ := http.NewRequest("GET", "http://foo.tld/", nil)
+ req.RemoteAddr = "1.2.3.4:56789"
+ rp := &ReverseProxy{
+ Director: func(req *http.Request) {
+ req.Header.Set("From-Director", "1")
+ },
+ Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ if v := req.Header.Get("From-Director"); v != "1" {
+ t.Errorf("From-Directory value = %q; want 1", v)
+ }
+ return nil, io.EOF
+ }),
+ }
+ rp.ServeHTTP(httptest.NewRecorder(), req)
+
+ for _, h := range []string{
+ "From-Director",
+ "X-Forwarded-For",
+ } {
+ if req.Header.Get(h) != "" {
+ t.Errorf("%v header mutation modified caller's request", h)
+ }
+ }
+}
+
+type roundTripperFunc func(req *http.Request) (*http.Response, error)
+
+func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return fn(req)
+}
+
+func TestModifyResponseClosesBody(t *testing.T) {
+ req, _ := http.NewRequest("GET", "http://foo.tld/", nil)
+ req.RemoteAddr = "1.2.3.4:56789"
+ closeCheck := new(checkCloser)
+ logBuf := new(strings.Builder)
+ outErr := errors.New("ModifyResponse error")
+ rp := &ReverseProxy{
+ Director: func(req *http.Request) {},
+ Transport: &staticTransport{&http.Response{
+ StatusCode: 200,
+ Body: closeCheck,
+ }},
+ ErrorLog: log.New(logBuf, "", 0),
+ ModifyResponse: func(*http.Response) error {
+ return outErr
+ },
+ }
+ rec := httptest.NewRecorder()
+ rp.ServeHTTP(rec, req)
+ res := rec.Result()
+ if g, e := res.StatusCode, http.StatusBadGateway; g != e {
+ t.Errorf("got res.StatusCode %d; expected %d", g, e)
+ }
+ if !closeCheck.closed {
+ t.Errorf("body should have been closed")
+ }
+ if g, e := logBuf.String(), outErr.Error(); !strings.Contains(g, e) {
+ t.Errorf("ErrorLog %q does not contain %q", g, e)
+ }
+}
+
+type checkCloser struct {
+ closed bool
+}
+
+func (cc *checkCloser) Close() error {
+ cc.closed = true
+ return nil
+}
+
+func (cc *checkCloser) Read(b []byte) (int, error) {
+ return len(b), nil
+}
+
+// Issue 23643: panic on body copy error
+func TestReverseProxy_PanicBodyError(t *testing.T) {
+ log.SetOutput(io.Discard)
+ defer log.SetOutput(os.Stderr)
+ backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ out := "this call was relayed by the reverse proxy"
+ // Coerce a wrong content length to induce io.ErrUnexpectedEOF
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(out)*2))
+ fmt.Fprintln(w, out)
+ }))
+ defer backendServer.Close()
+
+ rpURL, err := url.Parse(backendServer.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rproxy := NewSingleHostReverseProxy(rpURL)
+
+ // Ensure that the handler panics when the body read encounters an
+ // io.ErrUnexpectedEOF
+ defer func() {
+ err := recover()
+ if err == nil {
+ t.Fatal("handler should have panicked")
+ }
+ if err != http.ErrAbortHandler {
+ t.Fatal("expected ErrAbortHandler, got", err)
+ }
+ }()
+ req, _ := http.NewRequest("GET", "http://foo.tld/", nil)
+ rproxy.ServeHTTP(httptest.NewRecorder(), req)
+}
+
+// Issue #46866: panic without closing incoming request body causes a panic
+func TestReverseProxy_PanicClosesIncomingBody(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ out := "this call was relayed by the reverse proxy"
+ // Coerce a wrong content length to induce io.ErrUnexpectedEOF
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(out)*2))
+ fmt.Fprintln(w, out)
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ var wg sync.WaitGroup
+ for i := 0; i < 2; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for j := 0; j < 10; j++ {
+ const reqLen = 6 * 1024 * 1024
+ req, _ := http.NewRequest("POST", frontend.URL, &io.LimitedReader{R: neverEnding('x'), N: reqLen})
+ req.ContentLength = reqLen
+ resp, _ := frontendClient.Transport.RoundTrip(req)
+ if resp != nil {
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ }
+ }()
+ }
+ wg.Wait()
+}
+
+func TestSelectFlushInterval(t *testing.T) {
+ tests := []struct {
+ name string
+ p *ReverseProxy
+ res *http.Response
+ want time.Duration
+ }{
+ {
+ name: "default",
+ res: &http.Response{},
+ p: &ReverseProxy{FlushInterval: 123},
+ want: 123,
+ },
+ {
+ name: "server-sent events overrides non-zero",
+ res: &http.Response{
+ Header: http.Header{
+ "Content-Type": {"text/event-stream"},
+ },
+ },
+ p: &ReverseProxy{FlushInterval: 123},
+ want: -1,
+ },
+ {
+ name: "server-sent events overrides zero",
+ res: &http.Response{
+ Header: http.Header{
+ "Content-Type": {"text/event-stream"},
+ },
+ },
+ p: &ReverseProxy{FlushInterval: 0},
+ want: -1,
+ },
+ {
+ name: "server-sent events with media-type parameters overrides non-zero",
+ res: &http.Response{
+ Header: http.Header{
+ "Content-Type": {"text/event-stream;charset=utf-8"},
+ },
+ },
+ p: &ReverseProxy{FlushInterval: 123},
+ want: -1,
+ },
+ {
+ name: "server-sent events with media-type parameters overrides zero",
+ res: &http.Response{
+ Header: http.Header{
+ "Content-Type": {"text/event-stream;charset=utf-8"},
+ },
+ },
+ p: &ReverseProxy{FlushInterval: 0},
+ want: -1,
+ },
+ {
+ name: "Content-Length: -1, overrides non-zero",
+ res: &http.Response{
+ ContentLength: -1,
+ },
+ p: &ReverseProxy{FlushInterval: 123},
+ want: -1,
+ },
+ {
+ name: "Content-Length: -1, overrides zero",
+ res: &http.Response{
+ ContentLength: -1,
+ },
+ p: &ReverseProxy{FlushInterval: 0},
+ want: -1,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := tt.p.flushInterval(tt.res)
+ if got != tt.want {
+ t.Errorf("flushLatency = %v; want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestReverseProxyWebSocket(t *testing.T) {
+ backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if upgradeType(r.Header) != "websocket" {
+ t.Error("unexpected backend request")
+ http.Error(w, "unexpected request", 400)
+ return
+ }
+ c, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer c.Close()
+ io.WriteString(c, "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: WebSocket\r\n\r\n")
+ bs := bufio.NewScanner(c)
+ if !bs.Scan() {
+ t.Errorf("backend failed to read line from client: %v", bs.Err())
+ return
+ }
+ fmt.Fprintf(c, "backend got %q\n", bs.Text())
+ }))
+ defer backendServer.Close()
+
+ backURL, _ := url.Parse(backendServer.URL)
+ rproxy := NewSingleHostReverseProxy(backURL)
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ rproxy.ModifyResponse = func(res *http.Response) error {
+ res.Header.Add("X-Modified", "true")
+ return nil
+ }
+
+ handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+ rw.Header().Set("X-Header", "X-Value")
+ rproxy.ServeHTTP(rw, req)
+ if got, want := rw.Header().Get("X-Modified"), "true"; got != want {
+ t.Errorf("response writer X-Modified header = %q; want %q", got, want)
+ }
+ })
+
+ frontendProxy := httptest.NewServer(handler)
+ defer frontendProxy.Close()
+
+ req, _ := http.NewRequest("GET", frontendProxy.URL, nil)
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+
+ c := frontendProxy.Client()
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.StatusCode != 101 {
+ t.Fatalf("status = %v; want 101", res.Status)
+ }
+
+ got := res.Header.Get("X-Header")
+ want := "X-Value"
+ if got != want {
+ t.Errorf("Header(XHeader) = %q; want %q", got, want)
+ }
+
+ if !ascii.EqualFold(upgradeType(res.Header), "websocket") {
+ t.Fatalf("not websocket upgrade; got %#v", res.Header)
+ }
+ rwc, ok := res.Body.(io.ReadWriteCloser)
+ if !ok {
+ t.Fatalf("response body is of type %T; does not implement ReadWriteCloser", res.Body)
+ }
+ defer rwc.Close()
+
+ if got, want := res.Header.Get("X-Modified"), "true"; got != want {
+ t.Errorf("response X-Modified header = %q; want %q", got, want)
+ }
+
+ io.WriteString(rwc, "Hello\n")
+ bs := bufio.NewScanner(rwc)
+ if !bs.Scan() {
+ t.Fatalf("Scan: %v", bs.Err())
+ }
+ got = bs.Text()
+ want = `backend got "Hello"`
+ if got != want {
+ t.Errorf("got %#q, want %#q", got, want)
+ }
+}
+
+func TestReverseProxyWebSocketCancellation(t *testing.T) {
+ n := 5
+ triggerCancelCh := make(chan bool, n)
+ nthResponse := func(i int) string {
+ return fmt.Sprintf("backend response #%d\n", i)
+ }
+ terminalMsg := "final message"
+
+ cst := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if g, ws := upgradeType(r.Header), "websocket"; g != ws {
+ t.Errorf("Unexpected upgrade type %q, want %q", g, ws)
+ http.Error(w, "Unexpected request", 400)
+ return
+ }
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer conn.Close()
+
+ upgradeMsg := "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: WebSocket\r\n\r\n"
+ if _, err := io.WriteString(conn, upgradeMsg); err != nil {
+ t.Error(err)
+ return
+ }
+ if _, _, err := bufrw.ReadLine(); err != nil {
+ t.Errorf("Failed to read line from client: %v", err)
+ return
+ }
+
+ for i := 0; i < n; i++ {
+ if _, err := bufrw.WriteString(nthResponse(i)); err != nil {
+ select {
+ case <-triggerCancelCh:
+ default:
+ t.Errorf("Writing response #%d failed: %v", i, err)
+ }
+ return
+ }
+ bufrw.Flush()
+ time.Sleep(time.Second)
+ }
+ if _, err := bufrw.WriteString(terminalMsg); err != nil {
+ select {
+ case <-triggerCancelCh:
+ default:
+ t.Errorf("Failed to write terminal message: %v", err)
+ }
+ }
+ bufrw.Flush()
+ }))
+ defer cst.Close()
+
+ backendURL, _ := url.Parse(cst.URL)
+ rproxy := NewSingleHostReverseProxy(backendURL)
+ rproxy.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ rproxy.ModifyResponse = func(res *http.Response) error {
+ res.Header.Add("X-Modified", "true")
+ return nil
+ }
+
+ handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+ rw.Header().Set("X-Header", "X-Value")
+ ctx, cancel := context.WithCancel(req.Context())
+ go func() {
+ <-triggerCancelCh
+ cancel()
+ }()
+ rproxy.ServeHTTP(rw, req.WithContext(ctx))
+ })
+
+ frontendProxy := httptest.NewServer(handler)
+ defer frontendProxy.Close()
+
+ req, _ := http.NewRequest("GET", frontendProxy.URL, nil)
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+
+ res, err := frontendProxy.Client().Do(req)
+ if err != nil {
+ t.Fatalf("Dialing to frontend proxy: %v", err)
+ }
+ defer res.Body.Close()
+ if g, w := res.StatusCode, 101; g != w {
+ t.Fatalf("Switching protocols failed, got: %d, want: %d", g, w)
+ }
+
+ if g, w := res.Header.Get("X-Header"), "X-Value"; g != w {
+ t.Errorf("X-Header mismatch\n\tgot: %q\n\twant: %q", g, w)
+ }
+
+ if g, w := upgradeType(res.Header), "websocket"; !ascii.EqualFold(g, w) {
+ t.Fatalf("Upgrade header mismatch\n\tgot: %q\n\twant: %q", g, w)
+ }
+
+ rwc, ok := res.Body.(io.ReadWriteCloser)
+ if !ok {
+ t.Fatalf("Response body type mismatch, got %T, want io.ReadWriteCloser", res.Body)
+ }
+
+ if got, want := res.Header.Get("X-Modified"), "true"; got != want {
+ t.Errorf("response X-Modified header = %q; want %q", got, want)
+ }
+
+ if _, err := io.WriteString(rwc, "Hello\n"); err != nil {
+ t.Fatalf("Failed to write first message: %v", err)
+ }
+
+ // Read loop.
+
+ br := bufio.NewReader(rwc)
+ for {
+ line, err := br.ReadString('\n')
+ switch {
+ case line == terminalMsg: // this case before "err == io.EOF"
+ t.Fatalf("The websocket request was not canceled, unfortunately!")
+
+ case err == io.EOF:
+ return
+
+ case err != nil:
+ t.Fatalf("Unexpected error: %v", err)
+
+ case line == nthResponse(0): // We've gotten the first response back
+ // Let's trigger a cancel.
+ close(triggerCancelCh)
+ }
+ }
+}
+
+func TestUnannouncedTrailer(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ w.(http.Flusher).Flush()
+ w.Header().Set(http.TrailerPrefix+"X-Unannounced-Trailer", "unannounced_trailer_value")
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ res, err := frontendClient.Get(frontend.URL)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+
+ io.ReadAll(res.Body)
+
+ if g, w := res.Trailer.Get("X-Unannounced-Trailer"), "unannounced_trailer_value"; g != w {
+ t.Errorf("Trailer(X-Unannounced-Trailer) = %q; want %q", g, w)
+ }
+
+}
+
+func TestSetURL(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(r.Host))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := &ReverseProxy{
+ Rewrite: func(r *ProxyRequest) {
+ r.SetURL(backendURL)
+ },
+ }
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ res, err := frontendClient.Get(frontend.URL)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatalf("Reading body: %v", err)
+ }
+
+ if got, want := string(body), backendURL.Host; got != want {
+ t.Errorf("backend got Host %q, want %q", got, want)
+ }
+}
+
+func TestSingleJoinSlash(t *testing.T) {
+ tests := []struct {
+ slasha string
+ slashb string
+ expected string
+ }{
+ {"https://www.google.com/", "/favicon.ico", "https://www.google.com/favicon.ico"},
+ {"https://www.google.com", "/favicon.ico", "https://www.google.com/favicon.ico"},
+ {"https://www.google.com", "favicon.ico", "https://www.google.com/favicon.ico"},
+ {"https://www.google.com", "", "https://www.google.com/"},
+ {"", "favicon.ico", "/favicon.ico"},
+ }
+ for _, tt := range tests {
+ if got := singleJoiningSlash(tt.slasha, tt.slashb); got != tt.expected {
+ t.Errorf("singleJoiningSlash(%q,%q) want %q got %q",
+ tt.slasha,
+ tt.slashb,
+ tt.expected,
+ got)
+ }
+ }
+}
+
+func TestJoinURLPath(t *testing.T) {
+ tests := []struct {
+ a *url.URL
+ b *url.URL
+ wantPath string
+ wantRaw string
+ }{
+ {&url.URL{Path: "/a/b"}, &url.URL{Path: "/c"}, "/a/b/c", ""},
+ {&url.URL{Path: "/a/b", RawPath: "badpath"}, &url.URL{Path: "c"}, "/a/b/c", "/a/b/c"},
+ {&url.URL{Path: "/a/b", RawPath: "/a%2Fb"}, &url.URL{Path: "/c"}, "/a/b/c", "/a%2Fb/c"},
+ {&url.URL{Path: "/a/b", RawPath: "/a%2Fb"}, &url.URL{Path: "/c"}, "/a/b/c", "/a%2Fb/c"},
+ {&url.URL{Path: "/a/b/", RawPath: "/a%2Fb%2F"}, &url.URL{Path: "c"}, "/a/b//c", "/a%2Fb%2F/c"},
+ {&url.URL{Path: "/a/b/", RawPath: "/a%2Fb/"}, &url.URL{Path: "/c/d", RawPath: "/c%2Fd"}, "/a/b/c/d", "/a%2Fb/c%2Fd"},
+ }
+
+ for _, tt := range tests {
+ p, rp := joinURLPath(tt.a, tt.b)
+ if p != tt.wantPath || rp != tt.wantRaw {
+ t.Errorf("joinURLPath(URL(%q,%q),URL(%q,%q)) want (%q,%q) got (%q,%q)",
+ tt.a.Path, tt.a.RawPath,
+ tt.b.Path, tt.b.RawPath,
+ tt.wantPath, tt.wantRaw,
+ p, rp)
+ }
+ }
+}
+
+func TestReverseProxyRewriteReplacesOut(t *testing.T) {
+ const content = "response_content"
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(content))
+ }))
+ defer backend.Close()
+ proxyHandler := &ReverseProxy{
+ Rewrite: func(r *ProxyRequest) {
+ r.Out, _ = http.NewRequest("GET", backend.URL, nil)
+ },
+ }
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ res, err := frontend.Client().Get(frontend.URL)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ body, _ := io.ReadAll(res.Body)
+ if got, want := string(body), content; got != want {
+ t.Errorf("got response %q, want %q", got, want)
+ }
+}
+
+func Test1xxResponses(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Add("Link", "; rel=preload; as=style")
+ h.Add("Link", "; rel=preload; as=script")
+ w.WriteHeader(http.StatusEarlyHints)
+
+ h.Add("Link", "; rel=preload; as=script")
+ w.WriteHeader(http.StatusProcessing)
+
+ w.Write([]byte("Hello"))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := NewSingleHostReverseProxy(backendURL)
+ proxyHandler.ErrorLog = log.New(io.Discard, "", 0) // quiet for tests
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+ frontendClient := frontend.Client()
+
+ checkLinkHeaders := func(t *testing.T, expected, got []string) {
+ t.Helper()
+
+ if len(expected) != len(got) {
+ t.Errorf("Expected %d link headers; got %d", len(expected), len(got))
+ }
+
+ for i := range expected {
+ if i >= len(got) {
+ t.Errorf("Expected %q link header; got nothing", expected[i])
+
+ continue
+ }
+
+ if expected[i] != got[i] {
+ t.Errorf("Expected %q link header; got %q", expected[i], got[i])
+ }
+ }
+ }
+
+ var respCounter uint8
+ trace := &httptrace.ClientTrace{
+ Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
+ switch code {
+ case http.StatusEarlyHints:
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script"}, header["Link"])
+ case http.StatusProcessing:
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script", "; rel=preload; as=script"}, header["Link"])
+ default:
+ t.Error("Unexpected 1xx response")
+ }
+
+ respCounter++
+
+ return nil
+ },
+ }
+ req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), "GET", frontend.URL, nil)
+
+ res, err := frontendClient.Do(req)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+
+ defer res.Body.Close()
+
+ if respCounter != 2 {
+ t.Errorf("Expected 2 1xx responses; got %d", respCounter)
+ }
+ checkLinkHeaders(t, []string{"; rel=preload; as=style", "; rel=preload; as=script", "; rel=preload; as=script"}, res.Header["Link"])
+
+ body, _ := io.ReadAll(res.Body)
+ if string(body) != "Hello" {
+ t.Errorf("Read body %q; want Hello", body)
+ }
+}
+
+const (
+ testWantsCleanQuery = true
+ testWantsRawQuery = false
+)
+
+func TestReverseProxyQueryParameterSmugglingDirectorDoesNotParseForm(t *testing.T) {
+ testReverseProxyQueryParameterSmuggling(t, testWantsRawQuery, func(u *url.URL) *ReverseProxy {
+ proxyHandler := NewSingleHostReverseProxy(u)
+ oldDirector := proxyHandler.Director
+ proxyHandler.Director = func(r *http.Request) {
+ oldDirector(r)
+ }
+ return proxyHandler
+ })
+}
+
+func TestReverseProxyQueryParameterSmugglingDirectorParsesForm(t *testing.T) {
+ testReverseProxyQueryParameterSmuggling(t, testWantsCleanQuery, func(u *url.URL) *ReverseProxy {
+ proxyHandler := NewSingleHostReverseProxy(u)
+ oldDirector := proxyHandler.Director
+ proxyHandler.Director = func(r *http.Request) {
+ // Parsing the form causes ReverseProxy to remove unparsable
+ // query parameters before forwarding.
+ r.FormValue("a")
+ oldDirector(r)
+ }
+ return proxyHandler
+ })
+}
+
+func TestReverseProxyQueryParameterSmugglingRewrite(t *testing.T) {
+ testReverseProxyQueryParameterSmuggling(t, testWantsCleanQuery, func(u *url.URL) *ReverseProxy {
+ return &ReverseProxy{
+ Rewrite: func(r *ProxyRequest) {
+ r.SetURL(u)
+ },
+ }
+ })
+}
+
+func TestReverseProxyQueryParameterSmugglingRewritePreservesRawQuery(t *testing.T) {
+ testReverseProxyQueryParameterSmuggling(t, testWantsRawQuery, func(u *url.URL) *ReverseProxy {
+ return &ReverseProxy{
+ Rewrite: func(r *ProxyRequest) {
+ r.SetURL(u)
+ r.Out.URL.RawQuery = r.In.URL.RawQuery
+ },
+ }
+ })
+}
+
+func testReverseProxyQueryParameterSmuggling(t *testing.T, wantCleanQuery bool, newProxy func(*url.URL) *ReverseProxy) {
+ const content = "response_content"
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(r.URL.RawQuery))
+ }))
+ defer backend.Close()
+ backendURL, err := url.Parse(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxyHandler := newProxy(backendURL)
+ frontend := httptest.NewServer(proxyHandler)
+ defer frontend.Close()
+
+ // Don't spam output with logs of queries containing semicolons.
+ backend.Config.ErrorLog = log.New(io.Discard, "", 0)
+ frontend.Config.ErrorLog = log.New(io.Discard, "", 0)
+
+ for _, test := range []struct {
+ rawQuery string
+ cleanQuery string
+ }{{
+ rawQuery: "a=1&a=2;b=3",
+ cleanQuery: "a=1",
+ }, {
+ rawQuery: "a=1&a=%zz&b=3",
+ cleanQuery: "a=1&b=3",
+ }} {
+ res, err := frontend.Client().Get(frontend.URL + "?" + test.rawQuery)
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer res.Body.Close()
+ body, _ := io.ReadAll(res.Body)
+ wantQuery := test.rawQuery
+ if wantCleanQuery {
+ wantQuery = test.cleanQuery
+ }
+ if got, want := string(body), wantQuery; got != want {
+ t.Errorf("proxy forwarded raw query %q as %q, want %q", test.rawQuery, got, want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print.go b/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print.go
new file mode 100644
index 0000000000000000000000000000000000000000..98dbf4e3d2d56e69d2fcf11300aff85cf26ca202
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print.go
@@ -0,0 +1,61 @@
+// 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 ascii
+
+import (
+ "strings"
+ "unicode"
+)
+
+// EqualFold is [strings.EqualFold], ASCII only. It reports whether s and t
+// are equal, ASCII-case-insensitively.
+func EqualFold(s, t string) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if lower(s[i]) != lower(t[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// lower returns the ASCII lowercase version of b.
+func lower(b byte) byte {
+ if 'A' <= b && b <= 'Z' {
+ return b + ('a' - 'A')
+ }
+ return b
+}
+
+// IsPrint returns whether s is ASCII and printable according to
+// https://tools.ietf.org/html/rfc20#section-4.2.
+func IsPrint(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < ' ' || s[i] > '~' {
+ return false
+ }
+ }
+ return true
+}
+
+// Is returns whether s is ASCII.
+func Is(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] > unicode.MaxASCII {
+ return false
+ }
+ }
+ return true
+}
+
+// ToLower returns the lowercase version of s if s is ASCII and printable.
+func ToLower(s string) (lower string, ok bool) {
+ if !IsPrint(s) {
+ return "", false
+ }
+ return strings.ToLower(s), true
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print_test.go b/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b7767ca331811813fd9729b25c6685d950e4e49
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/internal/ascii/print_test.go
@@ -0,0 +1,95 @@
+// 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 ascii
+
+import "testing"
+
+func TestEqualFold(t *testing.T) {
+ var tests = []struct {
+ name string
+ a, b string
+ want bool
+ }{
+ {
+ name: "empty",
+ want: true,
+ },
+ {
+ name: "simple match",
+ a: "CHUNKED",
+ b: "chunked",
+ want: true,
+ },
+ {
+ name: "same string",
+ a: "chunked",
+ b: "chunked",
+ want: true,
+ },
+ {
+ name: "Unicode Kelvin symbol",
+ a: "chunKed", // This "K" is 'KELVIN SIGN' (\u212A)
+ b: "chunked",
+ want: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := EqualFold(tt.a, tt.b); got != tt.want {
+ t.Errorf("AsciiEqualFold(%q,%q): got %v want %v", tt.a, tt.b, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsPrint(t *testing.T) {
+ var tests = []struct {
+ name string
+ in string
+ want bool
+ }{
+ {
+ name: "empty",
+ want: true,
+ },
+ {
+ name: "ASCII low",
+ in: "This is a space: ' '",
+ want: true,
+ },
+ {
+ name: "ASCII high",
+ in: "This is a tilde: '~'",
+ want: true,
+ },
+ {
+ name: "ASCII low non-print",
+ in: "This is a unit separator: \x1F",
+ want: false,
+ },
+ {
+ name: "Ascii high non-print",
+ in: "This is a Delete: \x7F",
+ want: false,
+ },
+ {
+ name: "Unicode letter",
+ in: "Today it's 280K outside: it's freezing!", // This "K" is 'KELVIN SIGN' (\u212A)
+ want: false,
+ },
+ {
+ name: "Unicode emoji",
+ in: "Gophers like 🧀",
+ want: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsPrint(tt.in); got != tt.want {
+ t.Errorf("IsASCIIPrint(%q): got %v want %v", tt.in, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/internal/chunked.go b/platform/dbops/binaries/go/go/src/net/http/internal/chunked.go
new file mode 100644
index 0000000000000000000000000000000000000000..196b5d892589ab104b9acf80b12e7237fb684bf2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/internal/chunked.go
@@ -0,0 +1,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.
+
+// The wire protocol for HTTP's "chunked" Transfer-Encoding.
+
+// Package internal contains HTTP internals shared by net/http and
+// net/http/httputil.
+package internal
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+)
+
+const maxLineLength = 4096 // assumed <= bufio.defaultBufSize
+
+var ErrLineTooLong = errors.New("header line too long")
+
+// NewChunkedReader returns a new chunkedReader that translates the data read from r
+// out of HTTP "chunked" format before returning it.
+// The chunkedReader returns [io.EOF] when the final 0-length chunk is read.
+//
+// NewChunkedReader is not needed by normal applications. The http package
+// automatically decodes chunking when reading response bodies.
+func NewChunkedReader(r io.Reader) io.Reader {
+ br, ok := r.(*bufio.Reader)
+ if !ok {
+ br = bufio.NewReader(r)
+ }
+ return &chunkedReader{r: br}
+}
+
+type chunkedReader struct {
+ r *bufio.Reader
+ n uint64 // unread bytes in chunk
+ err error
+ buf [2]byte
+ checkEnd bool // whether need to check for \r\n chunk footer
+ excess int64 // "excessive" chunk overhead, for malicious sender detection
+}
+
+func (cr *chunkedReader) beginChunk() {
+ // chunk-size CRLF
+ var line []byte
+ line, cr.err = readChunkLine(cr.r)
+ if cr.err != nil {
+ return
+ }
+ cr.excess += int64(len(line)) + 2 // header, plus \r\n after the chunk data
+ line = trimTrailingWhitespace(line)
+ line, cr.err = removeChunkExtension(line)
+ if cr.err != nil {
+ return
+ }
+ cr.n, cr.err = parseHexUint(line)
+ if cr.err != nil {
+ return
+ }
+ // A sender who sends one byte per chunk will send 5 bytes of overhead
+ // for every byte of data. ("1\r\nX\r\n" to send "X".)
+ // We want to allow this, since streaming a byte at a time can be legitimate.
+ //
+ // A sender can use chunk extensions to add arbitrary amounts of additional
+ // data per byte read. ("1;very long extension\r\nX\r\n" to send "X".)
+ // We don't want to disallow extensions (although we discard them),
+ // but we also don't want to allow a sender to reduce the signal/noise ratio
+ // arbitrarily.
+ //
+ // We track the amount of excess overhead read,
+ // and produce an error if it grows too large.
+ //
+ // Currently, we say that we're willing to accept 16 bytes of overhead per chunk,
+ // plus twice the amount of real data in the chunk.
+ cr.excess -= 16 + (2 * int64(cr.n))
+ cr.excess = max(cr.excess, 0)
+ if cr.excess > 16*1024 {
+ cr.err = errors.New("chunked encoding contains too much non-data")
+ }
+ if cr.n == 0 {
+ cr.err = io.EOF
+ }
+}
+
+func (cr *chunkedReader) chunkHeaderAvailable() bool {
+ n := cr.r.Buffered()
+ if n > 0 {
+ peek, _ := cr.r.Peek(n)
+ return bytes.IndexByte(peek, '\n') >= 0
+ }
+ return false
+}
+
+func (cr *chunkedReader) Read(b []uint8) (n int, err error) {
+ for cr.err == nil {
+ if cr.checkEnd {
+ if n > 0 && cr.r.Buffered() < 2 {
+ // We have some data. Return early (per the io.Reader
+ // contract) instead of potentially blocking while
+ // reading more.
+ break
+ }
+ if _, cr.err = io.ReadFull(cr.r, cr.buf[:2]); cr.err == nil {
+ if string(cr.buf[:]) != "\r\n" {
+ cr.err = errors.New("malformed chunked encoding")
+ break
+ }
+ } else {
+ if cr.err == io.EOF {
+ cr.err = io.ErrUnexpectedEOF
+ }
+ break
+ }
+ cr.checkEnd = false
+ }
+ if cr.n == 0 {
+ if n > 0 && !cr.chunkHeaderAvailable() {
+ // We've read enough. Don't potentially block
+ // reading a new chunk header.
+ break
+ }
+ cr.beginChunk()
+ continue
+ }
+ if len(b) == 0 {
+ break
+ }
+ rbuf := b
+ if uint64(len(rbuf)) > cr.n {
+ rbuf = rbuf[:cr.n]
+ }
+ var n0 int
+ n0, cr.err = cr.r.Read(rbuf)
+ n += n0
+ b = b[n0:]
+ cr.n -= uint64(n0)
+ // If we're at the end of a chunk, read the next two
+ // bytes to verify they are "\r\n".
+ if cr.n == 0 && cr.err == nil {
+ cr.checkEnd = true
+ } else if cr.err == io.EOF {
+ cr.err = io.ErrUnexpectedEOF
+ }
+ }
+ return n, cr.err
+}
+
+// Read a line of bytes (up to \n) from b.
+// Give up if the line exceeds maxLineLength.
+// The returned bytes are owned by the bufio.Reader
+// so they are only valid until the next bufio read.
+func readChunkLine(b *bufio.Reader) ([]byte, error) {
+ p, err := b.ReadSlice('\n')
+ if err != nil {
+ // We always know when EOF is coming.
+ // If the caller asked for a line, there should be a line.
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ } else if err == bufio.ErrBufferFull {
+ err = ErrLineTooLong
+ }
+ return nil, err
+ }
+ if len(p) >= maxLineLength {
+ return nil, ErrLineTooLong
+ }
+ return p, nil
+}
+
+func trimTrailingWhitespace(b []byte) []byte {
+ for len(b) > 0 && isASCIISpace(b[len(b)-1]) {
+ b = b[:len(b)-1]
+ }
+ return b
+}
+
+func isASCIISpace(b byte) bool {
+ return b == ' ' || b == '\t' || b == '\n' || b == '\r'
+}
+
+var semi = []byte(";")
+
+// removeChunkExtension removes any chunk-extension from p.
+// For example,
+//
+// "0" => "0"
+// "0;token" => "0"
+// "0;token=val" => "0"
+// `0;token="quoted string"` => "0"
+func removeChunkExtension(p []byte) ([]byte, error) {
+ p, _, _ = bytes.Cut(p, semi)
+ // TODO: care about exact syntax of chunk extensions? We're
+ // ignoring and stripping them anyway. For now just never
+ // return an error.
+ return p, nil
+}
+
+// NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP
+// "chunked" format before writing them to w. Closing the returned chunkedWriter
+// sends the final 0-length chunk that marks the end of the stream but does
+// not send the final CRLF that appears after trailers; trailers and the last
+// CRLF must be written separately.
+//
+// NewChunkedWriter is not needed by normal applications. The http
+// package adds chunking automatically if handlers don't set a
+// Content-Length header. Using newChunkedWriter inside a handler
+// would result in double chunking or chunking with a Content-Length
+// length, both of which are wrong.
+func NewChunkedWriter(w io.Writer) io.WriteCloser {
+ return &chunkedWriter{w}
+}
+
+// Writing to chunkedWriter translates to writing in HTTP chunked Transfer
+// Encoding wire format to the underlying Wire chunkedWriter.
+type chunkedWriter struct {
+ Wire io.Writer
+}
+
+// Write the contents of data as one chunk to Wire.
+// NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has
+// a bug since it does not check for success of [io.WriteString]
+func (cw *chunkedWriter) Write(data []byte) (n int, err error) {
+
+ // Don't send 0-length data. It looks like EOF for chunked encoding.
+ if len(data) == 0 {
+ return 0, nil
+ }
+
+ if _, err = fmt.Fprintf(cw.Wire, "%x\r\n", len(data)); err != nil {
+ return 0, err
+ }
+ if n, err = cw.Wire.Write(data); err != nil {
+ return
+ }
+ if n != len(data) {
+ err = io.ErrShortWrite
+ return
+ }
+ if _, err = io.WriteString(cw.Wire, "\r\n"); err != nil {
+ return
+ }
+ if bw, ok := cw.Wire.(*FlushAfterChunkWriter); ok {
+ err = bw.Flush()
+ }
+ return
+}
+
+func (cw *chunkedWriter) Close() error {
+ _, err := io.WriteString(cw.Wire, "0\r\n")
+ return err
+}
+
+// FlushAfterChunkWriter signals from the caller of [NewChunkedWriter]
+// that each chunk should be followed by a flush. It is used by the
+// [net/http.Transport] code to keep the buffering behavior for headers and
+// trailers, but flush out chunks aggressively in the middle for
+// request bodies which may be generated slowly. See Issue 6574.
+type FlushAfterChunkWriter struct {
+ *bufio.Writer
+}
+
+func parseHexUint(v []byte) (n uint64, err error) {
+ if len(v) == 0 {
+ return 0, errors.New("empty hex number for chunk length")
+ }
+ for i, b := range v {
+ switch {
+ case '0' <= b && b <= '9':
+ b = b - '0'
+ case 'a' <= b && b <= 'f':
+ b = b - 'a' + 10
+ case 'A' <= b && b <= 'F':
+ b = b - 'A' + 10
+ default:
+ return 0, errors.New("invalid byte in chunk length")
+ }
+ if i == 16 {
+ return 0, errors.New("http chunk length too large")
+ }
+ n <<= 4
+ n |= uint64(b)
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/internal/chunked_test.go b/platform/dbops/binaries/go/go/src/net/http/internal/chunked_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..af79711781a7edaf2479e2cc11d2e2233ee0cca9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/internal/chunked_test.go
@@ -0,0 +1,301 @@
+// 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 internal
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "strings"
+ "testing"
+ "testing/iotest"
+)
+
+func TestChunk(t *testing.T) {
+ var b bytes.Buffer
+
+ w := NewChunkedWriter(&b)
+ const chunk1 = "hello, "
+ const chunk2 = "world! 0123456789abcdef"
+ w.Write([]byte(chunk1))
+ w.Write([]byte(chunk2))
+ w.Close()
+
+ if g, e := b.String(), "7\r\nhello, \r\n17\r\nworld! 0123456789abcdef\r\n0\r\n"; g != e {
+ t.Fatalf("chunk writer wrote %q; want %q", g, e)
+ }
+
+ r := NewChunkedReader(&b)
+ data, err := io.ReadAll(r)
+ if err != nil {
+ t.Logf(`data: "%s"`, data)
+ t.Fatalf("ReadAll from reader: %v", err)
+ }
+ if g, e := string(data), chunk1+chunk2; g != e {
+ t.Errorf("chunk reader read %q; want %q", g, e)
+ }
+}
+
+func TestChunkReadMultiple(t *testing.T) {
+ // Bunch of small chunks, all read together.
+ {
+ var b bytes.Buffer
+ w := NewChunkedWriter(&b)
+ w.Write([]byte("foo"))
+ w.Write([]byte("bar"))
+ w.Close()
+
+ r := NewChunkedReader(&b)
+ buf := make([]byte, 10)
+ n, err := r.Read(buf)
+ if n != 6 || err != io.EOF {
+ t.Errorf("Read = %d, %v; want 6, EOF", n, err)
+ }
+ buf = buf[:n]
+ if string(buf) != "foobar" {
+ t.Errorf("Read = %q; want %q", buf, "foobar")
+ }
+ }
+
+ // One big chunk followed by a little chunk, but the small bufio.Reader size
+ // should prevent the second chunk header from being read.
+ {
+ var b bytes.Buffer
+ w := NewChunkedWriter(&b)
+ // fillBufChunk is 11 bytes + 3 bytes header + 2 bytes footer = 16 bytes,
+ // the same as the bufio ReaderSize below (the minimum), so even
+ // though we're going to try to Read with a buffer larger enough to also
+ // receive "foo", the second chunk header won't be read yet.
+ const fillBufChunk = "0123456789a"
+ const shortChunk = "foo"
+ w.Write([]byte(fillBufChunk))
+ w.Write([]byte(shortChunk))
+ w.Close()
+
+ r := NewChunkedReader(bufio.NewReaderSize(&b, 16))
+ buf := make([]byte, len(fillBufChunk)+len(shortChunk))
+ n, err := r.Read(buf)
+ if n != len(fillBufChunk) || err != nil {
+ t.Errorf("Read = %d, %v; want %d, nil", n, err, len(fillBufChunk))
+ }
+ buf = buf[:n]
+ if string(buf) != fillBufChunk {
+ t.Errorf("Read = %q; want %q", buf, fillBufChunk)
+ }
+
+ n, err = r.Read(buf)
+ if n != len(shortChunk) || err != io.EOF {
+ t.Errorf("Read = %d, %v; want %d, EOF", n, err, len(shortChunk))
+ }
+ }
+
+ // And test that we see an EOF chunk, even though our buffer is already full:
+ {
+ r := NewChunkedReader(bufio.NewReader(strings.NewReader("3\r\nfoo\r\n0\r\n")))
+ buf := make([]byte, 3)
+ n, err := r.Read(buf)
+ if n != 3 || err != io.EOF {
+ t.Errorf("Read = %d, %v; want 3, EOF", n, err)
+ }
+ if string(buf) != "foo" {
+ t.Errorf("buf = %q; want foo", buf)
+ }
+ }
+}
+
+func TestChunkReaderAllocs(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping in short mode")
+ }
+ var buf bytes.Buffer
+ w := NewChunkedWriter(&buf)
+ a, b, c := []byte("aaaaaa"), []byte("bbbbbbbbbbbb"), []byte("cccccccccccccccccccccccc")
+ w.Write(a)
+ w.Write(b)
+ w.Write(c)
+ w.Close()
+
+ readBuf := make([]byte, len(a)+len(b)+len(c)+1)
+ byter := bytes.NewReader(buf.Bytes())
+ bufr := bufio.NewReader(byter)
+ mallocs := testing.AllocsPerRun(100, func() {
+ byter.Seek(0, io.SeekStart)
+ bufr.Reset(byter)
+ r := NewChunkedReader(bufr)
+ n, err := io.ReadFull(r, readBuf)
+ if n != len(readBuf)-1 {
+ t.Fatalf("read %d bytes; want %d", n, len(readBuf)-1)
+ }
+ if err != io.ErrUnexpectedEOF {
+ t.Fatalf("read error = %v; want ErrUnexpectedEOF", err)
+ }
+ })
+ if mallocs > 1.5 {
+ t.Errorf("mallocs = %v; want 1", mallocs)
+ }
+}
+
+func TestParseHexUint(t *testing.T) {
+ type testCase struct {
+ in string
+ want uint64
+ wantErr string
+ }
+ tests := []testCase{
+ {"x", 0, "invalid byte in chunk length"},
+ {"0000000000000000", 0, ""},
+ {"0000000000000001", 1, ""},
+ {"ffffffffffffffff", 1<<64 - 1, ""},
+ {"000000000000bogus", 0, "invalid byte in chunk length"},
+ {"00000000000000000", 0, "http chunk length too large"}, // could accept if we wanted
+ {"10000000000000000", 0, "http chunk length too large"},
+ {"00000000000000001", 0, "http chunk length too large"}, // could accept if we wanted
+ {"", 0, "empty hex number for chunk length"},
+ }
+ for i := uint64(0); i <= 1234; i++ {
+ tests = append(tests, testCase{in: fmt.Sprintf("%x", i), want: i})
+ }
+ for _, tt := range tests {
+ got, err := parseHexUint([]byte(tt.in))
+ if tt.wantErr != "" {
+ if !strings.Contains(fmt.Sprint(err), tt.wantErr) {
+ t.Errorf("parseHexUint(%q) = %v, %v; want error %q", tt.in, got, err, tt.wantErr)
+ }
+ } else {
+ if err != nil || got != tt.want {
+ t.Errorf("parseHexUint(%q) = %v, %v; want %v", tt.in, got, err, tt.want)
+ }
+ }
+ }
+}
+
+func TestChunkReadingIgnoresExtensions(t *testing.T) {
+ in := "7;ext=\"some quoted string\"\r\n" + // token=quoted string
+ "hello, \r\n" +
+ "17;someext\r\n" + // token without value
+ "world! 0123456789abcdef\r\n" +
+ "0;someextension=sometoken\r\n" // token=token
+ data, err := io.ReadAll(NewChunkedReader(strings.NewReader(in)))
+ if err != nil {
+ t.Fatalf("ReadAll = %q, %v", data, err)
+ }
+ if g, e := string(data), "hello, world! 0123456789abcdef"; g != e {
+ t.Errorf("read %q; want %q", g, e)
+ }
+}
+
+// Issue 17355: ChunkedReader shouldn't block waiting for more data
+// if it can return something.
+func TestChunkReadPartial(t *testing.T) {
+ pr, pw := io.Pipe()
+ go func() {
+ pw.Write([]byte("7\r\n1234567"))
+ }()
+ cr := NewChunkedReader(pr)
+ readBuf := make([]byte, 7)
+ n, err := cr.Read(readBuf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "1234567"
+ if n != 7 || string(readBuf) != want {
+ t.Fatalf("Read: %v %q; want %d, %q", n, readBuf[:n], len(want), want)
+ }
+ go func() {
+ pw.Write([]byte("xx"))
+ }()
+ _, err = cr.Read(readBuf)
+ if got := fmt.Sprint(err); !strings.Contains(got, "malformed") {
+ t.Fatalf("second read = %v; want malformed error", err)
+ }
+
+}
+
+// Issue 48861: ChunkedReader should report incomplete chunks
+func TestIncompleteChunk(t *testing.T) {
+ const valid = "4\r\nabcd\r\n" + "5\r\nabc\r\n\r\n" + "0\r\n"
+
+ for i := 0; i < len(valid); i++ {
+ incomplete := valid[:i]
+ r := NewChunkedReader(strings.NewReader(incomplete))
+ if _, err := io.ReadAll(r); err != io.ErrUnexpectedEOF {
+ t.Errorf("expected io.ErrUnexpectedEOF for %q, got %v", incomplete, err)
+ }
+ }
+
+ r := NewChunkedReader(strings.NewReader(valid))
+ if _, err := io.ReadAll(r); err != nil {
+ t.Errorf("unexpected error for %q: %v", valid, err)
+ }
+}
+
+func TestChunkEndReadError(t *testing.T) {
+ readErr := fmt.Errorf("chunk end read error")
+
+ r := NewChunkedReader(io.MultiReader(strings.NewReader("4\r\nabcd"), iotest.ErrReader(readErr)))
+ if _, err := io.ReadAll(r); err != readErr {
+ t.Errorf("expected %v, got %v", readErr, err)
+ }
+}
+
+func TestChunkReaderTooMuchOverhead(t *testing.T) {
+ // If the sender is sending 100x as many chunk header bytes as chunk data,
+ // we should reject the stream at some point.
+ chunk := []byte("1;")
+ for i := 0; i < 100; i++ {
+ chunk = append(chunk, 'a') // chunk extension
+ }
+ chunk = append(chunk, "\r\nX\r\n"...)
+ const bodylen = 1 << 20
+ r := NewChunkedReader(&funcReader{f: func(i int) ([]byte, error) {
+ if i < bodylen {
+ return chunk, nil
+ }
+ return []byte("0\r\n"), nil
+ }})
+ _, err := io.ReadAll(r)
+ if err == nil {
+ t.Fatalf("successfully read body with excessive overhead; want error")
+ }
+}
+
+func TestChunkReaderByteAtATime(t *testing.T) {
+ // Sending one byte per chunk should not trip the excess-overhead detection.
+ const bodylen = 1 << 20
+ r := NewChunkedReader(&funcReader{f: func(i int) ([]byte, error) {
+ if i < bodylen {
+ return []byte("1\r\nX\r\n"), nil
+ }
+ return []byte("0\r\n"), nil
+ }})
+ got, err := io.ReadAll(r)
+ if err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+ if len(got) != bodylen {
+ t.Errorf("read %v bytes, want %v", len(got), bodylen)
+ }
+}
+
+type funcReader struct {
+ f func(iteration int) ([]byte, error)
+ i int
+ b []byte
+ err error
+}
+
+func (r *funcReader) Read(p []byte) (n int, err error) {
+ if len(r.b) == 0 && r.err == nil {
+ r.b, r.err = r.f(r.i)
+ r.i++
+ }
+ n = copy(p, r.b)
+ r.b = r.b[n:]
+ if len(r.b) > 0 {
+ return n, nil
+ }
+ return n, r.err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/internal/testcert/testcert.go b/platform/dbops/binaries/go/go/src/net/http/internal/testcert/testcert.go
new file mode 100644
index 0000000000000000000000000000000000000000..d510e791d617cb778d13c481b393c58f683776f2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/internal/testcert/testcert.go
@@ -0,0 +1,65 @@
+// 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.
+
+// Package testcert contains a test-only localhost certificate.
+package testcert
+
+import "strings"
+
+// LocalhostCert is a PEM-encoded TLS cert with SAN IPs
+// "127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT.
+// generated from src/crypto/tls:
+// go run generate_cert.go --rsa-bits 2048 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h
+var LocalhostCert = []byte(`-----BEGIN CERTIFICATE-----
+MIIDOTCCAiGgAwIBAgIQSRJrEpBGFc7tNb1fb5pKFzANBgkqhkiG9w0BAQsFADAS
+MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw
+MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
+MIIBCgKCAQEA6Gba5tHV1dAKouAaXO3/ebDUU4rvwCUg/CNaJ2PT5xLD4N1Vcb8r
+bFSW2HXKq+MPfVdwIKR/1DczEoAGf/JWQTW7EgzlXrCd3rlajEX2D73faWJekD0U
+aUgz5vtrTXZ90BQL7WvRICd7FlEZ6FPOcPlumiyNmzUqtwGhO+9ad1W5BqJaRI6P
+YfouNkwR6Na4TzSj5BrqUfP0FwDizKSJ0XXmh8g8G9mtwxOSN3Ru1QFc61Xyeluk
+POGKBV/q6RBNklTNe0gI8usUMlYyoC7ytppNMW7X2vodAelSu25jgx2anj9fDVZu
+h7AXF5+4nJS4AAt0n1lNY7nGSsdZas8PbQIDAQABo4GIMIGFMA4GA1UdDwEB/wQE
+AwICpDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud
+DgQWBBStsdjh3/JCXXYlQryOrL4Sh7BW5TAuBgNVHREEJzAlggtleGFtcGxlLmNv
+bYcEfwAAAYcQAAAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQsFAAOCAQEAxWGI
+5NhpF3nwwy/4yB4i/CwwSpLrWUa70NyhvprUBC50PxiXav1TeDzwzLx/o5HyNwsv
+cxv3HdkLW59i/0SlJSrNnWdfZ19oTcS+6PtLoVyISgtyN6DpkKpdG1cOkW3Cy2P2
++tK/tKHRP1Y/Ra0RiDpOAmqn0gCOFGz8+lqDIor/T7MTpibL3IxqWfPrvfVRHL3B
+grw/ZQTTIVjjh4JBSW3WyWgNo/ikC1lrVxzl4iPUGptxT36Cr7Zk2Bsg0XqwbOvK
+5d+NTDREkSnUbie4GeutujmX3Dsx88UiV6UY/4lHJa6I5leHUNOHahRbpbWeOfs/
+WkBKOclmOV2xlTVuPw==
+-----END CERTIFICATE-----`)
+
+// LocalhostKey is the private key for LocalhostCert.
+var LocalhostKey = []byte(testingKey(`-----BEGIN RSA TESTING KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDoZtrm0dXV0Aqi
+4Bpc7f95sNRTiu/AJSD8I1onY9PnEsPg3VVxvytsVJbYdcqr4w99V3AgpH/UNzMS
+gAZ/8lZBNbsSDOVesJ3euVqMRfYPvd9pYl6QPRRpSDPm+2tNdn3QFAvta9EgJ3sW
+URnoU85w+W6aLI2bNSq3AaE771p3VbkGolpEjo9h+i42TBHo1rhPNKPkGupR8/QX
+AOLMpInRdeaHyDwb2a3DE5I3dG7VAVzrVfJ6W6Q84YoFX+rpEE2SVM17SAjy6xQy
+VjKgLvK2mk0xbtfa+h0B6VK7bmODHZqeP18NVm6HsBcXn7iclLgAC3SfWU1jucZK
+x1lqzw9tAgMBAAECggEABWzxS1Y2wckblnXY57Z+sl6YdmLV+gxj2r8Qib7g4ZIk
+lIlWR1OJNfw7kU4eryib4fc6nOh6O4AWZyYqAK6tqNQSS/eVG0LQTLTTEldHyVJL
+dvBe+MsUQOj4nTndZW+QvFzbcm2D8lY5n2nBSxU5ypVoKZ1EqQzytFcLZpTN7d89
+EPj0qDyrV4NZlWAwL1AygCwnlwhMQjXEalVF1ylXwU3QzyZ/6MgvF6d3SSUlh+sq
+XefuyigXw484cQQgbzopv6niMOmGP3of+yV4JQqUSb3IDmmT68XjGd2Dkxl4iPki
+6ZwXf3CCi+c+i/zVEcufgZ3SLf8D99kUGE7v7fZ6AQKBgQD1ZX3RAla9hIhxCf+O
+3D+I1j2LMrdjAh0ZKKqwMR4JnHX3mjQI6LwqIctPWTU8wYFECSh9klEclSdCa64s
+uI/GNpcqPXejd0cAAdqHEEeG5sHMDt0oFSurL4lyud0GtZvwlzLuwEweuDtvT9cJ
+Wfvl86uyO36IW8JdvUprYDctrQKBgQDycZ697qutBieZlGkHpnYWUAeImVA878sJ
+w44NuXHvMxBPz+lbJGAg8Cn8fcxNAPqHIraK+kx3po8cZGQywKHUWsxi23ozHoxo
++bGqeQb9U661TnfdDspIXia+xilZt3mm5BPzOUuRqlh4Y9SOBpSWRmEhyw76w4ZP
+OPxjWYAgwQKBgA/FehSYxeJgRjSdo+MWnK66tjHgDJE8bYpUZsP0JC4R9DL5oiaA
+brd2fI6Y+SbyeNBallObt8LSgzdtnEAbjIH8uDJqyOmknNePRvAvR6mP4xyuR+Bv
+m+Lgp0DMWTw5J9CKpydZDItc49T/mJ5tPhdFVd+am0NAQnmr1MCZ6nHxAoGABS3Y
+LkaC9FdFUUqSU8+Chkd/YbOkuyiENdkvl6t2e52jo5DVc1T7mLiIrRQi4SI8N9bN
+/3oJWCT+uaSLX2ouCtNFunblzWHBrhxnZzTeqVq4SLc8aESAnbslKL4i8/+vYZlN
+s8xtiNcSvL+lMsOBORSXzpj/4Ot8WwTkn1qyGgECgYBKNTypzAHeLE6yVadFp3nQ
+Ckq9yzvP/ib05rvgbvrne00YeOxqJ9gtTrzgh7koqJyX1L4NwdkEza4ilDWpucn0
+xiUZS4SoaJq6ZvcBYS62Yr1t8n09iG47YL8ibgtmH3L+svaotvpVxVK+d7BLevA/
+ZboOWVe3icTy64BT3OQhmg==
+-----END RSA TESTING KEY-----`))
+
+func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
diff --git a/platform/dbops/binaries/go/go/src/net/http/jar.go b/platform/dbops/binaries/go/go/src/net/http/jar.go
new file mode 100644
index 0000000000000000000000000000000000000000..5c3de0dad254086d39c4176f4477161d50530065
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/jar.go
@@ -0,0 +1,27 @@
+// 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 http
+
+import (
+ "net/url"
+)
+
+// A CookieJar manages storage and use of cookies in HTTP requests.
+//
+// Implementations of CookieJar must be safe for concurrent use by multiple
+// goroutines.
+//
+// The net/http/cookiejar package provides a CookieJar implementation.
+type CookieJar interface {
+ // SetCookies handles the receipt of the cookies in a reply for the
+ // given URL. It may or may not choose to save the cookies, depending
+ // on the jar's policy and implementation.
+ SetCookies(u *url.URL, cookies []*Cookie)
+
+ // Cookies returns the cookies to send in a request for the given URL.
+ // It is up to the implementation to honor the standard cookie use
+ // restrictions such as in RFC 6265.
+ Cookies(u *url.URL) []*Cookie
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/main_test.go b/platform/dbops/binaries/go/go/src/net/http/main_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ff56ef883d834cd27d22e7372e8a9747a25cc72a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/main_test.go
@@ -0,0 +1,175 @@
+// 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 http_test
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "runtime"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+var quietLog = log.New(io.Discard, "", 0)
+
+func TestMain(m *testing.M) {
+ *http.MaxWriteWaitBeforeConnReuse = 60 * time.Minute
+ v := m.Run()
+ if v == 0 && goroutineLeaked() {
+ os.Exit(1)
+ }
+ os.Exit(v)
+}
+
+func interestingGoroutines() (gs []string) {
+ buf := make([]byte, 2<<20)
+ buf = buf[:runtime.Stack(buf, true)]
+ for _, g := range strings.Split(string(buf), "\n\n") {
+ _, stack, _ := strings.Cut(g, "\n")
+ stack = strings.TrimSpace(stack)
+ if stack == "" ||
+ strings.Contains(stack, "testing.(*M).before.func1") ||
+ strings.Contains(stack, "os/signal.signal_recv") ||
+ strings.Contains(stack, "created by net.startServer") ||
+ strings.Contains(stack, "created by testing.RunTests") ||
+ strings.Contains(stack, "closeWriteAndWait") ||
+ strings.Contains(stack, "testing.Main(") ||
+ // These only show up with GOTRACEBACK=2; Issue 5005 (comment 28)
+ strings.Contains(stack, "runtime.goexit") ||
+ strings.Contains(stack, "created by runtime.gc") ||
+ strings.Contains(stack, "interestingGoroutines") ||
+ strings.Contains(stack, "runtime.MHeap_Scavenger") {
+ continue
+ }
+ gs = append(gs, stack)
+ }
+ sort.Strings(gs)
+ return
+}
+
+// Verify the other tests didn't leave any goroutines running.
+func goroutineLeaked() bool {
+ if testing.Short() || runningBenchmarks() {
+ // Don't worry about goroutine leaks in -short mode or in
+ // benchmark mode. Too distracting when there are false positives.
+ return false
+ }
+
+ var stackCount map[string]int
+ for i := 0; i < 5; i++ {
+ n := 0
+ stackCount = make(map[string]int)
+ gs := interestingGoroutines()
+ for _, g := range gs {
+ stackCount[g]++
+ n++
+ }
+ if n == 0 {
+ return false
+ }
+ // Wait for goroutines to schedule and die off:
+ time.Sleep(100 * time.Millisecond)
+ }
+ fmt.Fprintf(os.Stderr, "Too many goroutines running after net/http test(s).\n")
+ for stack, count := range stackCount {
+ fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
+ }
+ return true
+}
+
+// setParallel marks t as a parallel test if we're in short mode
+// (all.bash), but as a serial test otherwise. Using t.Parallel isn't
+// compatible with the afterTest func in non-short mode.
+func setParallel(t *testing.T) {
+ if strings.Contains(t.Name(), "HTTP2") {
+ http.CondSkipHTTP2(t)
+ }
+ if testing.Short() {
+ t.Parallel()
+ }
+}
+
+func runningBenchmarks() bool {
+ for i, arg := range os.Args {
+ if strings.HasPrefix(arg, "-test.bench=") && !strings.HasSuffix(arg, "=") {
+ return true
+ }
+ if arg == "-test.bench" && i < len(os.Args)-1 && os.Args[i+1] != "" {
+ return true
+ }
+ }
+ return false
+}
+
+var leakReported bool
+
+func afterTest(t testing.TB) {
+ http.DefaultTransport.(*http.Transport).CloseIdleConnections()
+ if testing.Short() {
+ return
+ }
+ if leakReported {
+ // To avoid confusion, only report the first leak of each test run.
+ // After the first leak has been reported, we can't tell whether the leaked
+ // goroutines are a new leak from a subsequent test or just the same
+ // goroutines from the first leak still hanging around, and we may add a lot
+ // of latency waiting for them to exit at the end of each test.
+ return
+ }
+
+ // We shouldn't be running the leak check for parallel tests, because we might
+ // report the goroutines from a test that is still running as a leak from a
+ // completely separate test that has just finished. So we use non-atomic loads
+ // and stores for the leakReported variable, and store every time we start a
+ // leak check so that the race detector will flag concurrent leak checks as a
+ // race even if we don't detect any leaks.
+ leakReported = true
+
+ var bad string
+ badSubstring := map[string]string{
+ ").readLoop(": "a Transport",
+ ").writeLoop(": "a Transport",
+ "created by net/http/httptest.(*Server).Start": "an httptest.Server",
+ "timeoutHandler": "a TimeoutHandler",
+ "net.(*netFD).connect(": "a timing out dial",
+ ").noteClientGone(": "a closenotifier sender",
+ }
+ var stacks string
+ for i := 0; i < 10; i++ {
+ bad = ""
+ stacks = strings.Join(interestingGoroutines(), "\n\n")
+ for substr, what := range badSubstring {
+ if strings.Contains(stacks, substr) {
+ bad = what
+ }
+ }
+ if bad == "" {
+ leakReported = false
+ return
+ }
+ // Bad stuff found, but goroutines might just still be
+ // shutting down, so give it some time.
+ time.Sleep(250 * time.Millisecond)
+ }
+ t.Errorf("Test appears to have leaked %s:\n%s", bad, stacks)
+}
+
+// waitCondition waits for fn to return true,
+// checking immediately and then at exponentially increasing intervals.
+func waitCondition(t testing.TB, delay time.Duration, fn func(time.Duration) bool) {
+ t.Helper()
+ start := time.Now()
+ var since time.Duration
+ for !fn(since) {
+ time.Sleep(delay)
+ delay = 2*delay - (delay / 2) // 1.5x, rounded up
+ since = time.Since(start)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/mapping.go b/platform/dbops/binaries/go/go/src/net/http/mapping.go
new file mode 100644
index 0000000000000000000000000000000000000000..87e6d5ae5d3f2e676139b6714151f0d8726513c4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/mapping.go
@@ -0,0 +1,78 @@
+// 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 http
+
+// A mapping is a collection of key-value pairs where the keys are unique.
+// A zero mapping is empty and ready to use.
+// A mapping tries to pick a representation that makes [mapping.find] most efficient.
+type mapping[K comparable, V any] struct {
+ s []entry[K, V] // for few pairs
+ m map[K]V // for many pairs
+}
+
+type entry[K comparable, V any] struct {
+ key K
+ value V
+}
+
+// maxSlice is the maximum number of pairs for which a slice is used.
+// It is a variable for benchmarking.
+var maxSlice int = 8
+
+// add adds a key-value pair to the mapping.
+func (h *mapping[K, V]) add(k K, v V) {
+ if h.m == nil && len(h.s) < maxSlice {
+ h.s = append(h.s, entry[K, V]{k, v})
+ } else {
+ if h.m == nil {
+ h.m = map[K]V{}
+ for _, e := range h.s {
+ h.m[e.key] = e.value
+ }
+ h.s = nil
+ }
+ h.m[k] = v
+ }
+}
+
+// find returns the value corresponding to the given key.
+// The second return value is false if there is no value
+// with that key.
+func (h *mapping[K, V]) find(k K) (v V, found bool) {
+ if h == nil {
+ return v, false
+ }
+ if h.m != nil {
+ v, found = h.m[k]
+ return v, found
+ }
+ for _, e := range h.s {
+ if e.key == k {
+ return e.value, true
+ }
+ }
+ return v, false
+}
+
+// eachPair calls f for each pair in the mapping.
+// If f returns false, pairs returns immediately.
+func (h *mapping[K, V]) eachPair(f func(k K, v V) bool) {
+ if h == nil {
+ return
+ }
+ if h.m != nil {
+ for k, v := range h.m {
+ if !f(k, v) {
+ return
+ }
+ }
+ } else {
+ for _, e := range h.s {
+ if !f(e.key, e.value) {
+ return
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/mapping_test.go b/platform/dbops/binaries/go/go/src/net/http/mapping_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0aed9d9e318c0ae8a5eb27a3fcd9fdf64b97a515
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/mapping_test.go
@@ -0,0 +1,154 @@
+// 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 http
+
+import (
+ "cmp"
+ "fmt"
+ "slices"
+ "strconv"
+ "testing"
+)
+
+func TestMapping(t *testing.T) {
+ var m mapping[int, string]
+ for i := 0; i < maxSlice; i++ {
+ m.add(i, strconv.Itoa(i))
+ }
+ if m.m != nil {
+ t.Fatal("m.m != nil")
+ }
+ for i := 0; i < maxSlice; i++ {
+ g, _ := m.find(i)
+ w := strconv.Itoa(i)
+ if g != w {
+ t.Fatalf("%d: got %s, want %s", i, g, w)
+ }
+ }
+ m.add(4, "4")
+ if m.s != nil {
+ t.Fatal("m.s != nil")
+ }
+ if m.m == nil {
+ t.Fatal("m.m == nil")
+ }
+ g, _ := m.find(4)
+ if w := "4"; g != w {
+ t.Fatalf("got %s, want %s", g, w)
+ }
+}
+
+func TestMappingEachPair(t *testing.T) {
+ var m mapping[int, string]
+ var want []entry[int, string]
+ for i := 0; i < maxSlice*2; i++ {
+ v := strconv.Itoa(i)
+ m.add(i, v)
+ want = append(want, entry[int, string]{i, v})
+
+ }
+
+ var got []entry[int, string]
+ m.eachPair(func(k int, v string) bool {
+ got = append(got, entry[int, string]{k, v})
+ return true
+ })
+ slices.SortFunc(got, func(e1, e2 entry[int, string]) int {
+ return cmp.Compare(e1.key, e2.key)
+ })
+ if !slices.Equal(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+}
+
+func BenchmarkFindChild(b *testing.B) {
+ key := "articles"
+ children := []string{
+ "*",
+ "cmd.html",
+ "code.html",
+ "contrib.html",
+ "contribute.html",
+ "debugging_with_gdb.html",
+ "docs.html",
+ "effective_go.html",
+ "files.log",
+ "gccgo_contribute.html",
+ "gccgo_install.html",
+ "go-logo-black.png",
+ "go-logo-blue.png",
+ "go-logo-white.png",
+ "go1.1.html",
+ "go1.2.html",
+ "go1.html",
+ "go1compat.html",
+ "go_faq.html",
+ "go_mem.html",
+ "go_spec.html",
+ "help.html",
+ "ie.css",
+ "install-source.html",
+ "install.html",
+ "logo-153x55.png",
+ "Makefile",
+ "root.html",
+ "share.png",
+ "sieve.gif",
+ "tos.html",
+ "articles",
+ }
+ if len(children) != 32 {
+ panic("bad len")
+ }
+ for _, n := range []int{2, 4, 8, 16, 32} {
+ list := children[:n]
+ b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
+
+ b.Run("rep=linear", func(b *testing.B) {
+ var entries []entry[string, any]
+ for _, c := range list {
+ entries = append(entries, entry[string, any]{c, nil})
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ findChildLinear(key, entries)
+ }
+ })
+ b.Run("rep=map", func(b *testing.B) {
+ m := map[string]any{}
+ for _, c := range list {
+ m[c] = nil
+ }
+ var x any
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ x = m[key]
+ }
+ _ = x
+ })
+ b.Run(fmt.Sprintf("rep=hybrid%d", maxSlice), func(b *testing.B) {
+ var h mapping[string, any]
+ for _, c := range list {
+ h.add(c, nil)
+ }
+ var x any
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ x, _ = h.find(key)
+ }
+ _ = x
+ })
+ })
+ }
+}
+
+func findChildLinear(key string, entries []entry[string, any]) any {
+ for _, e := range entries {
+ if key == e.key {
+ return e.value
+ }
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/method.go b/platform/dbops/binaries/go/go/src/net/http/method.go
new file mode 100644
index 0000000000000000000000000000000000000000..6f46155069f0e419515444e4ad6593f30ea74067
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/method.go
@@ -0,0 +1,20 @@
+// 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.
+
+package http
+
+// Common HTTP methods.
+//
+// Unless otherwise noted, these are defined in RFC 7231 section 4.3.
+const (
+ MethodGet = "GET"
+ MethodHead = "HEAD"
+ MethodPost = "POST"
+ MethodPut = "PUT"
+ MethodPatch = "PATCH" // RFC 5789
+ MethodDelete = "DELETE"
+ MethodConnect = "CONNECT"
+ MethodOptions = "OPTIONS"
+ MethodTrace = "TRACE"
+)
diff --git a/platform/dbops/binaries/go/go/src/net/http/omithttp2.go b/platform/dbops/binaries/go/go/src/net/http/omithttp2.go
new file mode 100644
index 0000000000000000000000000000000000000000..ca08ddfad83a995ea11607f7c3872b0077dba743
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/omithttp2.go
@@ -0,0 +1,79 @@
+// 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 nethttpomithttp2
+
+package http
+
+import (
+ "errors"
+ "sync"
+ "time"
+)
+
+func init() {
+ omitBundledHTTP2 = true
+}
+
+const noHTTP2 = "no bundled HTTP/2" // should never see this
+
+var http2errRequestCanceled = errors.New("net/http: request canceled")
+
+var http2goAwayTimeout = 1 * time.Second
+
+const http2NextProtoTLS = "h2"
+
+type http2Transport struct {
+ MaxHeaderListSize uint32
+ ConnPool any
+}
+
+func (*http2Transport) RoundTrip(*Request) (*Response, error) { panic(noHTTP2) }
+func (*http2Transport) CloseIdleConnections() {}
+
+type http2noDialH2RoundTripper struct{}
+
+func (http2noDialH2RoundTripper) RoundTrip(*Request) (*Response, error) { panic(noHTTP2) }
+
+type http2noDialClientConnPool struct {
+ http2clientConnPool http2clientConnPool
+}
+
+type http2clientConnPool struct {
+ mu *sync.Mutex
+ conns map[string][]*http2clientConn
+}
+
+type http2clientConn struct{}
+
+type http2clientConnIdleState struct {
+ canTakeNewRequest bool
+}
+
+func (cc *http2clientConn) idleState() http2clientConnIdleState { return http2clientConnIdleState{} }
+
+func http2configureTransports(*Transport) (*http2Transport, error) { panic(noHTTP2) }
+
+func http2isNoCachedConnError(err error) bool {
+ _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
+ return ok
+}
+
+type http2Server struct {
+ NewWriteScheduler func() http2WriteScheduler
+}
+
+type http2WriteScheduler any
+
+func http2NewPriorityWriteScheduler(any) http2WriteScheduler { panic(noHTTP2) }
+
+func http2ConfigureServer(s *Server, conf *http2Server) error { panic(noHTTP2) }
+
+var http2ErrNoCachedConn = http2noCachedConnError{}
+
+type http2noCachedConnError struct{}
+
+func (http2noCachedConnError) IsHTTP2NoCachedConnError() {}
+
+func (http2noCachedConnError) Error() string { return "http2: no cached connection was available" }
diff --git a/platform/dbops/binaries/go/go/src/net/http/pattern.go b/platform/dbops/binaries/go/go/src/net/http/pattern.go
new file mode 100644
index 0000000000000000000000000000000000000000..f6af19b0f4437f0011e50a69ac91eaf636d53257
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/pattern.go
@@ -0,0 +1,529 @@
+// 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.
+
+// Patterns for ServeMux routing.
+
+package http
+
+import (
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+ "unicode"
+)
+
+// A pattern is something that can be matched against an HTTP request.
+// It has an optional method, an optional host, and a path.
+type pattern struct {
+ str string // original string
+ method string
+ host string
+ // The representation of a path differs from the surface syntax, which
+ // simplifies most algorithms.
+ //
+ // Paths ending in '/' are represented with an anonymous "..." wildcard.
+ // For example, the path "a/" is represented as a literal segment "a" followed
+ // by a segment with multi==true.
+ //
+ // Paths ending in "{$}" are represented with the literal segment "/".
+ // For example, the path "a/{$}" is represented as a literal segment "a" followed
+ // by a literal segment "/".
+ segments []segment
+ loc string // source location of registering call, for helpful messages
+}
+
+func (p *pattern) String() string { return p.str }
+
+func (p *pattern) lastSegment() segment {
+ return p.segments[len(p.segments)-1]
+}
+
+// A segment is a pattern piece that matches one or more path segments, or
+// a trailing slash.
+//
+// If wild is false, it matches a literal segment, or, if s == "/", a trailing slash.
+// Examples:
+//
+// "a" => segment{s: "a"}
+// "/{$}" => segment{s: "/"}
+//
+// If wild is true and multi is false, it matches a single path segment.
+// Example:
+//
+// "{x}" => segment{s: "x", wild: true}
+//
+// If both wild and multi are true, it matches all remaining path segments.
+// Example:
+//
+// "{rest...}" => segment{s: "rest", wild: true, multi: true}
+type segment struct {
+ s string // literal or wildcard name or "/" for "/{$}".
+ wild bool
+ multi bool // "..." wildcard
+}
+
+// parsePattern parses a string into a Pattern.
+// The string's syntax is
+//
+// [METHOD] [HOST]/[PATH]
+//
+// where:
+// - METHOD is an HTTP method
+// - HOST is a hostname
+// - PATH consists of slash-separated segments, where each segment is either
+// a literal or a wildcard of the form "{name}", "{name...}", or "{$}".
+//
+// METHOD, HOST and PATH are all optional; that is, the string can be "/".
+// If METHOD is present, it must be followed by a single space.
+// Wildcard names must be valid Go identifiers.
+// The "{$}" and "{name...}" wildcard must occur at the end of PATH.
+// PATH may end with a '/'.
+// Wildcard names in a path must be distinct.
+func parsePattern(s string) (_ *pattern, err error) {
+ if len(s) == 0 {
+ return nil, errors.New("empty pattern")
+ }
+ off := 0 // offset into string
+ defer func() {
+ if err != nil {
+ err = fmt.Errorf("at offset %d: %w", off, err)
+ }
+ }()
+
+ method, rest, found := strings.Cut(s, " ")
+ if !found {
+ rest = method
+ method = ""
+ }
+ if method != "" && !validMethod(method) {
+ return nil, fmt.Errorf("invalid method %q", method)
+ }
+ p := &pattern{str: s, method: method}
+
+ if found {
+ off = len(method) + 1
+ }
+ i := strings.IndexByte(rest, '/')
+ if i < 0 {
+ return nil, errors.New("host/path missing /")
+ }
+ p.host = rest[:i]
+ rest = rest[i:]
+ if j := strings.IndexByte(p.host, '{'); j >= 0 {
+ off += j
+ return nil, errors.New("host contains '{' (missing initial '/'?)")
+ }
+ // At this point, rest is the path.
+ off += i
+
+ // An unclean path with a method that is not CONNECT can never match,
+ // because paths are cleaned before matching.
+ if method != "" && method != "CONNECT" && rest != cleanPath(rest) {
+ return nil, errors.New("non-CONNECT pattern with unclean path can never match")
+ }
+
+ seenNames := map[string]bool{} // remember wildcard names to catch dups
+ for len(rest) > 0 {
+ // Invariant: rest[0] == '/'.
+ rest = rest[1:]
+ off = len(s) - len(rest)
+ if len(rest) == 0 {
+ // Trailing slash.
+ p.segments = append(p.segments, segment{wild: true, multi: true})
+ break
+ }
+ i := strings.IndexByte(rest, '/')
+ if i < 0 {
+ i = len(rest)
+ }
+ var seg string
+ seg, rest = rest[:i], rest[i:]
+ if i := strings.IndexByte(seg, '{'); i < 0 {
+ // Literal.
+ seg = pathUnescape(seg)
+ p.segments = append(p.segments, segment{s: seg})
+ } else {
+ // Wildcard.
+ if i != 0 {
+ return nil, errors.New("bad wildcard segment (must start with '{')")
+ }
+ if seg[len(seg)-1] != '}' {
+ return nil, errors.New("bad wildcard segment (must end with '}')")
+ }
+ name := seg[1 : len(seg)-1]
+ if name == "$" {
+ if len(rest) != 0 {
+ return nil, errors.New("{$} not at end")
+ }
+ p.segments = append(p.segments, segment{s: "/"})
+ break
+ }
+ name, multi := strings.CutSuffix(name, "...")
+ if multi && len(rest) != 0 {
+ return nil, errors.New("{...} wildcard not at end")
+ }
+ if name == "" {
+ return nil, errors.New("empty wildcard")
+ }
+ if !isValidWildcardName(name) {
+ return nil, fmt.Errorf("bad wildcard name %q", name)
+ }
+ if seenNames[name] {
+ return nil, fmt.Errorf("duplicate wildcard name %q", name)
+ }
+ seenNames[name] = true
+ p.segments = append(p.segments, segment{s: name, wild: true, multi: multi})
+ }
+ }
+ return p, nil
+}
+
+func isValidWildcardName(s string) bool {
+ if s == "" {
+ return false
+ }
+ // Valid Go identifier.
+ for i, c := range s {
+ if !unicode.IsLetter(c) && c != '_' && (i == 0 || !unicode.IsDigit(c)) {
+ return false
+ }
+ }
+ return true
+}
+
+func pathUnescape(path string) string {
+ u, err := url.PathUnescape(path)
+ if err != nil {
+ // Invalidly escaped path; use the original
+ return path
+ }
+ return u
+}
+
+// relationship is a relationship between two patterns, p1 and p2.
+type relationship string
+
+const (
+ equivalent relationship = "equivalent" // both match the same requests
+ moreGeneral relationship = "moreGeneral" // p1 matches everything p2 does & more
+ moreSpecific relationship = "moreSpecific" // p2 matches everything p1 does & more
+ disjoint relationship = "disjoint" // there is no request that both match
+ overlaps relationship = "overlaps" // there is a request that both match, but neither is more specific
+)
+
+// conflictsWith reports whether p1 conflicts with p2, that is, whether
+// there is a request that both match but where neither is higher precedence
+// than the other.
+//
+// Precedence is defined by two rules:
+// 1. Patterns with a host win over patterns without a host.
+// 2. Patterns whose method and path is more specific win. One pattern is more
+// specific than another if the second matches all the (method, path) pairs
+// of the first and more.
+//
+// If rule 1 doesn't apply, then two patterns conflict if their relationship
+// is either equivalence (they match the same set of requests) or overlap
+// (they both match some requests, but neither is more specific than the other).
+func (p1 *pattern) conflictsWith(p2 *pattern) bool {
+ if p1.host != p2.host {
+ // Either one host is empty and the other isn't, in which case the
+ // one with the host wins by rule 1, or neither host is empty
+ // and they differ, so they won't match the same paths.
+ return false
+ }
+ rel := p1.comparePathsAndMethods(p2)
+ return rel == equivalent || rel == overlaps
+}
+
+func (p1 *pattern) comparePathsAndMethods(p2 *pattern) relationship {
+ mrel := p1.compareMethods(p2)
+ // Optimization: avoid a call to comparePaths.
+ if mrel == disjoint {
+ return disjoint
+ }
+ prel := p1.comparePaths(p2)
+ return combineRelationships(mrel, prel)
+}
+
+// compareMethods determines the relationship between the method
+// part of patterns p1 and p2.
+//
+// A method can either be empty, "GET", or something else.
+// The empty string matches any method, so it is the most general.
+// "GET" matches both GET and HEAD.
+// Anything else matches only itself.
+func (p1 *pattern) compareMethods(p2 *pattern) relationship {
+ if p1.method == p2.method {
+ return equivalent
+ }
+ if p1.method == "" {
+ // p1 matches any method, but p2 does not, so p1 is more general.
+ return moreGeneral
+ }
+ if p2.method == "" {
+ return moreSpecific
+ }
+ if p1.method == "GET" && p2.method == "HEAD" {
+ // p1 matches GET and HEAD; p2 matches only HEAD.
+ return moreGeneral
+ }
+ if p2.method == "GET" && p1.method == "HEAD" {
+ return moreSpecific
+ }
+ return disjoint
+}
+
+// comparePaths determines the relationship between the path
+// part of two patterns.
+func (p1 *pattern) comparePaths(p2 *pattern) relationship {
+ // Optimization: if a path pattern doesn't end in a multi ("...") wildcard, then it
+ // can only match paths with the same number of segments.
+ if len(p1.segments) != len(p2.segments) && !p1.lastSegment().multi && !p2.lastSegment().multi {
+ return disjoint
+ }
+
+ // Consider corresponding segments in the two path patterns.
+ var segs1, segs2 []segment
+ rel := equivalent
+ for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] {
+ rel = combineRelationships(rel, compareSegments(segs1[0], segs2[0]))
+ if rel == disjoint {
+ return rel
+ }
+ }
+ // We've reached the end of the corresponding segments of the patterns.
+ // If they have the same number of segments, then we've already determined
+ // their relationship.
+ if len(segs1) == 0 && len(segs2) == 0 {
+ return rel
+ }
+ // Otherwise, the only way they could fail to be disjoint is if the shorter
+ // pattern ends in a multi. In that case, that multi is more general
+ // than the remainder of the longer pattern, so combine those two relationships.
+ if len(segs1) < len(segs2) && p1.lastSegment().multi {
+ return combineRelationships(rel, moreGeneral)
+ }
+ if len(segs2) < len(segs1) && p2.lastSegment().multi {
+ return combineRelationships(rel, moreSpecific)
+ }
+ return disjoint
+}
+
+// compareSegments determines the relationship between two segments.
+func compareSegments(s1, s2 segment) relationship {
+ if s1.multi && s2.multi {
+ return equivalent
+ }
+ if s1.multi {
+ return moreGeneral
+ }
+ if s2.multi {
+ return moreSpecific
+ }
+ if s1.wild && s2.wild {
+ return equivalent
+ }
+ if s1.wild {
+ if s2.s == "/" {
+ // A single wildcard doesn't match a trailing slash.
+ return disjoint
+ }
+ return moreGeneral
+ }
+ if s2.wild {
+ if s1.s == "/" {
+ return disjoint
+ }
+ return moreSpecific
+ }
+ // Both literals.
+ if s1.s == s2.s {
+ return equivalent
+ }
+ return disjoint
+}
+
+// combineRelationships determines the overall relationship of two patterns
+// given the relationships of a partition of the patterns into two parts.
+//
+// For example, if p1 is more general than p2 in one way but equivalent
+// in the other, then it is more general overall.
+//
+// Or if p1 is more general in one way and more specific in the other, then
+// they overlap.
+func combineRelationships(r1, r2 relationship) relationship {
+ switch r1 {
+ case equivalent:
+ return r2
+ case disjoint:
+ return disjoint
+ case overlaps:
+ if r2 == disjoint {
+ return disjoint
+ }
+ return overlaps
+ case moreGeneral, moreSpecific:
+ switch r2 {
+ case equivalent:
+ return r1
+ case inverseRelationship(r1):
+ return overlaps
+ default:
+ return r2
+ }
+ default:
+ panic(fmt.Sprintf("unknown relationship %q", r1))
+ }
+}
+
+// If p1 has relationship `r` to p2, then
+// p2 has inverseRelationship(r) to p1.
+func inverseRelationship(r relationship) relationship {
+ switch r {
+ case moreSpecific:
+ return moreGeneral
+ case moreGeneral:
+ return moreSpecific
+ default:
+ return r
+ }
+}
+
+// isLitOrSingle reports whether the segment is a non-dollar literal or a single wildcard.
+func isLitOrSingle(seg segment) bool {
+ if seg.wild {
+ return !seg.multi
+ }
+ return seg.s != "/"
+}
+
+// describeConflict returns an explanation of why two patterns conflict.
+func describeConflict(p1, p2 *pattern) string {
+ mrel := p1.compareMethods(p2)
+ prel := p1.comparePaths(p2)
+ rel := combineRelationships(mrel, prel)
+ if rel == equivalent {
+ return fmt.Sprintf("%s matches the same requests as %s", p1, p2)
+ }
+ if rel != overlaps {
+ panic("describeConflict called with non-conflicting patterns")
+ }
+ if prel == overlaps {
+ return fmt.Sprintf(`%[1]s and %[2]s both match some paths, like %[3]q.
+But neither is more specific than the other.
+%[1]s matches %[4]q, but %[2]s doesn't.
+%[2]s matches %[5]q, but %[1]s doesn't.`,
+ p1, p2, commonPath(p1, p2), differencePath(p1, p2), differencePath(p2, p1))
+ }
+ if mrel == moreGeneral && prel == moreSpecific {
+ return fmt.Sprintf("%s matches more methods than %s, but has a more specific path pattern", p1, p2)
+ }
+ if mrel == moreSpecific && prel == moreGeneral {
+ return fmt.Sprintf("%s matches fewer methods than %s, but has a more general path pattern", p1, p2)
+ }
+ return fmt.Sprintf("bug: unexpected way for two patterns %s and %s to conflict: methods %s, paths %s", p1, p2, mrel, prel)
+}
+
+// writeMatchingPath writes to b a path that matches the segments.
+func writeMatchingPath(b *strings.Builder, segs []segment) {
+ for _, s := range segs {
+ writeSegment(b, s)
+ }
+}
+
+func writeSegment(b *strings.Builder, s segment) {
+ b.WriteByte('/')
+ if !s.multi && s.s != "/" {
+ b.WriteString(s.s)
+ }
+}
+
+// commonPath returns a path that both p1 and p2 match.
+// It assumes there is such a path.
+func commonPath(p1, p2 *pattern) string {
+ var b strings.Builder
+ var segs1, segs2 []segment
+ for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] {
+ if s1 := segs1[0]; s1.wild {
+ writeSegment(&b, segs2[0])
+ } else {
+ writeSegment(&b, s1)
+ }
+ }
+ if len(segs1) > 0 {
+ writeMatchingPath(&b, segs1)
+ } else if len(segs2) > 0 {
+ writeMatchingPath(&b, segs2)
+ }
+ return b.String()
+}
+
+// differencePath returns a path that p1 matches and p2 doesn't.
+// It assumes there is such a path.
+func differencePath(p1, p2 *pattern) string {
+ var b strings.Builder
+
+ var segs1, segs2 []segment
+ for segs1, segs2 = p1.segments, p2.segments; len(segs1) > 0 && len(segs2) > 0; segs1, segs2 = segs1[1:], segs2[1:] {
+ s1 := segs1[0]
+ s2 := segs2[0]
+ if s1.multi && s2.multi {
+ // From here the patterns match the same paths, so we must have found a difference earlier.
+ b.WriteByte('/')
+ return b.String()
+
+ }
+ if s1.multi && !s2.multi {
+ // s1 ends in a "..." wildcard but s2 does not.
+ // A trailing slash will distinguish them, unless s2 ends in "{$}",
+ // in which case any segment will do; prefer the wildcard name if
+ // it has one.
+ b.WriteByte('/')
+ if s2.s == "/" {
+ if s1.s != "" {
+ b.WriteString(s1.s)
+ } else {
+ b.WriteString("x")
+ }
+ }
+ return b.String()
+ }
+ if !s1.multi && s2.multi {
+ writeSegment(&b, s1)
+ } else if s1.wild && s2.wild {
+ // Both patterns will match whatever we put here; use
+ // the first wildcard name.
+ writeSegment(&b, s1)
+ } else if s1.wild && !s2.wild {
+ // s1 is a wildcard, s2 is a literal.
+ // Any segment other than s2.s will work.
+ // Prefer the wildcard name, but if it's the same as the literal,
+ // tweak the literal.
+ if s1.s != s2.s {
+ writeSegment(&b, s1)
+ } else {
+ b.WriteByte('/')
+ b.WriteString(s2.s + "x")
+ }
+ } else if !s1.wild && s2.wild {
+ writeSegment(&b, s1)
+ } else {
+ // Both are literals. A precondition of this function is that the
+ // patterns overlap, so they must be the same literal. Use it.
+ if s1.s != s2.s {
+ panic(fmt.Sprintf("literals differ: %q and %q", s1.s, s2.s))
+ }
+ writeSegment(&b, s1)
+ }
+ }
+ if len(segs1) > 0 {
+ // p1 is longer than p2, and p2 does not end in a multi.
+ // Anything that matches the rest of p1 will do.
+ writeMatchingPath(&b, segs1)
+ } else if len(segs2) > 0 {
+ writeMatchingPath(&b, segs2)
+ }
+ return b.String()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/pattern_test.go b/platform/dbops/binaries/go/go/src/net/http/pattern_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0c84d243ec96c547918de7c1faa312728e2292d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/pattern_test.go
@@ -0,0 +1,494 @@
+// 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 http
+
+import (
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestParsePattern(t *testing.T) {
+ lit := func(name string) segment {
+ return segment{s: name}
+ }
+
+ wild := func(name string) segment {
+ return segment{s: name, wild: true}
+ }
+
+ multi := func(name string) segment {
+ s := wild(name)
+ s.multi = true
+ return s
+ }
+
+ for _, test := range []struct {
+ in string
+ want pattern
+ }{
+ {"/", pattern{segments: []segment{multi("")}}},
+ {"/a", pattern{segments: []segment{lit("a")}}},
+ {
+ "/a/",
+ pattern{segments: []segment{lit("a"), multi("")}},
+ },
+ {"/path/to/something", pattern{segments: []segment{
+ lit("path"), lit("to"), lit("something"),
+ }}},
+ {
+ "/{w1}/lit/{w2}",
+ pattern{
+ segments: []segment{wild("w1"), lit("lit"), wild("w2")},
+ },
+ },
+ {
+ "/{w1}/lit/{w2}/",
+ pattern{
+ segments: []segment{wild("w1"), lit("lit"), wild("w2"), multi("")},
+ },
+ },
+ {
+ "example.com/",
+ pattern{host: "example.com", segments: []segment{multi("")}},
+ },
+ {
+ "GET /",
+ pattern{method: "GET", segments: []segment{multi("")}},
+ },
+ {
+ "POST example.com/foo/{w}",
+ pattern{
+ method: "POST",
+ host: "example.com",
+ segments: []segment{lit("foo"), wild("w")},
+ },
+ },
+ {
+ "/{$}",
+ pattern{segments: []segment{lit("/")}},
+ },
+ {
+ "DELETE example.com/a/{foo12}/{$}",
+ pattern{method: "DELETE", host: "example.com", segments: []segment{lit("a"), wild("foo12"), lit("/")}},
+ },
+ {
+ "/foo/{$}",
+ pattern{segments: []segment{lit("foo"), lit("/")}},
+ },
+ {
+ "/{a}/foo/{rest...}",
+ pattern{segments: []segment{wild("a"), lit("foo"), multi("rest")}},
+ },
+ {
+ "//",
+ pattern{segments: []segment{lit(""), multi("")}},
+ },
+ {
+ "/foo///./../bar",
+ pattern{segments: []segment{lit("foo"), lit(""), lit(""), lit("."), lit(".."), lit("bar")}},
+ },
+ {
+ "a.com/foo//",
+ pattern{host: "a.com", segments: []segment{lit("foo"), lit(""), multi("")}},
+ },
+ {
+ "/%61%62/%7b/%",
+ pattern{segments: []segment{lit("ab"), lit("{"), lit("%")}},
+ },
+ } {
+ got := mustParsePattern(t, test.in)
+ if !got.equal(&test.want) {
+ t.Errorf("%q:\ngot %#v\nwant %#v", test.in, got, &test.want)
+ }
+ }
+}
+
+func TestParsePatternError(t *testing.T) {
+ for _, test := range []struct {
+ in string
+ contains string
+ }{
+ {"", "empty pattern"},
+ {"A=B /", "at offset 0: invalid method"},
+ {" ", "at offset 1: host/path missing /"},
+ {"/{w}x", "at offset 1: bad wildcard segment"},
+ {"/x{w}", "at offset 1: bad wildcard segment"},
+ {"/{wx", "at offset 1: bad wildcard segment"},
+ {"/a/{/}/c", "at offset 3: bad wildcard segment"},
+ {"/a/{%61}/c", "at offset 3: bad wildcard name"}, // wildcard names aren't unescaped
+ {"/{a$}", "at offset 1: bad wildcard name"},
+ {"/{}", "at offset 1: empty wildcard"},
+ {"POST a.com/x/{}/y", "at offset 13: empty wildcard"},
+ {"/{...}", "at offset 1: empty wildcard"},
+ {"/{$...}", "at offset 1: bad wildcard"},
+ {"/{$}/", "at offset 1: {$} not at end"},
+ {"/{$}/x", "at offset 1: {$} not at end"},
+ {"/abc/{$}/x", "at offset 5: {$} not at end"},
+ {"/{a...}/", "at offset 1: {...} wildcard not at end"},
+ {"/{a...}/x", "at offset 1: {...} wildcard not at end"},
+ {"{a}/b", "at offset 0: host contains '{' (missing initial '/'?)"},
+ {"/a/{x}/b/{x...}", "at offset 9: duplicate wildcard name"},
+ {"GET //", "at offset 4: non-CONNECT pattern with unclean path"},
+ } {
+ _, err := parsePattern(test.in)
+ if err == nil || !strings.Contains(err.Error(), test.contains) {
+ t.Errorf("%q:\ngot %v, want error containing %q", test.in, err, test.contains)
+ }
+ }
+}
+
+func (p1 *pattern) equal(p2 *pattern) bool {
+ return p1.method == p2.method && p1.host == p2.host &&
+ slices.Equal(p1.segments, p2.segments)
+}
+
+func mustParsePattern(tb testing.TB, s string) *pattern {
+ tb.Helper()
+ p, err := parsePattern(s)
+ if err != nil {
+ tb.Fatal(err)
+ }
+ return p
+}
+
+func TestCompareMethods(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want relationship
+ }{
+ {"/", "/", equivalent},
+ {"GET /", "GET /", equivalent},
+ {"HEAD /", "HEAD /", equivalent},
+ {"POST /", "POST /", equivalent},
+ {"GET /", "POST /", disjoint},
+ {"GET /", "/", moreSpecific},
+ {"HEAD /", "/", moreSpecific},
+ {"GET /", "HEAD /", moreGeneral},
+ } {
+ pat1 := mustParsePattern(t, test.p1)
+ pat2 := mustParsePattern(t, test.p2)
+ got := pat1.compareMethods(pat2)
+ if got != test.want {
+ t.Errorf("%s vs %s: got %s, want %s", test.p1, test.p2, got, test.want)
+ }
+ got2 := pat2.compareMethods(pat1)
+ want2 := inverseRelationship(test.want)
+ if got2 != want2 {
+ t.Errorf("%s vs %s: got %s, want %s", test.p2, test.p1, got2, want2)
+ }
+ }
+}
+
+func TestComparePaths(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want relationship
+ }{
+ // A non-final pattern segment can have one of two values: literal or
+ // single wildcard. A final pattern segment can have one of 5: empty
+ // (trailing slash), literal, dollar, single wildcard, or multi
+ // wildcard. Trailing slash and multi wildcard are the same.
+
+ // A literal should be more specific than anything it overlaps, except itself.
+ {"/a", "/a", equivalent},
+ {"/a", "/b", disjoint},
+ {"/a", "/", moreSpecific},
+ {"/a", "/{$}", disjoint},
+ {"/a", "/{x}", moreSpecific},
+ {"/a", "/{x...}", moreSpecific},
+
+ // Adding a segment doesn't change that.
+ {"/b/a", "/b/a", equivalent},
+ {"/b/a", "/b/b", disjoint},
+ {"/b/a", "/b/", moreSpecific},
+ {"/b/a", "/b/{$}", disjoint},
+ {"/b/a", "/b/{x}", moreSpecific},
+ {"/b/a", "/b/{x...}", moreSpecific},
+ {"/{z}/a", "/{z}/a", equivalent},
+ {"/{z}/a", "/{z}/b", disjoint},
+ {"/{z}/a", "/{z}/", moreSpecific},
+ {"/{z}/a", "/{z}/{$}", disjoint},
+ {"/{z}/a", "/{z}/{x}", moreSpecific},
+ {"/{z}/a", "/{z}/{x...}", moreSpecific},
+
+ // Single wildcard on left.
+ {"/{z}", "/a", moreGeneral},
+ {"/{z}", "/a/b", disjoint},
+ {"/{z}", "/{$}", disjoint},
+ {"/{z}", "/{x}", equivalent},
+ {"/{z}", "/", moreSpecific},
+ {"/{z}", "/{x...}", moreSpecific},
+ {"/b/{z}", "/b/a", moreGeneral},
+ {"/b/{z}", "/b/a/b", disjoint},
+ {"/b/{z}", "/b/{$}", disjoint},
+ {"/b/{z}", "/b/{x}", equivalent},
+ {"/b/{z}", "/b/", moreSpecific},
+ {"/b/{z}", "/b/{x...}", moreSpecific},
+
+ // Trailing slash on left.
+ {"/", "/a", moreGeneral},
+ {"/", "/a/b", moreGeneral},
+ {"/", "/{$}", moreGeneral},
+ {"/", "/{x}", moreGeneral},
+ {"/", "/", equivalent},
+ {"/", "/{x...}", equivalent},
+
+ {"/b/", "/b/a", moreGeneral},
+ {"/b/", "/b/a/b", moreGeneral},
+ {"/b/", "/b/{$}", moreGeneral},
+ {"/b/", "/b/{x}", moreGeneral},
+ {"/b/", "/b/", equivalent},
+ {"/b/", "/b/{x...}", equivalent},
+
+ {"/{z}/", "/{z}/a", moreGeneral},
+ {"/{z}/", "/{z}/a/b", moreGeneral},
+ {"/{z}/", "/{z}/{$}", moreGeneral},
+ {"/{z}/", "/{z}/{x}", moreGeneral},
+ {"/{z}/", "/{z}/", equivalent},
+ {"/{z}/", "/a/", moreGeneral},
+ {"/{z}/", "/{z}/{x...}", equivalent},
+ {"/{z}/", "/a/{x...}", moreGeneral},
+ {"/a/{z}/", "/{z}/a/", overlaps},
+ {"/a/{z}/b/", "/{x}/c/{y...}", overlaps},
+
+ // Multi wildcard on left.
+ {"/{m...}", "/a", moreGeneral},
+ {"/{m...}", "/a/b", moreGeneral},
+ {"/{m...}", "/{$}", moreGeneral},
+ {"/{m...}", "/{x}", moreGeneral},
+ {"/{m...}", "/", equivalent},
+ {"/{m...}", "/{x...}", equivalent},
+
+ {"/b/{m...}", "/b/a", moreGeneral},
+ {"/b/{m...}", "/b/a/b", moreGeneral},
+ {"/b/{m...}", "/b/{$}", moreGeneral},
+ {"/b/{m...}", "/b/{x}", moreGeneral},
+ {"/b/{m...}", "/b/", equivalent},
+ {"/b/{m...}", "/b/{x...}", equivalent},
+ {"/b/{m...}", "/a/{x...}", disjoint},
+
+ {"/{z}/{m...}", "/{z}/a", moreGeneral},
+ {"/{z}/{m...}", "/{z}/a/b", moreGeneral},
+ {"/{z}/{m...}", "/{z}/{$}", moreGeneral},
+ {"/{z}/{m...}", "/{z}/{x}", moreGeneral},
+ {"/{z}/{m...}", "/{w}/", equivalent},
+ {"/{z}/{m...}", "/a/", moreGeneral},
+ {"/{z}/{m...}", "/{z}/{x...}", equivalent},
+ {"/{z}/{m...}", "/a/{x...}", moreGeneral},
+ {"/a/{m...}", "/a/b/{y...}", moreGeneral},
+ {"/a/{m...}", "/a/{x}/{y...}", moreGeneral},
+ {"/a/{z}/{m...}", "/a/b/{y...}", moreGeneral},
+ {"/a/{z}/{m...}", "/{z}/a/", overlaps},
+ {"/a/{z}/{m...}", "/{z}/b/{y...}", overlaps},
+ {"/a/{z}/b/{m...}", "/{x}/c/{y...}", overlaps},
+ {"/a/{z}/a/{m...}", "/{x}/b", disjoint},
+
+ // Dollar on left.
+ {"/{$}", "/a", disjoint},
+ {"/{$}", "/a/b", disjoint},
+ {"/{$}", "/{$}", equivalent},
+ {"/{$}", "/{x}", disjoint},
+ {"/{$}", "/", moreSpecific},
+ {"/{$}", "/{x...}", moreSpecific},
+
+ {"/b/{$}", "/b", disjoint},
+ {"/b/{$}", "/b/a", disjoint},
+ {"/b/{$}", "/b/a/b", disjoint},
+ {"/b/{$}", "/b/{$}", equivalent},
+ {"/b/{$}", "/b/{x}", disjoint},
+ {"/b/{$}", "/b/", moreSpecific},
+ {"/b/{$}", "/b/{x...}", moreSpecific},
+ {"/b/{$}", "/b/c/{x...}", disjoint},
+ {"/b/{x}/a/{$}", "/{x}/c/{y...}", overlaps},
+ {"/{x}/b/{$}", "/a/{x}/{y}", disjoint},
+ {"/{x}/b/{$}", "/a/{x}/c", disjoint},
+
+ {"/{z}/{$}", "/{z}/a", disjoint},
+ {"/{z}/{$}", "/{z}/a/b", disjoint},
+ {"/{z}/{$}", "/{z}/{$}", equivalent},
+ {"/{z}/{$}", "/{z}/{x}", disjoint},
+ {"/{z}/{$}", "/{z}/", moreSpecific},
+ {"/{z}/{$}", "/a/", overlaps},
+ {"/{z}/{$}", "/a/{x...}", overlaps},
+ {"/{z}/{$}", "/{z}/{x...}", moreSpecific},
+ {"/a/{z}/{$}", "/{z}/a/", overlaps},
+ } {
+ pat1 := mustParsePattern(t, test.p1)
+ pat2 := mustParsePattern(t, test.p2)
+ if g := pat1.comparePaths(pat1); g != equivalent {
+ t.Errorf("%s does not match itself; got %s", pat1, g)
+ }
+ if g := pat2.comparePaths(pat2); g != equivalent {
+ t.Errorf("%s does not match itself; got %s", pat2, g)
+ }
+ got := pat1.comparePaths(pat2)
+ if got != test.want {
+ t.Errorf("%s vs %s: got %s, want %s", test.p1, test.p2, got, test.want)
+ t.Logf("pat1: %+v\n", pat1.segments)
+ t.Logf("pat2: %+v\n", pat2.segments)
+ }
+ want2 := inverseRelationship(test.want)
+ got2 := pat2.comparePaths(pat1)
+ if got2 != want2 {
+ t.Errorf("%s vs %s: got %s, want %s", test.p2, test.p1, got2, want2)
+ }
+ }
+}
+
+func TestConflictsWith(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want bool
+ }{
+ {"/a", "/a", true},
+ {"/a", "/ab", false},
+ {"/a/b/cd", "/a/b/cd", true},
+ {"/a/b/cd", "/a/b/c", false},
+ {"/a/b/c", "/a/c/c", false},
+ {"/{x}", "/{y}", true},
+ {"/{x}", "/a", false}, // more specific
+ {"/{x}/{y}", "/{x}/a", false},
+ {"/{x}/{y}", "/{x}/a/b", false},
+ {"/{x}", "/a/{y}", false},
+ {"/{x}/{y}", "/{x}/a/", false},
+ {"/{x}", "/a/{y...}", false}, // more specific
+ {"/{x}/a/{y}", "/{x}/a/{y...}", false}, // more specific
+ {"/{x}/{y}", "/{x}/a/{$}", false}, // more specific
+ {"/{x}/{y}/{$}", "/{x}/a/{$}", false},
+ {"/a/{x}", "/{x}/b", true},
+ {"/", "GET /", false},
+ {"/", "GET /foo", false},
+ {"GET /", "GET /foo", false},
+ {"GET /", "/foo", true},
+ {"GET /foo", "HEAD /", true},
+ } {
+ pat1 := mustParsePattern(t, test.p1)
+ pat2 := mustParsePattern(t, test.p2)
+ got := pat1.conflictsWith(pat2)
+ if got != test.want {
+ t.Errorf("%q.ConflictsWith(%q) = %t, want %t",
+ test.p1, test.p2, got, test.want)
+ }
+ // conflictsWith should be commutative.
+ got = pat2.conflictsWith(pat1)
+ if got != test.want {
+ t.Errorf("%q.ConflictsWith(%q) = %t, want %t",
+ test.p2, test.p1, got, test.want)
+ }
+ }
+}
+
+func TestRegisterConflict(t *testing.T) {
+ mux := NewServeMux()
+ pat1 := "/a/{x}/"
+ if err := mux.registerErr(pat1, NotFoundHandler()); err != nil {
+ t.Fatal(err)
+ }
+ pat2 := "/a/{y}/{z...}"
+ err := mux.registerErr(pat2, NotFoundHandler())
+ var got string
+ if err == nil {
+ got = ""
+ } else {
+ got = err.Error()
+ }
+ want := "matches the same requests as"
+ if !strings.Contains(got, want) {
+ t.Errorf("got\n%s\nwant\n%s", got, want)
+ }
+}
+
+func TestDescribeConflict(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want string
+ }{
+ {"/a/{x}", "/a/{y}", "the same requests"},
+ {"/", "/{m...}", "the same requests"},
+ {"/a/{x}", "/{y}/b", "both match some paths"},
+ {"/a", "GET /{x}", "matches more methods than GET /{x}, but has a more specific path pattern"},
+ {"GET /a", "HEAD /", "matches more methods than HEAD /, but has a more specific path pattern"},
+ {"POST /", "/a", "matches fewer methods than /a, but has a more general path pattern"},
+ } {
+ got := describeConflict(mustParsePattern(t, test.p1), mustParsePattern(t, test.p2))
+ if !strings.Contains(got, test.want) {
+ t.Errorf("%s vs. %s:\ngot:\n%s\nwhich does not contain %q",
+ test.p1, test.p2, got, test.want)
+ }
+ }
+}
+
+func TestCommonPath(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want string
+ }{
+ {"/a/{x}", "/{x}/a", "/a/a"},
+ {"/a/{z}/", "/{z}/a/", "/a/a/"},
+ {"/a/{z}/{m...}", "/{z}/a/", "/a/a/"},
+ {"/{z}/{$}", "/a/", "/a/"},
+ {"/{z}/{$}", "/a/{x...}", "/a/"},
+ {"/a/{z}/{$}", "/{z}/a/", "/a/a/"},
+ {"/a/{x}/b/{y...}", "/{x}/c/{y...}", "/a/c/b/"},
+ {"/a/{x}/b/", "/{x}/c/{y...}", "/a/c/b/"},
+ {"/a/{x}/b/{$}", "/{x}/c/{y...}", "/a/c/b/"},
+ {"/a/{z}/{x...}", "/{z}/b/{y...}", "/a/b/"},
+ } {
+ pat1 := mustParsePattern(t, test.p1)
+ pat2 := mustParsePattern(t, test.p2)
+ if pat1.comparePaths(pat2) != overlaps {
+ t.Fatalf("%s does not overlap %s", test.p1, test.p2)
+ }
+ got := commonPath(pat1, pat2)
+ if got != test.want {
+ t.Errorf("%s vs. %s: got %q, want %q", test.p1, test.p2, got, test.want)
+ }
+ }
+}
+
+func TestDifferencePath(t *testing.T) {
+ for _, test := range []struct {
+ p1, p2 string
+ want string
+ }{
+ {"/a/{x}", "/{x}/a", "/a/x"},
+ {"/{x}/a", "/a/{x}", "/x/a"},
+ {"/a/{z}/", "/{z}/a/", "/a/z/"},
+ {"/{z}/a/", "/a/{z}/", "/z/a/"},
+ {"/{a}/a/", "/a/{z}/", "/ax/a/"},
+ {"/a/{z}/{x...}", "/{z}/b/{y...}", "/a/z/"},
+ {"/{z}/b/{y...}", "/a/{z}/{x...}", "/z/b/"},
+ {"/a/b/", "/a/b/c", "/a/b/"},
+ {"/a/b/{x...}", "/a/b/c", "/a/b/"},
+ {"/a/b/{x...}", "/a/b/c/d", "/a/b/"},
+ {"/a/b/{x...}", "/a/b/c/d/", "/a/b/"},
+ {"/a/{z}/{m...}", "/{z}/a/", "/a/z/"},
+ {"/{z}/a/", "/a/{z}/{m...}", "/z/a/"},
+ {"/{z}/{$}", "/a/", "/z/"},
+ {"/a/", "/{z}/{$}", "/a/x"},
+ {"/{z}/{$}", "/a/{x...}", "/z/"},
+ {"/a/{foo...}", "/{z}/{$}", "/a/foo"},
+ {"/a/{z}/{$}", "/{z}/a/", "/a/z/"},
+ {"/{z}/a/", "/a/{z}/{$}", "/z/a/x"},
+ {"/a/{x}/b/{y...}", "/{x}/c/{y...}", "/a/x/b/"},
+ {"/{x}/c/{y...}", "/a/{x}/b/{y...}", "/x/c/"},
+ {"/a/{c}/b/", "/{x}/c/{y...}", "/a/cx/b/"},
+ {"/{x}/c/{y...}", "/a/{c}/b/", "/x/c/"},
+ {"/a/{x}/b/{$}", "/{x}/c/{y...}", "/a/x/b/"},
+ {"/{x}/c/{y...}", "/a/{x}/b/{$}", "/x/c/"},
+ } {
+ pat1 := mustParsePattern(t, test.p1)
+ pat2 := mustParsePattern(t, test.p2)
+ rel := pat1.comparePaths(pat2)
+ if rel != overlaps && rel != moreGeneral {
+ t.Fatalf("%s vs. %s are %s, need overlaps or moreGeneral", pat1, pat2, rel)
+ }
+ got := differencePath(pat1, pat2)
+ if got != test.want {
+ t.Errorf("%s vs. %s: got %q, want %q", test.p1, test.p2, got, test.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/pprof/pprof.go b/platform/dbops/binaries/go/go/src/net/http/pprof/pprof.go
new file mode 100644
index 0000000000000000000000000000000000000000..bc48f11834130a4120f3ed0b63eea92456cd6afc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/pprof/pprof.go
@@ -0,0 +1,464 @@
+// 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 pprof serves via its HTTP server runtime profiling data
+// in the format expected by the pprof visualization tool.
+//
+// The package is typically only imported for the side effect of
+// registering its HTTP handlers.
+// The handled paths all begin with /debug/pprof/.
+//
+// To use pprof, link this package into your program:
+//
+// import _ "net/http/pprof"
+//
+// If your application is not already running an http server, you
+// need to start one. Add "net/http" and "log" to your imports and
+// the following code to your main function:
+//
+// go func() {
+// log.Println(http.ListenAndServe("localhost:6060", nil))
+// }()
+//
+// By default, all the profiles listed in [runtime/pprof.Profile] are
+// available (via [Handler]), in addition to the [Cmdline], [Profile], [Symbol],
+// and [Trace] profiles defined in this package.
+// If you are not using DefaultServeMux, you will have to register handlers
+// with the mux you are using.
+//
+// # Parameters
+//
+// Parameters can be passed via GET query params:
+//
+// - debug=N (all profiles): response format: N = 0: binary (default), N > 0: plaintext
+// - gc=N (heap profile): N > 0: run a garbage collection cycle before profiling
+// - seconds=N (allocs, block, goroutine, heap, mutex, threadcreate profiles): return a delta profile
+// - seconds=N (cpu (profile), trace profiles): profile for the given duration
+//
+// # Usage examples
+//
+// Use the pprof tool to look at the heap profile:
+//
+// go tool pprof http://localhost:6060/debug/pprof/heap
+//
+// Or to look at a 30-second CPU profile:
+//
+// go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
+//
+// Or to look at the goroutine blocking profile, after calling
+// [runtime.SetBlockProfileRate] in your program:
+//
+// go tool pprof http://localhost:6060/debug/pprof/block
+//
+// Or to look at the holders of contended mutexes, after calling
+// [runtime.SetMutexProfileFraction] in your program:
+//
+// go tool pprof http://localhost:6060/debug/pprof/mutex
+//
+// The package also exports a handler that serves execution trace data
+// for the "go tool trace" command. To collect a 5-second execution trace:
+//
+// curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
+// go tool trace trace.out
+//
+// To view all available profiles, open http://localhost:6060/debug/pprof/
+// in your browser.
+//
+// For a study of the facility in action, visit
+// https://blog.golang.org/2011/06/profiling-go-programs.html.
+package pprof
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "fmt"
+ "html"
+ "internal/profile"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "runtime"
+ "runtime/pprof"
+ "runtime/trace"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+func init() {
+ http.HandleFunc("/debug/pprof/", Index)
+ http.HandleFunc("/debug/pprof/cmdline", Cmdline)
+ http.HandleFunc("/debug/pprof/profile", Profile)
+ http.HandleFunc("/debug/pprof/symbol", Symbol)
+ http.HandleFunc("/debug/pprof/trace", Trace)
+}
+
+// Cmdline responds with the running program's
+// command line, with arguments separated by NUL bytes.
+// The package initialization registers it as /debug/pprof/cmdline.
+func Cmdline(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ fmt.Fprint(w, strings.Join(os.Args, "\x00"))
+}
+
+func sleep(r *http.Request, d time.Duration) {
+ select {
+ case <-time.After(d):
+ case <-r.Context().Done():
+ }
+}
+
+func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool {
+ srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server)
+ return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds()
+}
+
+func serveError(w http.ResponseWriter, status int, txt string) {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.Header().Set("X-Go-Pprof", "1")
+ w.Header().Del("Content-Disposition")
+ w.WriteHeader(status)
+ fmt.Fprintln(w, txt)
+}
+
+// Profile responds with the pprof-formatted cpu profile.
+// Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
+// The package initialization registers it as /debug/pprof/profile.
+func Profile(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
+ if sec <= 0 || err != nil {
+ sec = 30
+ }
+
+ if durationExceedsWriteTimeout(r, float64(sec)) {
+ serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
+ return
+ }
+
+ // Set Content Type assuming StartCPUProfile will work,
+ // because if it does it starts writing.
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", `attachment; filename="profile"`)
+ if err := pprof.StartCPUProfile(w); err != nil {
+ // StartCPUProfile failed, so no writes yet.
+ serveError(w, http.StatusInternalServerError,
+ fmt.Sprintf("Could not enable CPU profiling: %s", err))
+ return
+ }
+ sleep(r, time.Duration(sec)*time.Second)
+ pprof.StopCPUProfile()
+}
+
+// Trace responds with the execution trace in binary form.
+// Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
+// The package initialization registers it as /debug/pprof/trace.
+func Trace(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64)
+ if sec <= 0 || err != nil {
+ sec = 1
+ }
+
+ if durationExceedsWriteTimeout(r, sec) {
+ serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
+ return
+ }
+
+ // Set Content Type assuming trace.Start will work,
+ // because if it does it starts writing.
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", `attachment; filename="trace"`)
+ if err := trace.Start(w); err != nil {
+ // trace.Start failed, so no writes yet.
+ serveError(w, http.StatusInternalServerError,
+ fmt.Sprintf("Could not enable tracing: %s", err))
+ return
+ }
+ sleep(r, time.Duration(sec*float64(time.Second)))
+ trace.Stop()
+}
+
+// Symbol looks up the program counters listed in the request,
+// responding with a table mapping program counters to function names.
+// The package initialization registers it as /debug/pprof/symbol.
+func Symbol(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+
+ // We have to read the whole POST body before
+ // writing any output. Buffer the output here.
+ var buf bytes.Buffer
+
+ // We don't know how many symbols we have, but we
+ // do have symbol information. Pprof only cares whether
+ // this number is 0 (no symbols available) or > 0.
+ fmt.Fprintf(&buf, "num_symbols: 1\n")
+
+ var b *bufio.Reader
+ if r.Method == "POST" {
+ b = bufio.NewReader(r.Body)
+ } else {
+ b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
+ }
+
+ for {
+ word, err := b.ReadSlice('+')
+ if err == nil {
+ word = word[0 : len(word)-1] // trim +
+ }
+ pc, _ := strconv.ParseUint(string(word), 0, 64)
+ if pc != 0 {
+ f := runtime.FuncForPC(uintptr(pc))
+ if f != nil {
+ fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
+ }
+ }
+
+ // Wait until here to check for err; the last
+ // symbol will have an err because it doesn't end in +.
+ if err != nil {
+ if err != io.EOF {
+ fmt.Fprintf(&buf, "reading request: %v\n", err)
+ }
+ break
+ }
+ }
+
+ w.Write(buf.Bytes())
+}
+
+// Handler returns an HTTP handler that serves the named profile.
+// Available profiles can be found in [runtime/pprof.Profile].
+func Handler(name string) http.Handler {
+ return handler(name)
+}
+
+type handler string
+
+func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ p := pprof.Lookup(string(name))
+ if p == nil {
+ serveError(w, http.StatusNotFound, "Unknown profile")
+ return
+ }
+ if sec := r.FormValue("seconds"); sec != "" {
+ name.serveDeltaProfile(w, r, p, sec)
+ return
+ }
+ gc, _ := strconv.Atoi(r.FormValue("gc"))
+ if name == "heap" && gc > 0 {
+ runtime.GC()
+ }
+ debug, _ := strconv.Atoi(r.FormValue("debug"))
+ if debug != 0 {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ } else {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
+ }
+ p.WriteTo(w, debug)
+}
+
+func (name handler) serveDeltaProfile(w http.ResponseWriter, r *http.Request, p *pprof.Profile, secStr string) {
+ sec, err := strconv.ParseInt(secStr, 10, 64)
+ if err != nil || sec <= 0 {
+ serveError(w, http.StatusBadRequest, `invalid value for "seconds" - must be a positive integer`)
+ return
+ }
+ if !profileSupportsDelta[name] {
+ serveError(w, http.StatusBadRequest, `"seconds" parameter is not supported for this profile type`)
+ return
+ }
+ // 'name' should be a key in profileSupportsDelta.
+ if durationExceedsWriteTimeout(r, float64(sec)) {
+ serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
+ return
+ }
+ debug, _ := strconv.Atoi(r.FormValue("debug"))
+ if debug != 0 {
+ serveError(w, http.StatusBadRequest, "seconds and debug params are incompatible")
+ return
+ }
+ p0, err := collectProfile(p)
+ if err != nil {
+ serveError(w, http.StatusInternalServerError, "failed to collect profile")
+ return
+ }
+
+ t := time.NewTimer(time.Duration(sec) * time.Second)
+ defer t.Stop()
+
+ select {
+ case <-r.Context().Done():
+ err := r.Context().Err()
+ if err == context.DeadlineExceeded {
+ serveError(w, http.StatusRequestTimeout, err.Error())
+ } else { // TODO: what's a good status code for canceled requests? 400?
+ serveError(w, http.StatusInternalServerError, err.Error())
+ }
+ return
+ case <-t.C:
+ }
+
+ p1, err := collectProfile(p)
+ if err != nil {
+ serveError(w, http.StatusInternalServerError, "failed to collect profile")
+ return
+ }
+ ts := p1.TimeNanos
+ dur := p1.TimeNanos - p0.TimeNanos
+
+ p0.Scale(-1)
+
+ p1, err = profile.Merge([]*profile.Profile{p0, p1})
+ if err != nil {
+ serveError(w, http.StatusInternalServerError, "failed to compute delta")
+ return
+ }
+
+ p1.TimeNanos = ts // set since we don't know what profile.Merge set for TimeNanos.
+ p1.DurationNanos = dur
+
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s-delta"`, name))
+ p1.Write(w)
+}
+
+func collectProfile(p *pprof.Profile) (*profile.Profile, error) {
+ var buf bytes.Buffer
+ if err := p.WriteTo(&buf, 0); err != nil {
+ return nil, err
+ }
+ ts := time.Now().UnixNano()
+ p0, err := profile.Parse(&buf)
+ if err != nil {
+ return nil, err
+ }
+ p0.TimeNanos = ts
+ return p0, nil
+}
+
+var profileSupportsDelta = map[handler]bool{
+ "allocs": true,
+ "block": true,
+ "goroutine": true,
+ "heap": true,
+ "mutex": true,
+ "threadcreate": true,
+}
+
+var profileDescriptions = map[string]string{
+ "allocs": "A sampling of all past memory allocations",
+ "block": "Stack traces that led to blocking on synchronization primitives",
+ "cmdline": "The command line invocation of the current program",
+ "goroutine": "Stack traces of all current goroutines. Use debug=2 as a query parameter to export in the same format as an unrecovered panic.",
+ "heap": "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.",
+ "mutex": "Stack traces of holders of contended mutexes",
+ "profile": "CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.",
+ "threadcreate": "Stack traces that led to the creation of new OS threads",
+ "trace": "A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.",
+}
+
+type profileEntry struct {
+ Name string
+ Href string
+ Desc string
+ Count int
+}
+
+// Index responds with the pprof-formatted profile named by the request.
+// For example, "/debug/pprof/heap" serves the "heap" profile.
+// Index responds to a request for "/debug/pprof/" with an HTML page
+// listing the available profiles.
+func Index(w http.ResponseWriter, r *http.Request) {
+ if name, found := strings.CutPrefix(r.URL.Path, "/debug/pprof/"); found {
+ if name != "" {
+ handler(name).ServeHTTP(w, r)
+ return
+ }
+ }
+
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+
+ var profiles []profileEntry
+ for _, p := range pprof.Profiles() {
+ profiles = append(profiles, profileEntry{
+ Name: p.Name(),
+ Href: p.Name(),
+ Desc: profileDescriptions[p.Name()],
+ Count: p.Count(),
+ })
+ }
+
+ // Adding other profiles exposed from within this package
+ for _, p := range []string{"cmdline", "profile", "trace"} {
+ profiles = append(profiles, profileEntry{
+ Name: p,
+ Href: p,
+ Desc: profileDescriptions[p],
+ })
+ }
+
+ sort.Slice(profiles, func(i, j int) bool {
+ return profiles[i].Name < profiles[j].Name
+ })
+
+ if err := indexTmplExecute(w, profiles); err != nil {
+ log.Print(err)
+ }
+}
+
+func indexTmplExecute(w io.Writer, profiles []profileEntry) error {
+ var b bytes.Buffer
+ b.WriteString(`
+
+/debug/pprof/
+
+
+
+/debug/pprof/
+
+Set debug=1 as a query parameter to export in legacy text format
+
+Types of profiles available:
+
+| Count | Profile |
+`)
+
+ for _, profile := range profiles {
+ link := &url.URL{Path: profile.Href, RawQuery: "debug=1"}
+ fmt.Fprintf(&b, "| %d | %s |
\n", profile.Count, link, html.EscapeString(profile.Name))
+ }
+
+ b.WriteString(`
+full goroutine stack dump
+
+
+Profile Descriptions:
+
+`)
+ for _, profile := range profiles {
+ fmt.Fprintf(&b, "%s:
%s \n", html.EscapeString(profile.Name), html.EscapeString(profile.Desc))
+ }
+ b.WriteString(`
+
+
+`)
+
+ _, err := w.Write(b.Bytes())
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/http/pprof/pprof_test.go b/platform/dbops/binaries/go/go/src/net/http/pprof/pprof_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..24ad59ab397687dc1764ac04639e2f49847001d9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/http/pprof/pprof_test.go
@@ -0,0 +1,326 @@
+// 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 pprof
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "internal/profile"
+ "internal/testenv"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "runtime"
+ "runtime/pprof"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// TestDescriptions checks that the profile names under runtime/pprof package
+// have a key in the description map.
+func TestDescriptions(t *testing.T) {
+ for _, p := range pprof.Profiles() {
+ _, ok := profileDescriptions[p.Name()]
+ if ok != true {
+ t.Errorf("%s does not exist in profileDescriptions map\n", p.Name())
+ }
+ }
+}
+
+func TestHandlers(t *testing.T) {
+ testCases := []struct {
+ path string
+ handler http.HandlerFunc
+ statusCode int
+ contentType string
+ contentDisposition string
+ resp []byte
+ }{
+ {"/debug/pprof/