diff --git a/.gitattributes b/.gitattributes
index 8a7cd01d7414d7702f628f51497c60dd33543b12..11947ece23fdbfb374bb71a39490e78dbad3b934 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3135,3 +3135,20 @@ platform/dbops/binaries/build/bin/bison filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/build/bin/flex filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/build/bin/flex++ filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/weaviate-src/adapters/repos/db/vector/hnsw/compression_tests/fixtures/restart-from-zero-segments/1234567 filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/addr2line filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/asm filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/buildid filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cgo filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/compile filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/covdata filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cover filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/doc filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/fix filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/link filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/nm filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/objdump filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pack filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pprof filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/test2json filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/trace filter=lfs diff=lfs merge=lfs -text
+platform/dbops/binaries/go/go/pkg/tool/linux_amd64/vet filter=lfs diff=lfs merge=lfs -text
diff --git a/platform/dbops/binaries/go/go/lib/time/README b/platform/dbops/binaries/go/go/lib/time/README
new file mode 100644
index 0000000000000000000000000000000000000000..0de06df13b9a4575a0f510e854d171878ec7b89d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/lib/time/README
@@ -0,0 +1,10 @@
+The zoneinfo.zip archive contains time zone files compiled using
+the code and data maintained as part of the IANA Time Zone Database.
+The IANA asserts that the database is in the public domain.
+
+For more information, see
+https://www.iana.org/time-zones
+ftp://ftp.iana.org/tz/code/tz-link.html
+https://datatracker.ietf.org/doc/html/rfc6557
+
+To rebuild the archive, read and run update.bash.
diff --git a/platform/dbops/binaries/go/go/lib/time/mkzip.go b/platform/dbops/binaries/go/go/lib/time/mkzip.go
new file mode 100644
index 0000000000000000000000000000000000000000..3920b11b6c251ba67da3e51cf0a86dc22b507470
--- /dev/null
+++ b/platform/dbops/binaries/go/go/lib/time/mkzip.go
@@ -0,0 +1,94 @@
+// 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 ignore
+
+// Mkzip writes a zoneinfo.zip with the content of the current directory
+// and its subdirectories, with no compression, suitable for package time.
+//
+// Usage:
+//
+// go run ../../mkzip.go ../../zoneinfo.zip
+//
+// We use this program instead of 'zip -0 -r ../../zoneinfo.zip *' to get
+// a reproducible generator that does not depend on which version of the
+// external zip tool is used or the ordering of file names in a directory
+// or the current time.
+package main
+
+import (
+ "archive/zip"
+ "bytes"
+ "flag"
+ "fmt"
+ "hash/crc32"
+ "io/fs"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+func usage() {
+ fmt.Fprintf(os.Stderr, "usage: go run mkzip.go ../../zoneinfo.zip\n")
+ os.Exit(2)
+}
+
+func main() {
+ log.SetPrefix("mkzip: ")
+ log.SetFlags(0)
+ flag.Usage = usage
+ flag.Parse()
+ args := flag.Args()
+ if len(args) != 1 || !strings.HasSuffix(args[0], ".zip") {
+ usage()
+ }
+
+ var zb bytes.Buffer
+ zw := zip.NewWriter(&zb)
+ seen := make(map[string]bool)
+ err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
+ if d.IsDir() {
+ return nil
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if strings.HasSuffix(path, ".zip") {
+ log.Fatalf("unexpected file during walk: %s", path)
+ }
+ name := filepath.ToSlash(path)
+ w, err := zw.CreateRaw(&zip.FileHeader{
+ Name: name,
+ Method: zip.Store,
+ CompressedSize64: uint64(len(data)),
+ UncompressedSize64: uint64(len(data)),
+ CRC32: crc32.ChecksumIEEE(data),
+ })
+ if err != nil {
+ log.Fatal(err)
+ }
+ if _, err := w.Write(data); err != nil {
+ log.Fatal(err)
+ }
+ seen[name] = true
+ return nil
+ })
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := zw.Close(); err != nil {
+ log.Fatal(err)
+ }
+ if len(seen) == 0 {
+ log.Fatalf("did not find any files to add")
+ }
+ if !seen["US/Eastern"] {
+ log.Fatalf("did not find US/Eastern to add")
+ }
+ if err := os.WriteFile(args[0], zb.Bytes(), 0666); err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/lib/time/update.bash b/platform/dbops/binaries/go/go/lib/time/update.bash
new file mode 100644
index 0000000000000000000000000000000000000000..e72850079f4a91af5f2280027af1330277e146f9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/lib/time/update.bash
@@ -0,0 +1,86 @@
+#!/bin/bash
+# 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 script rebuilds the time zone files using files
+# downloaded from the ICANN/IANA distribution.
+#
+# To prepare an update for a new Go release,
+# consult https://www.iana.org/time-zones for the latest versions,
+# update CODE and DATA below, and then run
+#
+# ./update.bash -commit
+#
+# That will prepare the files and create the commit.
+#
+# To review such a commit (as the reviewer), use:
+#
+# git codereview change NNNNNN # CL number
+# cd lib/time
+# ./update.bash
+#
+# If it prints "No updates needed.", then the generated files
+# in the CL match the update.bash in the CL.
+
+# Versions to use.
+CODE=2023d
+DATA=2023d
+
+set -e
+
+cd $(dirname $0)
+rm -rf work
+mkdir work
+go build -o work/mkzip mkzip.go # build now for correct paths in build errors
+cd work
+mkdir zoneinfo
+curl -sS -L -O https://www.iana.org/time-zones/repository/releases/tzcode$CODE.tar.gz
+curl -sS -L -O https://www.iana.org/time-zones/repository/releases/tzdata$DATA.tar.gz
+tar xzf tzcode$CODE.tar.gz
+tar xzf tzdata$DATA.tar.gz
+
+if ! make CFLAGS=-DSTD_INSPIRED AWK=awk TZDIR=zoneinfo posix_only >make.out 2>&1; then
+ cat make.out
+ exit 2
+fi
+
+cd zoneinfo
+../mkzip ../../zoneinfo.zip
+cd ../..
+
+files="update.bash zoneinfo.zip"
+modified=true
+if git diff --quiet $files; then
+ modified=false
+fi
+
+if [ "$1" = "-work" ]; then
+ echo Left workspace behind in work/.
+ shift
+else
+ rm -rf work
+fi
+
+if ! $modified; then
+ echo No updates needed.
+ exit 0
+fi
+
+echo Updated for $CODE/$DATA: $files
+
+commitmsg="lib/time: update to $CODE/$DATA
+
+Commit generated by update.bash.
+
+For #22487.
+"
+
+if [ "$1" = "-commit" ]; then
+ echo "Creating commit. Run 'git reset HEAD^' to undo commit."
+ echo
+ git commit -m "$commitmsg" $files
+ echo
+ git log -n1 --stat
+ echo
+fi
diff --git a/platform/dbops/binaries/go/go/lib/time/zoneinfo.zip b/platform/dbops/binaries/go/go/lib/time/zoneinfo.zip
new file mode 100644
index 0000000000000000000000000000000000000000..3977ac1ed58ef3bde379be8d93ec2ef287deb0ba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/lib/time/zoneinfo.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:19ffc039dc3fd174849b8d18b1420c48a7b0d97a1ddaaa6d14e9216da6c11597
+size 401728
diff --git a/platform/dbops/binaries/go/go/misc/cgo/gmp/fib.go b/platform/dbops/binaries/go/go/misc/cgo/gmp/fib.go
new file mode 100644
index 0000000000000000000000000000000000000000..48b070049fc374a958e8889e3f601c6273d03a5a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/cgo/gmp/fib.go
@@ -0,0 +1,45 @@
+// 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
+
+// Compute Fibonacci numbers with two goroutines
+// that pass integers back and forth. No actual
+// concurrency, just threads and synchronization
+// and foreign code on multiple pthreads.
+
+package main
+
+import (
+ big "."
+ "runtime"
+)
+
+func fibber(c chan *big.Int, out chan string, n int64) {
+ // Keep the fibbers in dedicated operating system
+ // threads, so that this program tests coordination
+ // between pthreads and not just goroutines.
+ runtime.LockOSThread()
+
+ i := big.NewInt(n)
+ if n == 0 {
+ c <- i
+ }
+ for {
+ j := <-c
+ out <- j.String()
+ i.Add(i, j)
+ c <- i
+ }
+}
+
+func main() {
+ c := make(chan *big.Int)
+ out := make(chan string)
+ go fibber(c, out, 0)
+ go fibber(c, out, 1)
+ for i := 0; i < 200; i++ {
+ println(<-out)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/misc/cgo/gmp/gmp.go b/platform/dbops/binaries/go/go/misc/cgo/gmp/gmp.go
new file mode 100644
index 0000000000000000000000000000000000000000..0835fdc8dea661dbaf71735d2864d1b06ecf6a45
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/cgo/gmp/gmp.go
@@ -0,0 +1,379 @@
+// 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.
+
+/*
+An example of wrapping a C library in Go. This is the GNU
+multiprecision library gmp's integer type mpz_t wrapped to look like
+the Go package big's integer type Int.
+
+This is a syntactically valid Go program—it can be parsed with the Go
+parser and processed by godoc—but it is not compiled directly by gc.
+Instead, a separate tool, cgo, processes it to produce three output
+files. The first two, 6g.go and 6c.c, are a Go source file for 6g and
+a C source file for 6c; both compile as part of the named package
+(gmp, in this example). The third, gcc.c, is a C source file for gcc;
+it compiles into a shared object (.so) that is dynamically linked into
+any 6.out that imports the first two files.
+
+The stanza
+
+ // #include
+ import "C"
+
+is a signal to cgo. The doc comment on the import of "C" provides
+additional context for the C file. Here it is just a single #include
+but it could contain arbitrary C definitions to be imported and used.
+
+Cgo recognizes any use of a qualified identifier C.xxx and uses gcc to
+find the definition of xxx. If xxx is a type, cgo replaces C.xxx with
+a Go translation. C arithmetic types translate to precisely-sized Go
+arithmetic types. A C struct translates to a Go struct, field by
+field; unrepresentable fields are replaced with opaque byte arrays. A
+C union translates into a struct containing the first union member and
+perhaps additional padding. C arrays become Go arrays. C pointers
+become Go pointers. C function pointers become Go's uintptr.
+C void pointers become Go's unsafe.Pointer.
+
+For example, mpz_t is defined in as:
+
+ typedef unsigned long int mp_limb_t;
+
+ typedef struct
+ {
+ int _mp_alloc;
+ int _mp_size;
+ mp_limb_t *_mp_d;
+ } __mpz_struct;
+
+ typedef __mpz_struct mpz_t[1];
+
+Cgo generates:
+
+ type _C_int int32
+ type _C_mp_limb_t uint64
+ type _C___mpz_struct struct {
+ _mp_alloc _C_int;
+ _mp_size _C_int;
+ _mp_d *_C_mp_limb_t;
+ }
+ type _C_mpz_t [1]_C___mpz_struct
+
+and then replaces each occurrence of a type C.xxx with _C_xxx.
+
+If xxx is data, cgo arranges for C.xxx to refer to the C variable,
+with the type translated as described above. To do this, cgo must
+introduce a Go variable that points at the C variable (the linker can
+be told to initialize this pointer). For example, if the gmp library
+provided
+
+ mpz_t zero;
+
+then cgo would rewrite a reference to C.zero by introducing
+
+ var _C_zero *C.mpz_t
+
+and then replacing all instances of C.zero with (*_C_zero).
+
+Cgo's most interesting translation is for functions. If xxx is a C
+function, then cgo rewrites C.xxx into a new function _C_xxx that
+calls the C xxx in a standard pthread. The new function translates
+its arguments, calls xxx, and translates the return value.
+
+Translation of parameters and the return value follows the type
+translation above except that arrays passed as parameters translate
+explicitly in Go to pointers to arrays, as they do (implicitly) in C.
+
+Garbage collection is the big problem. It is fine for the Go world to
+have pointers into the C world and to free those pointers when they
+are no longer needed. To help, the Go code can define Go objects
+holding the C pointers and use runtime.SetFinalizer on those Go objects.
+
+It is much more difficult for the C world to have pointers into the Go
+world, because the Go garbage collector is unaware of the memory
+allocated by C. The most important consideration is not to
+constrain future implementations, so the rule is that Go code can
+hand a Go pointer to C code but must separately arrange for
+Go to hang on to a reference to the pointer until C is done with it.
+*/
+package gmp
+
+/*
+#cgo LDFLAGS: -lgmp
+#include
+#include
+
+// gmp 5.0.0+ changed the type of the 3rd argument to mp_bitcnt_t,
+// so, to support older versions, we wrap these two functions.
+void _mpz_mul_2exp(mpz_ptr a, mpz_ptr b, unsigned long n) {
+ mpz_mul_2exp(a, b, n);
+}
+void _mpz_div_2exp(mpz_ptr a, mpz_ptr b, unsigned long n) {
+ mpz_div_2exp(a, b, n);
+}
+*/
+import "C"
+
+import (
+ "os"
+ "unsafe"
+)
+
+/*
+ * one of a kind
+ */
+
+// An Int represents a signed multi-precision integer.
+// The zero value for an Int represents the value 0.
+type Int struct {
+ i C.mpz_t
+ init bool
+}
+
+// NewInt returns a new Int initialized to x.
+func NewInt(x int64) *Int { return new(Int).SetInt64(x) }
+
+// Int promises that the zero value is a 0, but in gmp
+// the zero value is a crash. To bridge the gap, the
+// init bool says whether this is a valid gmp value.
+// doinit initializes z.i if it needs it. This is not inherent
+// to FFI, just a mismatch between Go's convention of
+// making zero values useful and gmp's decision not to.
+func (z *Int) doinit() {
+ if z.init {
+ return
+ }
+ z.init = true
+ C.mpz_init(&z.i[0])
+}
+
+// Bytes returns z's representation as a big-endian byte array.
+func (z *Int) Bytes() []byte {
+ b := make([]byte, (z.Len()+7)/8)
+ n := C.size_t(len(b))
+ C.mpz_export(unsafe.Pointer(&b[0]), &n, 1, 1, 1, 0, &z.i[0])
+ return b[0:n]
+}
+
+// Len returns the length of z in bits. 0 is considered to have length 1.
+func (z *Int) Len() int {
+ z.doinit()
+ return int(C.mpz_sizeinbase(&z.i[0], 2))
+}
+
+// Set sets z = x and returns z.
+func (z *Int) Set(x *Int) *Int {
+ z.doinit()
+ C.mpz_set(&z.i[0], &x.i[0])
+ return z
+}
+
+// SetBytes interprets b as the bytes of a big-endian integer
+// and sets z to that value.
+func (z *Int) SetBytes(b []byte) *Int {
+ z.doinit()
+ if len(b) == 0 {
+ z.SetInt64(0)
+ } else {
+ C.mpz_import(&z.i[0], C.size_t(len(b)), 1, 1, 1, 0, unsafe.Pointer(&b[0]))
+ }
+ return z
+}
+
+// SetInt64 sets z = x and returns z.
+func (z *Int) SetInt64(x int64) *Int {
+ z.doinit()
+ // TODO(rsc): more work on 32-bit platforms
+ C.mpz_set_si(&z.i[0], C.long(x))
+ return z
+}
+
+// SetString interprets s as a number in the given base
+// and sets z to that value. The base must be in the range [2,36].
+// SetString returns an error if s cannot be parsed or the base is invalid.
+func (z *Int) SetString(s string, base int) error {
+ z.doinit()
+ if base < 2 || base > 36 {
+ return os.ErrInvalid
+ }
+ p := C.CString(s)
+ defer C.free(unsafe.Pointer(p))
+ if C.mpz_set_str(&z.i[0], p, C.int(base)) < 0 {
+ return os.ErrInvalid
+ }
+ return nil
+}
+
+// String returns the decimal representation of z.
+func (z *Int) String() string {
+ if z == nil {
+ return "nil"
+ }
+ z.doinit()
+ p := C.mpz_get_str(nil, 10, &z.i[0])
+ s := C.GoString(p)
+ C.free(unsafe.Pointer(p))
+ return s
+}
+
+func (z *Int) destroy() {
+ if z.init {
+ C.mpz_clear(&z.i[0])
+ }
+ z.init = false
+}
+
+/*
+ * arithmetic
+ */
+
+// Add sets z = x + y and returns z.
+func (z *Int) Add(x, y *Int) *Int {
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ C.mpz_add(&z.i[0], &x.i[0], &y.i[0])
+ return z
+}
+
+// Sub sets z = x - y and returns z.
+func (z *Int) Sub(x, y *Int) *Int {
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ C.mpz_sub(&z.i[0], &x.i[0], &y.i[0])
+ return z
+}
+
+// Mul sets z = x * y and returns z.
+func (z *Int) Mul(x, y *Int) *Int {
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ C.mpz_mul(&z.i[0], &x.i[0], &y.i[0])
+ return z
+}
+
+// Div sets z = x / y, rounding toward zero, and returns z.
+func (z *Int) Div(x, y *Int) *Int {
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ C.mpz_tdiv_q(&z.i[0], &x.i[0], &y.i[0])
+ return z
+}
+
+// Mod sets z = x % y and returns z.
+// Like the result of the Go % operator, z has the same sign as x.
+func (z *Int) Mod(x, y *Int) *Int {
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ C.mpz_tdiv_r(&z.i[0], &x.i[0], &y.i[0])
+ return z
+}
+
+// Lsh sets z = x << s and returns z.
+func (z *Int) Lsh(x *Int, s uint) *Int {
+ x.doinit()
+ z.doinit()
+ C._mpz_mul_2exp(&z.i[0], &x.i[0], C.ulong(s))
+ return z
+}
+
+// Rsh sets z = x >> s and returns z.
+func (z *Int) Rsh(x *Int, s uint) *Int {
+ x.doinit()
+ z.doinit()
+ C._mpz_div_2exp(&z.i[0], &x.i[0], C.ulong(s))
+ return z
+}
+
+// Exp sets z = x^y % m and returns z.
+// If m == nil, Exp sets z = x^y.
+func (z *Int) Exp(x, y, m *Int) *Int {
+ m.doinit()
+ x.doinit()
+ y.doinit()
+ z.doinit()
+ if m == nil {
+ C.mpz_pow_ui(&z.i[0], &x.i[0], C.mpz_get_ui(&y.i[0]))
+ } else {
+ C.mpz_powm(&z.i[0], &x.i[0], &y.i[0], &m.i[0])
+ }
+ return z
+}
+
+func (z *Int) Int64() int64 {
+ if !z.init {
+ return 0
+ }
+ return int64(C.mpz_get_si(&z.i[0]))
+}
+
+// Neg sets z = -x and returns z.
+func (z *Int) Neg(x *Int) *Int {
+ x.doinit()
+ z.doinit()
+ C.mpz_neg(&z.i[0], &x.i[0])
+ return z
+}
+
+// Abs sets z to the absolute value of x and returns z.
+func (z *Int) Abs(x *Int) *Int {
+ x.doinit()
+ z.doinit()
+ C.mpz_abs(&z.i[0], &x.i[0])
+ return z
+}
+
+/*
+ * functions without a clear receiver
+ */
+
+// CmpInt compares x and y. The result is
+//
+// -1 if x < y
+// 0 if x == y
+// +1 if x > y
+func CmpInt(x, y *Int) int {
+ x.doinit()
+ y.doinit()
+ switch cmp := C.mpz_cmp(&x.i[0], &y.i[0]); {
+ case cmp < 0:
+ return -1
+ case cmp == 0:
+ return 0
+ }
+ return +1
+}
+
+// DivModInt sets q = x / y and r = x % y.
+func DivModInt(q, r, x, y *Int) {
+ q.doinit()
+ r.doinit()
+ x.doinit()
+ y.doinit()
+ C.mpz_tdiv_qr(&q.i[0], &r.i[0], &x.i[0], &y.i[0])
+}
+
+// GcdInt sets d to the greatest common divisor of a and b,
+// which must be positive numbers.
+// If x and y are not nil, GcdInt sets x and y such that d = a*x + b*y.
+// If either a or b is not positive, GcdInt sets d = x = y = 0.
+func GcdInt(d, x, y, a, b *Int) {
+ d.doinit()
+ x.doinit()
+ y.doinit()
+ a.doinit()
+ b.doinit()
+ C.mpz_gcdext(&d.i[0], &x.i[0], &y.i[0], &a.i[0], &b.i[0])
+}
+
+// ProbablyPrime performs n Miller-Rabin tests to check whether z is prime.
+// If it returns true, z is prime with probability 1 - 1/4^n.
+// If it returns false, z is not prime.
+func (z *Int) ProbablyPrime(n int) bool {
+ z.doinit()
+ return int(C.mpz_probab_prime_p(&z.i[0], C.int(n))) > 0
+}
diff --git a/platform/dbops/binaries/go/go/misc/cgo/gmp/pi.go b/platform/dbops/binaries/go/go/misc/cgo/gmp/pi.go
new file mode 100644
index 0000000000000000000000000000000000000000..537a426b3804b39be477bcc42ab69202e7b0ffbf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/cgo/gmp/pi.go
@@ -0,0 +1,73 @@
+// 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
+
+package main
+
+import (
+ big "."
+ "fmt"
+ "runtime"
+)
+
+var (
+ tmp1 = big.NewInt(0)
+ tmp2 = big.NewInt(0)
+ numer = big.NewInt(1)
+ accum = big.NewInt(0)
+ denom = big.NewInt(1)
+ ten = big.NewInt(10)
+)
+
+func extractDigit() int64 {
+ if big.CmpInt(numer, accum) > 0 {
+ return -1
+ }
+ tmp1.Lsh(numer, 1).Add(tmp1, numer).Add(tmp1, accum)
+ big.DivModInt(tmp1, tmp2, tmp1, denom)
+ tmp2.Add(tmp2, numer)
+ if big.CmpInt(tmp2, denom) >= 0 {
+ return -1
+ }
+ return tmp1.Int64()
+}
+
+func nextTerm(k int64) {
+ y2 := k*2 + 1
+ accum.Add(accum, tmp1.Lsh(numer, 1))
+ accum.Mul(accum, tmp1.SetInt64(y2))
+ numer.Mul(numer, tmp1.SetInt64(k))
+ denom.Mul(denom, tmp1.SetInt64(y2))
+}
+
+func eliminateDigit(d int64) {
+ accum.Sub(accum, tmp1.Mul(denom, tmp1.SetInt64(d)))
+ accum.Mul(accum, ten)
+ numer.Mul(numer, ten)
+}
+
+func main() {
+ i := 0
+ k := int64(0)
+ for {
+ d := int64(-1)
+ for d < 0 {
+ k++
+ nextTerm(k)
+ d = extractDigit()
+ }
+ eliminateDigit(d)
+ fmt.Printf("%c", d+'0')
+
+ if i++; i%50 == 0 {
+ fmt.Printf("\n")
+ if i >= 1000 {
+ break
+ }
+ }
+ }
+
+ fmt.Printf("\n%d calls; bit sizes: %d %d %d\n", runtime.NumCgoCall(), numer.Len(), accum.Len(), denom.Len())
+}
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/README.txt b/platform/dbops/binaries/go/go/misc/chrome/gophertool/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a7c0b4b26817e1561b17a956277516c5e1a54c1f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/README.txt
@@ -0,0 +1,8 @@
+To install:
+
+1) chrome://extensions/
+2) click "[+] Developer Mode" in top right
+3) "Load unpacked extension..."
+4) pick $GOROOT/misc/chrome/gophertool
+
+Done. It'll now auto-reload from source.
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.html b/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.html
new file mode 100644
index 0000000000000000000000000000000000000000..06daa98b1420ea2955c32e1a0a86f996be392472
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.js b/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.js
new file mode 100644
index 0000000000000000000000000000000000000000..79ae05db4f711cee282960b9ef1a477b8339d276
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/background.js
@@ -0,0 +1,9 @@
+chrome.omnibox.onInputEntered.addListener(function(t) {
+ var url = urlForInput(t);
+ if (url) {
+ chrome.tabs.query({ "active": true, "currentWindow": true }, function(tab) {
+ if (!tab) return;
+ chrome.tabs.update(tab.id, { "url": url, "selected": true });
+ });
+ }
+});
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.js b/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.js
new file mode 100644
index 0000000000000000000000000000000000000000..09edb2957bdeadc11f57a7968ca145fce7bbd8c3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.js
@@ -0,0 +1,41 @@
+// 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.
+
+var numericRE = /^\d+$/;
+var commitRE = /^(?:\d+:)?([0-9a-f]{6,40})$/; // e.g "8486:ab29d2698a47" or "ab29d2698a47"
+var gerritChangeIdRE = /^I[0-9a-f]{4,40}$/; // e.g. Id69c00d908d18151486007ec03da5495b34b05f5
+var pkgRE = /^[a-z0-9_\/]+$/;
+
+function urlForInput(t) {
+ if (!t) {
+ return null;
+ }
+
+ if (numericRE.test(t)) {
+ if (t < 150000) {
+ // We could use the golang.org/cl/ handler here, but
+ // avoid some redirect latency and go right there, since
+ // one is easy. (no server-side mapping)
+ return "https://github.com/golang/go/issues/" + t;
+ }
+ return "https://golang.org/cl/" + t;
+ }
+
+ if (gerritChangeIdRE.test(t)) {
+ return "https://golang.org/cl/" + t;
+ }
+
+ var match = commitRE.exec(t);
+ if (match) {
+ return "https://golang.org/change/" + match[1];
+ }
+
+ if (pkgRE.test(t)) {
+ // TODO: make this smarter, using a list of packages + substring matches.
+ // Get the list from godoc itself in JSON format?
+ return "https://golang.org/pkg/" + t;
+ }
+
+ return null;
+}
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.png b/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.png
new file mode 100644
index 0000000000000000000000000000000000000000..ccf67539e4672e4328b1363a53c562594a45bae0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/gopher.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1e510d795337f3693248d60f733f729701ec970add5b3d7d2e2d05dcfe488730
+size 5588
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/manifest.json b/platform/dbops/binaries/go/go/misc/chrome/gophertool/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..04386594ae57902e6dd665dff7acf58eaa6798f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/manifest.json
@@ -0,0 +1,20 @@
+{
+ "name": "Hacking Gopher",
+ "version": "1.0",
+ "manifest_version": 2,
+ "description": "Go Hacking utility",
+ "background": {
+ "page": "background.html"
+ },
+ "browser_action": {
+ "default_icon": "gopher.png",
+ "default_popup": "popup.html"
+ },
+ "omnibox": { "keyword": "golang" },
+ "icons": {
+ "16": "gopher.png"
+ },
+ "permissions": [
+ "tabs"
+ ]
+}
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.html b/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.html
new file mode 100644
index 0000000000000000000000000000000000000000..ad42a3847c7d6265e1f666eb00c7122af7465c0f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.html
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+issue,
+codereview,
+commit, or
+pkg id/name:
+
+Also: buildbots
+GitHub
+
+
+
diff --git a/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.js b/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.js
new file mode 100644
index 0000000000000000000000000000000000000000..410d65120e6f067023f1c407b5dc76adfdae4e15
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/chrome/gophertool/popup.js
@@ -0,0 +1,46 @@
+function openURL(url) {
+ chrome.tabs.create({ "url": url })
+}
+
+function addLinks() {
+ var links = document.getElementsByTagName("a");
+ for (var i = 0; i < links.length; i++) {
+ var url = links[i].getAttribute("url");
+ if (url)
+ links[i].addEventListener("click", function () {
+ openURL(this.getAttribute("url"));
+ });
+ }
+}
+
+window.addEventListener("load", function () {
+ addLinks();
+ console.log("hacking gopher pop-up loaded.");
+ document.getElementById("inputbox").focus();
+});
+
+window.addEventListener("submit", function () {
+ console.log("submitting form");
+ var box = document.getElementById("inputbox");
+ box.focus();
+
+ var t = box.value;
+ if (t == "") {
+ return false;
+ }
+
+ var success = function(url) {
+ console.log("matched " + t + " to: " + url)
+ box.value = "";
+ openURL(url);
+ return false; // cancel form submission
+ };
+
+ var url = urlForInput(t);
+ if (url) {
+ return success(url);
+ }
+
+ console.log("no match for text: " + t)
+ return false;
+});
diff --git a/platform/dbops/binaries/go/go/misc/go_android_exec/README b/platform/dbops/binaries/go/go/misc/go_android_exec/README
new file mode 100644
index 0000000000000000000000000000000000000000..13b59d92f4859e99d7c2d1d1b4edaf6b83fb87f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/go_android_exec/README
@@ -0,0 +1,25 @@
+Android
+=======
+
+For details on developing Go for Android, see the documentation in the
+mobile subrepository:
+
+ https://github.com/golang/mobile
+
+To run the standard library tests, enable Cgo and use an appropriate
+C compiler from the Android NDK. For example,
+
+ CGO_ENABLED=1 \
+ GOOS=android \
+ GOARCH=arm64 \
+ CC_FOR_TARGET=$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang \
+ ./all.bash
+
+To run tests on the Android device, add the bin directory to PATH so the
+go tool can find the go_android_$GOARCH_exec wrapper generated by
+make.bash. For example, to run the go1 benchmarks
+
+ export PATH=$GOROOT/bin:$PATH
+ cd $GOROOT/test/bench/go1/
+ GOOS=android GOARCH=arm64 go test -bench=. -count=N -timeout=T
+
diff --git a/platform/dbops/binaries/go/go/misc/go_android_exec/exitcode_test.go b/platform/dbops/binaries/go/go/misc/go_android_exec/exitcode_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4ad2f60f86f43319c558d1f1e8ee6eb0f5459459
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/go_android_exec/exitcode_test.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.
+
+//go:build !(windows || js || wasip1)
+
+package main
+
+import (
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestExitCodeFilter(t *testing.T) {
+ // Write text to the filter one character at a time.
+ var out strings.Builder
+ f, exitStr := newExitCodeFilter(&out)
+ // Embed a "fake" exit code in the middle to check that we don't get caught on it.
+ pre := "abc" + exitStr + "123def"
+ text := pre + exitStr + `1`
+ for i := 0; i < len(text); i++ {
+ _, err := f.Write([]byte{text[i]})
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ // The "pre" output should all have been flushed already.
+ if want, got := pre, out.String(); want != got {
+ t.Errorf("filter should have already flushed %q, but flushed %q", want, got)
+ }
+
+ code, err := f.Finish()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Nothing more should have been written to out.
+ if want, got := pre, out.String(); want != got {
+ t.Errorf("want output %q, got %q", want, got)
+ }
+ if want := 1; want != code {
+ t.Errorf("want exit code %d, got %d", want, code)
+ }
+}
+
+func TestExitCodeMissing(t *testing.T) {
+ var wantErr *regexp.Regexp
+ check := func(text string) {
+ t.Helper()
+ var out strings.Builder
+ f, exitStr := newExitCodeFilter(&out)
+ if want := "exitcode="; want != exitStr {
+ t.Fatalf("test assumes exitStr will be %q, but got %q", want, exitStr)
+ }
+ f.Write([]byte(text))
+ _, err := f.Finish()
+ // We should get a no exit code error
+ if err == nil || !wantErr.MatchString(err.Error()) {
+ t.Errorf("want error matching %s, got %s", wantErr, err)
+ }
+ // And it should flush all output (even if it looks
+ // like we may be getting an exit code)
+ if got := out.String(); text != got {
+ t.Errorf("want full output %q, got %q", text, got)
+ }
+ }
+ wantErr = regexp.MustCompile("^no exit code")
+ check("abc")
+ check("exitcode")
+ check("exitcode=")
+ check("exitcode=123\n")
+ wantErr = regexp.MustCompile("^bad exit code: .* value out of range")
+ check("exitcode=999999999999999999999999")
+}
diff --git a/platform/dbops/binaries/go/go/misc/go_android_exec/main.go b/platform/dbops/binaries/go/go/misc/go_android_exec/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..33b669399c67d7943c6a69c26e8456ebbd080904
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/go_android_exec/main.go
@@ -0,0 +1,527 @@
+// 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 wrapper uses syscall.Flock to prevent concurrent adb commands,
+// so for now it only builds on platforms that support that system call.
+// TODO(#33974): use a more portable library for file locking.
+
+//go:build darwin || dragonfly || freebsd || illumos || linux || netbsd || openbsd
+
+// This program can be used as go_android_GOARCH_exec by the Go tool.
+// It executes binaries on an android device using adb.
+package main
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+)
+
+func adbRun(args string) (int, error) {
+ // The exit code of adb is often wrong. In theory it was fixed in 2016
+ // (https://code.google.com/p/android/issues/detail?id=3254), but it's
+ // still broken on our builders in 2023. Instead, append the exitcode to
+ // the output and parse it from there.
+ filter, exitStr := newExitCodeFilter(os.Stdout)
+ args += "; echo -n " + exitStr + "$?"
+
+ cmd := adbCmd("exec-out", args)
+ cmd.Stdout = filter
+ // If the adb subprocess somehow hangs, go test will kill this wrapper
+ // and wait for our os.Stderr (and os.Stdout) to close as a result.
+ // However, if the os.Stderr (or os.Stdout) file descriptors are
+ // passed on, the hanging adb subprocess will hold them open and
+ // go test will hang forever.
+ //
+ // Avoid that by wrapping stderr, breaking the short circuit and
+ // forcing cmd.Run to use another pipe and goroutine to pass
+ // along stderr from adb.
+ cmd.Stderr = struct{ io.Writer }{os.Stderr}
+ err := cmd.Run()
+
+ // Before we process err, flush any further output and get the exit code.
+ exitCode, err2 := filter.Finish()
+
+ if err != nil {
+ return 0, fmt.Errorf("adb exec-out %s: %v", args, err)
+ }
+ return exitCode, err2
+}
+
+func adb(args ...string) error {
+ if out, err := adbCmd(args...).CombinedOutput(); err != nil {
+ fmt.Fprintf(os.Stderr, "adb %s\n%s", strings.Join(args, " "), out)
+ return err
+ }
+ return nil
+}
+
+func adbCmd(args ...string) *exec.Cmd {
+ if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {
+ args = append(strings.Split(flags, " "), args...)
+ }
+ return exec.Command("adb", args...)
+}
+
+const (
+ deviceRoot = "/data/local/tmp/go_android_exec"
+ deviceGoroot = deviceRoot + "/goroot"
+)
+
+func main() {
+ log.SetFlags(0)
+ log.SetPrefix("go_android_exec: ")
+ exitCode, err := runMain()
+ if err != nil {
+ log.Fatal(err)
+ }
+ os.Exit(exitCode)
+}
+
+func runMain() (int, error) {
+ // Concurrent use of adb is flaky, so serialize adb commands.
+ // See https://github.com/golang/go/issues/23795 or
+ // https://issuetracker.google.com/issues/73230216.
+ lockPath := filepath.Join(os.TempDir(), "go_android_exec-adb-lock")
+ lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0666)
+ if err != nil {
+ return 0, err
+ }
+ defer lock.Close()
+ if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
+ return 0, err
+ }
+
+ // In case we're booting a device or emulator alongside all.bash, wait for
+ // it to be ready. adb wait-for-device is not enough, we have to
+ // wait for sys.boot_completed.
+ if err := adb("wait-for-device", "exec-out", "while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;"); err != nil {
+ return 0, err
+ }
+
+ // Done once per make.bash.
+ if err := adbCopyGoroot(); err != nil {
+ return 0, err
+ }
+
+ // Prepare a temporary directory that will be cleaned up at the end.
+ // Binary names can conflict.
+ // E.g. template.test from the {html,text}/template packages.
+ binName := filepath.Base(os.Args[1])
+ deviceGotmp := fmt.Sprintf(deviceRoot+"/%s-%d", binName, os.Getpid())
+ deviceGopath := deviceGotmp + "/gopath"
+ defer adb("exec-out", "rm", "-rf", deviceGotmp) // Clean up.
+
+ // Determine the package by examining the current working
+ // directory, which will look something like
+ // "$GOROOT/src/mime/multipart" or "$GOPATH/src/golang.org/x/mobile".
+ // We extract everything after the $GOROOT or $GOPATH to run on the
+ // same relative directory on the target device.
+ importPath, isStd, modPath, modDir, err := pkgPath()
+ if err != nil {
+ return 0, err
+ }
+ var deviceCwd string
+ if isStd {
+ // Note that we use path.Join here instead of filepath.Join:
+ // The device paths should be slash-separated even if the go_android_exec
+ // wrapper itself is compiled for Windows.
+ deviceCwd = path.Join(deviceGoroot, "src", importPath)
+ } else {
+ deviceCwd = path.Join(deviceGopath, "src", importPath)
+ if modDir != "" {
+ // In module mode, the user may reasonably expect the entire module
+ // to be present. Copy it over.
+ deviceModDir := path.Join(deviceGopath, "src", modPath)
+ if err := adb("exec-out", "mkdir", "-p", path.Dir(deviceModDir)); err != nil {
+ return 0, err
+ }
+ // We use a single recursive 'adb push' of the module root instead of
+ // walking the tree and copying it piecewise. If the directory tree
+ // contains nested modules this could push a lot of unnecessary contents,
+ // but for the golang.org/x repos it seems to be significantly (~2x)
+ // faster than copying one file at a time (via filepath.WalkDir),
+ // apparently due to high latency in 'adb' commands.
+ if err := adb("push", modDir, deviceModDir); err != nil {
+ return 0, err
+ }
+ } else {
+ if err := adb("exec-out", "mkdir", "-p", deviceCwd); err != nil {
+ return 0, err
+ }
+ if err := adbCopyTree(deviceCwd, importPath); err != nil {
+ return 0, err
+ }
+
+ // Copy .go files from the package.
+ goFiles, err := filepath.Glob("*.go")
+ if err != nil {
+ return 0, err
+ }
+ if len(goFiles) > 0 {
+ args := append(append([]string{"push"}, goFiles...), deviceCwd)
+ if err := adb(args...); err != nil {
+ return 0, err
+ }
+ }
+ }
+ }
+
+ deviceBin := fmt.Sprintf("%s/%s", deviceGotmp, binName)
+ if err := adb("push", os.Args[1], deviceBin); err != nil {
+ return 0, err
+ }
+
+ // Forward SIGQUIT from the go command to show backtraces from
+ // the binary instead of from this wrapper.
+ quit := make(chan os.Signal, 1)
+ signal.Notify(quit, syscall.SIGQUIT)
+ go func() {
+ for range quit {
+ // We don't have the PID of the running process; use the
+ // binary name instead.
+ adb("exec-out", "killall -QUIT "+binName)
+ }
+ }()
+ cmd := `export TMPDIR="` + deviceGotmp + `"` +
+ `; export GOROOT="` + deviceGoroot + `"` +
+ `; export GOPATH="` + deviceGopath + `"` +
+ `; export CGO_ENABLED=0` +
+ `; export GOPROXY=` + os.Getenv("GOPROXY") +
+ `; export GOCACHE="` + deviceRoot + `/gocache"` +
+ `; export PATH="` + deviceGoroot + `/bin":$PATH` +
+ `; export HOME="` + deviceRoot + `/home"` +
+ `; cd "` + deviceCwd + `"` +
+ "; '" + deviceBin + "' " + strings.Join(os.Args[2:], " ")
+ code, err := adbRun(cmd)
+ signal.Reset(syscall.SIGQUIT)
+ close(quit)
+ return code, err
+}
+
+type exitCodeFilter struct {
+ w io.Writer // Pass through to w
+ exitRe *regexp.Regexp
+ buf bytes.Buffer
+}
+
+func newExitCodeFilter(w io.Writer) (*exitCodeFilter, string) {
+ const exitStr = "exitcode="
+
+ // Build a regexp that matches any prefix of the exit string at the end of
+ // the input. We do it this way to avoid assuming anything about the
+ // subcommand output (e.g., it might not be \n-terminated).
+ var exitReStr strings.Builder
+ for i := 1; i <= len(exitStr); i++ {
+ fmt.Fprintf(&exitReStr, "%s$|", exitStr[:i])
+ }
+ // Finally, match the exit string along with an exit code.
+ // This is the only case we use a group, and we'll use this
+ // group to extract the numeric code.
+ fmt.Fprintf(&exitReStr, "%s([0-9]+)$", exitStr)
+ exitRe := regexp.MustCompile(exitReStr.String())
+
+ return &exitCodeFilter{w: w, exitRe: exitRe}, exitStr
+}
+
+func (f *exitCodeFilter) Write(data []byte) (int, error) {
+ n := len(data)
+ f.buf.Write(data)
+ // Flush to w until a potential match of exitRe
+ b := f.buf.Bytes()
+ match := f.exitRe.FindIndex(b)
+ if match == nil {
+ // Flush all of the buffer.
+ _, err := f.w.Write(b)
+ f.buf.Reset()
+ if err != nil {
+ return n, err
+ }
+ } else {
+ // Flush up to the beginning of the (potential) match.
+ _, err := f.w.Write(b[:match[0]])
+ f.buf.Next(match[0])
+ if err != nil {
+ return n, err
+ }
+ }
+ return n, nil
+}
+
+func (f *exitCodeFilter) Finish() (int, error) {
+ // f.buf could be empty, contain a partial match of exitRe, or
+ // contain a full match.
+ b := f.buf.Bytes()
+ defer f.buf.Reset()
+ match := f.exitRe.FindSubmatch(b)
+ if len(match) < 2 || match[1] == nil {
+ // Not a full match. Flush.
+ if _, err := f.w.Write(b); err != nil {
+ return 0, err
+ }
+ return 0, fmt.Errorf("no exit code (in %q)", string(b))
+ }
+
+ // Parse the exit code.
+ code, err := strconv.Atoi(string(match[1]))
+ if err != nil {
+ // Something is malformed. Flush.
+ if _, err := f.w.Write(b); err != nil {
+ return 0, err
+ }
+ return 0, fmt.Errorf("bad exit code: %v (in %q)", err, string(b))
+ }
+ return code, nil
+}
+
+// pkgPath determines the package import path of the current working directory,
+// and indicates whether it is
+// and returns the path to the package source relative to $GOROOT (or $GOPATH).
+func pkgPath() (importPath string, isStd bool, modPath, modDir string, err error) {
+ errorf := func(format string, args ...any) (string, bool, string, string, error) {
+ return "", false, "", "", fmt.Errorf(format, args...)
+ }
+ goTool, err := goTool()
+ if err != nil {
+ return errorf("%w", err)
+ }
+ cmd := exec.Command(goTool, "list", "-e", "-f", "{{.ImportPath}}:{{.Standard}}{{with .Module}}:{{.Path}}:{{.Dir}}{{end}}", ".")
+ out, err := cmd.Output()
+ if err != nil {
+ if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
+ return errorf("%v: %s", cmd, ee.Stderr)
+ }
+ return errorf("%v: %w", cmd, err)
+ }
+
+ parts := strings.SplitN(string(bytes.TrimSpace(out)), ":", 4)
+ if len(parts) < 2 {
+ return errorf("%v: missing ':' in output: %q", cmd, out)
+ }
+ importPath = parts[0]
+ if importPath == "" || importPath == "." {
+ return errorf("current directory does not have a Go import path")
+ }
+ isStd, err = strconv.ParseBool(parts[1])
+ if err != nil {
+ return errorf("%v: non-boolean .Standard in output: %q", cmd, out)
+ }
+ if len(parts) >= 4 {
+ modPath = parts[2]
+ modDir = parts[3]
+ }
+
+ return importPath, isStd, modPath, modDir, nil
+}
+
+// adbCopyTree copies testdata, go.mod, go.sum files from subdir
+// and from parent directories all the way up to the root of subdir.
+// go.mod and go.sum files are needed for the go tool modules queries,
+// and the testdata directories for tests. It is common for tests to
+// reach out into testdata from parent packages.
+func adbCopyTree(deviceCwd, subdir string) error {
+ dir := ""
+ for {
+ for _, name := range []string{"testdata", "go.mod", "go.sum"} {
+ hostPath := filepath.Join(dir, name)
+ if _, err := os.Stat(hostPath); err != nil {
+ continue
+ }
+ devicePath := path.Join(deviceCwd, dir)
+ if err := adb("exec-out", "mkdir", "-p", devicePath); err != nil {
+ return err
+ }
+ if err := adb("push", hostPath, devicePath); err != nil {
+ return err
+ }
+ }
+ if subdir == "." {
+ break
+ }
+ subdir = filepath.Dir(subdir)
+ dir = path.Join(dir, "..")
+ }
+ return nil
+}
+
+// adbCopyGoroot clears deviceRoot for previous versions of GOROOT, GOPATH
+// and temporary data. Then, it copies relevant parts of GOROOT to the device,
+// including the go tool built for android.
+// A lock file ensures this only happens once, even with concurrent exec
+// wrappers.
+func adbCopyGoroot() error {
+ goTool, err := goTool()
+ if err != nil {
+ return err
+ }
+ cmd := exec.Command(goTool, "version")
+ cmd.Stderr = os.Stderr
+ out, err := cmd.Output()
+ if err != nil {
+ return fmt.Errorf("%v: %w", cmd, err)
+ }
+ goVersion := string(out)
+
+ // Also known by cmd/dist. The bootstrap command deletes the file.
+ statPath := filepath.Join(os.TempDir(), "go_android_exec-adb-sync-status")
+ stat, err := os.OpenFile(statPath, os.O_CREATE|os.O_RDWR, 0666)
+ if err != nil {
+ return err
+ }
+ defer stat.Close()
+ // Serialize check and copying.
+ if err := syscall.Flock(int(stat.Fd()), syscall.LOCK_EX); err != nil {
+ return err
+ }
+ s, err := io.ReadAll(stat)
+ if err != nil {
+ return err
+ }
+ if string(s) == goVersion {
+ return nil
+ }
+
+ goroot, err := findGoroot()
+ if err != nil {
+ return err
+ }
+
+ // Delete the device's GOROOT, GOPATH and any leftover test data,
+ // and recreate GOROOT.
+ if err := adb("exec-out", "rm", "-rf", deviceRoot); err != nil {
+ return err
+ }
+
+ // Build Go for Android.
+ cmd = exec.Command(goTool, "install", "cmd")
+ out, err = cmd.CombinedOutput()
+ if err != nil {
+ if len(bytes.TrimSpace(out)) > 0 {
+ log.Printf("\n%s", out)
+ }
+ return fmt.Errorf("%v: %w", cmd, err)
+ }
+ if err := adb("exec-out", "mkdir", "-p", deviceGoroot); err != nil {
+ return err
+ }
+
+ // Copy the Android tools from the relevant bin subdirectory to GOROOT/bin.
+ cmd = exec.Command(goTool, "list", "-f", "{{.Target}}", "cmd/go")
+ cmd.Stderr = os.Stderr
+ out, err = cmd.Output()
+ if err != nil {
+ return fmt.Errorf("%v: %w", cmd, err)
+ }
+ platformBin := filepath.Dir(string(bytes.TrimSpace(out)))
+ if platformBin == "." {
+ return errors.New("failed to locate cmd/go for target platform")
+ }
+ if err := adb("push", platformBin, path.Join(deviceGoroot, "bin")); err != nil {
+ return err
+ }
+
+ // Copy only the relevant subdirectories from pkg: pkg/include and the
+ // platform-native binaries in pkg/tool.
+ if err := adb("exec-out", "mkdir", "-p", path.Join(deviceGoroot, "pkg", "tool")); err != nil {
+ return err
+ }
+ if err := adb("push", filepath.Join(goroot, "pkg", "include"), path.Join(deviceGoroot, "pkg", "include")); err != nil {
+ return err
+ }
+
+ cmd = exec.Command(goTool, "list", "-f", "{{.Target}}", "cmd/compile")
+ cmd.Stderr = os.Stderr
+ out, err = cmd.Output()
+ if err != nil {
+ return fmt.Errorf("%v: %w", cmd, err)
+ }
+ platformToolDir := filepath.Dir(string(bytes.TrimSpace(out)))
+ if platformToolDir == "." {
+ return errors.New("failed to locate cmd/compile for target platform")
+ }
+ relToolDir, err := filepath.Rel(filepath.Join(goroot), platformToolDir)
+ if err != nil {
+ return err
+ }
+ if err := adb("push", platformToolDir, path.Join(deviceGoroot, relToolDir)); err != nil {
+ return err
+ }
+
+ // Copy all other files from GOROOT.
+ dirents, err := os.ReadDir(goroot)
+ if err != nil {
+ return err
+ }
+ for _, de := range dirents {
+ switch de.Name() {
+ case "bin", "pkg":
+ // We already created GOROOT/bin and GOROOT/pkg above; skip those.
+ continue
+ }
+ if err := adb("push", filepath.Join(goroot, de.Name()), path.Join(deviceGoroot, de.Name())); err != nil {
+ return err
+ }
+ }
+
+ if _, err := stat.WriteString(goVersion); err != nil {
+ return err
+ }
+ return nil
+}
+
+func findGoroot() (string, error) {
+ gorootOnce.Do(func() {
+ // If runtime.GOROOT reports a non-empty path, assume that it is valid.
+ // (It may be empty if this binary was built with -trimpath.)
+ gorootPath = runtime.GOROOT()
+ if gorootPath != "" {
+ return
+ }
+
+ // runtime.GOROOT is empty — perhaps go_android_exec was built with
+ // -trimpath and GOROOT is unset. Try 'go env GOROOT' as a fallback,
+ // assuming that the 'go' command in $PATH is the correct one.
+
+ cmd := exec.Command("go", "env", "GOROOT")
+ cmd.Stderr = os.Stderr
+ out, err := cmd.Output()
+ if err != nil {
+ gorootErr = fmt.Errorf("%v: %w", cmd, err)
+ }
+
+ gorootPath = string(bytes.TrimSpace(out))
+ if gorootPath == "" {
+ gorootErr = errors.New("GOROOT not found")
+ }
+ })
+
+ return gorootPath, gorootErr
+}
+
+func goTool() (string, error) {
+ goroot, err := findGoroot()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(goroot, "bin", "go"), nil
+}
+
+var (
+ gorootOnce sync.Once
+ gorootPath string
+ gorootErr error
+)
diff --git a/platform/dbops/binaries/go/go/misc/ios/README b/platform/dbops/binaries/go/go/misc/ios/README
new file mode 100644
index 0000000000000000000000000000000000000000..0f5e9e335ea000251c469d6e80b3d6ae897254a6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/ios/README
@@ -0,0 +1,57 @@
+Go on iOS
+=========
+
+To run the standard library tests, run all.bash as usual, but with the compiler
+set to the clang wrapper that invokes clang for iOS. For example, this command runs
+ all.bash on the iOS emulator:
+
+ GOOS=ios GOARCH=amd64 CGO_ENABLED=1 CC_FOR_TARGET=$(pwd)/../misc/ios/clangwrap.sh ./all.bash
+
+If CC_FOR_TARGET is not set when the toolchain is built (make.bash or all.bash), CC
+can be set on the command line. For example,
+
+ GOOS=ios GOARCH=amd64 CGO_ENABLED=1 CC=$(go env GOROOT)/misc/ios/clangwrap.sh go build
+
+Setting CC is not necessary if the toolchain is built with CC_FOR_TARGET set.
+
+To use the go tool to run individual programs and tests, put $GOROOT/bin into PATH to ensure
+the go_ios_$GOARCH_exec wrapper is found. For example, to run the archive/tar tests:
+
+ export PATH=$GOROOT/bin:$PATH
+ GOOS=ios GOARCH=amd64 CGO_ENABLED=1 go test archive/tar
+
+The go_ios_exec wrapper uses GOARCH to select the emulator (amd64) or the device (arm64).
+However, further setup is required to run tests or programs directly on a device.
+
+First make sure you have a valid developer certificate and have setup your device properly
+to run apps signed by your developer certificate. Then install the libimobiledevice and
+ideviceinstaller tools from https://www.libimobiledevice.org/. Use the HEAD versions from
+source; the stable versions have bugs that prevents the Go exec wrapper to install and run
+apps.
+
+Second, the Go exec wrapper must be told the developer account signing identity, the team
+id and a provisioned bundle id to use. They're specified with the environment variables
+GOIOS_DEV_ID, GOIOS_TEAM_ID and GOIOS_APP_ID. The detect.go program in this directory will
+attempt to auto-detect suitable values. Run it as
+
+ go run detect.go
+
+which will output something similar to
+
+ export GOIOS_DEV_ID="iPhone Developer: xxx@yyy.zzz (XXXXXXXX)"
+ export GOIOS_APP_ID=YYYYYYYY.some.bundle.id
+ export GOIOS_TEAM_ID=ZZZZZZZZ
+
+If you have multiple devices connected, specify the device UDID with the GOIOS_DEVICE_ID
+variable. Use `idevice_id -l` to list all available UDIDs. Then, setting GOARCH to arm64
+will select the device:
+
+ GOOS=ios GOARCH=arm64 CGO_ENABLED=1 CC_FOR_TARGET=$(pwd)/../misc/ios/clangwrap.sh ./all.bash
+
+Note that the go_darwin_$GOARCH_exec wrapper uninstalls any existing app identified by
+the bundle id before installing a new app. If the uninstalled app is the last app by
+the developer identity, the device might also remove the permission to run apps from
+that developer, and the exec wrapper will fail to install the new app. To avoid that,
+install another app with the same developer identity but with a different bundle id.
+That way, the permission to install apps is held on to while the primary app is
+uninstalled.
diff --git a/platform/dbops/binaries/go/go/misc/ios/clangwrap.sh b/platform/dbops/binaries/go/go/misc/ios/clangwrap.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8f7b439315bff743618ad74ad1818ed6da017e2f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/ios/clangwrap.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# This uses the latest available iOS SDK, which is recommended.
+# To select a specific SDK, run 'xcodebuild -showsdks'
+# to see the available SDKs and replace iphoneos with one of them.
+if [ "$GOARCH" == "arm64" ]; then
+ SDK=iphoneos
+ PLATFORM=ios
+ CLANGARCH="arm64"
+else
+ SDK=iphonesimulator
+ PLATFORM=ios-simulator
+ CLANGARCH="x86_64"
+fi
+
+SDK_PATH=`xcrun --sdk $SDK --show-sdk-path`
+export IPHONEOS_DEPLOYMENT_TARGET=5.1
+# cmd/cgo doesn't support llvm-gcc-4.2, so we have to use clang.
+CLANG=`xcrun --sdk $SDK --find clang`
+
+exec "$CLANG" -arch $CLANGARCH -isysroot "$SDK_PATH" -m${PLATFORM}-version-min=12.0 "$@"
diff --git a/platform/dbops/binaries/go/go/misc/ios/detect.go b/platform/dbops/binaries/go/go/misc/ios/detect.go
new file mode 100644
index 0000000000000000000000000000000000000000..1a72eafda02436e53d14011963ff43c624cf69b9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/ios/detect.go
@@ -0,0 +1,133 @@
+// 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 ignore
+
+// detect attempts to autodetect the correct
+// values of the environment variables
+// used by go_ios_exec.
+// detect shells out to ideviceinfo, a third party program that can
+// be obtained by following the instructions at
+// https://github.com/libimobiledevice/libimobiledevice.
+package main
+
+import (
+ "bytes"
+ "crypto/x509"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+func main() {
+ udids := getLines(exec.Command("idevice_id", "-l"))
+ if len(udids) == 0 {
+ fail("no udid found; is a device connected?")
+ }
+
+ mps := detectMobileProvisionFiles(udids)
+ if len(mps) == 0 {
+ fail("did not find mobile provision matching device udids %q", udids)
+ }
+
+ fmt.Println("# Available provisioning profiles below.")
+ fmt.Println("# NOTE: Any existing app on the device with the app id specified by GOIOS_APP_ID")
+ fmt.Println("# will be overwritten when running Go programs.")
+ for _, mp := range mps {
+ fmt.Println()
+ f, err := os.CreateTemp("", "go_ios_detect_")
+ check(err)
+ fname := f.Name()
+ defer os.Remove(fname)
+
+ out := output(parseMobileProvision(mp))
+ _, err = f.Write(out)
+ check(err)
+ check(f.Close())
+
+ cert, err := plistExtract(fname, "DeveloperCertificates:0")
+ check(err)
+ pcert, err := x509.ParseCertificate(cert)
+ check(err)
+ fmt.Printf("export GOIOS_DEV_ID=\"%s\"\n", pcert.Subject.CommonName)
+
+ appID, err := plistExtract(fname, "Entitlements:application-identifier")
+ check(err)
+ fmt.Printf("export GOIOS_APP_ID=%s\n", appID)
+
+ teamID, err := plistExtract(fname, "Entitlements:com.apple.developer.team-identifier")
+ check(err)
+ fmt.Printf("export GOIOS_TEAM_ID=%s\n", teamID)
+ }
+}
+
+func detectMobileProvisionFiles(udids [][]byte) []string {
+ cmd := exec.Command("mdfind", "-name", ".mobileprovision")
+ lines := getLines(cmd)
+
+ var files []string
+ for _, line := range lines {
+ if len(line) == 0 {
+ continue
+ }
+ xmlLines := getLines(parseMobileProvision(string(line)))
+ matches := 0
+ for _, udid := range udids {
+ for _, xmlLine := range xmlLines {
+ if bytes.Contains(xmlLine, udid) {
+ matches++
+ }
+ }
+ }
+ if matches == len(udids) {
+ files = append(files, string(line))
+ }
+ }
+ return files
+}
+
+func parseMobileProvision(fname string) *exec.Cmd {
+ return exec.Command("security", "cms", "-D", "-i", string(fname))
+}
+
+func plistExtract(fname string, path string) ([]byte, error) {
+ out, err := exec.Command("/usr/libexec/PlistBuddy", "-c", "Print "+path, fname).CombinedOutput()
+ if err != nil {
+ return nil, err
+ }
+ return bytes.TrimSpace(out), nil
+}
+
+func getLines(cmd *exec.Cmd) [][]byte {
+ out := output(cmd)
+ lines := bytes.Split(out, []byte("\n"))
+ // Skip the empty line at the end.
+ if len(lines[len(lines)-1]) == 0 {
+ lines = lines[:len(lines)-1]
+ }
+ return lines
+}
+
+func output(cmd *exec.Cmd) []byte {
+ out, err := cmd.Output()
+ if err != nil {
+ fmt.Println(strings.Join(cmd.Args, "\n"))
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ return out
+}
+
+func check(err error) {
+ if err != nil {
+ fail(err.Error())
+ }
+}
+
+func fail(msg string, v ...interface{}) {
+ fmt.Fprintf(os.Stderr, msg, v...)
+ fmt.Fprintln(os.Stderr)
+ os.Exit(1)
+}
diff --git a/platform/dbops/binaries/go/go/misc/ios/go_ios_exec.go b/platform/dbops/binaries/go/go/misc/ios/go_ios_exec.go
new file mode 100644
index 0000000000000000000000000000000000000000..c275dd339cc9bd9bc953f4ba8170cb46f9dcead1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/ios/go_ios_exec.go
@@ -0,0 +1,911 @@
+// 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 program can be used as go_ios_$GOARCH_exec by the Go tool.
+// It executes binaries on an iOS device using the XCode toolchain
+// and the ios-deploy program: https://github.com/phonegap/ios-deploy
+//
+// This script supports an extra flag, -lldb, that pauses execution
+// just before the main program begins and allows the user to control
+// the remote lldb session. This flag is appended to the end of the
+// script's arguments and is not passed through to the underlying
+// binary.
+//
+// This script requires that three environment variables be set:
+//
+// GOIOS_DEV_ID: The codesigning developer id or certificate identifier
+// GOIOS_APP_ID: The provisioning app id prefix. Must support wildcard app ids.
+// GOIOS_TEAM_ID: The team id that owns the app id prefix.
+//
+// $GOROOT/misc/ios contains a script, detect.go, that attempts to autodetect these.
+package main
+
+import (
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "go/build"
+ "io"
+ "log"
+ "net"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+)
+
+const debug = false
+
+var tmpdir string
+
+var (
+ devID string
+ appID string
+ teamID string
+ bundleID string
+ deviceID string
+)
+
+// lock is a file lock to serialize iOS runs. It is global to avoid the
+// garbage collector finalizing it, closing the file and releasing the
+// lock prematurely.
+var lock *os.File
+
+func main() {
+ log.SetFlags(0)
+ log.SetPrefix("go_ios_exec: ")
+ if debug {
+ log.Println(strings.Join(os.Args, " "))
+ }
+ if len(os.Args) < 2 {
+ log.Fatal("usage: go_ios_exec a.out")
+ }
+
+ // For compatibility with the old builders, use a fallback bundle ID
+ bundleID = "golang.gotest"
+
+ exitCode, err := runMain()
+ if err != nil {
+ log.Fatalf("%v\n", err)
+ }
+ os.Exit(exitCode)
+}
+
+func runMain() (int, error) {
+ var err error
+ tmpdir, err = os.MkdirTemp("", "go_ios_exec_")
+ if err != nil {
+ return 1, err
+ }
+ if !debug {
+ defer os.RemoveAll(tmpdir)
+ }
+
+ appdir := filepath.Join(tmpdir, "gotest.app")
+ os.RemoveAll(appdir)
+
+ if err := assembleApp(appdir, os.Args[1]); err != nil {
+ return 1, err
+ }
+
+ // This wrapper uses complicated machinery to run iOS binaries. It
+ // works, but only when running one binary at a time.
+ // Use a file lock to make sure only one wrapper is running at a time.
+ //
+ // The lock file is never deleted, to avoid concurrent locks on distinct
+ // files with the same path.
+ lockName := filepath.Join(os.TempDir(), "go_ios_exec-"+deviceID+".lock")
+ lock, err = os.OpenFile(lockName, os.O_CREATE|os.O_RDONLY, 0666)
+ if err != nil {
+ return 1, err
+ }
+ if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
+ return 1, err
+ }
+
+ if goarch := os.Getenv("GOARCH"); goarch == "arm64" {
+ err = runOnDevice(appdir)
+ } else {
+ err = runOnSimulator(appdir)
+ }
+ if err != nil {
+ // If the lldb driver completed with an exit code, use that.
+ if err, ok := err.(*exec.ExitError); ok {
+ if ws, ok := err.Sys().(interface{ ExitStatus() int }); ok {
+ return ws.ExitStatus(), nil
+ }
+ }
+ return 1, err
+ }
+ return 0, nil
+}
+
+func runOnSimulator(appdir string) error {
+ if err := installSimulator(appdir); err != nil {
+ return err
+ }
+
+ return runSimulator(appdir, bundleID, os.Args[2:])
+}
+
+func runOnDevice(appdir string) error {
+ // e.g. B393DDEB490947F5A463FD074299B6C0AXXXXXXX
+ devID = getenv("GOIOS_DEV_ID")
+
+ // e.g. Z8B3JBXXXX.org.golang.sample, Z8B3JBXXXX prefix is available at
+ // https://developer.apple.com/membercenter/index.action#accountSummary as Team ID.
+ appID = getenv("GOIOS_APP_ID")
+
+ // e.g. Z8B3JBXXXX, available at
+ // https://developer.apple.com/membercenter/index.action#accountSummary as Team ID.
+ teamID = getenv("GOIOS_TEAM_ID")
+
+ // Device IDs as listed with ios-deploy -c.
+ deviceID = os.Getenv("GOIOS_DEVICE_ID")
+
+ if _, id, ok := strings.Cut(appID, "."); ok {
+ bundleID = id
+ }
+
+ if err := signApp(appdir); err != nil {
+ return err
+ }
+
+ if err := uninstallDevice(bundleID); err != nil {
+ return err
+ }
+
+ if err := installDevice(appdir); err != nil {
+ return err
+ }
+
+ if err := mountDevImage(); err != nil {
+ return err
+ }
+
+ // Kill any hanging debug bridges that might take up port 3222.
+ exec.Command("killall", "idevicedebugserverproxy").Run()
+
+ closer, err := startDebugBridge()
+ if err != nil {
+ return err
+ }
+ defer closer()
+
+ return runDevice(appdir, bundleID, os.Args[2:])
+}
+
+func getenv(envvar string) string {
+ s := os.Getenv(envvar)
+ if s == "" {
+ log.Fatalf("%s not set\nrun $GOROOT/misc/ios/detect.go to attempt to autodetect", envvar)
+ }
+ return s
+}
+
+func assembleApp(appdir, bin string) error {
+ if err := os.MkdirAll(appdir, 0755); err != nil {
+ return err
+ }
+
+ if err := cp(filepath.Join(appdir, "gotest"), bin); err != nil {
+ return err
+ }
+
+ pkgpath, err := copyLocalData(appdir)
+ if err != nil {
+ return err
+ }
+
+ entitlementsPath := filepath.Join(tmpdir, "Entitlements.plist")
+ if err := os.WriteFile(entitlementsPath, []byte(entitlementsPlist()), 0744); err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(appdir, "Info.plist"), []byte(infoPlist(pkgpath)), 0744); err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(appdir, "ResourceRules.plist"), []byte(resourceRules), 0744); err != nil {
+ return err
+ }
+ return nil
+}
+
+func signApp(appdir string) error {
+ entitlementsPath := filepath.Join(tmpdir, "Entitlements.plist")
+ cmd := exec.Command(
+ "codesign",
+ "-f",
+ "-s", devID,
+ "--entitlements", entitlementsPath,
+ appdir,
+ )
+ if debug {
+ log.Println(strings.Join(cmd.Args, " "))
+ }
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("codesign: %v", err)
+ }
+ return nil
+}
+
+// mountDevImage ensures a developer image is mounted on the device.
+// The image contains the device lldb server for idevicedebugserverproxy
+// to connect to.
+func mountDevImage() error {
+ // Check for existing mount.
+ cmd := idevCmd(exec.Command("ideviceimagemounter", "-l", "-x"))
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ os.Stderr.Write(out)
+ return fmt.Errorf("ideviceimagemounter: %v", err)
+ }
+ var info struct {
+ Dict struct {
+ Data []byte `xml:",innerxml"`
+ } `xml:"dict"`
+ }
+ if err := xml.Unmarshal(out, &info); err != nil {
+ return fmt.Errorf("mountDevImage: failed to decode mount information: %v", err)
+ }
+ dict, err := parsePlistDict(info.Dict.Data)
+ if err != nil {
+ return fmt.Errorf("mountDevImage: failed to parse mount information: %v", err)
+ }
+ if dict["ImagePresent"] == "true" && dict["Status"] == "Complete" {
+ return nil
+ }
+ // Some devices only give us an ImageSignature key.
+ if _, exists := dict["ImageSignature"]; exists {
+ return nil
+ }
+ // No image is mounted. Find a suitable image.
+ imgPath, err := findDevImage()
+ if err != nil {
+ return err
+ }
+ sigPath := imgPath + ".signature"
+ cmd = idevCmd(exec.Command("ideviceimagemounter", imgPath, sigPath))
+ if out, err := cmd.CombinedOutput(); err != nil {
+ os.Stderr.Write(out)
+ return fmt.Errorf("ideviceimagemounter: %v", err)
+ }
+ return nil
+}
+
+// findDevImage use the device iOS version and build to locate a suitable
+// developer image.
+func findDevImage() (string, error) {
+ cmd := idevCmd(exec.Command("ideviceinfo"))
+ out, err := cmd.Output()
+ if err != nil {
+ return "", fmt.Errorf("ideviceinfo: %v", err)
+ }
+ var iosVer, buildVer string
+ lines := bytes.Split(out, []byte("\n"))
+ for _, line := range lines {
+ key, val, ok := strings.Cut(string(line), ": ")
+ if !ok {
+ continue
+ }
+ switch key {
+ case "ProductVersion":
+ iosVer = val
+ case "BuildVersion":
+ buildVer = val
+ }
+ }
+ if iosVer == "" || buildVer == "" {
+ return "", errors.New("failed to parse ideviceinfo output")
+ }
+ verSplit := strings.Split(iosVer, ".")
+ if len(verSplit) > 2 {
+ // Developer images are specific to major.minor ios version.
+ // Cut off the patch version.
+ iosVer = strings.Join(verSplit[:2], ".")
+ }
+ sdkBase := "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
+ patterns := []string{fmt.Sprintf("%s (%s)", iosVer, buildVer), fmt.Sprintf("%s (*)", iosVer), fmt.Sprintf("%s*", iosVer)}
+ for _, pattern := range patterns {
+ matches, err := filepath.Glob(filepath.Join(sdkBase, pattern, "DeveloperDiskImage.dmg"))
+ if err != nil {
+ return "", fmt.Errorf("findDevImage: %v", err)
+ }
+ if len(matches) > 0 {
+ return matches[0], nil
+ }
+ }
+ return "", fmt.Errorf("failed to find matching developer image for iOS version %s build %s", iosVer, buildVer)
+}
+
+// startDebugBridge ensures that the idevicedebugserverproxy runs on
+// port 3222.
+func startDebugBridge() (func(), error) {
+ errChan := make(chan error, 1)
+ cmd := idevCmd(exec.Command("idevicedebugserverproxy", "3222"))
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ if err := cmd.Start(); err != nil {
+ return nil, fmt.Errorf("idevicedebugserverproxy: %v", err)
+ }
+ go func() {
+ if err := cmd.Wait(); err != nil {
+ if _, ok := err.(*exec.ExitError); ok {
+ errChan <- fmt.Errorf("idevicedebugserverproxy: %s", stderr.Bytes())
+ } else {
+ errChan <- fmt.Errorf("idevicedebugserverproxy: %v", err)
+ }
+ }
+ errChan <- nil
+ }()
+ closer := func() {
+ cmd.Process.Kill()
+ <-errChan
+ }
+ // Dial localhost:3222 to ensure the proxy is ready.
+ delay := time.Second / 4
+ for attempt := 0; attempt < 5; attempt++ {
+ conn, err := net.DialTimeout("tcp", "localhost:3222", 5*time.Second)
+ if err == nil {
+ conn.Close()
+ return closer, nil
+ }
+ select {
+ case <-time.After(delay):
+ delay *= 2
+ case err := <-errChan:
+ return nil, err
+ }
+ }
+ closer()
+ return nil, errors.New("failed to set up idevicedebugserverproxy")
+}
+
+// findDeviceAppPath returns the device path to the app with the
+// given bundle ID. It parses the output of ideviceinstaller -l -o xml,
+// looking for the bundle ID and the corresponding Path value.
+func findDeviceAppPath(bundleID string) (string, error) {
+ cmd := idevCmd(exec.Command("ideviceinstaller", "-l", "-o", "xml"))
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ os.Stderr.Write(out)
+ return "", fmt.Errorf("ideviceinstaller: -l -o xml %v", err)
+ }
+ var list struct {
+ Apps []struct {
+ Data []byte `xml:",innerxml"`
+ } `xml:"array>dict"`
+ }
+ if err := xml.Unmarshal(out, &list); err != nil {
+ return "", fmt.Errorf("failed to parse ideviceinstaller output: %v", err)
+ }
+ for _, app := range list.Apps {
+ values, err := parsePlistDict(app.Data)
+ if err != nil {
+ return "", fmt.Errorf("findDeviceAppPath: failed to parse app dict: %v", err)
+ }
+ if values["CFBundleIdentifier"] == bundleID {
+ if path, ok := values["Path"]; ok {
+ return path, nil
+ }
+ }
+ }
+ return "", fmt.Errorf("failed to find device path for bundle: %s", bundleID)
+}
+
+// Parse an xml encoded plist. Plist values are mapped to string.
+func parsePlistDict(dict []byte) (map[string]string, error) {
+ d := xml.NewDecoder(bytes.NewReader(dict))
+ values := make(map[string]string)
+ var key string
+ var hasKey bool
+ for {
+ tok, err := d.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, err
+ }
+ if tok, ok := tok.(xml.StartElement); ok {
+ if tok.Name.Local == "key" {
+ if err := d.DecodeElement(&key, &tok); err != nil {
+ return nil, err
+ }
+ hasKey = true
+ } else if hasKey {
+ var val string
+ var err error
+ switch n := tok.Name.Local; n {
+ case "true", "false":
+ // Bools are represented as and .
+ val = n
+ err = d.Skip()
+ default:
+ err = d.DecodeElement(&val, &tok)
+ }
+ if err != nil {
+ return nil, err
+ }
+ values[key] = val
+ hasKey = false
+ } else {
+ if err := d.Skip(); err != nil {
+ return nil, err
+ }
+ }
+ }
+ }
+ return values, nil
+}
+
+func installSimulator(appdir string) error {
+ cmd := exec.Command(
+ "xcrun", "simctl", "install",
+ "booted", // Install to the booted simulator.
+ appdir,
+ )
+ if out, err := cmd.CombinedOutput(); err != nil {
+ os.Stderr.Write(out)
+ return fmt.Errorf("xcrun simctl install booted %q: %v", appdir, err)
+ }
+ return nil
+}
+
+func uninstallDevice(bundleID string) error {
+ cmd := idevCmd(exec.Command(
+ "ideviceinstaller",
+ "-U", bundleID,
+ ))
+ if out, err := cmd.CombinedOutput(); err != nil {
+ os.Stderr.Write(out)
+ return fmt.Errorf("ideviceinstaller -U %q: %s", bundleID, err)
+ }
+ return nil
+}
+
+func installDevice(appdir string) error {
+ attempt := 0
+ for {
+ cmd := idevCmd(exec.Command(
+ "ideviceinstaller",
+ "-i", appdir,
+ ))
+ if out, err := cmd.CombinedOutput(); err != nil {
+ // Sometimes, installing the app fails for some reason.
+ // Give the device a few seconds and try again.
+ if attempt < 5 {
+ time.Sleep(5 * time.Second)
+ attempt++
+ continue
+ }
+ os.Stderr.Write(out)
+ return fmt.Errorf("ideviceinstaller -i %q: %v (%d attempts)", appdir, err, attempt)
+ }
+ return nil
+ }
+}
+
+func idevCmd(cmd *exec.Cmd) *exec.Cmd {
+ if deviceID != "" {
+ // Inject -u device_id after the executable, but before the arguments.
+ args := []string{cmd.Args[0], "-u", deviceID}
+ cmd.Args = append(args, cmd.Args[1:]...)
+ }
+ return cmd
+}
+
+func runSimulator(appdir, bundleID string, args []string) error {
+ cmd := exec.Command(
+ "xcrun", "simctl", "launch",
+ "--wait-for-debugger",
+ "booted",
+ bundleID,
+ )
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ os.Stderr.Write(out)
+ return fmt.Errorf("xcrun simctl launch booted %q: %v", bundleID, err)
+ }
+ var processID int
+ var ignore string
+ if _, err := fmt.Sscanf(string(out), "%s %d", &ignore, &processID); err != nil {
+ return fmt.Errorf("runSimulator: couldn't find processID from `simctl launch`: %v (%q)", err, out)
+ }
+ _, err = runLLDB("ios-simulator", appdir, strconv.Itoa(processID), args)
+ return err
+}
+
+func runDevice(appdir, bundleID string, args []string) error {
+ attempt := 0
+ for {
+ // The device app path reported by the device might be stale, so retry
+ // the lookup of the device path along with the lldb launching below.
+ deviceapp, err := findDeviceAppPath(bundleID)
+ if err != nil {
+ // The device app path might not yet exist for a newly installed app.
+ if attempt == 5 {
+ return err
+ }
+ attempt++
+ time.Sleep(5 * time.Second)
+ continue
+ }
+ out, err := runLLDB("remote-ios", appdir, deviceapp, args)
+ // If the program was not started it can be retried without papering over
+ // real test failures.
+ started := bytes.HasPrefix(out, []byte("lldb: running program"))
+ if started || err == nil || attempt == 5 {
+ return err
+ }
+ // Sometimes, the app was not yet ready to launch or the device path was
+ // stale. Retry.
+ attempt++
+ time.Sleep(5 * time.Second)
+ }
+}
+
+func runLLDB(target, appdir, deviceapp string, args []string) ([]byte, error) {
+ var env []string
+ for _, e := range os.Environ() {
+ // Don't override TMPDIR, HOME, GOCACHE on the device.
+ if strings.HasPrefix(e, "TMPDIR=") || strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "GOCACHE=") {
+ continue
+ }
+ env = append(env, e)
+ }
+ lldb := exec.Command(
+ "python",
+ "-", // Read script from stdin.
+ target,
+ appdir,
+ deviceapp,
+ )
+ lldb.Args = append(lldb.Args, args...)
+ lldb.Env = env
+ lldb.Stdin = strings.NewReader(lldbDriver)
+ lldb.Stdout = os.Stdout
+ var out bytes.Buffer
+ lldb.Stderr = io.MultiWriter(&out, os.Stderr)
+ err := lldb.Start()
+ if err == nil {
+ // Forward SIGQUIT to the lldb driver which in turn will forward
+ // to the running program.
+ sigs := make(chan os.Signal, 1)
+ signal.Notify(sigs, syscall.SIGQUIT)
+ proc := lldb.Process
+ go func() {
+ for sig := range sigs {
+ proc.Signal(sig)
+ }
+ }()
+ err = lldb.Wait()
+ signal.Stop(sigs)
+ close(sigs)
+ }
+ return out.Bytes(), err
+}
+
+func copyLocalDir(dst, src string) error {
+ if err := os.Mkdir(dst, 0755); err != nil {
+ return err
+ }
+
+ d, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ fi, err := d.Readdir(-1)
+ if err != nil {
+ return err
+ }
+
+ for _, f := range fi {
+ if f.IsDir() {
+ if f.Name() == "testdata" {
+ if err := cp(dst, filepath.Join(src, f.Name())); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if err := cp(dst, filepath.Join(src, f.Name())); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func cp(dst, src string) error {
+ out, err := exec.Command("cp", "-a", src, dst).CombinedOutput()
+ if err != nil {
+ os.Stderr.Write(out)
+ }
+ return err
+}
+
+func copyLocalData(dstbase string) (pkgpath string, err error) {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", err
+ }
+
+ finalPkgpath, underGoRoot, err := subdir()
+ if err != nil {
+ return "", err
+ }
+ cwd = strings.TrimSuffix(cwd, finalPkgpath)
+
+ // Copy all immediate files and testdata directories between
+ // the package being tested and the source root.
+ pkgpath = ""
+ for _, element := range strings.Split(finalPkgpath, string(filepath.Separator)) {
+ if debug {
+ log.Printf("copying %s", pkgpath)
+ }
+ pkgpath = filepath.Join(pkgpath, element)
+ dst := filepath.Join(dstbase, pkgpath)
+ src := filepath.Join(cwd, pkgpath)
+ if err := copyLocalDir(dst, src); err != nil {
+ return "", err
+ }
+ }
+
+ if underGoRoot {
+ // Copy timezone file.
+ //
+ // Typical apps have the zoneinfo.zip in the root of their app bundle,
+ // read by the time package as the working directory at initialization.
+ // As we move the working directory to the GOROOT pkg directory, we
+ // install the zoneinfo.zip file in the pkgpath.
+ err := cp(
+ filepath.Join(dstbase, pkgpath),
+ filepath.Join(cwd, "lib", "time", "zoneinfo.zip"),
+ )
+ if err != nil {
+ return "", err
+ }
+ // Copy src/runtime/textflag.h for (at least) Test386EndToEnd in
+ // cmd/asm/internal/asm.
+ runtimePath := filepath.Join(dstbase, "src", "runtime")
+ if err := os.MkdirAll(runtimePath, 0755); err != nil {
+ return "", err
+ }
+ err = cp(
+ filepath.Join(runtimePath, "textflag.h"),
+ filepath.Join(cwd, "src", "runtime", "textflag.h"),
+ )
+ if err != nil {
+ return "", err
+ }
+ }
+
+ return finalPkgpath, nil
+}
+
+// subdir determines the package based on the current working directory,
+// and returns the path to the package source relative to $GOROOT (or $GOPATH).
+func subdir() (pkgpath string, underGoRoot bool, err error) {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", false, err
+ }
+ cwd, err = filepath.EvalSymlinks(cwd)
+ if err != nil {
+ log.Fatal(err)
+ }
+ goroot, err := filepath.EvalSymlinks(runtime.GOROOT())
+ if err != nil {
+ return "", false, err
+ }
+ if strings.HasPrefix(cwd, goroot) {
+ subdir, err := filepath.Rel(goroot, cwd)
+ if err != nil {
+ return "", false, err
+ }
+ return subdir, true, nil
+ }
+
+ for _, p := range filepath.SplitList(build.Default.GOPATH) {
+ pabs, err := filepath.EvalSymlinks(p)
+ if err != nil {
+ return "", false, err
+ }
+ if !strings.HasPrefix(cwd, pabs) {
+ continue
+ }
+ subdir, err := filepath.Rel(pabs, cwd)
+ if err == nil {
+ return subdir, false, nil
+ }
+ }
+ return "", false, fmt.Errorf(
+ "working directory %q is not in either GOROOT(%q) or GOPATH(%q)",
+ cwd,
+ runtime.GOROOT(),
+ build.Default.GOPATH,
+ )
+}
+
+func infoPlist(pkgpath string) string {
+ return `
+
+
+
+CFBundleNamegolang.gotest
+CFBundleSupportedPlatformsiPhoneOS
+CFBundleExecutablegotest
+CFBundleVersion1.0
+CFBundleShortVersionString1.0
+CFBundleIdentifier` + bundleID + `
+CFBundleResourceSpecificationResourceRules.plist
+LSRequiresIPhoneOS
+CFBundleDisplayNamegotest
+GoExecWrapperWorkingDirectory` + pkgpath + `
+
+
+`
+}
+
+func entitlementsPlist() string {
+ return `
+
+
+
+ keychain-access-groups
+ ` + appID + `
+ get-task-allow
+
+ application-identifier
+ ` + appID + `
+ com.apple.developer.team-identifier
+ ` + teamID + `
+
+
+`
+}
+
+const resourceRules = `
+
+
+
+ rules
+
+ .*
+
+ Info.plist
+
+ omit
+
+ weight
+ 10
+
+ ResourceRules.plist
+
+ omit
+
+ weight
+ 100
+
+
+
+
+`
+
+const lldbDriver = `
+import sys
+import os
+import signal
+
+platform, exe, device_exe_or_pid, args = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:]
+
+env = []
+for k, v in os.environ.items():
+ env.append(k + "=" + v)
+
+sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
+
+import lldb
+
+debugger = lldb.SBDebugger.Create()
+debugger.SetAsync(True)
+debugger.SkipLLDBInitFiles(True)
+
+err = lldb.SBError()
+target = debugger.CreateTarget(exe, None, platform, True, err)
+if not target.IsValid() or not err.Success():
+ sys.stderr.write("lldb: failed to setup up target: %s\n" % (err))
+ sys.exit(1)
+
+listener = debugger.GetListener()
+
+if platform == 'remote-ios':
+ target.modules[0].SetPlatformFileSpec(lldb.SBFileSpec(device_exe_or_pid))
+ process = target.ConnectRemote(listener, 'connect://localhost:3222', None, err)
+else:
+ process = target.AttachToProcessWithID(listener, int(device_exe_or_pid), err)
+
+if not err.Success():
+ sys.stderr.write("lldb: failed to connect to remote target %s: %s\n" % (device_exe_or_pid, err))
+ sys.exit(1)
+
+# Don't stop on signals.
+sigs = process.GetUnixSignals()
+for i in range(0, sigs.GetNumSignals()):
+ sig = sigs.GetSignalAtIndex(i)
+ sigs.SetShouldStop(sig, False)
+ sigs.SetShouldNotify(sig, False)
+
+event = lldb.SBEvent()
+running = False
+prev_handler = None
+
+def signal_handler(signal, frame):
+ process.Signal(signal)
+
+def run_program():
+ # Forward SIGQUIT to the program.
+ prev_handler = signal.signal(signal.SIGQUIT, signal_handler)
+ # Tell the Go driver that the program is running and should not be retried.
+ sys.stderr.write("lldb: running program\n")
+ running = True
+ # Process is stopped at attach/launch. Let it run.
+ process.Continue()
+
+if platform != 'remote-ios':
+ # For the local emulator the program is ready to run.
+ # For remote device runs, we need to wait for eStateConnected,
+ # below.
+ run_program()
+
+while True:
+ if not listener.WaitForEvent(1, event):
+ continue
+ if not lldb.SBProcess.EventIsProcessEvent(event):
+ continue
+ if running:
+ # Pass through stdout and stderr.
+ while True:
+ out = process.GetSTDOUT(8192)
+ if not out:
+ break
+ sys.stdout.write(out)
+ while True:
+ out = process.GetSTDERR(8192)
+ if not out:
+ break
+ sys.stderr.write(out)
+ state = process.GetStateFromEvent(event)
+ if state in [lldb.eStateCrashed, lldb.eStateDetached, lldb.eStateUnloaded, lldb.eStateExited]:
+ if running:
+ signal.signal(signal.SIGQUIT, prev_handler)
+ break
+ elif state == lldb.eStateConnected:
+ if platform == 'remote-ios':
+ process.RemoteLaunch(args, env, None, None, None, None, 0, False, err)
+ if not err.Success():
+ sys.stderr.write("lldb: failed to launch remote process: %s\n" % (err))
+ process.Kill()
+ debugger.Terminate()
+ sys.exit(1)
+ run_program()
+
+exitStatus = process.GetExitStatus()
+exitDesc = process.GetExitDescription()
+process.Kill()
+debugger.Terminate()
+if exitStatus == 0 and exitDesc is not None:
+ # Ensure tests fail when killed by a signal.
+ exitStatus = 123
+
+sys.exit(exitStatus)
+`
diff --git a/platform/dbops/binaries/go/go/misc/linkcheck/linkcheck.go b/platform/dbops/binaries/go/go/misc/linkcheck/linkcheck.go
new file mode 100644
index 0000000000000000000000000000000000000000..efe400965b2e06c7bdb9a02b5fd7d38d72cf07e6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/linkcheck/linkcheck.go
@@ -0,0 +1,191 @@
+// 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.
+
+// The linkcheck command finds missing links in the godoc website.
+// It crawls a URL recursively and notes URLs and URL fragments
+// that it's seen and prints a report of missing links at the end.
+package main
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "regexp"
+ "strings"
+ "sync"
+)
+
+var (
+ root = flag.String("root", "http://localhost:6060", "Root to crawl")
+ verbose = flag.Bool("verbose", false, "verbose")
+)
+
+var wg sync.WaitGroup // outstanding fetches
+var urlq = make(chan string) // URLs to crawl
+
+// urlFrag is a URL and its optional #fragment (without the #)
+type urlFrag struct {
+ url, frag string
+}
+
+var (
+ mu sync.Mutex
+ crawled = make(map[string]bool) // URL without fragment -> true
+ neededFrags = make(map[urlFrag][]string) // URL#frag -> who needs it
+)
+
+var aRx = regexp.MustCompile(`]+)`)
+
+// Owned by crawlLoop goroutine:
+var (
+ linkSources = make(map[string][]string) // url no fragment -> sources
+ fragExists = make(map[urlFrag]bool)
+ problems []string
+)
+
+func localLinks(body string) (links []string) {
+ seen := map[string]bool{}
+ mv := aRx.FindAllStringSubmatch(body, -1)
+ for _, m := range mv {
+ ref := m[1]
+ if strings.HasPrefix(ref, "/src/") {
+ continue
+ }
+ if !seen[ref] {
+ seen[ref] = true
+ links = append(links, m[1])
+ }
+ }
+ return
+}
+
+var idRx = regexp.MustCompile(`\bid=['"]?([^\s'">]+)`)
+
+func pageIDs(body string) (ids []string) {
+ mv := idRx.FindAllStringSubmatch(body, -1)
+ for _, m := range mv {
+ ids = append(ids, m[1])
+ }
+ return
+}
+
+// url may contain a #fragment, and the fragment is then noted as needing to exist.
+func crawl(url string, sourceURL string) {
+ if strings.Contains(url, "/devel/release") {
+ return
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if u, frag, ok := strings.Cut(url, "#"); ok {
+ url = u
+ if frag != "" {
+ uf := urlFrag{url, frag}
+ neededFrags[uf] = append(neededFrags[uf], sourceURL)
+ }
+ }
+ if crawled[url] {
+ return
+ }
+ crawled[url] = true
+
+ wg.Add(1)
+ go func() {
+ urlq <- url
+ }()
+}
+
+func addProblem(url, errmsg string) {
+ msg := fmt.Sprintf("Error on %s: %s (from %s)", url, errmsg, linkSources[url])
+ if *verbose {
+ log.Print(msg)
+ }
+ problems = append(problems, msg)
+}
+
+func crawlLoop() {
+ for url := range urlq {
+ if err := doCrawl(url); err != nil {
+ addProblem(url, err.Error())
+ }
+ }
+}
+
+func doCrawl(url string) error {
+ defer wg.Done()
+
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ return err
+ }
+ res, err := http.DefaultTransport.RoundTrip(req)
+ if err != nil {
+ return err
+ }
+ // Handle redirects.
+ if res.StatusCode/100 == 3 {
+ newURL, err := res.Location()
+ if err != nil {
+ return fmt.Errorf("resolving redirect: %v", err)
+ }
+ if !strings.HasPrefix(newURL.String(), *root) {
+ // Skip off-site redirects.
+ return nil
+ }
+ crawl(newURL.String(), url)
+ return nil
+ }
+ if res.StatusCode != 200 {
+ return errors.New(res.Status)
+ }
+ slurp, err := io.ReadAll(res.Body)
+ res.Body.Close()
+ if err != nil {
+ log.Fatalf("Error reading %s body: %v", url, err)
+ }
+ if *verbose {
+ log.Printf("Len of %s: %d", url, len(slurp))
+ }
+ body := string(slurp)
+ for _, ref := range localLinks(body) {
+ if *verbose {
+ log.Printf(" links to %s", ref)
+ }
+ dest := *root + ref
+ linkSources[dest] = append(linkSources[dest], url)
+ crawl(dest, url)
+ }
+ for _, id := range pageIDs(body) {
+ if *verbose {
+ log.Printf(" url %s has #%s", url, id)
+ }
+ fragExists[urlFrag{url, id}] = true
+ }
+ return nil
+}
+
+func main() {
+ flag.Parse()
+
+ go crawlLoop()
+ crawl(*root, "")
+
+ wg.Wait()
+ close(urlq)
+ for uf, needers := range neededFrags {
+ if !fragExists[uf] {
+ problems = append(problems, fmt.Sprintf("Missing fragment for %+v from %v", uf, needers))
+ }
+ }
+
+ for _, s := range problems {
+ fmt.Println(s)
+ }
+ if len(problems) > 0 {
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/misc/wasm/go_js_wasm_exec b/platform/dbops/binaries/go/go/misc/wasm/go_js_wasm_exec
new file mode 100644
index 0000000000000000000000000000000000000000..ff592579e034166c5337bbe2c60dd75c56e6713f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/wasm/go_js_wasm_exec
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# 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.
+
+SOURCE="${BASH_SOURCE[0]}"
+while [ -h "$SOURCE" ]; do
+ DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
+ SOURCE="$(readlink "$SOURCE")"
+ [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
+done
+DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
+
+# Increase the V8 stack size from the default of 984K
+# to 8192K to ensure all tests can pass without hitting
+# stack size limits.
+exec node --stack-size=8192 "$DIR/wasm_exec_node.js" "$@"
diff --git a/platform/dbops/binaries/go/go/misc/wasm/go_wasip1_wasm_exec b/platform/dbops/binaries/go/go/misc/wasm/go_wasip1_wasm_exec
new file mode 100644
index 0000000000000000000000000000000000000000..cd16b96ea719ef849cb061a5a86567414c6ea52f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/wasm/go_wasip1_wasm_exec
@@ -0,0 +1,31 @@
+#!/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.
+
+case "$GOWASIRUNTIME" in
+ "wasmedge")
+ exec wasmedge --dir=/ --env PWD="$PWD" --env PATH="$PATH" ${GOWASIRUNTIMEARGS:-} "$1" "${@:2}"
+ ;;
+ "wasmer")
+ exec wasmer run --dir=/ --env PWD="$PWD" --env PATH="$PATH" ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
+ ;;
+ "wazero")
+ exec wazero run -mount /:/ -env-inherit -cachedir "${TMPDIR:-/tmp}"/wazero ${GOWASIRUNTIMEARGS:-} "$1" "${@:2}"
+ ;;
+ "wasmtime" | "")
+ # Match the major version in "wasmtime-cli 14.0.0". For versions before 14
+ # we need to use the old CLI. This requires Bash v3.0 and above.
+ # TODO(johanbrandhorst): Remove this condition once 1.22 is released.
+ # From 1.23 onwards we'll only support the new wasmtime CLI.
+ if [[ "$(wasmtime --version)" =~ wasmtime-cli[[:space:]]([0-9]+)\.[0-9]+\.[0-9]+ && "${BASH_REMATCH[1]}" -lt 14 ]]; then
+ exec wasmtime run --dir=/ --env PWD="$PWD" --env PATH="$PATH" --max-wasm-stack 1048576 ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
+ else
+ exec wasmtime run --dir=/ --env PWD="$PWD" --env PATH="$PATH" -W max-wasm-stack=1048576 ${GOWASIRUNTIMEARGS:-} "$1" "${@:2}"
+ fi
+ ;;
+ *)
+ echo "Unknown Go WASI runtime specified: $GOWASIRUNTIME"
+ exit 1
+ ;;
+esac
diff --git a/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.html b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.html
new file mode 100644
index 0000000000000000000000000000000000000000..72e64473eb588d231aff3cd29e7ae0ab5c3b24ac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.html
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+ Go wasm
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.js b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.js
new file mode 100644
index 0000000000000000000000000000000000000000..bc6f210242824c25b5ee619afa507767b6e587be
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec.js
@@ -0,0 +1,561 @@
+// 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.
+
+"use strict";
+
+(() => {
+ const enosys = () => {
+ const err = new Error("not implemented");
+ err.code = "ENOSYS";
+ return err;
+ };
+
+ if (!globalThis.fs) {
+ let outputBuf = "";
+ globalThis.fs = {
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
+ writeSync(fd, buf) {
+ outputBuf += decoder.decode(buf);
+ const nl = outputBuf.lastIndexOf("\n");
+ if (nl != -1) {
+ console.log(outputBuf.substring(0, nl));
+ outputBuf = outputBuf.substring(nl + 1);
+ }
+ return buf.length;
+ },
+ write(fd, buf, offset, length, position, callback) {
+ if (offset !== 0 || length !== buf.length || position !== null) {
+ callback(enosys());
+ return;
+ }
+ const n = this.writeSync(fd, buf);
+ callback(null, n);
+ },
+ chmod(path, mode, callback) { callback(enosys()); },
+ chown(path, uid, gid, callback) { callback(enosys()); },
+ close(fd, callback) { callback(enosys()); },
+ fchmod(fd, mode, callback) { callback(enosys()); },
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
+ fstat(fd, callback) { callback(enosys()); },
+ fsync(fd, callback) { callback(null); },
+ ftruncate(fd, length, callback) { callback(enosys()); },
+ lchown(path, uid, gid, callback) { callback(enosys()); },
+ link(path, link, callback) { callback(enosys()); },
+ lstat(path, callback) { callback(enosys()); },
+ mkdir(path, perm, callback) { callback(enosys()); },
+ open(path, flags, mode, callback) { callback(enosys()); },
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
+ readdir(path, callback) { callback(enosys()); },
+ readlink(path, callback) { callback(enosys()); },
+ rename(from, to, callback) { callback(enosys()); },
+ rmdir(path, callback) { callback(enosys()); },
+ stat(path, callback) { callback(enosys()); },
+ symlink(path, link, callback) { callback(enosys()); },
+ truncate(path, length, callback) { callback(enosys()); },
+ unlink(path, callback) { callback(enosys()); },
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
+ };
+ }
+
+ if (!globalThis.process) {
+ globalThis.process = {
+ getuid() { return -1; },
+ getgid() { return -1; },
+ geteuid() { return -1; },
+ getegid() { return -1; },
+ getgroups() { throw enosys(); },
+ pid: -1,
+ ppid: -1,
+ umask() { throw enosys(); },
+ cwd() { throw enosys(); },
+ chdir() { throw enosys(); },
+ }
+ }
+
+ if (!globalThis.crypto) {
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
+ }
+
+ if (!globalThis.performance) {
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
+ }
+
+ if (!globalThis.TextEncoder) {
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
+ }
+
+ if (!globalThis.TextDecoder) {
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
+ }
+
+ const encoder = new TextEncoder("utf-8");
+ const decoder = new TextDecoder("utf-8");
+
+ globalThis.Go = class {
+ constructor() {
+ this.argv = ["js"];
+ this.env = {};
+ this.exit = (code) => {
+ if (code !== 0) {
+ console.warn("exit code:", code);
+ }
+ };
+ this._exitPromise = new Promise((resolve) => {
+ this._resolveExitPromise = resolve;
+ });
+ this._pendingEvent = null;
+ this._scheduledTimeouts = new Map();
+ this._nextCallbackTimeoutID = 1;
+
+ const setInt64 = (addr, v) => {
+ this.mem.setUint32(addr + 0, v, true);
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
+ }
+
+ const setInt32 = (addr, v) => {
+ this.mem.setUint32(addr + 0, v, true);
+ }
+
+ const getInt64 = (addr) => {
+ const low = this.mem.getUint32(addr + 0, true);
+ const high = this.mem.getInt32(addr + 4, true);
+ return low + high * 4294967296;
+ }
+
+ const loadValue = (addr) => {
+ const f = this.mem.getFloat64(addr, true);
+ if (f === 0) {
+ return undefined;
+ }
+ if (!isNaN(f)) {
+ return f;
+ }
+
+ const id = this.mem.getUint32(addr, true);
+ return this._values[id];
+ }
+
+ const storeValue = (addr, v) => {
+ const nanHead = 0x7FF80000;
+
+ if (typeof v === "number" && v !== 0) {
+ if (isNaN(v)) {
+ this.mem.setUint32(addr + 4, nanHead, true);
+ this.mem.setUint32(addr, 0, true);
+ return;
+ }
+ this.mem.setFloat64(addr, v, true);
+ return;
+ }
+
+ if (v === undefined) {
+ this.mem.setFloat64(addr, 0, true);
+ return;
+ }
+
+ let id = this._ids.get(v);
+ if (id === undefined) {
+ id = this._idPool.pop();
+ if (id === undefined) {
+ id = this._values.length;
+ }
+ this._values[id] = v;
+ this._goRefCounts[id] = 0;
+ this._ids.set(v, id);
+ }
+ this._goRefCounts[id]++;
+ let typeFlag = 0;
+ switch (typeof v) {
+ case "object":
+ if (v !== null) {
+ typeFlag = 1;
+ }
+ break;
+ case "string":
+ typeFlag = 2;
+ break;
+ case "symbol":
+ typeFlag = 3;
+ break;
+ case "function":
+ typeFlag = 4;
+ break;
+ }
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
+ this.mem.setUint32(addr, id, true);
+ }
+
+ const loadSlice = (addr) => {
+ const array = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
+ }
+
+ const loadSliceOfValues = (addr) => {
+ const array = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ const a = new Array(len);
+ for (let i = 0; i < len; i++) {
+ a[i] = loadValue(array + i * 8);
+ }
+ return a;
+ }
+
+ const loadString = (addr) => {
+ const saddr = getInt64(addr + 0);
+ const len = getInt64(addr + 8);
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
+ }
+
+ const timeOrigin = Date.now() - performance.now();
+ this.importObject = {
+ _gotest: {
+ add: (a, b) => a + b,
+ },
+ gojs: {
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
+ // This changes the SP, thus we have to update the SP used by the imported function.
+
+ // func wasmExit(code int32)
+ "runtime.wasmExit": (sp) => {
+ sp >>>= 0;
+ const code = this.mem.getInt32(sp + 8, true);
+ this.exited = true;
+ delete this._inst;
+ delete this._values;
+ delete this._goRefCounts;
+ delete this._ids;
+ delete this._idPool;
+ this.exit(code);
+ },
+
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
+ "runtime.wasmWrite": (sp) => {
+ sp >>>= 0;
+ const fd = getInt64(sp + 8);
+ const p = getInt64(sp + 16);
+ const n = this.mem.getInt32(sp + 24, true);
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
+ },
+
+ // func resetMemoryDataView()
+ "runtime.resetMemoryDataView": (sp) => {
+ sp >>>= 0;
+ this.mem = new DataView(this._inst.exports.mem.buffer);
+ },
+
+ // func nanotime1() int64
+ "runtime.nanotime1": (sp) => {
+ sp >>>= 0;
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
+ },
+
+ // func walltime() (sec int64, nsec int32)
+ "runtime.walltime": (sp) => {
+ sp >>>= 0;
+ const msec = (new Date).getTime();
+ setInt64(sp + 8, msec / 1000);
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
+ },
+
+ // func scheduleTimeoutEvent(delay int64) int32
+ "runtime.scheduleTimeoutEvent": (sp) => {
+ sp >>>= 0;
+ const id = this._nextCallbackTimeoutID;
+ this._nextCallbackTimeoutID++;
+ this._scheduledTimeouts.set(id, setTimeout(
+ () => {
+ this._resume();
+ while (this._scheduledTimeouts.has(id)) {
+ // for some reason Go failed to register the timeout event, log and try again
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
+ console.warn("scheduleTimeoutEvent: missed timeout event");
+ this._resume();
+ }
+ },
+ getInt64(sp + 8),
+ ));
+ this.mem.setInt32(sp + 16, id, true);
+ },
+
+ // func clearTimeoutEvent(id int32)
+ "runtime.clearTimeoutEvent": (sp) => {
+ sp >>>= 0;
+ const id = this.mem.getInt32(sp + 8, true);
+ clearTimeout(this._scheduledTimeouts.get(id));
+ this._scheduledTimeouts.delete(id);
+ },
+
+ // func getRandomData(r []byte)
+ "runtime.getRandomData": (sp) => {
+ sp >>>= 0;
+ crypto.getRandomValues(loadSlice(sp + 8));
+ },
+
+ // func finalizeRef(v ref)
+ "syscall/js.finalizeRef": (sp) => {
+ sp >>>= 0;
+ const id = this.mem.getUint32(sp + 8, true);
+ this._goRefCounts[id]--;
+ if (this._goRefCounts[id] === 0) {
+ const v = this._values[id];
+ this._values[id] = null;
+ this._ids.delete(v);
+ this._idPool.push(id);
+ }
+ },
+
+ // func stringVal(value string) ref
+ "syscall/js.stringVal": (sp) => {
+ sp >>>= 0;
+ storeValue(sp + 24, loadString(sp + 8));
+ },
+
+ // func valueGet(v ref, p string) ref
+ "syscall/js.valueGet": (sp) => {
+ sp >>>= 0;
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 32, result);
+ },
+
+ // func valueSet(v ref, p string, x ref)
+ "syscall/js.valueSet": (sp) => {
+ sp >>>= 0;
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
+ },
+
+ // func valueDelete(v ref, p string)
+ "syscall/js.valueDelete": (sp) => {
+ sp >>>= 0;
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
+ },
+
+ // func valueIndex(v ref, i int) ref
+ "syscall/js.valueIndex": (sp) => {
+ sp >>>= 0;
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
+ },
+
+ // valueSetIndex(v ref, i int, x ref)
+ "syscall/js.valueSetIndex": (sp) => {
+ sp >>>= 0;
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
+ },
+
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
+ "syscall/js.valueCall": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const m = Reflect.get(v, loadString(sp + 16));
+ const args = loadSliceOfValues(sp + 32);
+ const result = Reflect.apply(m, v, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 56, result);
+ this.mem.setUint8(sp + 64, 1);
+ } catch (err) {
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 56, err);
+ this.mem.setUint8(sp + 64, 0);
+ }
+ },
+
+ // func valueInvoke(v ref, args []ref) (ref, bool)
+ "syscall/js.valueInvoke": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const args = loadSliceOfValues(sp + 16);
+ const result = Reflect.apply(v, undefined, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, result);
+ this.mem.setUint8(sp + 48, 1);
+ } catch (err) {
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, err);
+ this.mem.setUint8(sp + 48, 0);
+ }
+ },
+
+ // func valueNew(v ref, args []ref) (ref, bool)
+ "syscall/js.valueNew": (sp) => {
+ sp >>>= 0;
+ try {
+ const v = loadValue(sp + 8);
+ const args = loadSliceOfValues(sp + 16);
+ const result = Reflect.construct(v, args);
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, result);
+ this.mem.setUint8(sp + 48, 1);
+ } catch (err) {
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
+ storeValue(sp + 40, err);
+ this.mem.setUint8(sp + 48, 0);
+ }
+ },
+
+ // func valueLength(v ref) int
+ "syscall/js.valueLength": (sp) => {
+ sp >>>= 0;
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
+ },
+
+ // valuePrepareString(v ref) (ref, int)
+ "syscall/js.valuePrepareString": (sp) => {
+ sp >>>= 0;
+ const str = encoder.encode(String(loadValue(sp + 8)));
+ storeValue(sp + 16, str);
+ setInt64(sp + 24, str.length);
+ },
+
+ // valueLoadString(v ref, b []byte)
+ "syscall/js.valueLoadString": (sp) => {
+ sp >>>= 0;
+ const str = loadValue(sp + 8);
+ loadSlice(sp + 16).set(str);
+ },
+
+ // func valueInstanceOf(v ref, t ref) bool
+ "syscall/js.valueInstanceOf": (sp) => {
+ sp >>>= 0;
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
+ },
+
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
+ "syscall/js.copyBytesToGo": (sp) => {
+ sp >>>= 0;
+ const dst = loadSlice(sp + 8);
+ const src = loadValue(sp + 32);
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
+ this.mem.setUint8(sp + 48, 0);
+ return;
+ }
+ const toCopy = src.subarray(0, dst.length);
+ dst.set(toCopy);
+ setInt64(sp + 40, toCopy.length);
+ this.mem.setUint8(sp + 48, 1);
+ },
+
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
+ "syscall/js.copyBytesToJS": (sp) => {
+ sp >>>= 0;
+ const dst = loadValue(sp + 8);
+ const src = loadSlice(sp + 16);
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
+ this.mem.setUint8(sp + 48, 0);
+ return;
+ }
+ const toCopy = src.subarray(0, dst.length);
+ dst.set(toCopy);
+ setInt64(sp + 40, toCopy.length);
+ this.mem.setUint8(sp + 48, 1);
+ },
+
+ "debug": (value) => {
+ console.log(value);
+ },
+ }
+ };
+ }
+
+ async run(instance) {
+ if (!(instance instanceof WebAssembly.Instance)) {
+ throw new Error("Go.run: WebAssembly.Instance expected");
+ }
+ this._inst = instance;
+ this.mem = new DataView(this._inst.exports.mem.buffer);
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
+ NaN,
+ 0,
+ null,
+ true,
+ false,
+ globalThis,
+ this,
+ ];
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
+ this._ids = new Map([ // mapping from JS values to reference ids
+ [0, 1],
+ [null, 2],
+ [true, 3],
+ [false, 4],
+ [globalThis, 5],
+ [this, 6],
+ ]);
+ this._idPool = []; // unused ids that have been garbage collected
+ this.exited = false; // whether the Go program has exited
+
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
+ let offset = 4096;
+
+ const strPtr = (str) => {
+ const ptr = offset;
+ const bytes = encoder.encode(str + "\0");
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
+ offset += bytes.length;
+ if (offset % 8 !== 0) {
+ offset += 8 - (offset % 8);
+ }
+ return ptr;
+ };
+
+ const argc = this.argv.length;
+
+ const argvPtrs = [];
+ this.argv.forEach((arg) => {
+ argvPtrs.push(strPtr(arg));
+ });
+ argvPtrs.push(0);
+
+ const keys = Object.keys(this.env).sort();
+ keys.forEach((key) => {
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
+ });
+ argvPtrs.push(0);
+
+ const argv = offset;
+ argvPtrs.forEach((ptr) => {
+ this.mem.setUint32(offset, ptr, true);
+ this.mem.setUint32(offset + 4, 0, true);
+ offset += 8;
+ });
+
+ // The linker guarantees global data starts from at least wasmMinDataAddr.
+ // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
+ const wasmMinDataAddr = 4096 + 8192;
+ if (offset >= wasmMinDataAddr) {
+ throw new Error("total length of command line and environment variables exceeds limit");
+ }
+
+ this._inst.exports.run(argc, argv);
+ if (this.exited) {
+ this._resolveExitPromise();
+ }
+ await this._exitPromise;
+ }
+
+ _resume() {
+ if (this.exited) {
+ throw new Error("Go program has already exited");
+ }
+ this._inst.exports.resume();
+ if (this.exited) {
+ this._resolveExitPromise();
+ }
+ }
+
+ _makeFuncWrapper(id) {
+ const go = this;
+ return function () {
+ const event = { id: id, this: this, args: arguments };
+ go._pendingEvent = event;
+ go._resume();
+ return event.result;
+ };
+ }
+ }
+})();
diff --git a/platform/dbops/binaries/go/go/misc/wasm/wasm_exec_node.js b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec_node.js
new file mode 100644
index 0000000000000000000000000000000000000000..986069087bc0bce0beddeb3fb19ebb2b42cf4fdb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/misc/wasm/wasm_exec_node.js
@@ -0,0 +1,39 @@
+// 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.
+
+"use strict";
+
+if (process.argv.length < 3) {
+ console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
+ process.exit(1);
+}
+
+globalThis.require = require;
+globalThis.fs = require("fs");
+globalThis.TextEncoder = require("util").TextEncoder;
+globalThis.TextDecoder = require("util").TextDecoder;
+
+globalThis.performance ??= require("performance");
+
+globalThis.crypto ??= require("crypto");
+
+require("./wasm_exec");
+
+const go = new Go();
+go.argv = process.argv.slice(2);
+go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
+go.exit = process.exit;
+WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
+ process.on("exit", (code) => { // Node.js exits if no event handler is pending
+ if (code === 0 && !go.exited) {
+ // deadlock, make Go print error and stack traces
+ go._pendingEvent = { id: 0 };
+ go._resume();
+ }
+ });
+ return go.run(result.instance);
+}).catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/platform/dbops/binaries/go/go/pkg/include/asm_amd64.h b/platform/dbops/binaries/go/go/pkg/include/asm_amd64.h
new file mode 100644
index 0000000000000000000000000000000000000000..b263ade8022a7786d8ee7b5ba185ebd02adef0e9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/include/asm_amd64.h
@@ -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.
+
+// Define features that are guaranteed to be supported by setting the AMD64 variable.
+// If a feature is supported, there's no need to check it at runtime every time.
+
+#ifdef GOAMD64_v2
+#define hasPOPCNT
+#define hasSSE42
+#endif
+
+#ifdef GOAMD64_v3
+#define hasAVX
+#define hasAVX2
+#define hasPOPCNT
+#define hasSSE42
+#endif
+
+#ifdef GOAMD64_v4
+#define hasAVX
+#define hasAVX2
+#define hasAVX512F
+#define hasAVX512BW
+#define hasAVX512VL
+#define hasPOPCNT
+#define hasSSE42
+#endif
diff --git a/platform/dbops/binaries/go/go/pkg/include/asm_ppc64x.h b/platform/dbops/binaries/go/go/pkg/include/asm_ppc64x.h
new file mode 100644
index 0000000000000000000000000000000000000000..65870fe020fa3d40a7a8799aae567c79b629d464
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/include/asm_ppc64x.h
@@ -0,0 +1,55 @@
+// 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.
+
+// FIXED_FRAME defines the size of the fixed part of a stack frame. A stack
+// frame looks like this:
+//
+// +---------------------+
+// | local variable area |
+// +---------------------+
+// | argument area |
+// +---------------------+ <- R1+FIXED_FRAME
+// | fixed area |
+// +---------------------+ <- R1
+//
+// So a function that sets up a stack frame at all uses as least FIXED_FRAME
+// bytes of stack. This mostly affects assembly that calls other functions
+// with arguments (the arguments should be stored at FIXED_FRAME+0(R1),
+// FIXED_FRAME+8(R1) etc) and some other low-level places.
+//
+// The reason for using a constant is to make supporting PIC easier (although
+// we only support PIC on ppc64le which has a minimum 32 bytes of stack frame,
+// and currently always use that much, PIC on ppc64 would need to use 48).
+
+#define FIXED_FRAME 32
+
+// aix/ppc64 uses XCOFF which uses function descriptors.
+// AIX cannot perform the TOC relocation in a text section.
+// Therefore, these descriptors must live in a data section.
+#ifdef GOOS_aix
+#ifdef GOARCH_ppc64
+#define GO_PPC64X_HAS_FUNCDESC
+#define DEFINE_PPC64X_FUNCDESC(funcname, localfuncname) \
+ DATA funcname+0(SB)/8, $localfuncname(SB) \
+ DATA funcname+8(SB)/8, $TOC(SB) \
+ DATA funcname+16(SB)/8, $0 \
+ GLOBL funcname(SB), NOPTR, $24
+#endif
+#endif
+
+// linux/ppc64 uses ELFv1 which uses function descriptors.
+// These must also look like ABI0 functions on linux/ppc64
+// to work with abi.FuncPCABI0(sigtramp) in os_linux.go.
+// Only static codegen is supported on linux/ppc64, so TOC
+// is not needed.
+#ifdef GOOS_linux
+#ifdef GOARCH_ppc64
+#define GO_PPC64X_HAS_FUNCDESC
+#define DEFINE_PPC64X_FUNCDESC(funcname, localfuncname) \
+ TEXT funcname(SB),NOSPLIT|NOFRAME,$0 \
+ DWORD $localfuncname(SB) \
+ DWORD $0 \
+ DWORD $0
+#endif
+#endif
diff --git a/platform/dbops/binaries/go/go/pkg/include/funcdata.h b/platform/dbops/binaries/go/go/pkg/include/funcdata.h
new file mode 100644
index 0000000000000000000000000000000000000000..4bbc58ea48823ee02a9f4ed96473205626cab9e0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/include/funcdata.h
@@ -0,0 +1,56 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This file defines the IDs for PCDATA and FUNCDATA instructions
+// in Go binaries. It is included by assembly sources, so it must
+// be written using #defines.
+//
+// These must agree with internal/abi/symtab.go.
+
+#define PCDATA_UnsafePoint 0
+#define PCDATA_StackMapIndex 1
+#define PCDATA_InlTreeIndex 2
+#define PCDATA_ArgLiveIndex 3
+
+#define FUNCDATA_ArgsPointerMaps 0 /* garbage collector blocks */
+#define FUNCDATA_LocalsPointerMaps 1
+#define FUNCDATA_StackObjects 2
+#define FUNCDATA_InlTree 3
+#define FUNCDATA_OpenCodedDeferInfo 4 /* info for func with open-coded defers */
+#define FUNCDATA_ArgInfo 5
+#define FUNCDATA_ArgLiveInfo 6
+#define FUNCDATA_WrapInfo 7
+
+// Pseudo-assembly statements.
+
+// GO_ARGS, GO_RESULTS_INITIALIZED, and NO_LOCAL_POINTERS are macros
+// that communicate to the runtime information about the location and liveness
+// of pointers in an assembly function's arguments, results, and stack frame.
+// This communication is only required in assembly functions that make calls
+// to other functions that might be preempted or grow the stack.
+// NOSPLIT functions that make no calls do not need to use these macros.
+
+// GO_ARGS indicates that the Go prototype for this assembly function
+// defines the pointer map for the function's arguments.
+// GO_ARGS should be the first instruction in a function that uses it.
+// It can be omitted if there are no arguments at all.
+// GO_ARGS is inserted implicitly by the assembler for any function
+// whose package-qualified symbol name belongs to the current package;
+// it is therefore usually not necessary to write explicitly.
+#define GO_ARGS FUNCDATA $FUNCDATA_ArgsPointerMaps, go_args_stackmap(SB)
+
+// GO_RESULTS_INITIALIZED indicates that the assembly function
+// has initialized the stack space for its results and that those results
+// should be considered live for the remainder of the function.
+#define GO_RESULTS_INITIALIZED PCDATA $PCDATA_StackMapIndex, $1
+
+// NO_LOCAL_POINTERS indicates that the assembly function stores
+// no pointers to heap objects in its local stack variables.
+#define NO_LOCAL_POINTERS FUNCDATA $FUNCDATA_LocalsPointerMaps, no_pointers_stackmap(SB)
+
+// ArgsSizeUnknown is set in Func.argsize to mark all functions
+// whose argument size is unknown (C vararg functions, and
+// assembly code without an explicit specification).
+// This value is generated by the compiler, assembler, or linker.
+#define ArgsSizeUnknown 0x80000000
diff --git a/platform/dbops/binaries/go/go/pkg/include/textflag.h b/platform/dbops/binaries/go/go/pkg/include/textflag.h
new file mode 100644
index 0000000000000000000000000000000000000000..893031220120c153d9ac8bebed0861deddc3f0ce
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/include/textflag.h
@@ -0,0 +1,38 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// This file defines flags attached to various functions
+// and data objects. The compilers, assemblers, and linker must
+// all agree on these values.
+//
+// Keep in sync with src/cmd/internal/obj/textflag.go.
+
+// Don't profile the marked routine. This flag is deprecated.
+#define NOPROF 1
+// It is ok for the linker to get multiple of these symbols. It will
+// pick one of the duplicates to use.
+#define DUPOK 2
+// Don't insert stack check preamble.
+#define NOSPLIT 4
+// Put this data in a read-only section.
+#define RODATA 8
+// This data contains no pointers.
+#define NOPTR 16
+// This is a wrapper function and should not count as disabling 'recover'.
+#define WRAPPER 32
+// This function uses its incoming context register.
+#define NEEDCTXT 64
+// Allocate a word of thread local storage and store the offset from the
+// thread local base to the thread local storage in this variable.
+#define TLSBSS 256
+// Do not insert instructions to allocate a stack frame for this function.
+// Only valid on functions that declare a frame size of 0.
+#define NOFRAME 512
+// Function can call reflect.Type.Method or reflect.Type.MethodByName.
+#define REFLECTMETHOD 1024
+// Function is the outermost frame of the call stack. Call stack unwinders
+// should stop at this function.
+#define TOPFRAME 2048
+// Function is an ABI wrapper.
+#define ABIWRAPPER 4096
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/addr2line b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/addr2line
new file mode 100644
index 0000000000000000000000000000000000000000..64baf8d86d9dd069961c9a90d5229790619a0f41
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/addr2line
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0b02a8739961c2046260428136f7eae9ce9945dc507e4933015ed47ec9bd2692
+size 2438886
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/asm b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/asm
new file mode 100644
index 0000000000000000000000000000000000000000..6060e2eeef027915e1e9436093494a2c5952aea2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/asm
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:15caf769e16ef4f45946ad3a75d1db530e24c85fa475c0349f53aa6b918f3d88
+size 3831435
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/buildid b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/buildid
new file mode 100644
index 0000000000000000000000000000000000000000..c708593e6074fe738effef4921e2c4d5da437533
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/buildid
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c10ad54c78cca8020d4f80a39f3aad81978c71e783aaf7fcdeab1640f2e8d42a
+size 1912930
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cgo b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cgo
new file mode 100644
index 0000000000000000000000000000000000000000..87918bfe78b323396346655be19c914880da92fb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cgo
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6c1ac2603d5bf81a81dfa23cc758e9ff1d6e91f960558bec23e8a5f2901fd78b
+size 3740784
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/compile b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/compile
new file mode 100644
index 0000000000000000000000000000000000000000..83573519621aab7a79d2e173625eaf80da6bc208
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/compile
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f383e7e2ca22d5a919f090d853dc64affcfbacee08cba01f2deaa2028b09670e
+size 19344805
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/covdata b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/covdata
new file mode 100644
index 0000000000000000000000000000000000000000..c17eefb9d4309a69c9f90c68831866ae1e1d4bb5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/covdata
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6f0ccc0d9c6af3436010511331a4b366dcf1416ebadfab92ee6267c175a30401
+size 2469664
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cover b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cover
new file mode 100644
index 0000000000000000000000000000000000000000..618e17f2176fd0e80b4a9c13a69148dfdc89af77
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/cover
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:afaa7cbaf4b5ffd934db56332244d1642cfa995ebd93a1cc8fcd906e97f8a96e
+size 4262861
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/doc b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/doc
new file mode 100644
index 0000000000000000000000000000000000000000..fd5d36ba6fdd6a6a8bc339241c3f7beb0567773f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/doc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:53252c278c34c6d391ee989266a170a5e0b169cd5e5b4b16f3c7cacae9b81599
+size 3092557
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/fix b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/fix
new file mode 100644
index 0000000000000000000000000000000000000000..d65f4aad794bdbd419a95636f5fbe5c563e2c461
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/fix
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e1b45cdc2462ba0805d6360ec15442bd1b1ea0d943c82ce8f6c8c9d3567f59cc
+size 2587022
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/link b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/link
new file mode 100644
index 0000000000000000000000000000000000000000..3e3b1bfedb29881801695ed31e3bfaf9b39fde6e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/link
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6e1dba72dde7241fbf2ee48d673207cc0ff919aa4c20d1012d3a0e8ebd82a0a5
+size 5294592
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/nm b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/nm
new file mode 100644
index 0000000000000000000000000000000000000000..6ad03a20d06a7292fda9fea885d3a591353c5f79
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/nm
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:762dae3c3b6be8ab66bc6500bf59d3fc2e32630d6403d874e12694455ef9f6ae
+size 2383139
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/objdump b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/objdump
new file mode 100644
index 0000000000000000000000000000000000000000..9ebd8378919e570f9b4b19fd183132cc49d71a74
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/objdump
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:235f23fcbb5ba7ab0f1fef284a659ecb5afcc439205f8269683295189d85283f
+size 3474997
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pack b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pack
new file mode 100644
index 0000000000000000000000000000000000000000..955f528fcc4b41f1b4080683f240a00f50c47390
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pack
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b6bd5de4c7fddc4cb4b47a6d4d02b24657da625ab468d4487cb4d38be57101ee
+size 1648605
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pprof b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pprof
new file mode 100644
index 0000000000000000000000000000000000000000..349900a6258dfa1b7a954138f08f45a2cf82ca44
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/pprof
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f096330f9273813f249bb33a9b6e500b07ebc481ac8c7c20649878220bde4e2a
+size 11756511
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/test2json b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/test2json
new file mode 100644
index 0000000000000000000000000000000000000000..ff81b2210a3a052ac5f3bb877c5f592fe431e7b5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/test2json
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:938056a19176a46de4e22235b7e1f9ccd553346a8bcb55583dd55753b44f56a1
+size 2034509
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/trace b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/trace
new file mode 100644
index 0000000000000000000000000000000000000000..53602104c367c0af01e0eeb0db4f63273a01462b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/trace
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5059b667ea1fdd76f651f0e72d212f0334e72bdd65414725bf0ad0c72ec759d8
+size 12107541
diff --git a/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/vet b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/vet
new file mode 100644
index 0000000000000000000000000000000000000000..54b56210e8a59ccd1d7f717d55e200887cbfbdd5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/pkg/tool/linux_amd64/vet
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:14956467adeefd6dfd463dc162df0a7e66ff242d00164eb6bbb2923320ec2fed
+size 6119625
diff --git a/platform/dbops/binaries/go/go/src/arena/arena.go b/platform/dbops/binaries/go/go/src/arena/arena.go
new file mode 100644
index 0000000000000000000000000000000000000000..35b2fbd2aadd8cf69db74a254715afb592e50833
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/arena/arena.go
@@ -0,0 +1,108 @@
+// 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 goexperiment.arenas
+
+/*
+The arena package provides the ability to allocate memory for a collection
+of Go values and free that space manually all at once, safely. The purpose
+of this functionality is to improve efficiency: manually freeing memory
+before a garbage collection delays that cycle. Less frequent cycles means
+the CPU cost of the garbage collector is incurred less frequently.
+
+This functionality in this package is mostly captured in the Arena type.
+Arenas allocate large chunks of memory for Go values, so they're likely to
+be inefficient for allocating only small amounts of small Go values. They're
+best used in bulk, on the order of MiB of memory allocated on each use.
+
+Note that by allowing for this limited form of manual memory allocation
+that use-after-free bugs are possible with regular Go values. This package
+limits the impact of these use-after-free bugs by preventing reuse of freed
+memory regions until the garbage collector is able to determine that it is
+safe. Typically, a use-after-free bug will result in a fault and a helpful
+error message, but this package reserves the right to not force a fault on
+freed memory. That means a valid implementation of this package is to just
+allocate all memory the way the runtime normally would, and in fact, it
+reserves the right to occasionally do so for some Go values.
+*/
+package arena
+
+import (
+ "internal/reflectlite"
+ "unsafe"
+)
+
+// Arena represents a collection of Go values allocated and freed together.
+// Arenas are useful for improving efficiency as they may be freed back to
+// the runtime manually, though any memory obtained from freed arenas must
+// not be accessed once that happens. An Arena is automatically freed once
+// it is no longer referenced, so it must be kept alive (see runtime.KeepAlive)
+// until any memory allocated from it is no longer needed.
+//
+// An Arena must never be used concurrently by multiple goroutines.
+type Arena struct {
+ a unsafe.Pointer
+}
+
+// NewArena allocates a new arena.
+func NewArena() *Arena {
+ return &Arena{a: runtime_arena_newArena()}
+}
+
+// Free frees the arena (and all objects allocated from the arena) so that
+// memory backing the arena can be reused fairly quickly without garbage
+// collection overhead. Applications must not call any method on this
+// arena after it has been freed.
+func (a *Arena) Free() {
+ runtime_arena_arena_Free(a.a)
+ a.a = nil
+}
+
+// New creates a new *T in the provided arena. The *T must not be used after
+// the arena is freed. Accessing the value after free may result in a fault,
+// but this fault is also not guaranteed.
+func New[T any](a *Arena) *T {
+ return runtime_arena_arena_New(a.a, reflectlite.TypeOf((*T)(nil))).(*T)
+}
+
+// MakeSlice creates a new []T with the provided capacity and length. The []T must
+// not be used after the arena is freed. Accessing the underlying storage of the
+// slice after free may result in a fault, but this fault is also not guaranteed.
+func MakeSlice[T any](a *Arena, len, cap int) []T {
+ var sl []T
+ runtime_arena_arena_Slice(a.a, &sl, cap)
+ return sl[:len]
+}
+
+// Clone makes a shallow copy of the input value that is no longer bound to any
+// arena it may have been allocated from, returning the copy. If it was not
+// allocated from an arena, it is returned untouched. This function is useful
+// to more easily let an arena-allocated value out-live its arena.
+// T must be a pointer, a slice, or a string, otherwise this function will panic.
+func Clone[T any](s T) T {
+ return runtime_arena_heapify(s).(T)
+}
+
+//go:linkname reflect_arena_New reflect.arena_New
+func reflect_arena_New(a *Arena, typ any) any {
+ return runtime_arena_arena_New(a.a, typ)
+}
+
+//go:linkname runtime_arena_newArena
+func runtime_arena_newArena() unsafe.Pointer
+
+//go:linkname runtime_arena_arena_New
+func runtime_arena_arena_New(arena unsafe.Pointer, typ any) any
+
+// Mark as noescape to avoid escaping the slice header.
+//
+//go:noescape
+//go:linkname runtime_arena_arena_Slice
+func runtime_arena_arena_Slice(arena unsafe.Pointer, slice any, cap int)
+
+//go:linkname runtime_arena_arena_Free
+func runtime_arena_arena_Free(arena unsafe.Pointer)
+
+//go:linkname runtime_arena_heapify
+func runtime_arena_heapify(any) any
diff --git a/platform/dbops/binaries/go/go/src/arena/arena_test.go b/platform/dbops/binaries/go/go/src/arena/arena_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..017c33c502a7183c7e64f839ac3b36d0cf82396b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/arena/arena_test.go
@@ -0,0 +1,42 @@
+// 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 goexperiment.arenas
+
+package arena_test
+
+import (
+ "arena"
+ "testing"
+)
+
+type T1 struct {
+ n int
+}
+type T2 [1 << 20]byte // 1MiB
+
+func TestSmoke(t *testing.T) {
+ a := arena.NewArena()
+ defer a.Free()
+
+ tt := arena.New[T1](a)
+ tt.n = 1
+
+ ts := arena.MakeSlice[T1](a, 99, 100)
+ if len(ts) != 99 {
+ t.Errorf("Slice() len = %d, want 99", len(ts))
+ }
+ if cap(ts) != 100 {
+ t.Errorf("Slice() cap = %d, want 100", cap(ts))
+ }
+ ts[1].n = 42
+}
+
+func TestSmokeLarge(t *testing.T) {
+ a := arena.NewArena()
+ defer a.Free()
+ for i := 0; i < 10*64; i++ {
+ _ = arena.New[T2](a)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/bufio.go b/platform/dbops/binaries/go/go/src/bufio/bufio.go
new file mode 100644
index 0000000000000000000000000000000000000000..880e52798e1aa96e1a6d2a086d262cdbf4ffec0d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/bufio.go
@@ -0,0 +1,839 @@
+// 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 bufio implements buffered I/O. It wraps an io.Reader or io.Writer
+// object, creating another object (Reader or Writer) that also implements
+// the interface but provides buffering and some help for textual I/O.
+package bufio
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "strings"
+ "unicode/utf8"
+)
+
+const (
+ defaultBufSize = 4096
+)
+
+var (
+ ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
+ ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
+ ErrBufferFull = errors.New("bufio: buffer full")
+ ErrNegativeCount = errors.New("bufio: negative count")
+)
+
+// Buffered input.
+
+// Reader implements buffering for an io.Reader object.
+type Reader struct {
+ buf []byte
+ rd io.Reader // reader provided by the client
+ r, w int // buf read and write positions
+ err error
+ lastByte int // last byte read for UnreadByte; -1 means invalid
+ lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
+}
+
+const minReadBufferSize = 16
+const maxConsecutiveEmptyReads = 100
+
+// NewReaderSize returns a new [Reader] whose buffer has at least the specified
+// size. If the argument io.Reader is already a [Reader] with large enough
+// size, it returns the underlying [Reader].
+func NewReaderSize(rd io.Reader, size int) *Reader {
+ // Is it already a Reader?
+ b, ok := rd.(*Reader)
+ if ok && len(b.buf) >= size {
+ return b
+ }
+ r := new(Reader)
+ r.reset(make([]byte, max(size, minReadBufferSize)), rd)
+ return r
+}
+
+// NewReader returns a new [Reader] whose buffer has the default size.
+func NewReader(rd io.Reader) *Reader {
+ return NewReaderSize(rd, defaultBufSize)
+}
+
+// Size returns the size of the underlying buffer in bytes.
+func (b *Reader) Size() int { return len(b.buf) }
+
+// Reset discards any buffered data, resets all state, and switches
+// the buffered reader to read from r.
+// Calling Reset on the zero value of [Reader] initializes the internal buffer
+// to the default size.
+// Calling b.Reset(b) (that is, resetting a [Reader] to itself) does nothing.
+func (b *Reader) Reset(r io.Reader) {
+ // If a Reader r is passed to NewReader, NewReader will return r.
+ // Different layers of code may do that, and then later pass r
+ // to Reset. Avoid infinite recursion in that case.
+ if b == r {
+ return
+ }
+ if b.buf == nil {
+ b.buf = make([]byte, defaultBufSize)
+ }
+ b.reset(b.buf, r)
+}
+
+func (b *Reader) reset(buf []byte, r io.Reader) {
+ *b = Reader{
+ buf: buf,
+ rd: r,
+ lastByte: -1,
+ lastRuneSize: -1,
+ }
+}
+
+var errNegativeRead = errors.New("bufio: reader returned negative count from Read")
+
+// fill reads a new chunk into the buffer.
+func (b *Reader) fill() {
+ // Slide existing data to beginning.
+ if b.r > 0 {
+ copy(b.buf, b.buf[b.r:b.w])
+ b.w -= b.r
+ b.r = 0
+ }
+
+ if b.w >= len(b.buf) {
+ panic("bufio: tried to fill full buffer")
+ }
+
+ // Read new data: try a limited number of times.
+ for i := maxConsecutiveEmptyReads; i > 0; i-- {
+ n, err := b.rd.Read(b.buf[b.w:])
+ if n < 0 {
+ panic(errNegativeRead)
+ }
+ b.w += n
+ if err != nil {
+ b.err = err
+ return
+ }
+ if n > 0 {
+ return
+ }
+ }
+ b.err = io.ErrNoProgress
+}
+
+func (b *Reader) readErr() error {
+ err := b.err
+ b.err = nil
+ return err
+}
+
+// Peek returns the next n bytes without advancing the reader. The bytes stop
+// being valid at the next read call. If Peek returns fewer than n bytes, it
+// also returns an error explaining why the read is short. The error is
+// [ErrBufferFull] if n is larger than b's buffer size.
+//
+// Calling Peek prevents a [Reader.UnreadByte] or [Reader.UnreadRune] call from succeeding
+// until the next read operation.
+func (b *Reader) Peek(n int) ([]byte, error) {
+ if n < 0 {
+ return nil, ErrNegativeCount
+ }
+
+ b.lastByte = -1
+ b.lastRuneSize = -1
+
+ for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
+ b.fill() // b.w-b.r < len(b.buf) => buffer is not full
+ }
+
+ if n > len(b.buf) {
+ return b.buf[b.r:b.w], ErrBufferFull
+ }
+
+ // 0 <= n <= len(b.buf)
+ var err error
+ if avail := b.w - b.r; avail < n {
+ // not enough data in buffer
+ n = avail
+ err = b.readErr()
+ if err == nil {
+ err = ErrBufferFull
+ }
+ }
+ return b.buf[b.r : b.r+n], err
+}
+
+// Discard skips the next n bytes, returning the number of bytes discarded.
+//
+// If Discard skips fewer than n bytes, it also returns an error.
+// If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
+// reading from the underlying io.Reader.
+func (b *Reader) Discard(n int) (discarded int, err error) {
+ if n < 0 {
+ return 0, ErrNegativeCount
+ }
+ if n == 0 {
+ return
+ }
+
+ b.lastByte = -1
+ b.lastRuneSize = -1
+
+ remain := n
+ for {
+ skip := b.Buffered()
+ if skip == 0 {
+ b.fill()
+ skip = b.Buffered()
+ }
+ if skip > remain {
+ skip = remain
+ }
+ b.r += skip
+ remain -= skip
+ if remain == 0 {
+ return n, nil
+ }
+ if b.err != nil {
+ return n - remain, b.readErr()
+ }
+ }
+}
+
+// Read reads data into p.
+// It returns the number of bytes read into p.
+// The bytes are taken from at most one Read on the underlying [Reader],
+// hence n may be less than len(p).
+// To read exactly len(p) bytes, use io.ReadFull(b, p).
+// If the underlying [Reader] can return a non-zero count with io.EOF,
+// then this Read method can do so as well; see the [io.Reader] docs.
+func (b *Reader) Read(p []byte) (n int, err error) {
+ n = len(p)
+ if n == 0 {
+ if b.Buffered() > 0 {
+ return 0, nil
+ }
+ return 0, b.readErr()
+ }
+ if b.r == b.w {
+ if b.err != nil {
+ return 0, b.readErr()
+ }
+ if len(p) >= len(b.buf) {
+ // Large read, empty buffer.
+ // Read directly into p to avoid copy.
+ n, b.err = b.rd.Read(p)
+ if n < 0 {
+ panic(errNegativeRead)
+ }
+ if n > 0 {
+ b.lastByte = int(p[n-1])
+ b.lastRuneSize = -1
+ }
+ return n, b.readErr()
+ }
+ // One read.
+ // Do not use b.fill, which will loop.
+ b.r = 0
+ b.w = 0
+ n, b.err = b.rd.Read(b.buf)
+ if n < 0 {
+ panic(errNegativeRead)
+ }
+ if n == 0 {
+ return 0, b.readErr()
+ }
+ b.w += n
+ }
+
+ // copy as much as we can
+ // Note: if the slice panics here, it is probably because
+ // the underlying reader returned a bad count. See issue 49795.
+ n = copy(p, b.buf[b.r:b.w])
+ b.r += n
+ b.lastByte = int(b.buf[b.r-1])
+ b.lastRuneSize = -1
+ return n, nil
+}
+
+// ReadByte reads and returns a single byte.
+// If no byte is available, returns an error.
+func (b *Reader) ReadByte() (byte, error) {
+ b.lastRuneSize = -1
+ for b.r == b.w {
+ if b.err != nil {
+ return 0, b.readErr()
+ }
+ b.fill() // buffer is empty
+ }
+ c := b.buf[b.r]
+ b.r++
+ b.lastByte = int(c)
+ return c, nil
+}
+
+// UnreadByte unreads the last byte. Only the most recently read byte can be unread.
+//
+// UnreadByte returns an error if the most recent method called on the
+// [Reader] was not a read operation. Notably, [Reader.Peek], [Reader.Discard], and [Reader.WriteTo] are not
+// considered read operations.
+func (b *Reader) UnreadByte() error {
+ if b.lastByte < 0 || b.r == 0 && b.w > 0 {
+ return ErrInvalidUnreadByte
+ }
+ // b.r > 0 || b.w == 0
+ if b.r > 0 {
+ b.r--
+ } else {
+ // b.r == 0 && b.w == 0
+ b.w = 1
+ }
+ b.buf[b.r] = byte(b.lastByte)
+ b.lastByte = -1
+ b.lastRuneSize = -1
+ return nil
+}
+
+// ReadRune reads a single UTF-8 encoded Unicode character and returns the
+// rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
+// and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
+func (b *Reader) ReadRune() (r rune, size int, err error) {
+ for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil && b.w-b.r < len(b.buf) {
+ b.fill() // b.w-b.r < len(buf) => buffer is not full
+ }
+ b.lastRuneSize = -1
+ if b.r == b.w {
+ return 0, 0, b.readErr()
+ }
+ r, size = rune(b.buf[b.r]), 1
+ if r >= utf8.RuneSelf {
+ r, size = utf8.DecodeRune(b.buf[b.r:b.w])
+ }
+ b.r += size
+ b.lastByte = int(b.buf[b.r-1])
+ b.lastRuneSize = size
+ return r, size, nil
+}
+
+// UnreadRune unreads the last rune. If the most recent method called on
+// the [Reader] was not a [Reader.ReadRune], [Reader.UnreadRune] returns an error. (In this
+// regard it is stricter than [Reader.UnreadByte], which will unread the last byte
+// from any read operation.)
+func (b *Reader) UnreadRune() error {
+ if b.lastRuneSize < 0 || b.r < b.lastRuneSize {
+ return ErrInvalidUnreadRune
+ }
+ b.r -= b.lastRuneSize
+ b.lastByte = -1
+ b.lastRuneSize = -1
+ return nil
+}
+
+// Buffered returns the number of bytes that can be read from the current buffer.
+func (b *Reader) Buffered() int { return b.w - b.r }
+
+// ReadSlice reads until the first occurrence of delim in the input,
+// returning a slice pointing at the bytes in the buffer.
+// The bytes stop being valid at the next read.
+// If ReadSlice encounters an error before finding a delimiter,
+// it returns all the data in the buffer and the error itself (often io.EOF).
+// ReadSlice fails with error [ErrBufferFull] if the buffer fills without a delim.
+// Because the data returned from ReadSlice will be overwritten
+// by the next I/O operation, most clients should use
+// [Reader.ReadBytes] or ReadString instead.
+// ReadSlice returns err != nil if and only if line does not end in delim.
+func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
+ s := 0 // search start index
+ for {
+ // Search buffer.
+ if i := bytes.IndexByte(b.buf[b.r+s:b.w], delim); i >= 0 {
+ i += s
+ line = b.buf[b.r : b.r+i+1]
+ b.r += i + 1
+ break
+ }
+
+ // Pending error?
+ if b.err != nil {
+ line = b.buf[b.r:b.w]
+ b.r = b.w
+ err = b.readErr()
+ break
+ }
+
+ // Buffer full?
+ if b.Buffered() >= len(b.buf) {
+ b.r = b.w
+ line = b.buf
+ err = ErrBufferFull
+ break
+ }
+
+ s = b.w - b.r // do not rescan area we scanned before
+
+ b.fill() // buffer is not full
+ }
+
+ // Handle last byte, if any.
+ if i := len(line) - 1; i >= 0 {
+ b.lastByte = int(line[i])
+ b.lastRuneSize = -1
+ }
+
+ return
+}
+
+// ReadLine is a low-level line-reading primitive. Most callers should use
+// [Reader.ReadBytes]('\n') or [Reader.ReadString]('\n') instead or use a [Scanner].
+//
+// ReadLine tries to return a single line, not including the end-of-line bytes.
+// If the line was too long for the buffer then isPrefix is set and the
+// beginning of the line is returned. The rest of the line will be returned
+// from future calls. isPrefix will be false when returning the last fragment
+// of the line. The returned buffer is only valid until the next call to
+// ReadLine. ReadLine either returns a non-nil line or it returns an error,
+// never both.
+//
+// The text returned from ReadLine does not include the line end ("\r\n" or "\n").
+// No indication or error is given if the input ends without a final line end.
+// Calling [Reader.UnreadByte] after ReadLine will always unread the last byte read
+// (possibly a character belonging to the line end) even if that byte is not
+// part of the line returned by ReadLine.
+func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
+ line, err = b.ReadSlice('\n')
+ if err == ErrBufferFull {
+ // Handle the case where "\r\n" straddles the buffer.
+ if len(line) > 0 && line[len(line)-1] == '\r' {
+ // Put the '\r' back on buf and drop it from line.
+ // Let the next call to ReadLine check for "\r\n".
+ if b.r == 0 {
+ // should be unreachable
+ panic("bufio: tried to rewind past start of buffer")
+ }
+ b.r--
+ line = line[:len(line)-1]
+ }
+ return line, true, nil
+ }
+
+ if len(line) == 0 {
+ if err != nil {
+ line = nil
+ }
+ return
+ }
+ err = nil
+
+ if line[len(line)-1] == '\n' {
+ drop := 1
+ if len(line) > 1 && line[len(line)-2] == '\r' {
+ drop = 2
+ }
+ line = line[:len(line)-drop]
+ }
+ return
+}
+
+// collectFragments reads until the first occurrence of delim in the input. It
+// returns (slice of full buffers, remaining bytes before delim, total number
+// of bytes in the combined first two elements, error).
+// The complete result is equal to
+// `bytes.Join(append(fullBuffers, finalFragment), nil)`, which has a
+// length of `totalLen`. The result is structured in this way to allow callers
+// to minimize allocations and copies.
+func (b *Reader) collectFragments(delim byte) (fullBuffers [][]byte, finalFragment []byte, totalLen int, err error) {
+ var frag []byte
+ // Use ReadSlice to look for delim, accumulating full buffers.
+ for {
+ var e error
+ frag, e = b.ReadSlice(delim)
+ if e == nil { // got final fragment
+ break
+ }
+ if e != ErrBufferFull { // unexpected error
+ err = e
+ break
+ }
+
+ // Make a copy of the buffer.
+ buf := bytes.Clone(frag)
+ fullBuffers = append(fullBuffers, buf)
+ totalLen += len(buf)
+ }
+
+ totalLen += len(frag)
+ return fullBuffers, frag, totalLen, err
+}
+
+// ReadBytes reads until the first occurrence of delim in the input,
+// returning a slice containing the data up to and including the delimiter.
+// If ReadBytes encounters an error before finding a delimiter,
+// it returns the data read before the error and the error itself (often io.EOF).
+// ReadBytes returns err != nil if and only if the returned data does not end in
+// delim.
+// For simple uses, a Scanner may be more convenient.
+func (b *Reader) ReadBytes(delim byte) ([]byte, error) {
+ full, frag, n, err := b.collectFragments(delim)
+ // Allocate new buffer to hold the full pieces and the fragment.
+ buf := make([]byte, n)
+ n = 0
+ // Copy full pieces and fragment in.
+ for i := range full {
+ n += copy(buf[n:], full[i])
+ }
+ copy(buf[n:], frag)
+ return buf, err
+}
+
+// ReadString reads until the first occurrence of delim in the input,
+// returning a string containing the data up to and including the delimiter.
+// If ReadString encounters an error before finding a delimiter,
+// it returns the data read before the error and the error itself (often io.EOF).
+// ReadString returns err != nil if and only if the returned data does not end in
+// delim.
+// For simple uses, a Scanner may be more convenient.
+func (b *Reader) ReadString(delim byte) (string, error) {
+ full, frag, n, err := b.collectFragments(delim)
+ // Allocate new buffer to hold the full pieces and the fragment.
+ var buf strings.Builder
+ buf.Grow(n)
+ // Copy full pieces and fragment in.
+ for _, fb := range full {
+ buf.Write(fb)
+ }
+ buf.Write(frag)
+ return buf.String(), err
+}
+
+// WriteTo implements io.WriterTo.
+// This may make multiple calls to the [Reader.Read] method of the underlying [Reader].
+// If the underlying reader supports the [Reader.WriteTo] method,
+// this calls the underlying [Reader.WriteTo] without buffering.
+func (b *Reader) WriteTo(w io.Writer) (n int64, err error) {
+ b.lastByte = -1
+ b.lastRuneSize = -1
+
+ n, err = b.writeBuf(w)
+ if err != nil {
+ return
+ }
+
+ if r, ok := b.rd.(io.WriterTo); ok {
+ m, err := r.WriteTo(w)
+ n += m
+ return n, err
+ }
+
+ if w, ok := w.(io.ReaderFrom); ok {
+ m, err := w.ReadFrom(b.rd)
+ n += m
+ return n, err
+ }
+
+ if b.w-b.r < len(b.buf) {
+ b.fill() // buffer not full
+ }
+
+ for b.r < b.w {
+ // b.r < b.w => buffer is not empty
+ m, err := b.writeBuf(w)
+ n += m
+ if err != nil {
+ return n, err
+ }
+ b.fill() // buffer is empty
+ }
+
+ if b.err == io.EOF {
+ b.err = nil
+ }
+
+ return n, b.readErr()
+}
+
+var errNegativeWrite = errors.New("bufio: writer returned negative count from Write")
+
+// writeBuf writes the [Reader]'s buffer to the writer.
+func (b *Reader) writeBuf(w io.Writer) (int64, error) {
+ n, err := w.Write(b.buf[b.r:b.w])
+ if n < 0 {
+ panic(errNegativeWrite)
+ }
+ b.r += n
+ return int64(n), err
+}
+
+// buffered output
+
+// Writer implements buffering for an [io.Writer] object.
+// If an error occurs writing to a [Writer], no more data will be
+// accepted and all subsequent writes, and [Writer.Flush], will return the error.
+// After all data has been written, the client should call the
+// [Writer.Flush] method to guarantee all data has been forwarded to
+// the underlying [io.Writer].
+type Writer struct {
+ err error
+ buf []byte
+ n int
+ wr io.Writer
+}
+
+// NewWriterSize returns a new [Writer] whose buffer has at least the specified
+// size. If the argument io.Writer is already a [Writer] with large enough
+// size, it returns the underlying [Writer].
+func NewWriterSize(w io.Writer, size int) *Writer {
+ // Is it already a Writer?
+ b, ok := w.(*Writer)
+ if ok && len(b.buf) >= size {
+ return b
+ }
+ if size <= 0 {
+ size = defaultBufSize
+ }
+ return &Writer{
+ buf: make([]byte, size),
+ wr: w,
+ }
+}
+
+// NewWriter returns a new [Writer] whose buffer has the default size.
+// If the argument io.Writer is already a [Writer] with large enough buffer size,
+// it returns the underlying [Writer].
+func NewWriter(w io.Writer) *Writer {
+ return NewWriterSize(w, defaultBufSize)
+}
+
+// Size returns the size of the underlying buffer in bytes.
+func (b *Writer) Size() int { return len(b.buf) }
+
+// Reset discards any unflushed buffered data, clears any error, and
+// resets b to write its output to w.
+// Calling Reset on the zero value of [Writer] initializes the internal buffer
+// to the default size.
+// Calling w.Reset(w) (that is, resetting a [Writer] to itself) does nothing.
+func (b *Writer) Reset(w io.Writer) {
+ // If a Writer w is passed to NewWriter, NewWriter will return w.
+ // Different layers of code may do that, and then later pass w
+ // to Reset. Avoid infinite recursion in that case.
+ if b == w {
+ return
+ }
+ if b.buf == nil {
+ b.buf = make([]byte, defaultBufSize)
+ }
+ b.err = nil
+ b.n = 0
+ b.wr = w
+}
+
+// Flush writes any buffered data to the underlying [io.Writer].
+func (b *Writer) Flush() error {
+ if b.err != nil {
+ return b.err
+ }
+ if b.n == 0 {
+ return nil
+ }
+ n, err := b.wr.Write(b.buf[0:b.n])
+ if n < b.n && err == nil {
+ err = io.ErrShortWrite
+ }
+ if err != nil {
+ if n > 0 && n < b.n {
+ copy(b.buf[0:b.n-n], b.buf[n:b.n])
+ }
+ b.n -= n
+ b.err = err
+ return err
+ }
+ b.n = 0
+ return nil
+}
+
+// Available returns how many bytes are unused in the buffer.
+func (b *Writer) Available() int { return len(b.buf) - b.n }
+
+// AvailableBuffer returns an empty buffer with b.Available() capacity.
+// This buffer is intended to be appended to and
+// passed to an immediately succeeding [Writer.Write] call.
+// The buffer is only valid until the next write operation on b.
+func (b *Writer) AvailableBuffer() []byte {
+ return b.buf[b.n:][:0]
+}
+
+// Buffered returns the number of bytes that have been written into the current buffer.
+func (b *Writer) Buffered() int { return b.n }
+
+// Write writes the contents of p into the buffer.
+// It returns the number of bytes written.
+// If nn < len(p), it also returns an error explaining
+// why the write is short.
+func (b *Writer) Write(p []byte) (nn int, err error) {
+ for len(p) > b.Available() && b.err == nil {
+ var n int
+ if b.Buffered() == 0 {
+ // Large write, empty buffer.
+ // Write directly from p to avoid copy.
+ n, b.err = b.wr.Write(p)
+ } else {
+ n = copy(b.buf[b.n:], p)
+ b.n += n
+ b.Flush()
+ }
+ nn += n
+ p = p[n:]
+ }
+ if b.err != nil {
+ return nn, b.err
+ }
+ n := copy(b.buf[b.n:], p)
+ b.n += n
+ nn += n
+ return nn, nil
+}
+
+// WriteByte writes a single byte.
+func (b *Writer) WriteByte(c byte) error {
+ if b.err != nil {
+ return b.err
+ }
+ if b.Available() <= 0 && b.Flush() != nil {
+ return b.err
+ }
+ b.buf[b.n] = c
+ b.n++
+ return nil
+}
+
+// WriteRune writes a single Unicode code point, returning
+// the number of bytes written and any error.
+func (b *Writer) WriteRune(r rune) (size int, err error) {
+ // Compare as uint32 to correctly handle negative runes.
+ if uint32(r) < utf8.RuneSelf {
+ err = b.WriteByte(byte(r))
+ if err != nil {
+ return 0, err
+ }
+ return 1, nil
+ }
+ if b.err != nil {
+ return 0, b.err
+ }
+ n := b.Available()
+ if n < utf8.UTFMax {
+ if b.Flush(); b.err != nil {
+ return 0, b.err
+ }
+ n = b.Available()
+ if n < utf8.UTFMax {
+ // Can only happen if buffer is silly small.
+ return b.WriteString(string(r))
+ }
+ }
+ size = utf8.EncodeRune(b.buf[b.n:], r)
+ b.n += size
+ return size, nil
+}
+
+// WriteString writes a string.
+// It returns the number of bytes written.
+// If the count is less than len(s), it also returns an error explaining
+// why the write is short.
+func (b *Writer) WriteString(s string) (int, error) {
+ var sw io.StringWriter
+ tryStringWriter := true
+
+ nn := 0
+ for len(s) > b.Available() && b.err == nil {
+ var n int
+ if b.Buffered() == 0 && sw == nil && tryStringWriter {
+ // Check at most once whether b.wr is a StringWriter.
+ sw, tryStringWriter = b.wr.(io.StringWriter)
+ }
+ if b.Buffered() == 0 && tryStringWriter {
+ // Large write, empty buffer, and the underlying writer supports
+ // WriteString: forward the write to the underlying StringWriter.
+ // This avoids an extra copy.
+ n, b.err = sw.WriteString(s)
+ } else {
+ n = copy(b.buf[b.n:], s)
+ b.n += n
+ b.Flush()
+ }
+ nn += n
+ s = s[n:]
+ }
+ if b.err != nil {
+ return nn, b.err
+ }
+ n := copy(b.buf[b.n:], s)
+ b.n += n
+ nn += n
+ return nn, nil
+}
+
+// ReadFrom implements [io.ReaderFrom]. If the underlying writer
+// supports the ReadFrom method, this calls the underlying ReadFrom.
+// If there is buffered data and an underlying ReadFrom, this fills
+// the buffer and writes it before calling ReadFrom.
+func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) {
+ if b.err != nil {
+ return 0, b.err
+ }
+ readerFrom, readerFromOK := b.wr.(io.ReaderFrom)
+ var m int
+ for {
+ if b.Available() == 0 {
+ if err1 := b.Flush(); err1 != nil {
+ return n, err1
+ }
+ }
+ if readerFromOK && b.Buffered() == 0 {
+ nn, err := readerFrom.ReadFrom(r)
+ b.err = err
+ n += nn
+ return n, err
+ }
+ nr := 0
+ for nr < maxConsecutiveEmptyReads {
+ m, err = r.Read(b.buf[b.n:])
+ if m != 0 || err != nil {
+ break
+ }
+ nr++
+ }
+ if nr == maxConsecutiveEmptyReads {
+ return n, io.ErrNoProgress
+ }
+ b.n += m
+ n += int64(m)
+ if err != nil {
+ break
+ }
+ }
+ if err == io.EOF {
+ // If we filled the buffer exactly, flush preemptively.
+ if b.Available() == 0 {
+ err = b.Flush()
+ } else {
+ err = nil
+ }
+ }
+ return n, err
+}
+
+// buffered input and output
+
+// ReadWriter stores pointers to a [Reader] and a [Writer].
+// It implements [io.ReadWriter].
+type ReadWriter struct {
+ *Reader
+ *Writer
+}
+
+// NewReadWriter allocates a new [ReadWriter] that dispatches to r and w.
+func NewReadWriter(r *Reader, w *Writer) *ReadWriter {
+ return &ReadWriter{r, w}
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/bufio_test.go b/platform/dbops/binaries/go/go/src/bufio/bufio_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a8c1e503978847c3473bf964349959397b0cf552
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/bufio_test.go
@@ -0,0 +1,1996 @@
+// 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 bufio_test
+
+import (
+ . "bufio"
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "math/rand"
+ "strconv"
+ "strings"
+ "testing"
+ "testing/iotest"
+ "time"
+ "unicode/utf8"
+)
+
+// Reads from a reader and rot13s the result.
+type rot13Reader struct {
+ r io.Reader
+}
+
+func newRot13Reader(r io.Reader) *rot13Reader {
+ r13 := new(rot13Reader)
+ r13.r = r
+ return r13
+}
+
+func (r13 *rot13Reader) Read(p []byte) (int, error) {
+ n, err := r13.r.Read(p)
+ for i := 0; i < n; i++ {
+ c := p[i] | 0x20 // lowercase byte
+ if 'a' <= c && c <= 'm' {
+ p[i] += 13
+ } else if 'n' <= c && c <= 'z' {
+ p[i] -= 13
+ }
+ }
+ return n, err
+}
+
+// Call ReadByte to accumulate the text of a file
+func readBytes(buf *Reader) string {
+ var b [1000]byte
+ nb := 0
+ for {
+ c, err := buf.ReadByte()
+ if err == io.EOF {
+ break
+ }
+ if err == nil {
+ b[nb] = c
+ nb++
+ } else if err != iotest.ErrTimeout {
+ panic("Data: " + err.Error())
+ }
+ }
+ return string(b[0:nb])
+}
+
+func TestReaderSimple(t *testing.T) {
+ data := "hello world"
+ b := NewReader(strings.NewReader(data))
+ if s := readBytes(b); s != "hello world" {
+ t.Errorf("simple hello world test failed: got %q", s)
+ }
+
+ b = NewReader(newRot13Reader(strings.NewReader(data)))
+ if s := readBytes(b); s != "uryyb jbeyq" {
+ t.Errorf("rot13 hello world test failed: got %q", s)
+ }
+}
+
+type readMaker struct {
+ name string
+ fn func(io.Reader) io.Reader
+}
+
+var readMakers = []readMaker{
+ {"full", func(r io.Reader) io.Reader { return r }},
+ {"byte", iotest.OneByteReader},
+ {"half", iotest.HalfReader},
+ {"data+err", iotest.DataErrReader},
+ {"timeout", iotest.TimeoutReader},
+}
+
+// Call ReadString (which ends up calling everything else)
+// to accumulate the text of a file.
+func readLines(b *Reader) string {
+ s := ""
+ for {
+ s1, err := b.ReadString('\n')
+ if err == io.EOF {
+ break
+ }
+ if err != nil && err != iotest.ErrTimeout {
+ panic("GetLines: " + err.Error())
+ }
+ s += s1
+ }
+ return s
+}
+
+// Call Read to accumulate the text of a file
+func reads(buf *Reader, m int) string {
+ var b [1000]byte
+ nb := 0
+ for {
+ n, err := buf.Read(b[nb : nb+m])
+ nb += n
+ if err == io.EOF {
+ break
+ }
+ }
+ return string(b[0:nb])
+}
+
+type bufReader struct {
+ name string
+ fn func(*Reader) string
+}
+
+var bufreaders = []bufReader{
+ {"1", func(b *Reader) string { return reads(b, 1) }},
+ {"2", func(b *Reader) string { return reads(b, 2) }},
+ {"3", func(b *Reader) string { return reads(b, 3) }},
+ {"4", func(b *Reader) string { return reads(b, 4) }},
+ {"5", func(b *Reader) string { return reads(b, 5) }},
+ {"7", func(b *Reader) string { return reads(b, 7) }},
+ {"bytes", readBytes},
+ {"lines", readLines},
+}
+
+const minReadBufferSize = 16
+
+var bufsizes = []int{
+ 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096,
+}
+
+func TestReader(t *testing.T) {
+ var texts [31]string
+ str := ""
+ all := ""
+ for i := 0; i < len(texts)-1; i++ {
+ texts[i] = str + "\n"
+ all += texts[i]
+ str += string(rune(i%26 + 'a'))
+ }
+ texts[len(texts)-1] = all
+
+ for h := 0; h < len(texts); h++ {
+ text := texts[h]
+ for i := 0; i < len(readMakers); i++ {
+ for j := 0; j < len(bufreaders); j++ {
+ for k := 0; k < len(bufsizes); k++ {
+ readmaker := readMakers[i]
+ bufreader := bufreaders[j]
+ bufsize := bufsizes[k]
+ read := readmaker.fn(strings.NewReader(text))
+ buf := NewReaderSize(read, bufsize)
+ s := bufreader.fn(buf)
+ if s != text {
+ t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
+ readmaker.name, bufreader.name, bufsize, text, s)
+ }
+ }
+ }
+ }
+ }
+}
+
+type zeroReader struct{}
+
+func (zeroReader) Read(p []byte) (int, error) {
+ return 0, nil
+}
+
+func TestZeroReader(t *testing.T) {
+ var z zeroReader
+ r := NewReader(z)
+
+ c := make(chan error)
+ go func() {
+ _, err := r.ReadByte()
+ c <- err
+ }()
+
+ select {
+ case err := <-c:
+ if err == nil {
+ t.Error("error expected")
+ } else if err != io.ErrNoProgress {
+ t.Error("unexpected error:", err)
+ }
+ case <-time.After(time.Second):
+ t.Error("test timed out (endless loop in ReadByte?)")
+ }
+}
+
+// A StringReader delivers its data one string segment at a time via Read.
+type StringReader struct {
+ data []string
+ step int
+}
+
+func (r *StringReader) Read(p []byte) (n int, err error) {
+ if r.step < len(r.data) {
+ s := r.data[r.step]
+ n = copy(p, s)
+ r.step++
+ } else {
+ err = io.EOF
+ }
+ return
+}
+
+func readRuneSegments(t *testing.T, segments []string) {
+ got := ""
+ want := strings.Join(segments, "")
+ r := NewReader(&StringReader{data: segments})
+ for {
+ r, _, err := r.ReadRune()
+ if err != nil {
+ if err != io.EOF {
+ return
+ }
+ break
+ }
+ got += string(r)
+ }
+ if got != want {
+ t.Errorf("segments=%v got=%s want=%s", segments, got, want)
+ }
+}
+
+var segmentList = [][]string{
+ {},
+ {""},
+ {"日", "本語"},
+ {"\u65e5", "\u672c", "\u8a9e"},
+ {"\U000065e5", "\U0000672c", "\U00008a9e"},
+ {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"},
+ {"Hello", ", ", "World", "!"},
+ {"Hello", ", ", "", "World", "!"},
+}
+
+func TestReadRune(t *testing.T) {
+ for _, s := range segmentList {
+ readRuneSegments(t, s)
+ }
+}
+
+func TestUnreadRune(t *testing.T) {
+ segments := []string{"Hello, world:", "日本語"}
+ r := NewReader(&StringReader{data: segments})
+ got := ""
+ want := strings.Join(segments, "")
+ // Normal execution.
+ for {
+ r1, _, err := r.ReadRune()
+ if err != nil {
+ if err != io.EOF {
+ t.Error("unexpected error on ReadRune:", err)
+ }
+ break
+ }
+ got += string(r1)
+ // Put it back and read it again.
+ if err = r.UnreadRune(); err != nil {
+ t.Fatal("unexpected error on UnreadRune:", err)
+ }
+ r2, _, err := r.ReadRune()
+ if err != nil {
+ t.Fatal("unexpected error reading after unreading:", err)
+ }
+ if r1 != r2 {
+ t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2)
+ }
+ }
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
+func TestNoUnreadRuneAfterPeek(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.ReadRune()
+ br.Peek(1)
+ if err := br.UnreadRune(); err == nil {
+ t.Error("UnreadRune didn't fail after Peek")
+ }
+}
+
+func TestNoUnreadByteAfterPeek(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.ReadByte()
+ br.Peek(1)
+ if err := br.UnreadByte(); err == nil {
+ t.Error("UnreadByte didn't fail after Peek")
+ }
+}
+
+func TestNoUnreadRuneAfterDiscard(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.ReadRune()
+ br.Discard(1)
+ if err := br.UnreadRune(); err == nil {
+ t.Error("UnreadRune didn't fail after Discard")
+ }
+}
+
+func TestNoUnreadByteAfterDiscard(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.ReadByte()
+ br.Discard(1)
+ if err := br.UnreadByte(); err == nil {
+ t.Error("UnreadByte didn't fail after Discard")
+ }
+}
+
+func TestNoUnreadRuneAfterWriteTo(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.WriteTo(io.Discard)
+ if err := br.UnreadRune(); err == nil {
+ t.Error("UnreadRune didn't fail after WriteTo")
+ }
+}
+
+func TestNoUnreadByteAfterWriteTo(t *testing.T) {
+ br := NewReader(strings.NewReader("example"))
+ br.WriteTo(io.Discard)
+ if err := br.UnreadByte(); err == nil {
+ t.Error("UnreadByte didn't fail after WriteTo")
+ }
+}
+
+func TestUnreadByte(t *testing.T) {
+ segments := []string{"Hello, ", "world"}
+ r := NewReader(&StringReader{data: segments})
+ got := ""
+ want := strings.Join(segments, "")
+ // Normal execution.
+ for {
+ b1, err := r.ReadByte()
+ if err != nil {
+ if err != io.EOF {
+ t.Error("unexpected error on ReadByte:", err)
+ }
+ break
+ }
+ got += string(b1)
+ // Put it back and read it again.
+ if err = r.UnreadByte(); err != nil {
+ t.Fatal("unexpected error on UnreadByte:", err)
+ }
+ b2, err := r.ReadByte()
+ if err != nil {
+ t.Fatal("unexpected error reading after unreading:", err)
+ }
+ if b1 != b2 {
+ t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2)
+ }
+ }
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
+func TestUnreadByteMultiple(t *testing.T) {
+ segments := []string{"Hello, ", "world"}
+ data := strings.Join(segments, "")
+ for n := 0; n <= len(data); n++ {
+ r := NewReader(&StringReader{data: segments})
+ // Read n bytes.
+ for i := 0; i < n; i++ {
+ b, err := r.ReadByte()
+ if err != nil {
+ t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err)
+ }
+ if b != data[i] {
+ t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i])
+ }
+ }
+ // Unread one byte if there is one.
+ if n > 0 {
+ if err := r.UnreadByte(); err != nil {
+ t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err)
+ }
+ }
+ // Test that we cannot unread any further.
+ if err := r.UnreadByte(); err == nil {
+ t.Errorf("n = %d: expected error on UnreadByte", n)
+ }
+ }
+}
+
+func TestUnreadByteOthers(t *testing.T) {
+ // A list of readers to use in conjunction with UnreadByte.
+ var readers = []func(*Reader, byte) ([]byte, error){
+ (*Reader).ReadBytes,
+ (*Reader).ReadSlice,
+ func(r *Reader, delim byte) ([]byte, error) {
+ data, err := r.ReadString(delim)
+ return []byte(data), err
+ },
+ // ReadLine doesn't fit the data/pattern easily
+ // so we leave it out. It should be covered via
+ // the ReadSlice test since ReadLine simply calls
+ // ReadSlice, and it's that function that handles
+ // the last byte.
+ }
+
+ // Try all readers with UnreadByte.
+ for rno, read := range readers {
+ // Some input data that is longer than the minimum reader buffer size.
+ const n = 10
+ var buf bytes.Buffer
+ for i := 0; i < n; i++ {
+ buf.WriteString("abcdefg")
+ }
+
+ r := NewReaderSize(&buf, minReadBufferSize)
+ readTo := func(delim byte, want string) {
+ data, err := read(r, delim)
+ if err != nil {
+ t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err)
+ }
+ if got := string(data); got != want {
+ t.Fatalf("#%d: got %q, want %q", rno, got, want)
+ }
+ }
+
+ // Read the data with occasional UnreadByte calls.
+ for i := 0; i < n; i++ {
+ readTo('d', "abcd")
+ for j := 0; j < 3; j++ {
+ if err := r.UnreadByte(); err != nil {
+ t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err)
+ }
+ readTo('d', "d")
+ }
+ readTo('g', "efg")
+ }
+
+ // All data should have been read.
+ _, err := r.ReadByte()
+ if err != io.EOF {
+ t.Errorf("#%d: got error %v; want EOF", rno, err)
+ }
+ }
+}
+
+// Test that UnreadRune fails if the preceding operation was not a ReadRune.
+func TestUnreadRuneError(t *testing.T) {
+ buf := make([]byte, 3) // All runes in this test are 3 bytes long
+ r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}})
+ if r.UnreadRune() == nil {
+ t.Error("expected error on UnreadRune from fresh buffer")
+ }
+ _, _, err := r.ReadRune()
+ if err != nil {
+ t.Error("unexpected error on ReadRune (1):", err)
+ }
+ if err = r.UnreadRune(); err != nil {
+ t.Error("unexpected error on UnreadRune (1):", err)
+ }
+ if r.UnreadRune() == nil {
+ t.Error("expected error after UnreadRune (1)")
+ }
+ // Test error after Read.
+ _, _, err = r.ReadRune() // reset state
+ if err != nil {
+ t.Error("unexpected error on ReadRune (2):", err)
+ }
+ _, err = r.Read(buf)
+ if err != nil {
+ t.Error("unexpected error on Read (2):", err)
+ }
+ if r.UnreadRune() == nil {
+ t.Error("expected error after Read (2)")
+ }
+ // Test error after ReadByte.
+ _, _, err = r.ReadRune() // reset state
+ if err != nil {
+ t.Error("unexpected error on ReadRune (2):", err)
+ }
+ for range buf {
+ _, err = r.ReadByte()
+ if err != nil {
+ t.Error("unexpected error on ReadByte (2):", err)
+ }
+ }
+ if r.UnreadRune() == nil {
+ t.Error("expected error after ReadByte")
+ }
+ // Test error after UnreadByte.
+ _, _, err = r.ReadRune() // reset state
+ if err != nil {
+ t.Error("unexpected error on ReadRune (3):", err)
+ }
+ _, err = r.ReadByte()
+ if err != nil {
+ t.Error("unexpected error on ReadByte (3):", err)
+ }
+ err = r.UnreadByte()
+ if err != nil {
+ t.Error("unexpected error on UnreadByte (3):", err)
+ }
+ if r.UnreadRune() == nil {
+ t.Error("expected error after UnreadByte (3)")
+ }
+ // Test error after ReadSlice.
+ _, _, err = r.ReadRune() // reset state
+ if err != nil {
+ t.Error("unexpected error on ReadRune (4):", err)
+ }
+ _, err = r.ReadSlice(0)
+ if err != io.EOF {
+ t.Error("unexpected error on ReadSlice (4):", err)
+ }
+ if r.UnreadRune() == nil {
+ t.Error("expected error after ReadSlice (4)")
+ }
+}
+
+func TestUnreadRuneAtEOF(t *testing.T) {
+ // UnreadRune/ReadRune should error at EOF (was a bug; used to panic)
+ r := NewReader(strings.NewReader("x"))
+ r.ReadRune()
+ r.ReadRune()
+ r.UnreadRune()
+ _, _, err := r.ReadRune()
+ if err == nil {
+ t.Error("expected error at EOF")
+ } else if err != io.EOF {
+ t.Error("expected EOF; got", err)
+ }
+}
+
+func TestReadWriteRune(t *testing.T) {
+ const NRune = 1000
+ byteBuf := new(bytes.Buffer)
+ w := NewWriter(byteBuf)
+ // Write the runes out using WriteRune
+ buf := make([]byte, utf8.UTFMax)
+ for r := rune(0); r < NRune; r++ {
+ size := utf8.EncodeRune(buf, r)
+ nbytes, err := w.WriteRune(r)
+ if err != nil {
+ t.Fatalf("WriteRune(0x%x) error: %s", r, err)
+ }
+ if nbytes != size {
+ t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes)
+ }
+ }
+ w.Flush()
+
+ r := NewReader(byteBuf)
+ // Read them back with ReadRune
+ for r1 := rune(0); r1 < NRune; r1++ {
+ size := utf8.EncodeRune(buf, r1)
+ nr, nbytes, err := r.ReadRune()
+ if nr != r1 || nbytes != size || err != nil {
+ t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err)
+ }
+ }
+}
+
+func TestWriteInvalidRune(t *testing.T) {
+ // Invalid runes, including negative ones, should be written as the
+ // replacement character.
+ for _, r := range []rune{-1, utf8.MaxRune + 1} {
+ var buf strings.Builder
+ w := NewWriter(&buf)
+ w.WriteRune(r)
+ w.Flush()
+ if s := buf.String(); s != "\uFFFD" {
+ t.Errorf("WriteRune(%d) wrote %q, not replacement character", r, s)
+ }
+ }
+}
+
+func TestReadStringAllocs(t *testing.T) {
+ r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
+ buf := NewReader(r)
+ allocs := testing.AllocsPerRun(100, func() {
+ r.Seek(0, io.SeekStart)
+ buf.Reset(r)
+
+ _, err := buf.ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ })
+ if allocs != 1 {
+ t.Errorf("Unexpected number of allocations, got %f, want 1", allocs)
+ }
+}
+
+func TestWriter(t *testing.T) {
+ var data [8192]byte
+
+ for i := 0; i < len(data); i++ {
+ data[i] = byte(' ' + i%('~'-' '))
+ }
+ w := new(bytes.Buffer)
+ for i := 0; i < len(bufsizes); i++ {
+ for j := 0; j < len(bufsizes); j++ {
+ nwrite := bufsizes[i]
+ bs := bufsizes[j]
+
+ // Write nwrite bytes using buffer size bs.
+ // Check that the right amount makes it out
+ // and that the data is correct.
+
+ w.Reset()
+ buf := NewWriterSize(w, bs)
+ context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
+ n, e1 := buf.Write(data[0:nwrite])
+ if e1 != nil || n != nwrite {
+ t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
+ continue
+ }
+ if e := buf.Flush(); e != nil {
+ t.Errorf("%s: buf.Flush = %v", context, e)
+ }
+
+ written := w.Bytes()
+ if len(written) != nwrite {
+ t.Errorf("%s: %d bytes written", context, len(written))
+ }
+ for l := 0; l < len(written); l++ {
+ if written[l] != data[l] {
+ t.Errorf("wrong bytes written")
+ t.Errorf("want=%q", data[0:len(written)])
+ t.Errorf("have=%q", written)
+ }
+ }
+ }
+ }
+}
+
+func TestWriterAppend(t *testing.T) {
+ got := new(bytes.Buffer)
+ var want []byte
+ rn := rand.New(rand.NewSource(0))
+ w := NewWriterSize(got, 64)
+ for i := 0; i < 100; i++ {
+ // Obtain a buffer to append to.
+ b := w.AvailableBuffer()
+ if w.Available() != cap(b) {
+ t.Fatalf("Available() = %v, want %v", w.Available(), cap(b))
+ }
+
+ // While not recommended, it is valid to append to a shifted buffer.
+ // This forces Write to copy the input.
+ if rn.Intn(8) == 0 && cap(b) > 0 {
+ b = b[1:1:cap(b)]
+ }
+
+ // Append a random integer of varying width.
+ n := int64(rn.Intn(1 << rn.Intn(30)))
+ want = append(strconv.AppendInt(want, n, 10), ' ')
+ b = append(strconv.AppendInt(b, n, 10), ' ')
+ w.Write(b)
+ }
+ w.Flush()
+
+ if !bytes.Equal(got.Bytes(), want) {
+ t.Errorf("output mismatch:\ngot %s\nwant %s", got.Bytes(), want)
+ }
+}
+
+// Check that write errors are returned properly.
+
+type errorWriterTest struct {
+ n, m int
+ err error
+ expect error
+}
+
+func (w errorWriterTest) Write(p []byte) (int, error) {
+ return len(p) * w.n / w.m, w.err
+}
+
+var errorWriterTests = []errorWriterTest{
+ {0, 1, nil, io.ErrShortWrite},
+ {1, 2, nil, io.ErrShortWrite},
+ {1, 1, nil, nil},
+ {0, 1, io.ErrClosedPipe, io.ErrClosedPipe},
+ {1, 2, io.ErrClosedPipe, io.ErrClosedPipe},
+ {1, 1, io.ErrClosedPipe, io.ErrClosedPipe},
+}
+
+func TestWriteErrors(t *testing.T) {
+ for _, w := range errorWriterTests {
+ buf := NewWriter(w)
+ _, e := buf.Write([]byte("hello world"))
+ if e != nil {
+ t.Errorf("Write hello to %v: %v", w, e)
+ continue
+ }
+ // Two flushes, to verify the error is sticky.
+ for i := 0; i < 2; i++ {
+ e = buf.Flush()
+ if e != w.expect {
+ t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect)
+ }
+ }
+ }
+}
+
+func TestNewReaderSizeIdempotent(t *testing.T) {
+ const BufSize = 1000
+ b := NewReaderSize(strings.NewReader("hello world"), BufSize)
+ // Does it recognize itself?
+ b1 := NewReaderSize(b, BufSize)
+ if b1 != b {
+ t.Error("NewReaderSize did not detect underlying Reader")
+ }
+ // Does it wrap if existing buffer is too small?
+ b2 := NewReaderSize(b, 2*BufSize)
+ if b2 == b {
+ t.Error("NewReaderSize did not enlarge buffer")
+ }
+}
+
+func TestNewWriterSizeIdempotent(t *testing.T) {
+ const BufSize = 1000
+ b := NewWriterSize(new(bytes.Buffer), BufSize)
+ // Does it recognize itself?
+ b1 := NewWriterSize(b, BufSize)
+ if b1 != b {
+ t.Error("NewWriterSize did not detect underlying Writer")
+ }
+ // Does it wrap if existing buffer is too small?
+ b2 := NewWriterSize(b, 2*BufSize)
+ if b2 == b {
+ t.Error("NewWriterSize did not enlarge buffer")
+ }
+}
+
+func TestWriteString(t *testing.T) {
+ const BufSize = 8
+ buf := new(strings.Builder)
+ b := NewWriterSize(buf, BufSize)
+ b.WriteString("0") // easy
+ b.WriteString("123456") // still easy
+ b.WriteString("7890") // easy after flush
+ b.WriteString("abcdefghijklmnopqrstuvwxy") // hard
+ b.WriteString("z")
+ if err := b.Flush(); err != nil {
+ t.Error("WriteString", err)
+ }
+ s := "01234567890abcdefghijklmnopqrstuvwxyz"
+ if buf.String() != s {
+ t.Errorf("WriteString wants %q gets %q", s, buf.String())
+ }
+}
+
+func TestWriteStringStringWriter(t *testing.T) {
+ const BufSize = 8
+ {
+ tw := &teststringwriter{}
+ b := NewWriterSize(tw, BufSize)
+ b.WriteString("1234")
+ tw.check(t, "", "")
+ b.WriteString("56789012") // longer than BufSize
+ tw.check(t, "12345678", "") // but not enough (after filling the partially-filled buffer)
+ b.Flush()
+ tw.check(t, "123456789012", "")
+ }
+ {
+ tw := &teststringwriter{}
+ b := NewWriterSize(tw, BufSize)
+ b.WriteString("123456789") // long string, empty buffer:
+ tw.check(t, "", "123456789") // use WriteString
+ }
+ {
+ tw := &teststringwriter{}
+ b := NewWriterSize(tw, BufSize)
+ b.WriteString("abc")
+ tw.check(t, "", "")
+ b.WriteString("123456789012345") // long string, non-empty buffer
+ tw.check(t, "abc12345", "6789012345") // use Write and then WriteString since the remaining part is still longer than BufSize
+ }
+ {
+ tw := &teststringwriter{}
+ b := NewWriterSize(tw, BufSize)
+ b.Write([]byte("abc")) // same as above, but use Write instead of WriteString
+ tw.check(t, "", "")
+ b.WriteString("123456789012345")
+ tw.check(t, "abc12345", "6789012345") // same as above
+ }
+}
+
+type teststringwriter struct {
+ write string
+ writeString string
+}
+
+func (w *teststringwriter) Write(b []byte) (int, error) {
+ w.write += string(b)
+ return len(b), nil
+}
+
+func (w *teststringwriter) WriteString(s string) (int, error) {
+ w.writeString += s
+ return len(s), nil
+}
+
+func (w *teststringwriter) check(t *testing.T, write, writeString string) {
+ t.Helper()
+ if w.write != write {
+ t.Errorf("write: expected %q, got %q", write, w.write)
+ }
+ if w.writeString != writeString {
+ t.Errorf("writeString: expected %q, got %q", writeString, w.writeString)
+ }
+}
+
+func TestBufferFull(t *testing.T) {
+ const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"
+ buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize)
+ line, err := buf.ReadSlice('!')
+ if string(line) != "And now, hello, " || err != ErrBufferFull {
+ t.Errorf("first ReadSlice(,) = %q, %v", line, err)
+ }
+ line, err = buf.ReadSlice('!')
+ if string(line) != "world!" || err != nil {
+ t.Errorf("second ReadSlice(,) = %q, %v", line, err)
+ }
+}
+
+func TestPeek(t *testing.T) {
+ p := make([]byte, 10)
+ // string is 16 (minReadBufferSize) long.
+ buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize)
+ if s, err := buf.Peek(1); string(s) != "a" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "a", string(s), err)
+ }
+ if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err)
+ }
+ if _, err := buf.Peek(-1); err != ErrNegativeCount {
+ t.Fatalf("want ErrNegativeCount got %v", err)
+ }
+ if s, err := buf.Peek(32); string(s) != "abcdefghijklmnop" || err != ErrBufferFull {
+ t.Fatalf("want %q, ErrBufFull got %q, err=%v", "abcdefghijklmnop", string(s), err)
+ }
+ if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err)
+ }
+ if s, err := buf.Peek(1); string(s) != "d" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "d", string(s), err)
+ }
+ if s, err := buf.Peek(2); string(s) != "de" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "de", string(s), err)
+ }
+ if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err)
+ }
+ if s, err := buf.Peek(4); string(s) != "ghij" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err)
+ }
+ if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err)
+ }
+ if s, err := buf.Peek(0); string(s) != "" || err != nil {
+ t.Fatalf("want %q got %q, err=%v", "", string(s), err)
+ }
+ if _, err := buf.Peek(1); err != io.EOF {
+ t.Fatalf("want EOF got %v", err)
+ }
+
+ // Test for issue 3022, not exposing a reader's error on a successful Peek.
+ buf = NewReaderSize(dataAndEOFReader("abcd"), 32)
+ if s, err := buf.Peek(2); string(s) != "ab" || err != nil {
+ t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err)
+ }
+ if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
+ t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err)
+ }
+ if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil {
+ t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err)
+ }
+ if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF {
+ t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err)
+ }
+}
+
+type dataAndEOFReader string
+
+func (r dataAndEOFReader) Read(p []byte) (int, error) {
+ return copy(p, r), io.EOF
+}
+
+func TestPeekThenUnreadRune(t *testing.T) {
+ // This sequence used to cause a crash.
+ r := NewReader(strings.NewReader("x"))
+ r.ReadRune()
+ r.Peek(1)
+ r.UnreadRune()
+ r.ReadRune() // Used to panic here
+}
+
+var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy")
+var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy")
+var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n")
+
+// TestReader wraps a []byte and returns reads of a specific length.
+type testReader struct {
+ data []byte
+ stride int
+}
+
+func (t *testReader) Read(buf []byte) (n int, err error) {
+ n = t.stride
+ if n > len(t.data) {
+ n = len(t.data)
+ }
+ if n > len(buf) {
+ n = len(buf)
+ }
+ copy(buf, t.data)
+ t.data = t.data[n:]
+ if len(t.data) == 0 {
+ err = io.EOF
+ }
+ return
+}
+
+func testReadLine(t *testing.T, input []byte) {
+ //for stride := 1; stride < len(input); stride++ {
+ for stride := 1; stride < 2; stride++ {
+ done := 0
+ reader := testReader{input, stride}
+ l := NewReaderSize(&reader, len(input)+1)
+ for {
+ line, isPrefix, err := l.ReadLine()
+ if len(line) > 0 && err != nil {
+ t.Errorf("ReadLine returned both data and error: %s", err)
+ }
+ if isPrefix {
+ t.Errorf("ReadLine returned prefix")
+ }
+ if err != nil {
+ if err != io.EOF {
+ t.Fatalf("Got unknown error: %s", err)
+ }
+ break
+ }
+ if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) {
+ t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line)
+ }
+ done += len(line)
+ }
+ if done != len(testOutput) {
+ t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride)
+ }
+ }
+}
+
+func TestReadLine(t *testing.T) {
+ testReadLine(t, testInput)
+ testReadLine(t, testInputrn)
+}
+
+func TestLineTooLong(t *testing.T) {
+ data := make([]byte, 0)
+ for i := 0; i < minReadBufferSize*5/2; i++ {
+ data = append(data, '0'+byte(i%10))
+ }
+ buf := bytes.NewReader(data)
+ l := NewReaderSize(buf, minReadBufferSize)
+ line, isPrefix, err := l.ReadLine()
+ if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
+ t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
+ }
+ data = data[len(line):]
+ line, isPrefix, err = l.ReadLine()
+ if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
+ t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
+ }
+ data = data[len(line):]
+ line, isPrefix, err = l.ReadLine()
+ if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
+ t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
+ }
+ line, isPrefix, err = l.ReadLine()
+ if isPrefix || err == nil {
+ t.Errorf("expected no more lines: %x %s", line, err)
+ }
+}
+
+func TestReadAfterLines(t *testing.T) {
+ line1 := "this is line1"
+ restData := "this is line2\nthis is line 3\n"
+ inbuf := bytes.NewReader([]byte(line1 + "\n" + restData))
+ outbuf := new(strings.Builder)
+ maxLineLength := len(line1) + len(restData)/2
+ l := NewReaderSize(inbuf, maxLineLength)
+ line, isPrefix, err := l.ReadLine()
+ if isPrefix || err != nil || string(line) != line1 {
+ t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line))
+ }
+ n, err := io.Copy(outbuf, l)
+ if int(n) != len(restData) || err != nil {
+ t.Errorf("bad result for Read: n=%d err=%v", n, err)
+ }
+ if outbuf.String() != restData {
+ t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData)
+ }
+}
+
+func TestReadEmptyBuffer(t *testing.T) {
+ l := NewReaderSize(new(bytes.Buffer), minReadBufferSize)
+ line, isPrefix, err := l.ReadLine()
+ if err != io.EOF {
+ t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
+ }
+}
+
+func TestLinesAfterRead(t *testing.T) {
+ l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
+ _, err := io.ReadAll(l)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ line, isPrefix, err := l.ReadLine()
+ if err != io.EOF {
+ t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
+ }
+}
+
+func TestReadLineNonNilLineOrError(t *testing.T) {
+ r := NewReader(strings.NewReader("line 1\n"))
+ for i := 0; i < 2; i++ {
+ l, _, err := r.ReadLine()
+ if l != nil && err != nil {
+ t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both",
+ i+1, l, err)
+ }
+ }
+}
+
+type readLineResult struct {
+ line []byte
+ isPrefix bool
+ err error
+}
+
+var readLineNewlinesTests = []struct {
+ input string
+ expect []readLineResult
+}{
+ {"012345678901234\r\n012345678901234\r\n", []readLineResult{
+ {[]byte("012345678901234"), true, nil},
+ {nil, false, nil},
+ {[]byte("012345678901234"), true, nil},
+ {nil, false, nil},
+ {nil, false, io.EOF},
+ }},
+ {"0123456789012345\r012345678901234\r", []readLineResult{
+ {[]byte("0123456789012345"), true, nil},
+ {[]byte("\r012345678901234"), true, nil},
+ {[]byte("\r"), false, nil},
+ {nil, false, io.EOF},
+ }},
+}
+
+func TestReadLineNewlines(t *testing.T) {
+ for _, e := range readLineNewlinesTests {
+ testReadLineNewlines(t, e.input, e.expect)
+ }
+}
+
+func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) {
+ b := NewReaderSize(strings.NewReader(input), minReadBufferSize)
+ for i, e := range expect {
+ line, isPrefix, err := b.ReadLine()
+ if !bytes.Equal(line, e.line) {
+ t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line)
+ return
+ }
+ if isPrefix != e.isPrefix {
+ t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix)
+ return
+ }
+ if err != e.err {
+ t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err)
+ return
+ }
+ }
+}
+
+func createTestInput(n int) []byte {
+ input := make([]byte, n)
+ for i := range input {
+ // 101 and 251 are arbitrary prime numbers.
+ // The idea is to create an input sequence
+ // which doesn't repeat too frequently.
+ input[i] = byte(i % 251)
+ if i%101 == 0 {
+ input[i] ^= byte(i / 101)
+ }
+ }
+ return input
+}
+
+func TestReaderWriteTo(t *testing.T) {
+ input := createTestInput(8192)
+ r := NewReader(onlyReader{bytes.NewReader(input)})
+ w := new(bytes.Buffer)
+ if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) {
+ t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input))
+ }
+
+ for i, val := range w.Bytes() {
+ if val != input[i] {
+ t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i])
+ }
+ }
+}
+
+type errorWriterToTest struct {
+ rn, wn int
+ rerr, werr error
+ expected error
+}
+
+func (r errorWriterToTest) Read(p []byte) (int, error) {
+ return len(p) * r.rn, r.rerr
+}
+
+func (w errorWriterToTest) Write(p []byte) (int, error) {
+ return len(p) * w.wn, w.werr
+}
+
+var errorWriterToTests = []errorWriterToTest{
+ {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe},
+ {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
+ {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe},
+ {0, 1, io.EOF, nil, nil},
+}
+
+func TestReaderWriteToErrors(t *testing.T) {
+ for i, rw := range errorWriterToTests {
+ r := NewReader(rw)
+ if _, err := r.WriteTo(rw); err != rw.expected {
+ t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
+ }
+ }
+}
+
+func TestWriterReadFrom(t *testing.T) {
+ ws := []func(io.Writer) io.Writer{
+ func(w io.Writer) io.Writer { return onlyWriter{w} },
+ func(w io.Writer) io.Writer { return w },
+ }
+
+ rs := []func(io.Reader) io.Reader{
+ iotest.DataErrReader,
+ func(r io.Reader) io.Reader { return r },
+ }
+
+ for ri, rfunc := range rs {
+ for wi, wfunc := range ws {
+ input := createTestInput(8192)
+ b := new(strings.Builder)
+ w := NewWriter(wfunc(b))
+ r := rfunc(bytes.NewReader(input))
+ if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) {
+ t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input))
+ continue
+ }
+ if err := w.Flush(); err != nil {
+ t.Errorf("Flush returned %v", err)
+ continue
+ }
+ if got, want := b.String(), string(input); got != want {
+ t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want)
+ }
+ }
+ }
+}
+
+type errorReaderFromTest struct {
+ rn, wn int
+ rerr, werr error
+ expected error
+}
+
+func (r errorReaderFromTest) Read(p []byte) (int, error) {
+ return len(p) * r.rn, r.rerr
+}
+
+func (w errorReaderFromTest) Write(p []byte) (int, error) {
+ return len(p) * w.wn, w.werr
+}
+
+var errorReaderFromTests = []errorReaderFromTest{
+ {0, 1, io.EOF, nil, nil},
+ {1, 1, io.EOF, nil, nil},
+ {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
+ {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe},
+ {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite},
+}
+
+func TestWriterReadFromErrors(t *testing.T) {
+ for i, rw := range errorReaderFromTests {
+ w := NewWriter(rw)
+ if _, err := w.ReadFrom(rw); err != rw.expected {
+ t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
+ }
+ }
+}
+
+// TestWriterReadFromCounts tests that using io.Copy to copy into a
+// bufio.Writer does not prematurely flush the buffer. For example, when
+// buffering writes to a network socket, excessive network writes should be
+// avoided.
+func TestWriterReadFromCounts(t *testing.T) {
+ var w0 writeCountingDiscard
+ b0 := NewWriterSize(&w0, 1234)
+ b0.WriteString(strings.Repeat("x", 1000))
+ if w0 != 0 {
+ t.Fatalf("write 1000 'x's: got %d writes, want 0", w0)
+ }
+ b0.WriteString(strings.Repeat("x", 200))
+ if w0 != 0 {
+ t.Fatalf("write 1200 'x's: got %d writes, want 0", w0)
+ }
+ io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))})
+ if w0 != 0 {
+ t.Fatalf("write 1230 'x's: got %d writes, want 0", w0)
+ }
+ io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))})
+ if w0 != 1 {
+ t.Fatalf("write 1239 'x's: got %d writes, want 1", w0)
+ }
+
+ var w1 writeCountingDiscard
+ b1 := NewWriterSize(&w1, 1234)
+ b1.WriteString(strings.Repeat("x", 1200))
+ b1.Flush()
+ if w1 != 1 {
+ t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1)
+ }
+ b1.WriteString(strings.Repeat("x", 89))
+ if w1 != 1 {
+ t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1)
+ }
+ io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))})
+ if w1 != 1 {
+ t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1)
+ }
+ io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))})
+ if w1 != 2 {
+ t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1)
+ }
+ b1.Flush()
+ if w1 != 3 {
+ t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1)
+ }
+}
+
+// A writeCountingDiscard is like io.Discard and counts the number of times
+// Write is called on it.
+type writeCountingDiscard int
+
+func (w *writeCountingDiscard) Write(p []byte) (int, error) {
+ *w++
+ return len(p), nil
+}
+
+type negativeReader int
+
+func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
+
+func TestNegativeRead(t *testing.T) {
+ // should panic with a description pointing at the reader, not at itself.
+ // (should NOT panic with slice index error, for example.)
+ b := NewReader(new(negativeReader))
+ defer func() {
+ switch err := recover().(type) {
+ case nil:
+ t.Fatal("read did not panic")
+ case error:
+ if !strings.Contains(err.Error(), "reader returned negative count from Read") {
+ t.Fatalf("wrong panic: %v", err)
+ }
+ default:
+ t.Fatalf("unexpected panic value: %T(%v)", err, err)
+ }
+ }()
+ b.Read(make([]byte, 100))
+}
+
+var errFake = errors.New("fake error")
+
+type errorThenGoodReader struct {
+ didErr bool
+ nread int
+}
+
+func (r *errorThenGoodReader) Read(p []byte) (int, error) {
+ r.nread++
+ if !r.didErr {
+ r.didErr = true
+ return 0, errFake
+ }
+ return len(p), nil
+}
+
+func TestReaderClearError(t *testing.T) {
+ r := &errorThenGoodReader{}
+ b := NewReader(r)
+ buf := make([]byte, 1)
+ if _, err := b.Read(nil); err != nil {
+ t.Fatalf("1st nil Read = %v; want nil", err)
+ }
+ if _, err := b.Read(buf); err != errFake {
+ t.Fatalf("1st Read = %v; want errFake", err)
+ }
+ if _, err := b.Read(nil); err != nil {
+ t.Fatalf("2nd nil Read = %v; want nil", err)
+ }
+ if _, err := b.Read(buf); err != nil {
+ t.Fatalf("3rd Read with buffer = %v; want nil", err)
+ }
+ if r.nread != 2 {
+ t.Errorf("num reads = %d; want 2", r.nread)
+ }
+}
+
+// Test for golang.org/issue/5947
+func TestWriterReadFromWhileFull(t *testing.T) {
+ buf := new(bytes.Buffer)
+ w := NewWriterSize(buf, 10)
+
+ // Fill buffer exactly.
+ n, err := w.Write([]byte("0123456789"))
+ if n != 10 || err != nil {
+ t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err)
+ }
+
+ // Use ReadFrom to read in some data.
+ n2, err := w.ReadFrom(strings.NewReader("abcdef"))
+ if n2 != 6 || err != nil {
+ t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err)
+ }
+}
+
+type emptyThenNonEmptyReader struct {
+ r io.Reader
+ n int
+}
+
+func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) {
+ if r.n <= 0 {
+ return r.r.Read(p)
+ }
+ r.n--
+ return 0, nil
+}
+
+// Test for golang.org/issue/7611
+func TestWriterReadFromUntilEOF(t *testing.T) {
+ buf := new(bytes.Buffer)
+ w := NewWriterSize(buf, 5)
+
+ // Partially fill buffer
+ n, err := w.Write([]byte("0123"))
+ if n != 4 || err != nil {
+ t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
+ }
+
+ // Use ReadFrom to read in some data.
+ r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3}
+ n2, err := w.ReadFrom(r)
+ if n2 != 4 || err != nil {
+ t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err)
+ }
+ w.Flush()
+ if got, want := buf.String(), "0123abcd"; got != want {
+ t.Fatalf("buf.Bytes() returned %q, want %q", got, want)
+ }
+}
+
+func TestWriterReadFromErrNoProgress(t *testing.T) {
+ buf := new(bytes.Buffer)
+ w := NewWriterSize(buf, 5)
+
+ // Partially fill buffer
+ n, err := w.Write([]byte("0123"))
+ if n != 4 || err != nil {
+ t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
+ }
+
+ // Use ReadFrom to read in some data.
+ r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100}
+ n2, err := w.ReadFrom(r)
+ if n2 != 0 || err != io.ErrNoProgress {
+ t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err)
+ }
+}
+
+type readFromWriter struct {
+ buf []byte
+ writeBytes int
+ readFromBytes int
+}
+
+func (w *readFromWriter) Write(p []byte) (int, error) {
+ w.buf = append(w.buf, p...)
+ w.writeBytes += len(p)
+ return len(p), nil
+}
+
+func (w *readFromWriter) ReadFrom(r io.Reader) (int64, error) {
+ b, err := io.ReadAll(r)
+ w.buf = append(w.buf, b...)
+ w.readFromBytes += len(b)
+ return int64(len(b)), err
+}
+
+// Test that calling (*Writer).ReadFrom with a partially-filled buffer
+// fills the buffer before switching over to ReadFrom.
+func TestWriterReadFromWithBufferedData(t *testing.T) {
+ const bufsize = 16
+
+ input := createTestInput(64)
+ rfw := &readFromWriter{}
+ w := NewWriterSize(rfw, bufsize)
+
+ const writeSize = 8
+ if n, err := w.Write(input[:writeSize]); n != writeSize || err != nil {
+ t.Errorf("w.Write(%v bytes) = %v, %v; want %v, nil", writeSize, n, err, writeSize)
+ }
+ n, err := w.ReadFrom(bytes.NewReader(input[writeSize:]))
+ if wantn := len(input[writeSize:]); int(n) != wantn || err != nil {
+ t.Errorf("io.Copy(w, %v bytes) = %v, %v; want %v, nil", wantn, n, err, wantn)
+ }
+ if err := w.Flush(); err != nil {
+ t.Errorf("w.Flush() = %v, want nil", err)
+ }
+
+ if got, want := rfw.writeBytes, bufsize; got != want {
+ t.Errorf("wrote %v bytes with Write, want %v", got, want)
+ }
+ if got, want := rfw.readFromBytes, len(input)-bufsize; got != want {
+ t.Errorf("wrote %v bytes with ReadFrom, want %v", got, want)
+ }
+}
+
+func TestReadZero(t *testing.T) {
+ for _, size := range []int{100, 2} {
+ t.Run(fmt.Sprintf("bufsize=%d", size), func(t *testing.T) {
+ r := io.MultiReader(strings.NewReader("abc"), &emptyThenNonEmptyReader{r: strings.NewReader("def"), n: 1})
+ br := NewReaderSize(r, size)
+ want := func(s string, wantErr error) {
+ p := make([]byte, 50)
+ n, err := br.Read(p)
+ if err != wantErr || n != len(s) || string(p[:n]) != s {
+ t.Fatalf("read(%d) = %q, %v, want %q, %v", len(p), string(p[:n]), err, s, wantErr)
+ }
+ t.Logf("read(%d) = %q, %v", len(p), string(p[:n]), err)
+ }
+ want("abc", nil)
+ want("", nil)
+ want("def", nil)
+ want("", io.EOF)
+ })
+ }
+}
+
+func TestReaderReset(t *testing.T) {
+ checkAll := func(r *Reader, want string) {
+ t.Helper()
+ all, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(all) != want {
+ t.Errorf("ReadAll returned %q, want %q", all, want)
+ }
+ }
+
+ r := NewReader(strings.NewReader("foo foo"))
+ buf := make([]byte, 3)
+ r.Read(buf)
+ if string(buf) != "foo" {
+ t.Errorf("buf = %q; want foo", buf)
+ }
+
+ r.Reset(strings.NewReader("bar bar"))
+ checkAll(r, "bar bar")
+
+ *r = Reader{} // zero out the Reader
+ r.Reset(strings.NewReader("bar bar"))
+ checkAll(r, "bar bar")
+
+ // Wrap a reader and then Reset to that reader.
+ r.Reset(strings.NewReader("recur"))
+ r2 := NewReader(r)
+ checkAll(r2, "recur")
+ r.Reset(strings.NewReader("recur2"))
+ r2.Reset(r)
+ checkAll(r2, "recur2")
+}
+
+func TestWriterReset(t *testing.T) {
+ var buf1, buf2, buf3, buf4, buf5 strings.Builder
+ w := NewWriter(&buf1)
+ w.WriteString("foo")
+
+ w.Reset(&buf2) // and not flushed
+ w.WriteString("bar")
+ w.Flush()
+ if buf1.String() != "" {
+ t.Errorf("buf1 = %q; want empty", buf1.String())
+ }
+ if buf2.String() != "bar" {
+ t.Errorf("buf2 = %q; want bar", buf2.String())
+ }
+
+ *w = Writer{} // zero out the Writer
+ w.Reset(&buf3) // and not flushed
+ w.WriteString("bar")
+ w.Flush()
+ if buf1.String() != "" {
+ t.Errorf("buf1 = %q; want empty", buf1.String())
+ }
+ if buf3.String() != "bar" {
+ t.Errorf("buf3 = %q; want bar", buf3.String())
+ }
+
+ // Wrap a writer and then Reset to that writer.
+ w.Reset(&buf4)
+ w2 := NewWriter(w)
+ w2.WriteString("recur")
+ w2.Flush()
+ if buf4.String() != "recur" {
+ t.Errorf("buf4 = %q, want %q", buf4.String(), "recur")
+ }
+ w.Reset(&buf5)
+ w2.Reset(w)
+ w2.WriteString("recur2")
+ w2.Flush()
+ if buf5.String() != "recur2" {
+ t.Errorf("buf5 = %q, want %q", buf5.String(), "recur2")
+ }
+}
+
+func TestReaderDiscard(t *testing.T) {
+ tests := []struct {
+ name string
+ r io.Reader
+ bufSize int // 0 means 16
+ peekSize int
+
+ n int // input to Discard
+
+ want int // from Discard
+ wantErr error // from Discard
+
+ wantBuffered int
+ }{
+ {
+ name: "normal case",
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
+ peekSize: 16,
+ n: 6,
+ want: 6,
+ wantBuffered: 10,
+ },
+ {
+ name: "discard causing read",
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
+ n: 6,
+ want: 6,
+ wantBuffered: 10,
+ },
+ {
+ name: "discard all without peek",
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
+ n: 26,
+ want: 26,
+ wantBuffered: 0,
+ },
+ {
+ name: "discard more than end",
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
+ n: 27,
+ want: 26,
+ wantErr: io.EOF,
+ wantBuffered: 0,
+ },
+ // Any error from filling shouldn't show up until we
+ // get past the valid bytes. Here we return 5 valid bytes at the same time
+ // as an error, but test that we don't see the error from Discard.
+ {
+ name: "fill error, discard less",
+ r: newScriptedReader(func(p []byte) (n int, err error) {
+ if len(p) < 5 {
+ panic("unexpected small read")
+ }
+ return 5, errors.New("5-then-error")
+ }),
+ n: 4,
+ want: 4,
+ wantErr: nil,
+ wantBuffered: 1,
+ },
+ {
+ name: "fill error, discard equal",
+ r: newScriptedReader(func(p []byte) (n int, err error) {
+ if len(p) < 5 {
+ panic("unexpected small read")
+ }
+ return 5, errors.New("5-then-error")
+ }),
+ n: 5,
+ want: 5,
+ wantErr: nil,
+ wantBuffered: 0,
+ },
+ {
+ name: "fill error, discard more",
+ r: newScriptedReader(func(p []byte) (n int, err error) {
+ if len(p) < 5 {
+ panic("unexpected small read")
+ }
+ return 5, errors.New("5-then-error")
+ }),
+ n: 6,
+ want: 5,
+ wantErr: errors.New("5-then-error"),
+ wantBuffered: 0,
+ },
+ // Discard of 0 shouldn't cause a read:
+ {
+ name: "discard zero",
+ r: newScriptedReader(), // will panic on Read
+ n: 0,
+ want: 0,
+ wantErr: nil,
+ wantBuffered: 0,
+ },
+ {
+ name: "discard negative",
+ r: newScriptedReader(), // will panic on Read
+ n: -1,
+ want: 0,
+ wantErr: ErrNegativeCount,
+ wantBuffered: 0,
+ },
+ }
+ for _, tt := range tests {
+ br := NewReaderSize(tt.r, tt.bufSize)
+ if tt.peekSize > 0 {
+ peekBuf, err := br.Peek(tt.peekSize)
+ if err != nil {
+ t.Errorf("%s: Peek(%d): %v", tt.name, tt.peekSize, err)
+ continue
+ }
+ if len(peekBuf) != tt.peekSize {
+ t.Errorf("%s: len(Peek(%d)) = %v; want %v", tt.name, tt.peekSize, len(peekBuf), tt.peekSize)
+ continue
+ }
+ }
+ discarded, err := br.Discard(tt.n)
+ if ge, we := fmt.Sprint(err), fmt.Sprint(tt.wantErr); discarded != tt.want || ge != we {
+ t.Errorf("%s: Discard(%d) = (%v, %v); want (%v, %v)", tt.name, tt.n, discarded, ge, tt.want, we)
+ continue
+ }
+ if bn := br.Buffered(); bn != tt.wantBuffered {
+ t.Errorf("%s: after Discard, Buffered = %d; want %d", tt.name, bn, tt.wantBuffered)
+ }
+ }
+
+}
+
+func TestReaderSize(t *testing.T) {
+ if got, want := NewReader(nil).Size(), DefaultBufSize; got != want {
+ t.Errorf("NewReader's Reader.Size = %d; want %d", got, want)
+ }
+ if got, want := NewReaderSize(nil, 1234).Size(), 1234; got != want {
+ t.Errorf("NewReaderSize's Reader.Size = %d; want %d", got, want)
+ }
+}
+
+func TestWriterSize(t *testing.T) {
+ if got, want := NewWriter(nil).Size(), DefaultBufSize; got != want {
+ t.Errorf("NewWriter's Writer.Size = %d; want %d", got, want)
+ }
+ if got, want := NewWriterSize(nil, 1234).Size(), 1234; got != want {
+ t.Errorf("NewWriterSize's Writer.Size = %d; want %d", got, want)
+ }
+}
+
+// An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have.
+type onlyReader struct {
+ io.Reader
+}
+
+// An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have.
+type onlyWriter struct {
+ io.Writer
+}
+
+// A scriptedReader is an io.Reader that executes its steps sequentially.
+type scriptedReader []func(p []byte) (n int, err error)
+
+func (sr *scriptedReader) Read(p []byte) (n int, err error) {
+ if len(*sr) == 0 {
+ panic("too many Read calls on scripted Reader. No steps remain.")
+ }
+ step := (*sr)[0]
+ *sr = (*sr)[1:]
+ return step(p)
+}
+
+func newScriptedReader(steps ...func(p []byte) (n int, err error)) io.Reader {
+ sr := scriptedReader(steps)
+ return &sr
+}
+
+// eofReader returns the number of bytes read and io.EOF for the read that consumes the last of the content.
+type eofReader struct {
+ buf []byte
+}
+
+func (r *eofReader) Read(p []byte) (int, error) {
+ read := copy(p, r.buf)
+ r.buf = r.buf[read:]
+
+ switch read {
+ case 0, len(r.buf):
+ // As allowed in the documentation, this will return io.EOF
+ // in the same call that consumes the last of the data.
+ // https://godoc.org/io#Reader
+ return read, io.EOF
+ }
+
+ return read, nil
+}
+
+func TestPartialReadEOF(t *testing.T) {
+ src := make([]byte, 10)
+ eofR := &eofReader{buf: src}
+ r := NewReader(eofR)
+
+ // Start by reading 5 of the 10 available bytes.
+ dest := make([]byte, 5)
+ read, err := r.Read(dest)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if n := len(dest); read != n {
+ t.Fatalf("read %d bytes; wanted %d bytes", read, n)
+ }
+
+ // The Reader should have buffered all the content from the io.Reader.
+ if n := len(eofR.buf); n != 0 {
+ t.Fatalf("got %d bytes left in bufio.Reader source; want 0 bytes", n)
+ }
+ // To prove the point, check that there are still 5 bytes available to read.
+ if n := r.Buffered(); n != 5 {
+ t.Fatalf("got %d bytes buffered in bufio.Reader; want 5 bytes", n)
+ }
+
+ // This is the second read of 0 bytes.
+ read, err = r.Read([]byte{})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if read != 0 {
+ t.Fatalf("read %d bytes; want 0 bytes", read)
+ }
+}
+
+type writerWithReadFromError struct{}
+
+func (w writerWithReadFromError) ReadFrom(r io.Reader) (int64, error) {
+ return 0, errors.New("writerWithReadFromError error")
+}
+
+func (w writerWithReadFromError) Write(b []byte) (n int, err error) {
+ return 10, nil
+}
+
+func TestWriterReadFromMustSetUnderlyingError(t *testing.T) {
+ var wr = NewWriter(writerWithReadFromError{})
+ if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
+ t.Fatal("expected ReadFrom returns error, got nil")
+ }
+ if _, err := wr.Write([]byte("123")); err == nil {
+ t.Fatal("expected Write returns error, got nil")
+ }
+}
+
+type writeErrorOnlyWriter struct{}
+
+func (w writeErrorOnlyWriter) Write(p []byte) (n int, err error) {
+ return 0, errors.New("writeErrorOnlyWriter error")
+}
+
+// Ensure that previous Write errors are immediately returned
+// on any ReadFrom. See golang.org/issue/35194.
+func TestWriterReadFromMustReturnUnderlyingError(t *testing.T) {
+ var wr = NewWriter(writeErrorOnlyWriter{})
+ s := "test1"
+ wantBuffered := len(s)
+ if _, err := wr.WriteString(s); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if err := wr.Flush(); err == nil {
+ t.Error("expected flush error, got nil")
+ }
+ if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ if buffered := wr.Buffered(); buffered != wantBuffered {
+ t.Fatalf("Buffered = %v; want %v", buffered, wantBuffered)
+ }
+}
+
+func BenchmarkReaderCopyOptimal(b *testing.B) {
+ // Optimal case is where the underlying reader implements io.WriterTo
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ src := NewReader(srcBuf)
+ dstBuf := new(bytes.Buffer)
+ dst := onlyWriter{dstBuf}
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ src.Reset(srcBuf)
+ dstBuf.Reset()
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkReaderCopyUnoptimal(b *testing.B) {
+ // Unoptimal case is where the underlying reader doesn't implement io.WriterTo
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ src := NewReader(onlyReader{srcBuf})
+ dstBuf := new(bytes.Buffer)
+ dst := onlyWriter{dstBuf}
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ src.Reset(onlyReader{srcBuf})
+ dstBuf.Reset()
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkReaderCopyNoWriteTo(b *testing.B) {
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ srcReader := NewReader(srcBuf)
+ src := onlyReader{srcReader}
+ dstBuf := new(bytes.Buffer)
+ dst := onlyWriter{dstBuf}
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ srcReader.Reset(srcBuf)
+ dstBuf.Reset()
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkReaderWriteToOptimal(b *testing.B) {
+ const bufSize = 16 << 10
+ buf := make([]byte, bufSize)
+ r := bytes.NewReader(buf)
+ srcReader := NewReaderSize(onlyReader{r}, 1<<10)
+ if _, ok := io.Discard.(io.ReaderFrom); !ok {
+ b.Fatal("io.Discard doesn't support ReaderFrom")
+ }
+ for i := 0; i < b.N; i++ {
+ r.Seek(0, io.SeekStart)
+ srcReader.Reset(onlyReader{r})
+ n, err := srcReader.WriteTo(io.Discard)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if n != bufSize {
+ b.Fatalf("n = %d; want %d", n, bufSize)
+ }
+ }
+}
+
+func BenchmarkReaderReadString(b *testing.B) {
+ r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
+ buf := NewReader(r)
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ r.Seek(0, io.SeekStart)
+ buf.Reset(r)
+
+ _, err := buf.ReadString('\n')
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkWriterCopyOptimal(b *testing.B) {
+ // Optimal case is where the underlying writer implements io.ReaderFrom
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ src := onlyReader{srcBuf}
+ dstBuf := new(bytes.Buffer)
+ dst := NewWriter(dstBuf)
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ dstBuf.Reset()
+ dst.Reset(dstBuf)
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkWriterCopyUnoptimal(b *testing.B) {
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ src := onlyReader{srcBuf}
+ dstBuf := new(bytes.Buffer)
+ dst := NewWriter(onlyWriter{dstBuf})
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ dstBuf.Reset()
+ dst.Reset(onlyWriter{dstBuf})
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkWriterCopyNoReadFrom(b *testing.B) {
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
+ src := onlyReader{srcBuf}
+ dstBuf := new(bytes.Buffer)
+ dstWriter := NewWriter(dstBuf)
+ dst := onlyWriter{dstWriter}
+ for i := 0; i < b.N; i++ {
+ srcBuf.Reset()
+ dstBuf.Reset()
+ dstWriter.Reset(dstBuf)
+ io.Copy(dst, src)
+ }
+}
+
+func BenchmarkReaderEmpty(b *testing.B) {
+ b.ReportAllocs()
+ str := strings.Repeat("x", 16<<10)
+ for i := 0; i < b.N; i++ {
+ br := NewReader(strings.NewReader(str))
+ n, err := io.Copy(io.Discard, br)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if n != int64(len(str)) {
+ b.Fatal("wrong length")
+ }
+ }
+}
+
+func BenchmarkWriterEmpty(b *testing.B) {
+ b.ReportAllocs()
+ str := strings.Repeat("x", 1<<10)
+ bs := []byte(str)
+ for i := 0; i < b.N; i++ {
+ bw := NewWriter(io.Discard)
+ bw.Flush()
+ bw.WriteByte('a')
+ bw.Flush()
+ bw.WriteRune('B')
+ bw.Flush()
+ bw.Write(bs)
+ bw.Flush()
+ bw.WriteString(str)
+ bw.Flush()
+ }
+}
+
+func BenchmarkWriterFlush(b *testing.B) {
+ b.ReportAllocs()
+ bw := NewWriter(io.Discard)
+ str := strings.Repeat("x", 50)
+ for i := 0; i < b.N; i++ {
+ bw.WriteString(str)
+ bw.Flush()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/example_test.go b/platform/dbops/binaries/go/go/src/bufio/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6d219aecc6584a703f600b84c3566e802dbc3b3d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/example_test.go
@@ -0,0 +1,173 @@
+// 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 bufio_test
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+)
+
+func ExampleWriter() {
+ w := bufio.NewWriter(os.Stdout)
+ fmt.Fprint(w, "Hello, ")
+ fmt.Fprint(w, "world!")
+ w.Flush() // Don't forget to flush!
+ // Output: Hello, world!
+}
+
+func ExampleWriter_AvailableBuffer() {
+ w := bufio.NewWriter(os.Stdout)
+ for _, i := range []int64{1, 2, 3, 4} {
+ b := w.AvailableBuffer()
+ b = strconv.AppendInt(b, i, 10)
+ b = append(b, ' ')
+ w.Write(b)
+ }
+ w.Flush()
+ // Output: 1 2 3 4
+}
+
+// The simplest use of a Scanner, to read standard input as a set of lines.
+func ExampleScanner_lines() {
+ scanner := bufio.NewScanner(os.Stdin)
+ for scanner.Scan() {
+ fmt.Println(scanner.Text()) // Println will add back the final '\n'
+ }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "reading standard input:", err)
+ }
+}
+
+// Return the most recent call to Scan as a []byte.
+func ExampleScanner_Bytes() {
+ scanner := bufio.NewScanner(strings.NewReader("gopher"))
+ for scanner.Scan() {
+ fmt.Println(len(scanner.Bytes()) == 6)
+ }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
+ }
+ // Output:
+ // true
+}
+
+// Use a Scanner to implement a simple word-count utility by scanning the
+// input as a sequence of space-delimited tokens.
+func ExampleScanner_words() {
+ // An artificial input source.
+ const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
+ scanner := bufio.NewScanner(strings.NewReader(input))
+ // Set the split function for the scanning operation.
+ scanner.Split(bufio.ScanWords)
+ // Count the words.
+ count := 0
+ for scanner.Scan() {
+ count++
+ }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "reading input:", err)
+ }
+ fmt.Printf("%d\n", count)
+ // Output: 15
+}
+
+// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
+// 32-bit decimal input.
+func ExampleScanner_custom() {
+ // An artificial input source.
+ const input = "1234 5678 1234567901234567890"
+ scanner := bufio.NewScanner(strings.NewReader(input))
+ // Create a custom split function by wrapping the existing ScanWords function.
+ split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ advance, token, err = bufio.ScanWords(data, atEOF)
+ if err == nil && token != nil {
+ _, err = strconv.ParseInt(string(token), 10, 32)
+ }
+ return
+ }
+ // Set the split function for the scanning operation.
+ scanner.Split(split)
+ // Validate the input
+ for scanner.Scan() {
+ fmt.Printf("%s\n", scanner.Text())
+ }
+
+ if err := scanner.Err(); err != nil {
+ fmt.Printf("Invalid input: %s", err)
+ }
+ // Output:
+ // 1234
+ // 5678
+ // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
+}
+
+// Use a Scanner with a custom split function to parse a comma-separated
+// list with an empty final value.
+func ExampleScanner_emptyFinalToken() {
+ // Comma-separated list; last entry is empty.
+ const input = "1,2,3,4,"
+ scanner := bufio.NewScanner(strings.NewReader(input))
+ // Define a split function that separates on commas.
+ onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ for i := 0; i < len(data); i++ {
+ if data[i] == ',' {
+ return i + 1, data[:i], nil
+ }
+ }
+ if !atEOF {
+ return 0, nil, nil
+ }
+ // There is one final token to be delivered, which may be the empty string.
+ // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
+ // but does not trigger an error to be returned from Scan itself.
+ return 0, data, bufio.ErrFinalToken
+ }
+ scanner.Split(onComma)
+ // Scan.
+ for scanner.Scan() {
+ fmt.Printf("%q ", scanner.Text())
+ }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "reading input:", err)
+ }
+ // Output: "1" "2" "3" "4" ""
+}
+
+// Use a Scanner with a custom split function to parse a comma-separated
+// list with an empty final value but stops at the token "STOP".
+func ExampleScanner_earlyStop() {
+ onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ i := bytes.IndexByte(data, ',')
+ if i == -1 {
+ if !atEOF {
+ return 0, nil, nil
+ }
+ // If we have reached the end, return the last token.
+ return 0, data, bufio.ErrFinalToken
+ }
+ // If the token is "STOP", stop the scanning and ignore the rest.
+ if string(data[:i]) == "STOP" {
+ return i + 1, nil, bufio.ErrFinalToken
+ }
+ // Otherwise, return the token before the comma.
+ return i + 1, data[:i], nil
+ }
+ const input = "1,2,STOP,4,"
+ scanner := bufio.NewScanner(strings.NewReader(input))
+ scanner.Split(onComma)
+ for scanner.Scan() {
+ fmt.Printf("Got a token %q\n", scanner.Text())
+ }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "reading input:", err)
+ }
+ // Output:
+ // Got a token "1"
+ // Got a token "2"
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/export_test.go b/platform/dbops/binaries/go/go/src/bufio/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1667f01a841e07cba04c62e8cf7da7ab3593ca2b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/export_test.go
@@ -0,0 +1,29 @@
+// 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 bufio
+
+// Exported for testing only.
+import (
+ "unicode/utf8"
+)
+
+var IsSpace = isSpace
+
+const DefaultBufSize = defaultBufSize
+
+func (s *Scanner) MaxTokenSize(n int) {
+ if n < utf8.UTFMax || n > 1e9 {
+ panic("bad max token size")
+ }
+ if n < len(s.buf) {
+ s.buf = make([]byte, n)
+ }
+ s.maxTokenSize = n
+}
+
+// ErrOrEOF is like Err, but returns EOF. Used to test a corner case.
+func (s *Scanner) ErrOrEOF() error {
+ return s.err
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/scan.go b/platform/dbops/binaries/go/go/src/bufio/scan.go
new file mode 100644
index 0000000000000000000000000000000000000000..a26b2ff17d3a26a423a94a4c54cf44b7a4d1227d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/scan.go
@@ -0,0 +1,424 @@
+// 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 bufio
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "unicode/utf8"
+)
+
+// Scanner provides a convenient interface for reading data such as
+// a file of newline-delimited lines of text. Successive calls to
+// the [Scanner.Scan] method will step through the 'tokens' of a file, skipping
+// the bytes between the tokens. The specification of a token is
+// defined by a split function of type [SplitFunc]; the default split
+// function breaks the input into lines with line termination stripped. [Scanner.Split]
+// functions are defined in this package for scanning a file into
+// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
+// client may instead provide a custom split function.
+//
+// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
+// large to fit in the [Scanner.Buffer]. When a scan stops, the reader may have
+// advanced arbitrarily far past the last token. Programs that need more
+// control over error handling or large tokens, or must run sequential scans
+// on a reader, should use [bufio.Reader] instead.
+type Scanner struct {
+ r io.Reader // The reader provided by the client.
+ split SplitFunc // The function to split the tokens.
+ maxTokenSize int // Maximum size of a token; modified by tests.
+ token []byte // Last token returned by split.
+ buf []byte // Buffer used as argument to split.
+ start int // First non-processed byte in buf.
+ end int // End of data in buf.
+ err error // Sticky error.
+ empties int // Count of successive empty tokens.
+ scanCalled bool // Scan has been called; buffer is in use.
+ done bool // Scan has finished.
+}
+
+// SplitFunc is the signature of the split function used to tokenize the
+// input. The arguments are an initial substring of the remaining unprocessed
+// data and a flag, atEOF, that reports whether the [Reader] has no more data
+// to give. The return values are the number of bytes to advance the input
+// and the next token to return to the user, if any, plus an error, if any.
+//
+// Scanning stops if the function returns an error, in which case some of
+// the input may be discarded. If that error is [ErrFinalToken], scanning
+// stops with no error. A non-nil token delivered with [ErrFinalToken]
+// will be the last token, and a nil token with [ErrFinalToken]
+// immediately stops the scanning.
+//
+// Otherwise, the [Scanner] advances the input. If the token is not nil,
+// the [Scanner] returns it to the user. If the token is nil, the
+// Scanner reads more data and continues scanning; if there is no more
+// data--if atEOF was true--the [Scanner] returns. If the data does not
+// yet hold a complete token, for instance if it has no newline while
+// scanning lines, a [SplitFunc] can return (0, nil, nil) to signal the
+// [Scanner] to read more data into the slice and try again with a
+// longer slice starting at the same point in the input.
+//
+// The function is never called with an empty data slice unless atEOF
+// is true. If atEOF is true, however, data may be non-empty and,
+// as always, holds unprocessed text.
+type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)
+
+// Errors returned by Scanner.
+var (
+ ErrTooLong = errors.New("bufio.Scanner: token too long")
+ ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
+ ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
+ ErrBadReadCount = errors.New("bufio.Scanner: Read returned impossible count")
+)
+
+const (
+ // MaxScanTokenSize is the maximum size used to buffer a token
+ // unless the user provides an explicit buffer with [Scanner.Buffer].
+ // The actual maximum token size may be smaller as the buffer
+ // may need to include, for instance, a newline.
+ MaxScanTokenSize = 64 * 1024
+
+ startBufSize = 4096 // Size of initial allocation for buffer.
+)
+
+// NewScanner returns a new [Scanner] to read from r.
+// The split function defaults to [ScanLines].
+func NewScanner(r io.Reader) *Scanner {
+ return &Scanner{
+ r: r,
+ split: ScanLines,
+ maxTokenSize: MaxScanTokenSize,
+ }
+}
+
+// Err returns the first non-EOF error that was encountered by the [Scanner].
+func (s *Scanner) Err() error {
+ if s.err == io.EOF {
+ return nil
+ }
+ return s.err
+}
+
+// Bytes returns the most recent token generated by a call to [Scanner.Scan].
+// The underlying array may point to data that will be overwritten
+// by a subsequent call to Scan. It does no allocation.
+func (s *Scanner) Bytes() []byte {
+ return s.token
+}
+
+// Text returns the most recent token generated by a call to [Scanner.Scan]
+// as a newly allocated string holding its bytes.
+func (s *Scanner) Text() string {
+ return string(s.token)
+}
+
+// ErrFinalToken is a special sentinel error value. It is intended to be
+// returned by a Split function to indicate that the scanning should stop
+// with no error. If the token being delivered with this error is not nil,
+// the token is the last token.
+//
+// The value is useful to stop processing early or when it is necessary to
+// deliver a final empty token (which is different from a nil token).
+// One could achieve the same behavior with a custom error value but
+// providing one here is tidier.
+// See the emptyFinalToken example for a use of this value.
+var ErrFinalToken = errors.New("final token")
+
+// Scan advances the [Scanner] to the next token, which will then be
+// available through the [Scanner.Bytes] or [Scanner.Text] method. It returns false when
+// there are no more tokens, either by reaching the end of the input or an error.
+// After Scan returns false, the [Scanner.Err] method will return any error that
+// occurred during scanning, except that if it was [io.EOF], [Scanner.Err]
+// will return nil.
+// Scan panics if the split function returns too many empty
+// tokens without advancing the input. This is a common error mode for
+// scanners.
+func (s *Scanner) Scan() bool {
+ if s.done {
+ return false
+ }
+ s.scanCalled = true
+ // Loop until we have a token.
+ for {
+ // See if we can get a token with what we already have.
+ // If we've run out of data but have an error, give the split function
+ // a chance to recover any remaining, possibly empty token.
+ if s.end > s.start || s.err != nil {
+ advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
+ if err != nil {
+ if err == ErrFinalToken {
+ s.token = token
+ s.done = true
+ // When token is not nil, it means the scanning stops
+ // with a trailing token, and thus the return value
+ // should be true to indicate the existence of the token.
+ return token != nil
+ }
+ s.setErr(err)
+ return false
+ }
+ if !s.advance(advance) {
+ return false
+ }
+ s.token = token
+ if token != nil {
+ if s.err == nil || advance > 0 {
+ s.empties = 0
+ } else {
+ // Returning tokens not advancing input at EOF.
+ s.empties++
+ if s.empties > maxConsecutiveEmptyReads {
+ panic("bufio.Scan: too many empty tokens without progressing")
+ }
+ }
+ return true
+ }
+ }
+ // We cannot generate a token with what we are holding.
+ // If we've already hit EOF or an I/O error, we are done.
+ if s.err != nil {
+ // Shut it down.
+ s.start = 0
+ s.end = 0
+ return false
+ }
+ // Must read more data.
+ // First, shift data to beginning of buffer if there's lots of empty space
+ // or space is needed.
+ if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
+ copy(s.buf, s.buf[s.start:s.end])
+ s.end -= s.start
+ s.start = 0
+ }
+ // Is the buffer full? If so, resize.
+ if s.end == len(s.buf) {
+ // Guarantee no overflow in the multiplication below.
+ const maxInt = int(^uint(0) >> 1)
+ if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 {
+ s.setErr(ErrTooLong)
+ return false
+ }
+ newSize := len(s.buf) * 2
+ if newSize == 0 {
+ newSize = startBufSize
+ }
+ newSize = min(newSize, s.maxTokenSize)
+ newBuf := make([]byte, newSize)
+ copy(newBuf, s.buf[s.start:s.end])
+ s.buf = newBuf
+ s.end -= s.start
+ s.start = 0
+ }
+ // Finally we can read some input. Make sure we don't get stuck with
+ // a misbehaving Reader. Officially we don't need to do this, but let's
+ // be extra careful: Scanner is for safe, simple jobs.
+ for loop := 0; ; {
+ n, err := s.r.Read(s.buf[s.end:len(s.buf)])
+ if n < 0 || len(s.buf)-s.end < n {
+ s.setErr(ErrBadReadCount)
+ break
+ }
+ s.end += n
+ if err != nil {
+ s.setErr(err)
+ break
+ }
+ if n > 0 {
+ s.empties = 0
+ break
+ }
+ loop++
+ if loop > maxConsecutiveEmptyReads {
+ s.setErr(io.ErrNoProgress)
+ break
+ }
+ }
+ }
+}
+
+// advance consumes n bytes of the buffer. It reports whether the advance was legal.
+func (s *Scanner) advance(n int) bool {
+ if n < 0 {
+ s.setErr(ErrNegativeAdvance)
+ return false
+ }
+ if n > s.end-s.start {
+ s.setErr(ErrAdvanceTooFar)
+ return false
+ }
+ s.start += n
+ return true
+}
+
+// setErr records the first error encountered.
+func (s *Scanner) setErr(err error) {
+ if s.err == nil || s.err == io.EOF {
+ s.err = err
+ }
+}
+
+// Buffer sets the initial buffer to use when scanning
+// and the maximum size of buffer that may be allocated during scanning.
+// The maximum token size must be less than the larger of max and cap(buf).
+// If max <= cap(buf), [Scanner.Scan] will use this buffer only and do no allocation.
+//
+// By default, [Scanner.Scan] uses an internal buffer and sets the
+// maximum token size to [MaxScanTokenSize].
+//
+// Buffer panics if it is called after scanning has started.
+func (s *Scanner) Buffer(buf []byte, max int) {
+ if s.scanCalled {
+ panic("Buffer called after Scan")
+ }
+ s.buf = buf[0:cap(buf)]
+ s.maxTokenSize = max
+}
+
+// Split sets the split function for the [Scanner].
+// The default split function is [ScanLines].
+//
+// Split panics if it is called after scanning has started.
+func (s *Scanner) Split(split SplitFunc) {
+ if s.scanCalled {
+ panic("Split called after Scan")
+ }
+ s.split = split
+}
+
+// Split functions
+
+// ScanBytes is a split function for a [Scanner] that returns each byte as a token.
+func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if atEOF && len(data) == 0 {
+ return 0, nil, nil
+ }
+ return 1, data[0:1], nil
+}
+
+var errorRune = []byte(string(utf8.RuneError))
+
+// ScanRunes is a split function for a [Scanner] that returns each
+// UTF-8-encoded rune as a token. The sequence of runes returned is
+// equivalent to that from a range loop over the input as a string, which
+// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
+// Because of the Scan interface, this makes it impossible for the client to
+// distinguish correctly encoded replacement runes from encoding errors.
+func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if atEOF && len(data) == 0 {
+ return 0, nil, nil
+ }
+
+ // Fast path 1: ASCII.
+ if data[0] < utf8.RuneSelf {
+ return 1, data[0:1], nil
+ }
+
+ // Fast path 2: Correct UTF-8 decode without error.
+ _, width := utf8.DecodeRune(data)
+ if width > 1 {
+ // It's a valid encoding. Width cannot be one for a correctly encoded
+ // non-ASCII rune.
+ return width, data[0:width], nil
+ }
+
+ // We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
+ // Is the error because there wasn't a full rune to be decoded?
+ // FullRune distinguishes correctly between erroneous and incomplete encodings.
+ if !atEOF && !utf8.FullRune(data) {
+ // Incomplete; get more bytes.
+ return 0, nil, nil
+ }
+
+ // We have a real UTF-8 encoding error. Return a properly encoded error rune
+ // but advance only one byte. This matches the behavior of a range loop over
+ // an incorrectly encoded string.
+ return 1, errorRune, nil
+}
+
+// dropCR drops a terminal \r from the data.
+func dropCR(data []byte) []byte {
+ if len(data) > 0 && data[len(data)-1] == '\r' {
+ return data[0 : len(data)-1]
+ }
+ return data
+}
+
+// ScanLines is a split function for a [Scanner] that returns each line of
+// text, stripped of any trailing end-of-line marker. The returned line may
+// be empty. The end-of-line marker is one optional carriage return followed
+// by one mandatory newline. In regular expression notation, it is `\r?\n`.
+// The last non-empty line of input will be returned even if it has no
+// newline.
+func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if atEOF && len(data) == 0 {
+ return 0, nil, nil
+ }
+ if i := bytes.IndexByte(data, '\n'); i >= 0 {
+ // We have a full newline-terminated line.
+ return i + 1, dropCR(data[0:i]), nil
+ }
+ // If we're at EOF, we have a final, non-terminated line. Return it.
+ if atEOF {
+ return len(data), dropCR(data), nil
+ }
+ // Request more data.
+ return 0, nil, nil
+}
+
+// isSpace reports whether the character is a Unicode white space character.
+// We avoid dependency on the unicode package, but check validity of the implementation
+// in the tests.
+func isSpace(r rune) bool {
+ if r <= '\u00FF' {
+ // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
+ switch r {
+ case ' ', '\t', '\n', '\v', '\f', '\r':
+ return true
+ case '\u0085', '\u00A0':
+ return true
+ }
+ return false
+ }
+ // High-valued ones.
+ if '\u2000' <= r && r <= '\u200a' {
+ return true
+ }
+ switch r {
+ case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
+ return true
+ }
+ return false
+}
+
+// ScanWords is a split function for a [Scanner] that returns each
+// space-separated word of text, with surrounding spaces deleted. It will
+// never return an empty string. The definition of space is set by
+// unicode.IsSpace.
+func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ // Skip leading spaces.
+ start := 0
+ for width := 0; start < len(data); start += width {
+ var r rune
+ r, width = utf8.DecodeRune(data[start:])
+ if !isSpace(r) {
+ break
+ }
+ }
+ // Scan until space, marking end of word.
+ for width, i := 0, start; i < len(data); i += width {
+ var r rune
+ r, width = utf8.DecodeRune(data[i:])
+ if isSpace(r) {
+ return i + width, data[start:i], nil
+ }
+ }
+ // If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
+ if atEOF && len(data) > start {
+ return len(data), data[start:], nil
+ }
+ // Request more data.
+ return start, nil, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/bufio/scan_test.go b/platform/dbops/binaries/go/go/src/bufio/scan_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6b64f7ba9c5d896356a4a3a7e2646de30e6837e0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bufio/scan_test.go
@@ -0,0 +1,596 @@
+// 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 bufio_test
+
+import (
+ . "bufio"
+ "bytes"
+ "errors"
+ "io"
+ "strings"
+ "testing"
+ "unicode"
+ "unicode/utf8"
+)
+
+const smallMaxTokenSize = 256 // Much smaller for more efficient testing.
+
+// Test white space table matches the Unicode definition.
+func TestSpace(t *testing.T) {
+ for r := rune(0); r <= utf8.MaxRune; r++ {
+ if IsSpace(r) != unicode.IsSpace(r) {
+ t.Fatalf("white space property disagrees: %#U should be %t", r, unicode.IsSpace(r))
+ }
+ }
+}
+
+var scanTests = []string{
+ "",
+ "a",
+ "¼",
+ "☹",
+ "\x81", // UTF-8 error
+ "\uFFFD", // correctly encoded RuneError
+ "abcdefgh",
+ "abc def\n\t\tgh ",
+ "abc¼☹\x81\uFFFD日本語\x82abc",
+}
+
+func TestScanByte(t *testing.T) {
+ for n, test := range scanTests {
+ buf := strings.NewReader(test)
+ s := NewScanner(buf)
+ s.Split(ScanBytes)
+ var i int
+ for i = 0; s.Scan(); i++ {
+ if b := s.Bytes(); len(b) != 1 || b[0] != test[i] {
+ t.Errorf("#%d: %d: expected %q got %q", n, i, test, b)
+ }
+ }
+ if i != len(test) {
+ t.Errorf("#%d: termination expected at %d; got %d", n, len(test), i)
+ }
+ err := s.Err()
+ if err != nil {
+ t.Errorf("#%d: %v", n, err)
+ }
+ }
+}
+
+// Test that the rune splitter returns same sequence of runes (not bytes) as for range string.
+func TestScanRune(t *testing.T) {
+ for n, test := range scanTests {
+ buf := strings.NewReader(test)
+ s := NewScanner(buf)
+ s.Split(ScanRunes)
+ var i, runeCount int
+ var expect rune
+ // Use a string range loop to validate the sequence of runes.
+ for i, expect = range test {
+ if !s.Scan() {
+ break
+ }
+ runeCount++
+ got, _ := utf8.DecodeRune(s.Bytes())
+ if got != expect {
+ t.Errorf("#%d: %d: expected %q got %q", n, i, expect, got)
+ }
+ }
+ if s.Scan() {
+ t.Errorf("#%d: scan ran too long, got %q", n, s.Text())
+ }
+ testRuneCount := utf8.RuneCountInString(test)
+ if runeCount != testRuneCount {
+ t.Errorf("#%d: termination expected at %d; got %d", n, testRuneCount, runeCount)
+ }
+ err := s.Err()
+ if err != nil {
+ t.Errorf("#%d: %v", n, err)
+ }
+ }
+}
+
+var wordScanTests = []string{
+ "",
+ " ",
+ "\n",
+ "a",
+ " a ",
+ "abc def",
+ " abc def ",
+ " abc\tdef\nghi\rjkl\fmno\vpqr\u0085stu\u00a0\n",
+}
+
+// Test that the word splitter returns the same data as strings.Fields.
+func TestScanWords(t *testing.T) {
+ for n, test := range wordScanTests {
+ buf := strings.NewReader(test)
+ s := NewScanner(buf)
+ s.Split(ScanWords)
+ words := strings.Fields(test)
+ var wordCount int
+ for wordCount = 0; wordCount < len(words); wordCount++ {
+ if !s.Scan() {
+ break
+ }
+ got := s.Text()
+ if got != words[wordCount] {
+ t.Errorf("#%d: %d: expected %q got %q", n, wordCount, words[wordCount], got)
+ }
+ }
+ if s.Scan() {
+ t.Errorf("#%d: scan ran too long, got %q", n, s.Text())
+ }
+ if wordCount != len(words) {
+ t.Errorf("#%d: termination expected at %d; got %d", n, len(words), wordCount)
+ }
+ err := s.Err()
+ if err != nil {
+ t.Errorf("#%d: %v", n, err)
+ }
+ }
+}
+
+// slowReader is a reader that returns only a few bytes at a time, to test the incremental
+// reads in Scanner.Scan.
+type slowReader struct {
+ max int
+ buf io.Reader
+}
+
+func (sr *slowReader) Read(p []byte) (n int, err error) {
+ if len(p) > sr.max {
+ p = p[0:sr.max]
+ }
+ return sr.buf.Read(p)
+}
+
+// genLine writes to buf a predictable but non-trivial line of text of length
+// n, including the terminal newline and an occasional carriage return.
+// If addNewline is false, the \r and \n are not emitted.
+func genLine(buf *bytes.Buffer, lineNum, n int, addNewline bool) {
+ buf.Reset()
+ doCR := lineNum%5 == 0
+ if doCR {
+ n--
+ }
+ for i := 0; i < n-1; i++ { // Stop early for \n.
+ c := 'a' + byte(lineNum+i)
+ if c == '\n' || c == '\r' { // Don't confuse us.
+ c = 'N'
+ }
+ buf.WriteByte(c)
+ }
+ if addNewline {
+ if doCR {
+ buf.WriteByte('\r')
+ }
+ buf.WriteByte('\n')
+ }
+}
+
+// Test the line splitter, including some carriage returns but no long lines.
+func TestScanLongLines(t *testing.T) {
+ // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize.
+ tmp := new(bytes.Buffer)
+ buf := new(bytes.Buffer)
+ lineNum := 0
+ j := 0
+ for i := 0; i < 2*smallMaxTokenSize; i++ {
+ genLine(tmp, lineNum, j, true)
+ if j < smallMaxTokenSize {
+ j++
+ } else {
+ j--
+ }
+ buf.Write(tmp.Bytes())
+ lineNum++
+ }
+ s := NewScanner(&slowReader{1, buf})
+ s.Split(ScanLines)
+ s.MaxTokenSize(smallMaxTokenSize)
+ j = 0
+ for lineNum := 0; s.Scan(); lineNum++ {
+ genLine(tmp, lineNum, j, false)
+ if j < smallMaxTokenSize {
+ j++
+ } else {
+ j--
+ }
+ line := tmp.String() // We use the string-valued token here, for variety.
+ if s.Text() != line {
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Text(), line)
+ }
+ }
+ err := s.Err()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// Test that the line splitter errors out on a long line.
+func TestScanLineTooLong(t *testing.T) {
+ const smallMaxTokenSize = 256 // Much smaller for more efficient testing.
+ // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize.
+ tmp := new(bytes.Buffer)
+ buf := new(bytes.Buffer)
+ lineNum := 0
+ j := 0
+ for i := 0; i < 2*smallMaxTokenSize; i++ {
+ genLine(tmp, lineNum, j, true)
+ j++
+ buf.Write(tmp.Bytes())
+ lineNum++
+ }
+ s := NewScanner(&slowReader{3, buf})
+ s.Split(ScanLines)
+ s.MaxTokenSize(smallMaxTokenSize)
+ j = 0
+ for lineNum := 0; s.Scan(); lineNum++ {
+ genLine(tmp, lineNum, j, false)
+ if j < smallMaxTokenSize {
+ j++
+ } else {
+ j--
+ }
+ line := tmp.Bytes()
+ if !bytes.Equal(s.Bytes(), line) {
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line)
+ }
+ }
+ err := s.Err()
+ if err != ErrTooLong {
+ t.Fatalf("expected ErrTooLong; got %s", err)
+ }
+}
+
+// Test that the line splitter handles a final line without a newline.
+func testNoNewline(text string, lines []string, t *testing.T) {
+ buf := strings.NewReader(text)
+ s := NewScanner(&slowReader{7, buf})
+ s.Split(ScanLines)
+ for lineNum := 0; s.Scan(); lineNum++ {
+ line := lines[lineNum]
+ if s.Text() != line {
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line)
+ }
+ }
+ err := s.Err()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// Test that the line splitter handles a final line without a newline.
+func TestScanLineNoNewline(t *testing.T) {
+ const text = "abcdefghijklmn\nopqrstuvwxyz"
+ lines := []string{
+ "abcdefghijklmn",
+ "opqrstuvwxyz",
+ }
+ testNoNewline(text, lines, t)
+}
+
+// Test that the line splitter handles a final line with a carriage return but no newline.
+func TestScanLineReturnButNoNewline(t *testing.T) {
+ const text = "abcdefghijklmn\nopqrstuvwxyz\r"
+ lines := []string{
+ "abcdefghijklmn",
+ "opqrstuvwxyz",
+ }
+ testNoNewline(text, lines, t)
+}
+
+// Test that the line splitter handles a final empty line.
+func TestScanLineEmptyFinalLine(t *testing.T) {
+ const text = "abcdefghijklmn\nopqrstuvwxyz\n\n"
+ lines := []string{
+ "abcdefghijklmn",
+ "opqrstuvwxyz",
+ "",
+ }
+ testNoNewline(text, lines, t)
+}
+
+// Test that the line splitter handles a final empty line with a carriage return but no newline.
+func TestScanLineEmptyFinalLineWithCR(t *testing.T) {
+ const text = "abcdefghijklmn\nopqrstuvwxyz\n\r"
+ lines := []string{
+ "abcdefghijklmn",
+ "opqrstuvwxyz",
+ "",
+ }
+ testNoNewline(text, lines, t)
+}
+
+var testError = errors.New("testError")
+
+// Test the correct error is returned when the split function errors out.
+func TestSplitError(t *testing.T) {
+ // Create a split function that delivers a little data, then a predictable error.
+ numSplits := 0
+ const okCount = 7
+ errorSplit := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if atEOF {
+ panic("didn't get enough data")
+ }
+ if numSplits >= okCount {
+ return 0, nil, testError
+ }
+ numSplits++
+ return 1, data[0:1], nil
+ }
+ // Read the data.
+ const text = "abcdefghijklmnopqrstuvwxyz"
+ buf := strings.NewReader(text)
+ s := NewScanner(&slowReader{1, buf})
+ s.Split(errorSplit)
+ var i int
+ for i = 0; s.Scan(); i++ {
+ if len(s.Bytes()) != 1 || text[i] != s.Bytes()[0] {
+ t.Errorf("#%d: expected %q got %q", i, text[i], s.Bytes()[0])
+ }
+ }
+ // Check correct termination location and error.
+ if i != okCount {
+ t.Errorf("unexpected termination; expected %d tokens got %d", okCount, i)
+ }
+ err := s.Err()
+ if err != testError {
+ t.Fatalf("expected %q got %v", testError, err)
+ }
+}
+
+// Test that an EOF is overridden by a user-generated scan error.
+func TestErrAtEOF(t *testing.T) {
+ s := NewScanner(strings.NewReader("1 2 33"))
+ // This splitter will fail on last entry, after s.err==EOF.
+ split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ advance, token, err = ScanWords(data, atEOF)
+ if len(token) > 1 {
+ if s.ErrOrEOF() != io.EOF {
+ t.Fatal("not testing EOF")
+ }
+ err = testError
+ }
+ return
+ }
+ s.Split(split)
+ for s.Scan() {
+ }
+ if s.Err() != testError {
+ t.Fatal("wrong error:", s.Err())
+ }
+}
+
+// Test for issue 5268.
+type alwaysError struct{}
+
+func (alwaysError) Read(p []byte) (int, error) {
+ return 0, io.ErrUnexpectedEOF
+}
+
+func TestNonEOFWithEmptyRead(t *testing.T) {
+ scanner := NewScanner(alwaysError{})
+ for scanner.Scan() {
+ t.Fatal("read should fail")
+ }
+ err := scanner.Err()
+ if err != io.ErrUnexpectedEOF {
+ t.Errorf("unexpected error: %v", err)
+ }
+}
+
+// Test that Scan finishes if we have endless empty reads.
+type endlessZeros struct{}
+
+func (endlessZeros) Read(p []byte) (int, error) {
+ return 0, nil
+}
+
+func TestBadReader(t *testing.T) {
+ scanner := NewScanner(endlessZeros{})
+ for scanner.Scan() {
+ t.Fatal("read should fail")
+ }
+ err := scanner.Err()
+ if err != io.ErrNoProgress {
+ t.Errorf("unexpected error: %v", err)
+ }
+}
+
+func TestScanWordsExcessiveWhiteSpace(t *testing.T) {
+ const word = "ipsum"
+ s := strings.Repeat(" ", 4*smallMaxTokenSize) + word
+ scanner := NewScanner(strings.NewReader(s))
+ scanner.MaxTokenSize(smallMaxTokenSize)
+ scanner.Split(ScanWords)
+ if !scanner.Scan() {
+ t.Fatalf("scan failed: %v", scanner.Err())
+ }
+ if token := scanner.Text(); token != word {
+ t.Fatalf("unexpected token: %v", token)
+ }
+}
+
+// Test that empty tokens, including at end of line or end of file, are found by the scanner.
+// Issue 8672: Could miss final empty token.
+
+func commaSplit(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ for i := 0; i < len(data); i++ {
+ if data[i] == ',' {
+ return i + 1, data[:i], nil
+ }
+ }
+ return 0, data, ErrFinalToken
+}
+
+func testEmptyTokens(t *testing.T, text string, values []string) {
+ s := NewScanner(strings.NewReader(text))
+ s.Split(commaSplit)
+ var i int
+ for i = 0; s.Scan(); i++ {
+ if i >= len(values) {
+ t.Fatalf("got %d fields, expected %d", i+1, len(values))
+ }
+ if s.Text() != values[i] {
+ t.Errorf("%d: expected %q got %q", i, values[i], s.Text())
+ }
+ }
+ if i != len(values) {
+ t.Fatalf("got %d fields, expected %d", i, len(values))
+ }
+ if err := s.Err(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestEmptyTokens(t *testing.T) {
+ testEmptyTokens(t, "1,2,3,", []string{"1", "2", "3", ""})
+}
+
+func TestWithNoEmptyTokens(t *testing.T) {
+ testEmptyTokens(t, "1,2,3", []string{"1", "2", "3"})
+}
+
+func loopAtEOFSplit(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if len(data) > 0 {
+ return 1, data[:1], nil
+ }
+ return 0, data, nil
+}
+
+func TestDontLoopForever(t *testing.T) {
+ s := NewScanner(strings.NewReader("abc"))
+ s.Split(loopAtEOFSplit)
+ // Expect a panic
+ defer func() {
+ err := recover()
+ if err == nil {
+ t.Fatal("should have panicked")
+ }
+ if msg, ok := err.(string); !ok || !strings.Contains(msg, "empty tokens") {
+ panic(err)
+ }
+ }()
+ for count := 0; s.Scan(); count++ {
+ if count > 1000 {
+ t.Fatal("looping")
+ }
+ }
+ if s.Err() != nil {
+ t.Fatal("after scan:", s.Err())
+ }
+}
+
+func TestBlankLines(t *testing.T) {
+ s := NewScanner(strings.NewReader(strings.Repeat("\n", 1000)))
+ for count := 0; s.Scan(); count++ {
+ if count > 2000 {
+ t.Fatal("looping")
+ }
+ }
+ if s.Err() != nil {
+ t.Fatal("after scan:", s.Err())
+ }
+}
+
+type countdown int
+
+func (c *countdown) split(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if *c > 0 {
+ *c--
+ return 1, data[:1], nil
+ }
+ return 0, nil, nil
+}
+
+// Check that the looping-at-EOF check doesn't trigger for merely empty tokens.
+func TestEmptyLinesOK(t *testing.T) {
+ c := countdown(10000)
+ s := NewScanner(strings.NewReader(strings.Repeat("\n", 10000)))
+ s.Split(c.split)
+ for s.Scan() {
+ }
+ if s.Err() != nil {
+ t.Fatal("after scan:", s.Err())
+ }
+ if c != 0 {
+ t.Fatalf("stopped with %d left to process", c)
+ }
+}
+
+// Make sure we can read a huge token if a big enough buffer is provided.
+func TestHugeBuffer(t *testing.T) {
+ text := strings.Repeat("x", 2*MaxScanTokenSize)
+ s := NewScanner(strings.NewReader(text + "\n"))
+ s.Buffer(make([]byte, 100), 3*MaxScanTokenSize)
+ for s.Scan() {
+ token := s.Text()
+ if token != text {
+ t.Errorf("scan got incorrect token of length %d", len(token))
+ }
+ }
+ if s.Err() != nil {
+ t.Fatal("after scan:", s.Err())
+ }
+}
+
+// negativeEOFReader returns an invalid -1 at the end, as though it
+// were wrapping the read system call.
+type negativeEOFReader int
+
+func (r *negativeEOFReader) Read(p []byte) (int, error) {
+ if *r > 0 {
+ c := int(*r)
+ if c > len(p) {
+ c = len(p)
+ }
+ for i := 0; i < c; i++ {
+ p[i] = 'a'
+ }
+ p[c-1] = '\n'
+ *r -= negativeEOFReader(c)
+ return c, nil
+ }
+ return -1, io.EOF
+}
+
+// Test that the scanner doesn't panic and returns ErrBadReadCount
+// on a reader that returns a negative count of bytes read (issue 38053).
+func TestNegativeEOFReader(t *testing.T) {
+ r := negativeEOFReader(10)
+ scanner := NewScanner(&r)
+ c := 0
+ for scanner.Scan() {
+ c++
+ if c > 1 {
+ t.Error("read too many lines")
+ break
+ }
+ }
+ if got, want := scanner.Err(), ErrBadReadCount; got != want {
+ t.Errorf("scanner.Err: got %v, want %v", got, want)
+ }
+}
+
+// largeReader returns an invalid count that is larger than the number
+// of bytes requested.
+type largeReader struct{}
+
+func (largeReader) Read(p []byte) (int, error) {
+ return len(p) + 1, nil
+}
+
+// Test that the scanner doesn't panic and returns ErrBadReadCount
+// on a reader that returns an impossibly large count of bytes read (issue 38053).
+func TestLargeReader(t *testing.T) {
+ scanner := NewScanner(largeReader{})
+ for scanner.Scan() {
+ }
+ if got, want := scanner.Err(), ErrBadReadCount; got != want {
+ t.Errorf("scanner.Err: got %v, want %v", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/builtin/builtin.go b/platform/dbops/binaries/go/go/src/builtin/builtin.go
new file mode 100644
index 0000000000000000000000000000000000000000..668c799ca74c90f7ed2b94117562c2d3c3936564
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/builtin/builtin.go
@@ -0,0 +1,310 @@
+// 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 builtin provides documentation for Go's predeclared identifiers.
+The items documented here are not actually in package builtin
+but their descriptions here allow godoc to present documentation
+for the language's special identifiers.
+*/
+package builtin
+
+import "cmp"
+
+// bool is the set of boolean values, true and false.
+type bool bool
+
+// true and false are the two untyped boolean values.
+const (
+ true = 0 == 0 // Untyped bool.
+ false = 0 != 0 // Untyped bool.
+)
+
+// uint8 is the set of all unsigned 8-bit integers.
+// Range: 0 through 255.
+type uint8 uint8
+
+// uint16 is the set of all unsigned 16-bit integers.
+// Range: 0 through 65535.
+type uint16 uint16
+
+// uint32 is the set of all unsigned 32-bit integers.
+// Range: 0 through 4294967295.
+type uint32 uint32
+
+// uint64 is the set of all unsigned 64-bit integers.
+// Range: 0 through 18446744073709551615.
+type uint64 uint64
+
+// int8 is the set of all signed 8-bit integers.
+// Range: -128 through 127.
+type int8 int8
+
+// int16 is the set of all signed 16-bit integers.
+// Range: -32768 through 32767.
+type int16 int16
+
+// int32 is the set of all signed 32-bit integers.
+// Range: -2147483648 through 2147483647.
+type int32 int32
+
+// int64 is the set of all signed 64-bit integers.
+// Range: -9223372036854775808 through 9223372036854775807.
+type int64 int64
+
+// float32 is the set of all IEEE-754 32-bit floating-point numbers.
+type float32 float32
+
+// float64 is the set of all IEEE-754 64-bit floating-point numbers.
+type float64 float64
+
+// complex64 is the set of all complex numbers with float32 real and
+// imaginary parts.
+type complex64 complex64
+
+// complex128 is the set of all complex numbers with float64 real and
+// imaginary parts.
+type complex128 complex128
+
+// string is the set of all strings of 8-bit bytes, conventionally but not
+// necessarily representing UTF-8-encoded text. A string may be empty, but
+// not nil. Values of string type are immutable.
+type string string
+
+// int is a signed integer type that is at least 32 bits in size. It is a
+// distinct type, however, and not an alias for, say, int32.
+type int int
+
+// uint is an unsigned integer type that is at least 32 bits in size. It is a
+// distinct type, however, and not an alias for, say, uint32.
+type uint uint
+
+// uintptr is an integer type that is large enough to hold the bit pattern of
+// any pointer.
+type uintptr uintptr
+
+// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
+// used, by convention, to distinguish byte values from 8-bit unsigned
+// integer values.
+type byte = uint8
+
+// rune is an alias for int32 and is equivalent to int32 in all ways. It is
+// used, by convention, to distinguish character values from integer values.
+type rune = int32
+
+// any is an alias for interface{} and is equivalent to interface{} in all ways.
+type any = interface{}
+
+// comparable is an interface that is implemented by all comparable types
+// (booleans, numbers, strings, pointers, channels, arrays of comparable types,
+// structs whose fields are all comparable types).
+// The comparable interface may only be used as a type parameter constraint,
+// not as the type of a variable.
+type comparable interface{ comparable }
+
+// iota is a predeclared identifier representing the untyped integer ordinal
+// number of the current const specification in a (usually parenthesized)
+// const declaration. It is zero-indexed.
+const iota = 0 // Untyped int.
+
+// nil is a predeclared identifier representing the zero value for a
+// pointer, channel, func, interface, map, or slice type.
+var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
+
+// Type is here for the purposes of documentation only. It is a stand-in
+// for any Go type, but represents the same type for any given function
+// invocation.
+type Type int
+
+// Type1 is here for the purposes of documentation only. It is a stand-in
+// for any Go type, but represents the same type for any given function
+// invocation.
+type Type1 int
+
+// IntegerType is here for the purposes of documentation only. It is a stand-in
+// for any integer type: int, uint, int8 etc.
+type IntegerType int
+
+// FloatType is here for the purposes of documentation only. It is a stand-in
+// for either float type: float32 or float64.
+type FloatType float32
+
+// ComplexType is here for the purposes of documentation only. It is a
+// stand-in for either complex type: complex64 or complex128.
+type ComplexType complex64
+
+// The append built-in function appends elements to the end of a slice. If
+// it has sufficient capacity, the destination is resliced to accommodate the
+// new elements. If it does not, a new underlying array will be allocated.
+// Append returns the updated slice. It is therefore necessary to store the
+// result of append, often in the variable holding the slice itself:
+//
+// slice = append(slice, elem1, elem2)
+// slice = append(slice, anotherSlice...)
+//
+// As a special case, it is legal to append a string to a byte slice, like this:
+//
+// slice = append([]byte("hello "), "world"...)
+func append(slice []Type, elems ...Type) []Type
+
+// The copy built-in function copies elements from a source slice into a
+// destination slice. (As a special case, it also will copy bytes from a
+// string to a slice of bytes.) The source and destination may overlap. Copy
+// returns the number of elements copied, which will be the minimum of
+// len(src) and len(dst).
+func copy(dst, src []Type) int
+
+// The delete built-in function deletes the element with the specified key
+// (m[key]) from the map. If m is nil or there is no such element, delete
+// is a no-op.
+func delete(m map[Type]Type1, key Type)
+
+// The len built-in function returns the length of v, according to its type:
+//
+// Array: the number of elements in v.
+// Pointer to array: the number of elements in *v (even if v is nil).
+// Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
+// String: the number of bytes in v.
+// Channel: the number of elements queued (unread) in the channel buffer;
+// if v is nil, len(v) is zero.
+//
+// For some arguments, such as a string literal or a simple array expression, the
+// result can be a constant. See the Go language specification's "Length and
+// capacity" section for details.
+func len(v Type) int
+
+// The cap built-in function returns the capacity of v, according to its type:
+//
+// Array: the number of elements in v (same as len(v)).
+// Pointer to array: the number of elements in *v (same as len(v)).
+// Slice: the maximum length the slice can reach when resliced;
+// if v is nil, cap(v) is zero.
+// Channel: the channel buffer capacity, in units of elements;
+// if v is nil, cap(v) is zero.
+//
+// For some arguments, such as a simple array expression, the result can be a
+// constant. See the Go language specification's "Length and capacity" section for
+// details.
+func cap(v Type) int
+
+// The make built-in function allocates and initializes an object of type
+// slice, map, or chan (only). Like new, the first argument is a type, not a
+// value. Unlike new, make's return type is the same as the type of its
+// argument, not a pointer to it. The specification of the result depends on
+// the type:
+//
+// Slice: The size specifies the length. The capacity of the slice is
+// equal to its length. A second integer argument may be provided to
+// specify a different capacity; it must be no smaller than the
+// length. For example, make([]int, 0, 10) allocates an underlying array
+// of size 10 and returns a slice of length 0 and capacity 10 that is
+// backed by this underlying array.
+// Map: An empty map is allocated with enough space to hold the
+// specified number of elements. The size may be omitted, in which case
+// a small starting size is allocated.
+// Channel: The channel's buffer is initialized with the specified
+// buffer capacity. If zero, or the size is omitted, the channel is
+// unbuffered.
+func make(t Type, size ...IntegerType) Type
+
+// The max built-in function returns the largest value of a fixed number of
+// arguments of [cmp.Ordered] types. There must be at least one argument.
+// If T is a floating-point type and any of the arguments are NaNs,
+// max will return NaN.
+func max[T cmp.Ordered](x T, y ...T) T
+
+// The min built-in function returns the smallest value of a fixed number of
+// arguments of [cmp.Ordered] types. There must be at least one argument.
+// If T is a floating-point type and any of the arguments are NaNs,
+// min will return NaN.
+func min[T cmp.Ordered](x T, y ...T) T
+
+// The new built-in function allocates memory. The first argument is a type,
+// not a value, and the value returned is a pointer to a newly
+// allocated zero value of that type.
+func new(Type) *Type
+
+// The complex built-in function constructs a complex value from two
+// floating-point values. The real and imaginary parts must be of the same
+// size, either float32 or float64 (or assignable to them), and the return
+// value will be the corresponding complex type (complex64 for float32,
+// complex128 for float64).
+func complex(r, i FloatType) ComplexType
+
+// The real built-in function returns the real part of the complex number c.
+// The return value will be floating point type corresponding to the type of c.
+func real(c ComplexType) FloatType
+
+// The imag built-in function returns the imaginary part of the complex
+// number c. The return value will be floating point type corresponding to
+// the type of c.
+func imag(c ComplexType) FloatType
+
+// The clear built-in function clears maps and slices.
+// For maps, clear deletes all entries, resulting in an empty map.
+// For slices, clear sets all elements up to the length of the slice
+// to the zero value of the respective element type. If the argument
+// type is a type parameter, the type parameter's type set must
+// contain only map or slice types, and clear performs the operation
+// implied by the type argument.
+func clear[T ~[]Type | ~map[Type]Type1](t T)
+
+// The close built-in function closes a channel, which must be either
+// bidirectional or send-only. It should be executed only by the sender,
+// never the receiver, and has the effect of shutting down the channel after
+// the last sent value is received. After the last value has been received
+// from a closed channel c, any receive from c will succeed without
+// blocking, returning the zero value for the channel element. The form
+//
+// x, ok := <-c
+//
+// will also set ok to false for a closed and empty channel.
+func close(c chan<- Type)
+
+// The panic built-in function stops normal execution of the current
+// goroutine. When a function F calls panic, normal execution of F stops
+// immediately. Any functions whose execution was deferred by F are run in
+// the usual way, and then F returns to its caller. To the caller G, the
+// invocation of F then behaves like a call to panic, terminating G's
+// execution and running any deferred functions. This continues until all
+// functions in the executing goroutine have stopped, in reverse order. At
+// that point, the program is terminated with a non-zero exit code. This
+// termination sequence is called panicking and can be controlled by the
+// built-in function recover.
+//
+// Starting in Go 1.21, calling panic with a nil interface value or an
+// untyped nil causes a run-time error (a different panic).
+// The GODEBUG setting panicnil=1 disables the run-time error.
+func panic(v any)
+
+// The recover built-in function allows a program to manage behavior of a
+// panicking goroutine. Executing a call to recover inside a deferred
+// function (but not any function called by it) stops the panicking sequence
+// by restoring normal execution and retrieves the error value passed to the
+// call of panic. If recover is called outside the deferred function it will
+// not stop a panicking sequence. In this case, or when the goroutine is not
+// panicking, recover returns nil.
+//
+// Prior to Go 1.21, recover would also return nil if panic is called with
+// a nil argument. See [panic] for details.
+func recover() any
+
+// The print built-in function formats its arguments in an
+// implementation-specific way and writes the result to standard error.
+// Print is useful for bootstrapping and debugging; it is not guaranteed
+// to stay in the language.
+func print(args ...Type)
+
+// The println built-in function formats its arguments in an
+// implementation-specific way and writes the result to standard error.
+// Spaces are always added between arguments and a newline is appended.
+// Println is useful for bootstrapping and debugging; it is not guaranteed
+// to stay in the language.
+func println(args ...Type)
+
+// The error built-in interface type is the conventional interface for
+// representing an error condition, with the nil value representing no error.
+type error interface {
+ Error() string
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/boundary_test.go b/platform/dbops/binaries/go/go/src/bytes/boundary_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..67f377e089634f15f06069c28d4779bb161b1614
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/boundary_test.go
@@ -0,0 +1,115 @@
+// 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 linux
+
+package bytes_test
+
+import (
+ . "bytes"
+ "syscall"
+ "testing"
+)
+
+// This file tests the situation where byte operations are checking
+// data very near to a page boundary. We want to make sure those
+// operations do not read across the boundary and cause a page
+// fault where they shouldn't.
+
+// These tests run only on linux. The code being tested is
+// not OS-specific, so it does not need to be tested on all
+// operating systems.
+
+// dangerousSlice returns a slice which is immediately
+// preceded and followed by a faulting page.
+func dangerousSlice(t *testing.T) []byte {
+ pagesize := syscall.Getpagesize()
+ b, err := syscall.Mmap(0, 0, 3*pagesize, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANONYMOUS|syscall.MAP_PRIVATE)
+ if err != nil {
+ t.Fatalf("mmap failed %s", err)
+ }
+ err = syscall.Mprotect(b[:pagesize], syscall.PROT_NONE)
+ if err != nil {
+ t.Fatalf("mprotect low failed %s\n", err)
+ }
+ err = syscall.Mprotect(b[2*pagesize:], syscall.PROT_NONE)
+ if err != nil {
+ t.Fatalf("mprotect high failed %s\n", err)
+ }
+ return b[pagesize : 2*pagesize]
+}
+
+func TestEqualNearPageBoundary(t *testing.T) {
+ t.Parallel()
+ b := dangerousSlice(t)
+ for i := range b {
+ b[i] = 'A'
+ }
+ for i := 0; i <= len(b); i++ {
+ Equal(b[:i], b[len(b)-i:])
+ Equal(b[len(b)-i:], b[:i])
+ }
+}
+
+func TestIndexByteNearPageBoundary(t *testing.T) {
+ t.Parallel()
+ b := dangerousSlice(t)
+ for i := range b {
+ idx := IndexByte(b[i:], 1)
+ if idx != -1 {
+ t.Fatalf("IndexByte(b[%d:])=%d, want -1\n", i, idx)
+ }
+ }
+}
+
+func TestIndexNearPageBoundary(t *testing.T) {
+ t.Parallel()
+ q := dangerousSlice(t)
+ if len(q) > 64 {
+ // Only worry about when we're near the end of a page.
+ q = q[len(q)-64:]
+ }
+ b := dangerousSlice(t)
+ if len(b) > 256 {
+ // Only worry about when we're near the end of a page.
+ b = b[len(b)-256:]
+ }
+ for j := 1; j < len(q); j++ {
+ q[j-1] = 1 // difference is only found on the last byte
+ for i := range b {
+ idx := Index(b[i:], q[:j])
+ if idx != -1 {
+ t.Fatalf("Index(b[%d:], q[:%d])=%d, want -1\n", i, j, idx)
+ }
+ }
+ q[j-1] = 0
+ }
+
+ // Test differing alignments and sizes of q which always end on a page boundary.
+ q[len(q)-1] = 1 // difference is only found on the last byte
+ for j := 0; j < len(q); j++ {
+ for i := range b {
+ idx := Index(b[i:], q[j:])
+ if idx != -1 {
+ t.Fatalf("Index(b[%d:], q[%d:])=%d, want -1\n", i, j, idx)
+ }
+ }
+ }
+ q[len(q)-1] = 0
+}
+
+func TestCountNearPageBoundary(t *testing.T) {
+ t.Parallel()
+ b := dangerousSlice(t)
+ for i := range b {
+ c := Count(b[i:], []byte{1})
+ if c != 0 {
+ t.Fatalf("Count(b[%d:], {1})=%d, want 0\n", i, c)
+ }
+ c = Count(b[:i], []byte{0})
+ if c != i {
+ t.Fatalf("Count(b[:%d], {0})=%d, want %d\n", i, c, i)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/buffer.go b/platform/dbops/binaries/go/go/src/bytes/buffer.go
new file mode 100644
index 0000000000000000000000000000000000000000..ba844ba9d3c67d68ebc7ea4af785c2626da33195
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/buffer.go
@@ -0,0 +1,482 @@
+// 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 bytes
+
+// Simple byte buffer for marshaling data.
+
+import (
+ "errors"
+ "io"
+ "unicode/utf8"
+)
+
+// smallBufferSize is an initial allocation minimal capacity.
+const smallBufferSize = 64
+
+// A Buffer is a variable-sized buffer of bytes with [Buffer.Read] and [Buffer.Write] methods.
+// The zero value for Buffer is an empty buffer ready to use.
+type Buffer struct {
+ buf []byte // contents are the bytes buf[off : len(buf)]
+ off int // read at &buf[off], write at &buf[len(buf)]
+ lastRead readOp // last read operation, so that Unread* can work correctly.
+}
+
+// The readOp constants describe the last action performed on
+// the buffer, so that UnreadRune and UnreadByte can check for
+// invalid usage. opReadRuneX constants are chosen such that
+// converted to int they correspond to the rune size that was read.
+type readOp int8
+
+// Don't use iota for these, as the values need to correspond with the
+// names and comments, which is easier to see when being explicit.
+const (
+ opRead readOp = -1 // Any other read operation.
+ opInvalid readOp = 0 // Non-read operation.
+ opReadRune1 readOp = 1 // Read rune of size 1.
+ opReadRune2 readOp = 2 // Read rune of size 2.
+ opReadRune3 readOp = 3 // Read rune of size 3.
+ opReadRune4 readOp = 4 // Read rune of size 4.
+)
+
+// ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
+var ErrTooLarge = errors.New("bytes.Buffer: too large")
+var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read")
+
+const maxInt = int(^uint(0) >> 1)
+
+// Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
+// The slice is valid for use only until the next buffer modification (that is,
+// only until the next call to a method like [Buffer.Read], [Buffer.Write], [Buffer.Reset], or [Buffer.Truncate]).
+// The slice aliases the buffer content at least until the next buffer modification,
+// so immediate changes to the slice will affect the result of future reads.
+func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
+
+// AvailableBuffer returns an empty buffer with b.Available() capacity.
+// This buffer is intended to be appended to and
+// passed to an immediately succeeding [Buffer.Write] call.
+// The buffer is only valid until the next write operation on b.
+func (b *Buffer) AvailableBuffer() []byte { return b.buf[len(b.buf):] }
+
+// String returns the contents of the unread portion of the buffer
+// as a string. If the [Buffer] is a nil pointer, it returns "".
+//
+// To build strings more efficiently, see the strings.Builder type.
+func (b *Buffer) String() string {
+ if b == nil {
+ // Special case, useful in debugging.
+ return ""
+ }
+ return string(b.buf[b.off:])
+}
+
+// empty reports whether the unread portion of the buffer is empty.
+func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
+
+// Len returns the number of bytes of the unread portion of the buffer;
+// b.Len() == len(b.Bytes()).
+func (b *Buffer) Len() int { return len(b.buf) - b.off }
+
+// Cap returns the capacity of the buffer's underlying byte slice, that is, the
+// total space allocated for the buffer's data.
+func (b *Buffer) Cap() int { return cap(b.buf) }
+
+// Available returns how many bytes are unused in the buffer.
+func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) }
+
+// Truncate discards all but the first n unread bytes from the buffer
+// but continues to use the same allocated storage.
+// It panics if n is negative or greater than the length of the buffer.
+func (b *Buffer) Truncate(n int) {
+ if n == 0 {
+ b.Reset()
+ return
+ }
+ b.lastRead = opInvalid
+ if n < 0 || n > b.Len() {
+ panic("bytes.Buffer: truncation out of range")
+ }
+ b.buf = b.buf[:b.off+n]
+}
+
+// Reset resets the buffer to be empty,
+// but it retains the underlying storage for use by future writes.
+// Reset is the same as [Buffer.Truncate](0).
+func (b *Buffer) Reset() {
+ b.buf = b.buf[:0]
+ b.off = 0
+ b.lastRead = opInvalid
+}
+
+// tryGrowByReslice is an inlineable version of grow for the fast-case where the
+// internal buffer only needs to be resliced.
+// It returns the index where bytes should be written and whether it succeeded.
+func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
+ if l := len(b.buf); n <= cap(b.buf)-l {
+ b.buf = b.buf[:l+n]
+ return l, true
+ }
+ return 0, false
+}
+
+// grow grows the buffer to guarantee space for n more bytes.
+// It returns the index where bytes should be written.
+// If the buffer can't grow it will panic with ErrTooLarge.
+func (b *Buffer) grow(n int) int {
+ m := b.Len()
+ // If buffer is empty, reset to recover space.
+ if m == 0 && b.off != 0 {
+ b.Reset()
+ }
+ // Try to grow by means of a reslice.
+ if i, ok := b.tryGrowByReslice(n); ok {
+ return i
+ }
+ if b.buf == nil && n <= smallBufferSize {
+ b.buf = make([]byte, n, smallBufferSize)
+ return 0
+ }
+ c := cap(b.buf)
+ if n <= c/2-m {
+ // We can slide things down instead of allocating a new
+ // slice. We only need m+n <= c to slide, but
+ // we instead let capacity get twice as large so we
+ // don't spend all our time copying.
+ copy(b.buf, b.buf[b.off:])
+ } else if c > maxInt-c-n {
+ panic(ErrTooLarge)
+ } else {
+ // Add b.off to account for b.buf[:b.off] being sliced off the front.
+ b.buf = growSlice(b.buf[b.off:], b.off+n)
+ }
+ // Restore b.off and len(b.buf).
+ b.off = 0
+ b.buf = b.buf[:m+n]
+ return m
+}
+
+// Grow grows the buffer's capacity, if necessary, to guarantee space for
+// another n bytes. After Grow(n), at least n bytes can be written to the
+// buffer without another allocation.
+// If n is negative, Grow will panic.
+// If the buffer can't grow it will panic with [ErrTooLarge].
+func (b *Buffer) Grow(n int) {
+ if n < 0 {
+ panic("bytes.Buffer.Grow: negative count")
+ }
+ m := b.grow(n)
+ b.buf = b.buf[:m]
+}
+
+// Write appends the contents of p to the buffer, growing the buffer as
+// needed. The return value n is the length of p; err is always nil. If the
+// buffer becomes too large, Write will panic with [ErrTooLarge].
+func (b *Buffer) Write(p []byte) (n int, err error) {
+ b.lastRead = opInvalid
+ m, ok := b.tryGrowByReslice(len(p))
+ if !ok {
+ m = b.grow(len(p))
+ }
+ return copy(b.buf[m:], p), nil
+}
+
+// WriteString appends the contents of s to the buffer, growing the buffer as
+// needed. The return value n is the length of s; err is always nil. If the
+// buffer becomes too large, WriteString will panic with [ErrTooLarge].
+func (b *Buffer) WriteString(s string) (n int, err error) {
+ b.lastRead = opInvalid
+ m, ok := b.tryGrowByReslice(len(s))
+ if !ok {
+ m = b.grow(len(s))
+ }
+ return copy(b.buf[m:], s), nil
+}
+
+// MinRead is the minimum slice size passed to a Read call by
+// [Buffer.ReadFrom]. As long as the [Buffer] has at least MinRead bytes beyond
+// what is required to hold the contents of r, ReadFrom will not grow the
+// underlying buffer.
+const MinRead = 512
+
+// ReadFrom reads data from r until EOF and appends it to the buffer, growing
+// the buffer as needed. The return value n is the number of bytes read. Any
+// error except io.EOF encountered during the read is also returned. If the
+// buffer becomes too large, ReadFrom will panic with [ErrTooLarge].
+func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
+ b.lastRead = opInvalid
+ for {
+ i := b.grow(MinRead)
+ b.buf = b.buf[:i]
+ m, e := r.Read(b.buf[i:cap(b.buf)])
+ if m < 0 {
+ panic(errNegativeRead)
+ }
+
+ b.buf = b.buf[:i+m]
+ n += int64(m)
+ if e == io.EOF {
+ return n, nil // e is EOF, so return nil explicitly
+ }
+ if e != nil {
+ return n, e
+ }
+ }
+}
+
+// growSlice grows b by n, preserving the original content of b.
+// If the allocation fails, it panics with ErrTooLarge.
+func growSlice(b []byte, n int) []byte {
+ defer func() {
+ if recover() != nil {
+ panic(ErrTooLarge)
+ }
+ }()
+ // TODO(http://golang.org/issue/51462): We should rely on the append-make
+ // pattern so that the compiler can call runtime.growslice. For example:
+ // return append(b, make([]byte, n)...)
+ // This avoids unnecessary zero-ing of the first len(b) bytes of the
+ // allocated slice, but this pattern causes b to escape onto the heap.
+ //
+ // Instead use the append-make pattern with a nil slice to ensure that
+ // we allocate buffers rounded up to the closest size class.
+ c := len(b) + n // ensure enough space for n elements
+ if c < 2*cap(b) {
+ // The growth rate has historically always been 2x. In the future,
+ // we could rely purely on append to determine the growth rate.
+ c = 2 * cap(b)
+ }
+ b2 := append([]byte(nil), make([]byte, c)...)
+ copy(b2, b)
+ return b2[:len(b)]
+}
+
+// WriteTo writes data to w until the buffer is drained or an error occurs.
+// The return value n is the number of bytes written; it always fits into an
+// int, but it is int64 to match the io.WriterTo interface. Any error
+// encountered during the write is also returned.
+func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
+ b.lastRead = opInvalid
+ if nBytes := b.Len(); nBytes > 0 {
+ m, e := w.Write(b.buf[b.off:])
+ if m > nBytes {
+ panic("bytes.Buffer.WriteTo: invalid Write count")
+ }
+ b.off += m
+ n = int64(m)
+ if e != nil {
+ return n, e
+ }
+ // all bytes should have been written, by definition of
+ // Write method in io.Writer
+ if m != nBytes {
+ return n, io.ErrShortWrite
+ }
+ }
+ // Buffer is now empty; reset.
+ b.Reset()
+ return n, nil
+}
+
+// WriteByte appends the byte c to the buffer, growing the buffer as needed.
+// The returned error is always nil, but is included to match [bufio.Writer]'s
+// WriteByte. If the buffer becomes too large, WriteByte will panic with
+// [ErrTooLarge].
+func (b *Buffer) WriteByte(c byte) error {
+ b.lastRead = opInvalid
+ m, ok := b.tryGrowByReslice(1)
+ if !ok {
+ m = b.grow(1)
+ }
+ b.buf[m] = c
+ return nil
+}
+
+// WriteRune appends the UTF-8 encoding of Unicode code point r to the
+// buffer, returning its length and an error, which is always nil but is
+// included to match [bufio.Writer]'s WriteRune. The buffer is grown as needed;
+// if it becomes too large, WriteRune will panic with [ErrTooLarge].
+func (b *Buffer) WriteRune(r rune) (n int, err error) {
+ // Compare as uint32 to correctly handle negative runes.
+ if uint32(r) < utf8.RuneSelf {
+ b.WriteByte(byte(r))
+ return 1, nil
+ }
+ b.lastRead = opInvalid
+ m, ok := b.tryGrowByReslice(utf8.UTFMax)
+ if !ok {
+ m = b.grow(utf8.UTFMax)
+ }
+ b.buf = utf8.AppendRune(b.buf[:m], r)
+ return len(b.buf) - m, nil
+}
+
+// Read reads the next len(p) bytes from the buffer or until the buffer
+// is drained. The return value n is the number of bytes read. If the
+// buffer has no data to return, err is io.EOF (unless len(p) is zero);
+// otherwise it is nil.
+func (b *Buffer) Read(p []byte) (n int, err error) {
+ b.lastRead = opInvalid
+ if b.empty() {
+ // Buffer is empty, reset to recover space.
+ b.Reset()
+ if len(p) == 0 {
+ return 0, nil
+ }
+ return 0, io.EOF
+ }
+ n = copy(p, b.buf[b.off:])
+ b.off += n
+ if n > 0 {
+ b.lastRead = opRead
+ }
+ return n, nil
+}
+
+// Next returns a slice containing the next n bytes from the buffer,
+// advancing the buffer as if the bytes had been returned by [Buffer.Read].
+// If there are fewer than n bytes in the buffer, Next returns the entire buffer.
+// The slice is only valid until the next call to a read or write method.
+func (b *Buffer) Next(n int) []byte {
+ b.lastRead = opInvalid
+ m := b.Len()
+ if n > m {
+ n = m
+ }
+ data := b.buf[b.off : b.off+n]
+ b.off += n
+ if n > 0 {
+ b.lastRead = opRead
+ }
+ return data
+}
+
+// ReadByte reads and returns the next byte from the buffer.
+// If no byte is available, it returns error io.EOF.
+func (b *Buffer) ReadByte() (byte, error) {
+ if b.empty() {
+ // Buffer is empty, reset to recover space.
+ b.Reset()
+ return 0, io.EOF
+ }
+ c := b.buf[b.off]
+ b.off++
+ b.lastRead = opRead
+ return c, nil
+}
+
+// ReadRune reads and returns the next UTF-8-encoded
+// Unicode code point from the buffer.
+// If no bytes are available, the error returned is io.EOF.
+// If the bytes are an erroneous UTF-8 encoding, it
+// consumes one byte and returns U+FFFD, 1.
+func (b *Buffer) ReadRune() (r rune, size int, err error) {
+ if b.empty() {
+ // Buffer is empty, reset to recover space.
+ b.Reset()
+ return 0, 0, io.EOF
+ }
+ c := b.buf[b.off]
+ if c < utf8.RuneSelf {
+ b.off++
+ b.lastRead = opReadRune1
+ return rune(c), 1, nil
+ }
+ r, n := utf8.DecodeRune(b.buf[b.off:])
+ b.off += n
+ b.lastRead = readOp(n)
+ return r, n, nil
+}
+
+// UnreadRune unreads the last rune returned by [Buffer.ReadRune].
+// If the most recent read or write operation on the buffer was
+// not a successful [Buffer.ReadRune], UnreadRune returns an error. (In this regard
+// it is stricter than [Buffer.UnreadByte], which will unread the last byte
+// from any read operation.)
+func (b *Buffer) UnreadRune() error {
+ if b.lastRead <= opInvalid {
+ return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune")
+ }
+ if b.off >= int(b.lastRead) {
+ b.off -= int(b.lastRead)
+ }
+ b.lastRead = opInvalid
+ return nil
+}
+
+var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")
+
+// UnreadByte unreads the last byte returned by the most recent successful
+// read operation that read at least one byte. If a write has happened since
+// the last read, if the last read returned an error, or if the read read zero
+// bytes, UnreadByte returns an error.
+func (b *Buffer) UnreadByte() error {
+ if b.lastRead == opInvalid {
+ return errUnreadByte
+ }
+ b.lastRead = opInvalid
+ if b.off > 0 {
+ b.off--
+ }
+ return nil
+}
+
+// ReadBytes reads until the first occurrence of delim in the input,
+// returning a slice containing the data up to and including the delimiter.
+// If ReadBytes encounters an error before finding a delimiter,
+// it returns the data read before the error and the error itself (often io.EOF).
+// ReadBytes returns err != nil if and only if the returned data does not end in
+// delim.
+func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
+ slice, err := b.readSlice(delim)
+ // return a copy of slice. The buffer's backing array may
+ // be overwritten by later calls.
+ line = append(line, slice...)
+ return line, err
+}
+
+// readSlice is like ReadBytes but returns a reference to internal buffer data.
+func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
+ i := IndexByte(b.buf[b.off:], delim)
+ end := b.off + i + 1
+ if i < 0 {
+ end = len(b.buf)
+ err = io.EOF
+ }
+ line = b.buf[b.off:end]
+ b.off = end
+ b.lastRead = opRead
+ return line, err
+}
+
+// ReadString reads until the first occurrence of delim in the input,
+// returning a string containing the data up to and including the delimiter.
+// If ReadString encounters an error before finding a delimiter,
+// it returns the data read before the error and the error itself (often io.EOF).
+// ReadString returns err != nil if and only if the returned data does not end
+// in delim.
+func (b *Buffer) ReadString(delim byte) (line string, err error) {
+ slice, err := b.readSlice(delim)
+ return string(slice), err
+}
+
+// NewBuffer creates and initializes a new [Buffer] using buf as its
+// initial contents. The new [Buffer] takes ownership of buf, and the
+// caller should not use buf after this call. NewBuffer is intended to
+// prepare a [Buffer] to read existing data. It can also be used to set
+// the initial size of the internal buffer for writing. To do that,
+// buf should have the desired capacity but a length of zero.
+//
+// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
+// sufficient to initialize a [Buffer].
+func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
+
+// NewBufferString creates and initializes a new [Buffer] using string s as its
+// initial contents. It is intended to prepare a buffer to read an existing
+// string.
+//
+// In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
+// sufficient to initialize a [Buffer].
+func NewBufferString(s string) *Buffer {
+ return &Buffer{buf: []byte(s)}
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/buffer_test.go b/platform/dbops/binaries/go/go/src/bytes/buffer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..845e5e2209e53e7090f08a29e443593422c4b8fb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/buffer_test.go
@@ -0,0 +1,730 @@
+// 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 bytes_test
+
+import (
+ . "bytes"
+ "fmt"
+ "io"
+ "math/rand"
+ "strconv"
+ "testing"
+ "unicode/utf8"
+)
+
+const N = 10000 // make this bigger for a larger (and slower) test
+var testString string // test data for write tests
+var testBytes []byte // test data; same as testString but as a slice.
+
+type negativeReader struct{}
+
+func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
+
+func init() {
+ testBytes = make([]byte, N)
+ for i := 0; i < N; i++ {
+ testBytes[i] = 'a' + byte(i%26)
+ }
+ testString = string(testBytes)
+}
+
+// Verify that contents of buf match the string s.
+func check(t *testing.T, testname string, buf *Buffer, s string) {
+ bytes := buf.Bytes()
+ str := buf.String()
+ if buf.Len() != len(bytes) {
+ t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d", testname, buf.Len(), len(bytes))
+ }
+
+ if buf.Len() != len(str) {
+ t.Errorf("%s: buf.Len() == %d, len(buf.String()) == %d", testname, buf.Len(), len(str))
+ }
+
+ if buf.Len() != len(s) {
+ t.Errorf("%s: buf.Len() == %d, len(s) == %d", testname, buf.Len(), len(s))
+ }
+
+ if string(bytes) != s {
+ t.Errorf("%s: string(buf.Bytes()) == %q, s == %q", testname, string(bytes), s)
+ }
+}
+
+// Fill buf through n writes of string fus.
+// The initial contents of buf corresponds to the string s;
+// the result is the final contents of buf returned as a string.
+func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string {
+ check(t, testname+" (fill 1)", buf, s)
+ for ; n > 0; n-- {
+ m, err := buf.WriteString(fus)
+ if m != len(fus) {
+ t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fus))
+ }
+ if err != nil {
+ t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
+ }
+ s += fus
+ check(t, testname+" (fill 4)", buf, s)
+ }
+ return s
+}
+
+// Fill buf through n writes of byte slice fub.
+// The initial contents of buf corresponds to the string s;
+// the result is the final contents of buf returned as a string.
+func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string {
+ check(t, testname+" (fill 1)", buf, s)
+ for ; n > 0; n-- {
+ m, err := buf.Write(fub)
+ if m != len(fub) {
+ t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fub))
+ }
+ if err != nil {
+ t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
+ }
+ s += string(fub)
+ check(t, testname+" (fill 4)", buf, s)
+ }
+ return s
+}
+
+func TestNewBuffer(t *testing.T) {
+ buf := NewBuffer(testBytes)
+ check(t, "NewBuffer", buf, testString)
+}
+
+func TestNewBufferString(t *testing.T) {
+ buf := NewBufferString(testString)
+ check(t, "NewBufferString", buf, testString)
+}
+
+// Empty buf through repeated reads into fub.
+// The initial contents of buf corresponds to the string s.
+func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
+ check(t, testname+" (empty 1)", buf, s)
+
+ for {
+ n, err := buf.Read(fub)
+ if n == 0 {
+ break
+ }
+ if err != nil {
+ t.Errorf(testname+" (empty 2): err should always be nil, found err == %s", err)
+ }
+ s = s[n:]
+ check(t, testname+" (empty 3)", buf, s)
+ }
+
+ check(t, testname+" (empty 4)", buf, "")
+}
+
+func TestBasicOperations(t *testing.T) {
+ var buf Buffer
+
+ for i := 0; i < 5; i++ {
+ check(t, "TestBasicOperations (1)", &buf, "")
+
+ buf.Reset()
+ check(t, "TestBasicOperations (2)", &buf, "")
+
+ buf.Truncate(0)
+ check(t, "TestBasicOperations (3)", &buf, "")
+
+ n, err := buf.Write(testBytes[0:1])
+ if want := 1; err != nil || n != want {
+ t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil)
+ }
+ check(t, "TestBasicOperations (4)", &buf, "a")
+
+ buf.WriteByte(testString[1])
+ check(t, "TestBasicOperations (5)", &buf, "ab")
+
+ n, err = buf.Write(testBytes[2:26])
+ if want := 24; err != nil || n != want {
+ t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil)
+ }
+ check(t, "TestBasicOperations (6)", &buf, testString[0:26])
+
+ buf.Truncate(26)
+ check(t, "TestBasicOperations (7)", &buf, testString[0:26])
+
+ buf.Truncate(20)
+ check(t, "TestBasicOperations (8)", &buf, testString[0:20])
+
+ empty(t, "TestBasicOperations (9)", &buf, testString[0:20], make([]byte, 5))
+ empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100))
+
+ buf.WriteByte(testString[1])
+ c, err := buf.ReadByte()
+ if want := testString[1]; err != nil || c != want {
+ t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, want, nil)
+ }
+ c, err = buf.ReadByte()
+ if err != io.EOF {
+ t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, byte(0), io.EOF)
+ }
+ }
+}
+
+func TestLargeStringWrites(t *testing.T) {
+ var buf Buffer
+ limit := 30
+ if testing.Short() {
+ limit = 9
+ }
+ for i := 3; i < limit; i += 3 {
+ s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, testString)
+ empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(testString)/i))
+ }
+ check(t, "TestLargeStringWrites (3)", &buf, "")
+}
+
+func TestLargeByteWrites(t *testing.T) {
+ var buf Buffer
+ limit := 30
+ if testing.Short() {
+ limit = 9
+ }
+ for i := 3; i < limit; i += 3 {
+ s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, testBytes)
+ empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(testString)/i))
+ }
+ check(t, "TestLargeByteWrites (3)", &buf, "")
+}
+
+func TestLargeStringReads(t *testing.T) {
+ var buf Buffer
+ for i := 3; i < 30; i += 3 {
+ s := fillString(t, "TestLargeReads (1)", &buf, "", 5, testString[0:len(testString)/i])
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString)))
+ }
+ check(t, "TestLargeStringReads (3)", &buf, "")
+}
+
+func TestLargeByteReads(t *testing.T) {
+ var buf Buffer
+ for i := 3; i < 30; i += 3 {
+ s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString)))
+ }
+ check(t, "TestLargeByteReads (3)", &buf, "")
+}
+
+func TestMixedReadsAndWrites(t *testing.T) {
+ var buf Buffer
+ s := ""
+ for i := 0; i < 50; i++ {
+ wlen := rand.Intn(len(testString))
+ if i%2 == 0 {
+ s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testString[0:wlen])
+ } else {
+ s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testBytes[0:wlen])
+ }
+
+ rlen := rand.Intn(len(testString))
+ fub := make([]byte, rlen)
+ n, _ := buf.Read(fub)
+ s = s[n:]
+ }
+ empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
+}
+
+func TestCapWithPreallocatedSlice(t *testing.T) {
+ buf := NewBuffer(make([]byte, 10))
+ n := buf.Cap()
+ if n != 10 {
+ t.Errorf("expected 10, got %d", n)
+ }
+}
+
+func TestCapWithSliceAndWrittenData(t *testing.T) {
+ buf := NewBuffer(make([]byte, 0, 10))
+ buf.Write([]byte("test"))
+ n := buf.Cap()
+ if n != 10 {
+ t.Errorf("expected 10, got %d", n)
+ }
+}
+
+func TestNil(t *testing.T) {
+ var b *Buffer
+ if b.String() != "" {
+ t.Errorf("expected ; got %q", b.String())
+ }
+}
+
+func TestReadFrom(t *testing.T) {
+ var buf Buffer
+ for i := 3; i < 30; i += 3 {
+ s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
+ var b Buffer
+ b.ReadFrom(&buf)
+ empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(testString)))
+ }
+}
+
+type panicReader struct{ panic bool }
+
+func (r panicReader) Read(p []byte) (int, error) {
+ if r.panic {
+ panic("oops")
+ }
+ return 0, io.EOF
+}
+
+// Make sure that an empty Buffer remains empty when
+// it is "grown" before a Read that panics
+func TestReadFromPanicReader(t *testing.T) {
+
+ // First verify non-panic behaviour
+ var buf Buffer
+ i, err := buf.ReadFrom(panicReader{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if i != 0 {
+ t.Fatalf("unexpected return from bytes.ReadFrom (1): got: %d, want %d", i, 0)
+ }
+ check(t, "TestReadFromPanicReader (1)", &buf, "")
+
+ // Confirm that when Reader panics, the empty buffer remains empty
+ var buf2 Buffer
+ defer func() {
+ recover()
+ check(t, "TestReadFromPanicReader (2)", &buf2, "")
+ }()
+ buf2.ReadFrom(panicReader{panic: true})
+}
+
+func TestReadFromNegativeReader(t *testing.T) {
+ var b Buffer
+ defer func() {
+ switch err := recover().(type) {
+ case nil:
+ t.Fatal("bytes.Buffer.ReadFrom didn't panic")
+ case error:
+ // this is the error string of errNegativeRead
+ wantError := "bytes.Buffer: reader returned negative count from Read"
+ if err.Error() != wantError {
+ t.Fatalf("recovered panic: got %v, want %v", err.Error(), wantError)
+ }
+ default:
+ t.Fatalf("unexpected panic value: %#v", err)
+ }
+ }()
+
+ b.ReadFrom(new(negativeReader))
+}
+
+func TestWriteTo(t *testing.T) {
+ var buf Buffer
+ for i := 3; i < 30; i += 3 {
+ s := fillBytes(t, "TestWriteTo (1)", &buf, "", 5, testBytes[0:len(testBytes)/i])
+ var b Buffer
+ buf.WriteTo(&b)
+ empty(t, "TestWriteTo (2)", &b, s, make([]byte, len(testString)))
+ }
+}
+
+func TestWriteAppend(t *testing.T) {
+ var got Buffer
+ var want []byte
+ for i := 0; i < 1000; i++ {
+ b := got.AvailableBuffer()
+ b = strconv.AppendInt(b, int64(i), 10)
+ want = strconv.AppendInt(want, int64(i), 10)
+ got.Write(b)
+ }
+ if !Equal(got.Bytes(), want) {
+ t.Fatalf("Bytes() = %q, want %q", got, want)
+ }
+
+ // With a sufficiently sized buffer, there should be no allocations.
+ n := testing.AllocsPerRun(100, func() {
+ got.Reset()
+ for i := 0; i < 1000; i++ {
+ b := got.AvailableBuffer()
+ b = strconv.AppendInt(b, int64(i), 10)
+ got.Write(b)
+ }
+ })
+ if n > 0 {
+ t.Errorf("allocations occurred while appending")
+ }
+}
+
+func TestRuneIO(t *testing.T) {
+ const NRune = 1000
+ // Built a test slice while we write the data
+ b := make([]byte, utf8.UTFMax*NRune)
+ var buf Buffer
+ n := 0
+ for r := rune(0); r < NRune; r++ {
+ size := utf8.EncodeRune(b[n:], r)
+ nbytes, err := buf.WriteRune(r)
+ if err != nil {
+ t.Fatalf("WriteRune(%U) error: %s", r, err)
+ }
+ if nbytes != size {
+ t.Fatalf("WriteRune(%U) expected %d, got %d", r, size, nbytes)
+ }
+ n += size
+ }
+ b = b[0:n]
+
+ // Check the resulting bytes
+ if !Equal(buf.Bytes(), b) {
+ t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b)
+ }
+
+ p := make([]byte, utf8.UTFMax)
+ // Read it back with ReadRune
+ for r := rune(0); r < NRune; r++ {
+ size := utf8.EncodeRune(p, r)
+ nr, nbytes, err := buf.ReadRune()
+ if nr != r || nbytes != size || err != nil {
+ t.Fatalf("ReadRune(%U) got %U,%d not %U,%d (err=%s)", r, nr, nbytes, r, size, err)
+ }
+ }
+
+ // Check that UnreadRune works
+ buf.Reset()
+
+ // check at EOF
+ if err := buf.UnreadRune(); err == nil {
+ t.Fatal("UnreadRune at EOF: got no error")
+ }
+ if _, _, err := buf.ReadRune(); err == nil {
+ t.Fatal("ReadRune at EOF: got no error")
+ }
+ if err := buf.UnreadRune(); err == nil {
+ t.Fatal("UnreadRune after ReadRune at EOF: got no error")
+ }
+
+ // check not at EOF
+ buf.Write(b)
+ for r := rune(0); r < NRune; r++ {
+ r1, size, _ := buf.ReadRune()
+ if err := buf.UnreadRune(); err != nil {
+ t.Fatalf("UnreadRune(%U) got error %q", r, err)
+ }
+ r2, nbytes, err := buf.ReadRune()
+ if r1 != r2 || r1 != r || nbytes != size || err != nil {
+ t.Fatalf("ReadRune(%U) after UnreadRune got %U,%d not %U,%d (err=%s)", r, r2, nbytes, r, size, err)
+ }
+ }
+}
+
+func TestWriteInvalidRune(t *testing.T) {
+ // Invalid runes, including negative ones, should be written as
+ // utf8.RuneError.
+ for _, r := range []rune{-1, utf8.MaxRune + 1} {
+ var buf Buffer
+ buf.WriteRune(r)
+ check(t, fmt.Sprintf("TestWriteInvalidRune (%d)", r), &buf, "\uFFFD")
+ }
+}
+
+func TestNext(t *testing.T) {
+ b := []byte{0, 1, 2, 3, 4}
+ tmp := make([]byte, 5)
+ for i := 0; i <= 5; i++ {
+ for j := i; j <= 5; j++ {
+ for k := 0; k <= 6; k++ {
+ // 0 <= i <= j <= 5; 0 <= k <= 6
+ // Check that if we start with a buffer
+ // of length j at offset i and ask for
+ // Next(k), we get the right bytes.
+ buf := NewBuffer(b[0:j])
+ n, _ := buf.Read(tmp[0:i])
+ if n != i {
+ t.Fatalf("Read %d returned %d", i, n)
+ }
+ bb := buf.Next(k)
+ want := k
+ if want > j-i {
+ want = j - i
+ }
+ if len(bb) != want {
+ t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb))
+ }
+ for l, v := range bb {
+ if v != byte(l+i) {
+ t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i)
+ }
+ }
+ }
+ }
+ }
+}
+
+var readBytesTests = []struct {
+ buffer string
+ delim byte
+ expected []string
+ err error
+}{
+ {"", 0, []string{""}, io.EOF},
+ {"a\x00", 0, []string{"a\x00"}, nil},
+ {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil},
+ {"hello\x01world", 1, []string{"hello\x01"}, nil},
+ {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF},
+ {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil},
+ {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF},
+}
+
+func TestReadBytes(t *testing.T) {
+ for _, test := range readBytesTests {
+ buf := NewBufferString(test.buffer)
+ var err error
+ for _, expected := range test.expected {
+ var bytes []byte
+ bytes, err = buf.ReadBytes(test.delim)
+ if string(bytes) != expected {
+ t.Errorf("expected %q, got %q", expected, bytes)
+ }
+ if err != nil {
+ break
+ }
+ }
+ if err != test.err {
+ t.Errorf("expected error %v, got %v", test.err, err)
+ }
+ }
+}
+
+func TestReadString(t *testing.T) {
+ for _, test := range readBytesTests {
+ buf := NewBufferString(test.buffer)
+ var err error
+ for _, expected := range test.expected {
+ var s string
+ s, err = buf.ReadString(test.delim)
+ if s != expected {
+ t.Errorf("expected %q, got %q", expected, s)
+ }
+ if err != nil {
+ break
+ }
+ }
+ if err != test.err {
+ t.Errorf("expected error %v, got %v", test.err, err)
+ }
+ }
+}
+
+func BenchmarkReadString(b *testing.B) {
+ const n = 32 << 10
+
+ data := make([]byte, n)
+ data[n-1] = 'x'
+ b.SetBytes(int64(n))
+ for i := 0; i < b.N; i++ {
+ buf := NewBuffer(data)
+ _, err := buf.ReadString('x')
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func TestGrow(t *testing.T) {
+ x := []byte{'x'}
+ y := []byte{'y'}
+ tmp := make([]byte, 72)
+ for _, growLen := range []int{0, 100, 1000, 10000, 100000} {
+ for _, startLen := range []int{0, 100, 1000, 10000, 100000} {
+ xBytes := Repeat(x, startLen)
+
+ buf := NewBuffer(xBytes)
+ // If we read, this affects buf.off, which is good to test.
+ readBytes, _ := buf.Read(tmp)
+ yBytes := Repeat(y, growLen)
+ allocs := testing.AllocsPerRun(100, func() {
+ buf.Grow(growLen)
+ buf.Write(yBytes)
+ })
+ // Check no allocation occurs in write, as long as we're single-threaded.
+ if allocs != 0 {
+ t.Errorf("allocation occurred during write")
+ }
+ // Check that buffer has correct data.
+ if !Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) {
+ t.Errorf("bad initial data at %d %d", startLen, growLen)
+ }
+ if !Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) {
+ t.Errorf("bad written data at %d %d", startLen, growLen)
+ }
+ }
+ }
+}
+
+func TestGrowOverflow(t *testing.T) {
+ defer func() {
+ if err := recover(); err != ErrTooLarge {
+ t.Errorf("after too-large Grow, recover() = %v; want %v", err, ErrTooLarge)
+ }
+ }()
+
+ buf := NewBuffer(make([]byte, 1))
+ const maxInt = int(^uint(0) >> 1)
+ buf.Grow(maxInt)
+}
+
+// Was a bug: used to give EOF reading empty slice at EOF.
+func TestReadEmptyAtEOF(t *testing.T) {
+ b := new(Buffer)
+ slice := make([]byte, 0)
+ n, err := b.Read(slice)
+ if err != nil {
+ t.Errorf("read error: %v", err)
+ }
+ if n != 0 {
+ t.Errorf("wrong count; got %d want 0", n)
+ }
+}
+
+func TestUnreadByte(t *testing.T) {
+ b := new(Buffer)
+
+ // check at EOF
+ if err := b.UnreadByte(); err == nil {
+ t.Fatal("UnreadByte at EOF: got no error")
+ }
+ if _, err := b.ReadByte(); err == nil {
+ t.Fatal("ReadByte at EOF: got no error")
+ }
+ if err := b.UnreadByte(); err == nil {
+ t.Fatal("UnreadByte after ReadByte at EOF: got no error")
+ }
+
+ // check not at EOF
+ b.WriteString("abcdefghijklmnopqrstuvwxyz")
+
+ // after unsuccessful read
+ if n, err := b.Read(nil); n != 0 || err != nil {
+ t.Fatalf("Read(nil) = %d,%v; want 0,nil", n, err)
+ }
+ if err := b.UnreadByte(); err == nil {
+ t.Fatal("UnreadByte after Read(nil): got no error")
+ }
+
+ // after successful read
+ if _, err := b.ReadBytes('m'); err != nil {
+ t.Fatalf("ReadBytes: %v", err)
+ }
+ if err := b.UnreadByte(); err != nil {
+ t.Fatalf("UnreadByte: %v", err)
+ }
+ c, err := b.ReadByte()
+ if err != nil {
+ t.Fatalf("ReadByte: %v", err)
+ }
+ if c != 'm' {
+ t.Errorf("ReadByte = %q; want %q", c, 'm')
+ }
+}
+
+// Tests that we occasionally compact. Issue 5154.
+func TestBufferGrowth(t *testing.T) {
+ var b Buffer
+ buf := make([]byte, 1024)
+ b.Write(buf[0:1])
+ var cap0 int
+ for i := 0; i < 5<<10; i++ {
+ b.Write(buf)
+ b.Read(buf)
+ if i == 0 {
+ cap0 = b.Cap()
+ }
+ }
+ cap1 := b.Cap()
+ // (*Buffer).grow allows for 2x capacity slop before sliding,
+ // so set our error threshold at 3x.
+ if cap1 > cap0*3 {
+ t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0)
+ }
+}
+
+func BenchmarkWriteByte(b *testing.B) {
+ const n = 4 << 10
+ b.SetBytes(n)
+ buf := NewBuffer(make([]byte, n))
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ for i := 0; i < n; i++ {
+ buf.WriteByte('x')
+ }
+ }
+}
+
+func BenchmarkWriteRune(b *testing.B) {
+ const n = 4 << 10
+ const r = '☺'
+ b.SetBytes(int64(n * utf8.RuneLen(r)))
+ buf := NewBuffer(make([]byte, n*utf8.UTFMax))
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ for i := 0; i < n; i++ {
+ buf.WriteRune(r)
+ }
+ }
+}
+
+// From Issue 5154.
+func BenchmarkBufferNotEmptyWriteRead(b *testing.B) {
+ buf := make([]byte, 1024)
+ for i := 0; i < b.N; i++ {
+ var b Buffer
+ b.Write(buf[0:1])
+ for i := 0; i < 5<<10; i++ {
+ b.Write(buf)
+ b.Read(buf)
+ }
+ }
+}
+
+// Check that we don't compact too often. From Issue 5154.
+func BenchmarkBufferFullSmallReads(b *testing.B) {
+ buf := make([]byte, 1024)
+ for i := 0; i < b.N; i++ {
+ var b Buffer
+ b.Write(buf)
+ for b.Len()+20 < b.Cap() {
+ b.Write(buf[:10])
+ }
+ for i := 0; i < 5<<10; i++ {
+ b.Read(buf[:1])
+ b.Write(buf[:1])
+ }
+ }
+}
+
+func BenchmarkBufferWriteBlock(b *testing.B) {
+ block := make([]byte, 1024)
+ for _, n := range []int{1 << 12, 1 << 16, 1 << 20} {
+ b.Run(fmt.Sprintf("N%d", n), func(b *testing.B) {
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ var bb Buffer
+ for bb.Len() < n {
+ bb.Write(block)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkBufferAppendNoCopy(b *testing.B) {
+ var bb Buffer
+ bb.Grow(16 << 20)
+ b.SetBytes(int64(bb.Available()))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ bb.Reset()
+ b := bb.AvailableBuffer()
+ b = b[:cap(b)] // use max capacity to simulate a large append operation
+ bb.Write(b) // should be nearly infinitely fast
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/bytes.go b/platform/dbops/binaries/go/go/src/bytes/bytes.go
new file mode 100644
index 0000000000000000000000000000000000000000..0679b43a20a3b1cc66c7a192f8c63ecb593633f5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/bytes.go
@@ -0,0 +1,1373 @@
+// 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 bytes implements functions for the manipulation of byte slices.
+// It is analogous to the facilities of the [strings] package.
+package bytes
+
+import (
+ "internal/bytealg"
+ "unicode"
+ "unicode/utf8"
+)
+
+// Equal reports whether a and b
+// are the same length and contain the same bytes.
+// A nil argument is equivalent to an empty slice.
+func Equal(a, b []byte) bool {
+ // Neither cmd/compile nor gccgo allocates for these string conversions.
+ return string(a) == string(b)
+}
+
+// Compare returns an integer comparing two byte slices lexicographically.
+// The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
+// A nil argument is equivalent to an empty slice.
+func Compare(a, b []byte) int {
+ return bytealg.Compare(a, b)
+}
+
+// explode splits s into a slice of UTF-8 sequences, one per Unicode code point (still slices of bytes),
+// up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes.
+func explode(s []byte, n int) [][]byte {
+ if n <= 0 || n > len(s) {
+ n = len(s)
+ }
+ a := make([][]byte, n)
+ var size int
+ na := 0
+ for len(s) > 0 {
+ if na+1 >= n {
+ a[na] = s
+ na++
+ break
+ }
+ _, size = utf8.DecodeRune(s)
+ a[na] = s[0:size:size]
+ s = s[size:]
+ na++
+ }
+ return a[0:na]
+}
+
+// Count counts the number of non-overlapping instances of sep in s.
+// If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
+func Count(s, sep []byte) int {
+ // special case
+ if len(sep) == 0 {
+ return utf8.RuneCount(s) + 1
+ }
+ if len(sep) == 1 {
+ return bytealg.Count(s, sep[0])
+ }
+ n := 0
+ for {
+ i := Index(s, sep)
+ if i == -1 {
+ return n
+ }
+ n++
+ s = s[i+len(sep):]
+ }
+}
+
+// Contains reports whether subslice is within b.
+func Contains(b, subslice []byte) bool {
+ return Index(b, subslice) != -1
+}
+
+// ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.
+func ContainsAny(b []byte, chars string) bool {
+ return IndexAny(b, chars) >= 0
+}
+
+// ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.
+func ContainsRune(b []byte, r rune) bool {
+ return IndexRune(b, r) >= 0
+}
+
+// ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).
+func ContainsFunc(b []byte, f func(rune) bool) bool {
+ return IndexFunc(b, f) >= 0
+}
+
+// IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.
+func IndexByte(b []byte, c byte) int {
+ return bytealg.IndexByte(b, c)
+}
+
+func indexBytePortable(s []byte, c byte) int {
+ for i, b := range s {
+ if b == c {
+ return i
+ }
+ }
+ return -1
+}
+
+// LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
+func LastIndex(s, sep []byte) int {
+ n := len(sep)
+ switch {
+ case n == 0:
+ return len(s)
+ case n == 1:
+ return bytealg.LastIndexByte(s, sep[0])
+ case n == len(s):
+ if Equal(s, sep) {
+ return 0
+ }
+ return -1
+ case n > len(s):
+ return -1
+ }
+ return bytealg.LastIndexRabinKarp(s, sep)
+}
+
+// LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.
+func LastIndexByte(s []byte, c byte) int {
+ return bytealg.LastIndexByte(s, c)
+}
+
+// IndexRune interprets s as a sequence of UTF-8-encoded code points.
+// It returns the byte index of the first occurrence in s of the given rune.
+// It returns -1 if rune is not present in s.
+// If r is utf8.RuneError, it returns the first instance of any
+// invalid UTF-8 byte sequence.
+func IndexRune(s []byte, r rune) int {
+ switch {
+ case 0 <= r && r < utf8.RuneSelf:
+ return IndexByte(s, byte(r))
+ case r == utf8.RuneError:
+ for i := 0; i < len(s); {
+ r1, n := utf8.DecodeRune(s[i:])
+ if r1 == utf8.RuneError {
+ return i
+ }
+ i += n
+ }
+ return -1
+ case !utf8.ValidRune(r):
+ return -1
+ default:
+ var b [utf8.UTFMax]byte
+ n := utf8.EncodeRune(b[:], r)
+ return Index(s, b[:n])
+ }
+}
+
+// IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points.
+// It returns the byte index of the first occurrence in s of any of the Unicode
+// code points in chars. It returns -1 if chars is empty or if there is no code
+// point in common.
+func IndexAny(s []byte, chars string) int {
+ if chars == "" {
+ // Avoid scanning all of s.
+ return -1
+ }
+ if len(s) == 1 {
+ r := rune(s[0])
+ if r >= utf8.RuneSelf {
+ // search utf8.RuneError.
+ for _, r = range chars {
+ if r == utf8.RuneError {
+ return 0
+ }
+ }
+ return -1
+ }
+ if bytealg.IndexByteString(chars, s[0]) >= 0 {
+ return 0
+ }
+ return -1
+ }
+ if len(chars) == 1 {
+ r := rune(chars[0])
+ if r >= utf8.RuneSelf {
+ r = utf8.RuneError
+ }
+ return IndexRune(s, r)
+ }
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i, c := range s {
+ if as.contains(c) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ var width int
+ for i := 0; i < len(s); i += width {
+ r := rune(s[i])
+ if r < utf8.RuneSelf {
+ if bytealg.IndexByteString(chars, s[i]) >= 0 {
+ return i
+ }
+ width = 1
+ continue
+ }
+ r, width = utf8.DecodeRune(s[i:])
+ if r != utf8.RuneError {
+ // r is 2 to 4 bytes
+ if len(chars) == width {
+ if chars == string(r) {
+ return i
+ }
+ continue
+ }
+ // Use bytealg.IndexString for performance if available.
+ if bytealg.MaxLen >= width {
+ if bytealg.IndexString(chars, string(r)) >= 0 {
+ return i
+ }
+ continue
+ }
+ }
+ for _, ch := range chars {
+ if r == ch {
+ return i
+ }
+ }
+ }
+ return -1
+}
+
+// LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code
+// points. It returns the byte index of the last occurrence in s of any of
+// the Unicode code points in chars. It returns -1 if chars is empty or if
+// there is no code point in common.
+func LastIndexAny(s []byte, chars string) int {
+ if chars == "" {
+ // Avoid scanning all of s.
+ return -1
+ }
+ if len(s) > 8 {
+ if as, isASCII := makeASCIISet(chars); isASCII {
+ for i := len(s) - 1; i >= 0; i-- {
+ if as.contains(s[i]) {
+ return i
+ }
+ }
+ return -1
+ }
+ }
+ if len(s) == 1 {
+ r := rune(s[0])
+ if r >= utf8.RuneSelf {
+ for _, r = range chars {
+ if r == utf8.RuneError {
+ return 0
+ }
+ }
+ return -1
+ }
+ if bytealg.IndexByteString(chars, s[0]) >= 0 {
+ return 0
+ }
+ return -1
+ }
+ if len(chars) == 1 {
+ cr := rune(chars[0])
+ if cr >= utf8.RuneSelf {
+ cr = utf8.RuneError
+ }
+ for i := len(s); i > 0; {
+ r, size := utf8.DecodeLastRune(s[:i])
+ i -= size
+ if r == cr {
+ return i
+ }
+ }
+ return -1
+ }
+ for i := len(s); i > 0; {
+ r := rune(s[i-1])
+ if r < utf8.RuneSelf {
+ if bytealg.IndexByteString(chars, s[i-1]) >= 0 {
+ return i - 1
+ }
+ i--
+ continue
+ }
+ r, size := utf8.DecodeLastRune(s[:i])
+ i -= size
+ if r != utf8.RuneError {
+ // r is 2 to 4 bytes
+ if len(chars) == size {
+ if chars == string(r) {
+ return i
+ }
+ continue
+ }
+ // Use bytealg.IndexString for performance if available.
+ if bytealg.MaxLen >= size {
+ if bytealg.IndexString(chars, string(r)) >= 0 {
+ return i
+ }
+ continue
+ }
+ }
+ for _, ch := range chars {
+ if r == ch {
+ return i
+ }
+ }
+ }
+ return -1
+}
+
+// Generic split: splits after each instance of sep,
+// including sepSave bytes of sep in the subslices.
+func genSplit(s, sep []byte, sepSave, n int) [][]byte {
+ if n == 0 {
+ return nil
+ }
+ if len(sep) == 0 {
+ return explode(s, n)
+ }
+ if n < 0 {
+ n = Count(s, sep) + 1
+ }
+ if n > len(s)+1 {
+ n = len(s) + 1
+ }
+
+ a := make([][]byte, n)
+ n--
+ i := 0
+ for i < n {
+ m := Index(s, sep)
+ if m < 0 {
+ break
+ }
+ a[i] = s[: m+sepSave : m+sepSave]
+ s = s[m+len(sep):]
+ i++
+ }
+ a[i] = s
+ return a[:i+1]
+}
+
+// SplitN slices s into subslices separated by sep and returns a slice of
+// the subslices between those separators.
+// If sep is empty, SplitN splits after each UTF-8 sequence.
+// The count determines the number of subslices to return:
+//
+// n > 0: at most n subslices; the last subslice will be the unsplit remainder.
+// n == 0: the result is nil (zero subslices)
+// n < 0: all subslices
+//
+// To split around the first instance of a separator, see Cut.
+func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
+
+// SplitAfterN slices s into subslices after each instance of sep and
+// returns a slice of those subslices.
+// If sep is empty, SplitAfterN splits after each UTF-8 sequence.
+// The count determines the number of subslices to return:
+//
+// n > 0: at most n subslices; the last subslice will be the unsplit remainder.
+// n == 0: the result is nil (zero subslices)
+// n < 0: all subslices
+func SplitAfterN(s, sep []byte, n int) [][]byte {
+ return genSplit(s, sep, len(sep), n)
+}
+
+// Split slices s into all subslices separated by sep and returns a slice of
+// the subslices between those separators.
+// If sep is empty, Split splits after each UTF-8 sequence.
+// It is equivalent to SplitN with a count of -1.
+//
+// To split around the first instance of a separator, see Cut.
+func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) }
+
+// SplitAfter slices s into all subslices after each instance of sep and
+// returns a slice of those subslices.
+// If sep is empty, SplitAfter splits after each UTF-8 sequence.
+// It is equivalent to SplitAfterN with a count of -1.
+func SplitAfter(s, sep []byte) [][]byte {
+ return genSplit(s, sep, len(sep), -1)
+}
+
+var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
+
+// Fields interprets s as a sequence of UTF-8-encoded code points.
+// It splits the slice s around each instance of one or more consecutive white space
+// characters, as defined by unicode.IsSpace, returning a slice of subslices of s or an
+// empty slice if s contains only white space.
+func Fields(s []byte) [][]byte {
+ // First count the fields.
+ // This is an exact count if s is ASCII, otherwise it is an approximation.
+ n := 0
+ wasSpace := 1
+ // setBits is used to track which bits are set in the bytes of s.
+ setBits := uint8(0)
+ for i := 0; i < len(s); i++ {
+ r := s[i]
+ setBits |= r
+ isSpace := int(asciiSpace[r])
+ n += wasSpace & ^isSpace
+ wasSpace = isSpace
+ }
+
+ if setBits >= utf8.RuneSelf {
+ // Some runes in the input slice are not ASCII.
+ return FieldsFunc(s, unicode.IsSpace)
+ }
+
+ // ASCII fast path
+ a := make([][]byte, n)
+ na := 0
+ fieldStart := 0
+ i := 0
+ // Skip spaces in the front of the input.
+ for i < len(s) && asciiSpace[s[i]] != 0 {
+ i++
+ }
+ fieldStart = i
+ for i < len(s) {
+ if asciiSpace[s[i]] == 0 {
+ i++
+ continue
+ }
+ a[na] = s[fieldStart:i:i]
+ na++
+ i++
+ // Skip spaces in between fields.
+ for i < len(s) && asciiSpace[s[i]] != 0 {
+ i++
+ }
+ fieldStart = i
+ }
+ if fieldStart < len(s) { // Last field might end at EOF.
+ a[na] = s[fieldStart:len(s):len(s)]
+ }
+ return a
+}
+
+// FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
+// It splits the slice s at each run of code points c satisfying f(c) and
+// returns a slice of subslices of s. If all code points in s satisfy f(c), or
+// len(s) == 0, an empty slice is returned.
+//
+// FieldsFunc makes no guarantees about the order in which it calls f(c)
+// and assumes that f always returns the same value for a given c.
+func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
+ // A span is used to record a slice of s of the form s[start:end].
+ // The start index is inclusive and the end index is exclusive.
+ type span struct {
+ start int
+ end int
+ }
+ spans := make([]span, 0, 32)
+
+ // Find the field start and end indices.
+ // Doing this in a separate pass (rather than slicing the string s
+ // and collecting the result substrings right away) is significantly
+ // more efficient, possibly due to cache effects.
+ start := -1 // valid span start if >= 0
+ for i := 0; i < len(s); {
+ size := 1
+ r := rune(s[i])
+ if r >= utf8.RuneSelf {
+ r, size = utf8.DecodeRune(s[i:])
+ }
+ if f(r) {
+ if start >= 0 {
+ spans = append(spans, span{start, i})
+ start = -1
+ }
+ } else {
+ if start < 0 {
+ start = i
+ }
+ }
+ i += size
+ }
+
+ // Last field might end at EOF.
+ if start >= 0 {
+ spans = append(spans, span{start, len(s)})
+ }
+
+ // Create subslices from recorded field indices.
+ a := make([][]byte, len(spans))
+ for i, span := range spans {
+ a[i] = s[span.start:span.end:span.end]
+ }
+
+ return a
+}
+
+// Join concatenates the elements of s to create a new byte slice. The separator
+// sep is placed between elements in the resulting slice.
+func Join(s [][]byte, sep []byte) []byte {
+ if len(s) == 0 {
+ return []byte{}
+ }
+ if len(s) == 1 {
+ // Just return a copy.
+ return append([]byte(nil), s[0]...)
+ }
+
+ var n int
+ if len(sep) > 0 {
+ if len(sep) >= maxInt/(len(s)-1) {
+ panic("bytes: Join output length overflow")
+ }
+ n += len(sep) * (len(s) - 1)
+ }
+ for _, v := range s {
+ if len(v) > maxInt-n {
+ panic("bytes: Join output length overflow")
+ }
+ n += len(v)
+ }
+
+ b := bytealg.MakeNoZero(n)
+ bp := copy(b, s[0])
+ for _, v := range s[1:] {
+ bp += copy(b[bp:], sep)
+ bp += copy(b[bp:], v)
+ }
+ return b
+}
+
+// HasPrefix reports whether the byte slice s begins with prefix.
+func HasPrefix(s, prefix []byte) bool {
+ return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix)
+}
+
+// HasSuffix reports whether the byte slice s ends with suffix.
+func HasSuffix(s, suffix []byte) bool {
+ return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix)
+}
+
+// Map returns a copy of the byte slice s with all its characters modified
+// according to the mapping function. If mapping returns a negative value, the character is
+// dropped from the byte slice with no replacement. The characters in s and the
+// output are interpreted as UTF-8-encoded code points.
+func Map(mapping func(r rune) rune, s []byte) []byte {
+ // In the worst case, the slice can grow when mapped, making
+ // things unpleasant. But it's so rare we barge in assuming it's
+ // fine. It could also shrink but that falls out naturally.
+ b := make([]byte, 0, len(s))
+ for i := 0; i < len(s); {
+ wid := 1
+ r := rune(s[i])
+ if r >= utf8.RuneSelf {
+ r, wid = utf8.DecodeRune(s[i:])
+ }
+ r = mapping(r)
+ if r >= 0 {
+ b = utf8.AppendRune(b, r)
+ }
+ i += wid
+ }
+ return b
+}
+
+// Repeat returns a new byte slice consisting of count copies of b.
+//
+// It panics if count is negative or if the result of (len(b) * count)
+// overflows.
+func Repeat(b []byte, count int) []byte {
+ if count == 0 {
+ return []byte{}
+ }
+
+ // Since we cannot return an error on overflow,
+ // we should panic if the repeat will generate an overflow.
+ // See golang.org/issue/16237.
+ if count < 0 {
+ panic("bytes: negative Repeat count")
+ }
+ if len(b) >= maxInt/count {
+ panic("bytes: Repeat output length overflow")
+ }
+ n := len(b) * count
+
+ if len(b) == 0 {
+ return []byte{}
+ }
+
+ // Past a certain chunk size it is counterproductive to use
+ // larger chunks as the source of the write, as when the source
+ // is too large we are basically just thrashing the CPU D-cache.
+ // So if the result length is larger than an empirically-found
+ // limit (8KB), we stop growing the source string once the limit
+ // is reached and keep reusing the same source string - that
+ // should therefore be always resident in the L1 cache - until we
+ // have completed the construction of the result.
+ // This yields significant speedups (up to +100%) in cases where
+ // the result length is large (roughly, over L2 cache size).
+ const chunkLimit = 8 * 1024
+ chunkMax := n
+ if chunkMax > chunkLimit {
+ chunkMax = chunkLimit / len(b) * len(b)
+ if chunkMax == 0 {
+ chunkMax = len(b)
+ }
+ }
+ nb := bytealg.MakeNoZero(n)
+ bp := copy(nb, b)
+ for bp < n {
+ chunk := bp
+ if chunk > chunkMax {
+ chunk = chunkMax
+ }
+ bp += copy(nb[bp:], nb[:chunk])
+ }
+ return nb
+}
+
+// ToUpper returns a copy of the byte slice s with all Unicode letters mapped to
+// their upper case.
+func ToUpper(s []byte) []byte {
+ isASCII, hasLower := true, false
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if c >= utf8.RuneSelf {
+ isASCII = false
+ break
+ }
+ hasLower = hasLower || ('a' <= c && c <= 'z')
+ }
+
+ if isASCII { // optimize for ASCII-only byte slices.
+ if !hasLower {
+ // Just return a copy.
+ return append([]byte(""), s...)
+ }
+ b := bytealg.MakeNoZero(len(s))
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if 'a' <= c && c <= 'z' {
+ c -= 'a' - 'A'
+ }
+ b[i] = c
+ }
+ return b
+ }
+ return Map(unicode.ToUpper, s)
+}
+
+// ToLower returns a copy of the byte slice s with all Unicode letters mapped to
+// their lower case.
+func ToLower(s []byte) []byte {
+ isASCII, hasUpper := true, false
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if c >= utf8.RuneSelf {
+ isASCII = false
+ break
+ }
+ hasUpper = hasUpper || ('A' <= c && c <= 'Z')
+ }
+
+ if isASCII { // optimize for ASCII-only byte slices.
+ if !hasUpper {
+ return append([]byte(""), s...)
+ }
+ b := bytealg.MakeNoZero(len(s))
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if 'A' <= c && c <= 'Z' {
+ c += 'a' - 'A'
+ }
+ b[i] = c
+ }
+ return b
+ }
+ return Map(unicode.ToLower, s)
+}
+
+// ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.
+func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
+
+// ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
+// upper case, giving priority to the special casing rules.
+func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte {
+ return Map(c.ToUpper, s)
+}
+
+// ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
+// lower case, giving priority to the special casing rules.
+func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte {
+ return Map(c.ToLower, s)
+}
+
+// ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
+// title case, giving priority to the special casing rules.
+func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte {
+ return Map(c.ToTitle, s)
+}
+
+// ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes
+// representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.
+func ToValidUTF8(s, replacement []byte) []byte {
+ b := make([]byte, 0, len(s)+len(replacement))
+ invalid := false // previous byte was from an invalid UTF-8 sequence
+ for i := 0; i < len(s); {
+ c := s[i]
+ if c < utf8.RuneSelf {
+ i++
+ invalid = false
+ b = append(b, c)
+ continue
+ }
+ _, wid := utf8.DecodeRune(s[i:])
+ if wid == 1 {
+ i++
+ if !invalid {
+ invalid = true
+ b = append(b, replacement...)
+ }
+ continue
+ }
+ invalid = false
+ b = append(b, s[i:i+wid]...)
+ i += wid
+ }
+ return b
+}
+
+// isSeparator reports whether the rune could mark a word boundary.
+// TODO: update when package unicode captures more of the properties.
+func isSeparator(r rune) bool {
+ // ASCII alphanumerics and underscore are not separators
+ if r <= 0x7F {
+ switch {
+ case '0' <= r && r <= '9':
+ return false
+ case 'a' <= r && r <= 'z':
+ return false
+ case 'A' <= r && r <= 'Z':
+ return false
+ case r == '_':
+ return false
+ }
+ return true
+ }
+ // Letters and digits are not separators
+ if unicode.IsLetter(r) || unicode.IsDigit(r) {
+ return false
+ }
+ // Otherwise, all we can do for now is treat spaces as separators.
+ return unicode.IsSpace(r)
+}
+
+// Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin
+// words mapped to their title case.
+//
+// Deprecated: The rule Title uses for word boundaries does not handle Unicode
+// punctuation properly. Use golang.org/x/text/cases instead.
+func Title(s []byte) []byte {
+ // Use a closure here to remember state.
+ // Hackish but effective. Depends on Map scanning in order and calling
+ // the closure once per rune.
+ prev := ' '
+ return Map(
+ func(r rune) rune {
+ if isSeparator(prev) {
+ prev = r
+ return unicode.ToTitle(r)
+ }
+ prev = r
+ return r
+ },
+ s)
+}
+
+// TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off
+// all leading UTF-8-encoded code points c that satisfy f(c).
+func TrimLeftFunc(s []byte, f func(r rune) bool) []byte {
+ i := indexFunc(s, f, false)
+ if i == -1 {
+ return nil
+ }
+ return s[i:]
+}
+
+// TrimRightFunc returns a subslice of s by slicing off all trailing
+// UTF-8-encoded code points c that satisfy f(c).
+func TrimRightFunc(s []byte, f func(r rune) bool) []byte {
+ i := lastIndexFunc(s, f, false)
+ if i >= 0 && s[i] >= utf8.RuneSelf {
+ _, wid := utf8.DecodeRune(s[i:])
+ i += wid
+ } else {
+ i++
+ }
+ return s[0:i]
+}
+
+// TrimFunc returns a subslice of s by slicing off all leading and trailing
+// UTF-8-encoded code points c that satisfy f(c).
+func TrimFunc(s []byte, f func(r rune) bool) []byte {
+ return TrimRightFunc(TrimLeftFunc(s, f), f)
+}
+
+// TrimPrefix returns s without the provided leading prefix string.
+// If s doesn't start with prefix, s is returned unchanged.
+func TrimPrefix(s, prefix []byte) []byte {
+ if HasPrefix(s, prefix) {
+ return s[len(prefix):]
+ }
+ return s
+}
+
+// TrimSuffix returns s without the provided trailing suffix string.
+// If s doesn't end with suffix, s is returned unchanged.
+func TrimSuffix(s, suffix []byte) []byte {
+ if HasSuffix(s, suffix) {
+ return s[:len(s)-len(suffix)]
+ }
+ return s
+}
+
+// IndexFunc interprets s as a sequence of UTF-8-encoded code points.
+// It returns the byte index in s of the first Unicode
+// code point satisfying f(c), or -1 if none do.
+func IndexFunc(s []byte, f func(r rune) bool) int {
+ return indexFunc(s, f, true)
+}
+
+// LastIndexFunc interprets s as a sequence of UTF-8-encoded code points.
+// It returns the byte index in s of the last Unicode
+// code point satisfying f(c), or -1 if none do.
+func LastIndexFunc(s []byte, f func(r rune) bool) int {
+ return lastIndexFunc(s, f, true)
+}
+
+// indexFunc is the same as IndexFunc except that if
+// truth==false, the sense of the predicate function is
+// inverted.
+func indexFunc(s []byte, f func(r rune) bool, truth bool) int {
+ start := 0
+ for start < len(s) {
+ wid := 1
+ r := rune(s[start])
+ if r >= utf8.RuneSelf {
+ r, wid = utf8.DecodeRune(s[start:])
+ }
+ if f(r) == truth {
+ return start
+ }
+ start += wid
+ }
+ return -1
+}
+
+// lastIndexFunc is the same as LastIndexFunc except that if
+// truth==false, the sense of the predicate function is
+// inverted.
+func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int {
+ for i := len(s); i > 0; {
+ r, size := rune(s[i-1]), 1
+ if r >= utf8.RuneSelf {
+ r, size = utf8.DecodeLastRune(s[0:i])
+ }
+ i -= size
+ if f(r) == truth {
+ return i
+ }
+ }
+ return -1
+}
+
+// asciiSet is a 32-byte value, where each bit represents the presence of a
+// given ASCII character in the set. The 128-bits of the lower 16 bytes,
+// starting with the least-significant bit of the lowest word to the
+// most-significant bit of the highest word, map to the full range of all
+// 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
+// ensuring that any non-ASCII character will be reported as not in the set.
+// This allocates a total of 32 bytes even though the upper half
+// is unused to avoid bounds checks in asciiSet.contains.
+type asciiSet [8]uint32
+
+// makeASCIISet creates a set of ASCII characters and reports whether all
+// characters in chars are ASCII.
+func makeASCIISet(chars string) (as asciiSet, ok bool) {
+ for i := 0; i < len(chars); i++ {
+ c := chars[i]
+ if c >= utf8.RuneSelf {
+ return as, false
+ }
+ as[c/32] |= 1 << (c % 32)
+ }
+ return as, true
+}
+
+// contains reports whether c is inside the set.
+func (as *asciiSet) contains(c byte) bool {
+ return (as[c/32] & (1 << (c % 32))) != 0
+}
+
+// containsRune is a simplified version of strings.ContainsRune
+// to avoid importing the strings package.
+// We avoid bytes.ContainsRune to avoid allocating a temporary copy of s.
+func containsRune(s string, r rune) bool {
+ for _, c := range s {
+ if c == r {
+ return true
+ }
+ }
+ return false
+}
+
+// Trim returns a subslice of s by slicing off all leading and
+// trailing UTF-8-encoded code points contained in cutset.
+func Trim(s []byte, cutset string) []byte {
+ if len(s) == 0 {
+ // This is what we've historically done.
+ return nil
+ }
+ if cutset == "" {
+ return s
+ }
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
+ return trimLeftByte(trimRightByte(s, cutset[0]), cutset[0])
+ }
+ if as, ok := makeASCIISet(cutset); ok {
+ return trimLeftASCII(trimRightASCII(s, &as), &as)
+ }
+ return trimLeftUnicode(trimRightUnicode(s, cutset), cutset)
+}
+
+// TrimLeft returns a subslice of s by slicing off all leading
+// UTF-8-encoded code points contained in cutset.
+func TrimLeft(s []byte, cutset string) []byte {
+ if len(s) == 0 {
+ // This is what we've historically done.
+ return nil
+ }
+ if cutset == "" {
+ return s
+ }
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
+ return trimLeftByte(s, cutset[0])
+ }
+ if as, ok := makeASCIISet(cutset); ok {
+ return trimLeftASCII(s, &as)
+ }
+ return trimLeftUnicode(s, cutset)
+}
+
+func trimLeftByte(s []byte, c byte) []byte {
+ for len(s) > 0 && s[0] == c {
+ s = s[1:]
+ }
+ if len(s) == 0 {
+ // This is what we've historically done.
+ return nil
+ }
+ return s
+}
+
+func trimLeftASCII(s []byte, as *asciiSet) []byte {
+ for len(s) > 0 {
+ if !as.contains(s[0]) {
+ break
+ }
+ s = s[1:]
+ }
+ if len(s) == 0 {
+ // This is what we've historically done.
+ return nil
+ }
+ return s
+}
+
+func trimLeftUnicode(s []byte, cutset string) []byte {
+ for len(s) > 0 {
+ r, n := rune(s[0]), 1
+ if r >= utf8.RuneSelf {
+ r, n = utf8.DecodeRune(s)
+ }
+ if !containsRune(cutset, r) {
+ break
+ }
+ s = s[n:]
+ }
+ if len(s) == 0 {
+ // This is what we've historically done.
+ return nil
+ }
+ return s
+}
+
+// TrimRight returns a subslice of s by slicing off all trailing
+// UTF-8-encoded code points that are contained in cutset.
+func TrimRight(s []byte, cutset string) []byte {
+ if len(s) == 0 || cutset == "" {
+ return s
+ }
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
+ return trimRightByte(s, cutset[0])
+ }
+ if as, ok := makeASCIISet(cutset); ok {
+ return trimRightASCII(s, &as)
+ }
+ return trimRightUnicode(s, cutset)
+}
+
+func trimRightByte(s []byte, c byte) []byte {
+ for len(s) > 0 && s[len(s)-1] == c {
+ s = s[:len(s)-1]
+ }
+ return s
+}
+
+func trimRightASCII(s []byte, as *asciiSet) []byte {
+ for len(s) > 0 {
+ if !as.contains(s[len(s)-1]) {
+ break
+ }
+ s = s[:len(s)-1]
+ }
+ return s
+}
+
+func trimRightUnicode(s []byte, cutset string) []byte {
+ for len(s) > 0 {
+ r, n := rune(s[len(s)-1]), 1
+ if r >= utf8.RuneSelf {
+ r, n = utf8.DecodeLastRune(s)
+ }
+ if !containsRune(cutset, r) {
+ break
+ }
+ s = s[:len(s)-n]
+ }
+ return s
+}
+
+// TrimSpace returns a subslice of s by slicing off all leading and
+// trailing white space, as defined by Unicode.
+func TrimSpace(s []byte) []byte {
+ // Fast path for ASCII: look for the first ASCII non-space byte
+ start := 0
+ for ; start < len(s); start++ {
+ c := s[start]
+ if c >= utf8.RuneSelf {
+ // If we run into a non-ASCII byte, fall back to the
+ // slower unicode-aware method on the remaining bytes
+ return TrimFunc(s[start:], unicode.IsSpace)
+ }
+ if asciiSpace[c] == 0 {
+ break
+ }
+ }
+
+ // Now look for the first ASCII non-space byte from the end
+ stop := len(s)
+ for ; stop > start; stop-- {
+ c := s[stop-1]
+ if c >= utf8.RuneSelf {
+ return TrimFunc(s[start:stop], unicode.IsSpace)
+ }
+ if asciiSpace[c] == 0 {
+ break
+ }
+ }
+
+ // At this point s[start:stop] starts and ends with an ASCII
+ // non-space bytes, so we're done. Non-ASCII cases have already
+ // been handled above.
+ if start == stop {
+ // Special case to preserve previous TrimLeftFunc behavior,
+ // returning nil instead of empty slice if all spaces.
+ return nil
+ }
+ return s[start:stop]
+}
+
+// Runes interprets s as a sequence of UTF-8-encoded code points.
+// It returns a slice of runes (Unicode code points) equivalent to s.
+func Runes(s []byte) []rune {
+ t := make([]rune, utf8.RuneCount(s))
+ i := 0
+ for len(s) > 0 {
+ r, l := utf8.DecodeRune(s)
+ t[i] = r
+ i++
+ s = s[l:]
+ }
+ return t
+}
+
+// Replace returns a copy of the slice s with the first n
+// non-overlapping instances of old replaced by new.
+// If old is empty, it matches at the beginning of the slice
+// and after each UTF-8 sequence, yielding up to k+1 replacements
+// for a k-rune slice.
+// If n < 0, there is no limit on the number of replacements.
+func Replace(s, old, new []byte, n int) []byte {
+ m := 0
+ if n != 0 {
+ // Compute number of replacements.
+ m = Count(s, old)
+ }
+ if m == 0 {
+ // Just return a copy.
+ return append([]byte(nil), s...)
+ }
+ if n < 0 || m < n {
+ n = m
+ }
+
+ // Apply replacements to buffer.
+ t := make([]byte, len(s)+n*(len(new)-len(old)))
+ w := 0
+ start := 0
+ for i := 0; i < n; i++ {
+ j := start
+ if len(old) == 0 {
+ if i > 0 {
+ _, wid := utf8.DecodeRune(s[start:])
+ j += wid
+ }
+ } else {
+ j += Index(s[start:], old)
+ }
+ w += copy(t[w:], s[start:j])
+ w += copy(t[w:], new)
+ start = j + len(old)
+ }
+ w += copy(t[w:], s[start:])
+ return t[0:w]
+}
+
+// ReplaceAll returns a copy of the slice s with all
+// non-overlapping instances of old replaced by new.
+// If old is empty, it matches at the beginning of the slice
+// and after each UTF-8 sequence, yielding up to k+1 replacements
+// for a k-rune slice.
+func ReplaceAll(s, old, new []byte) []byte {
+ return Replace(s, old, new, -1)
+}
+
+// EqualFold reports whether s and t, interpreted as UTF-8 strings,
+// are equal under simple Unicode case-folding, which is a more general
+// form of case-insensitivity.
+func EqualFold(s, t []byte) bool {
+ // ASCII fast path
+ i := 0
+ for ; i < len(s) && i < len(t); i++ {
+ sr := s[i]
+ tr := t[i]
+ if sr|tr >= utf8.RuneSelf {
+ goto hasUnicode
+ }
+
+ // Easy case.
+ if tr == sr {
+ continue
+ }
+
+ // Make sr < tr to simplify what follows.
+ if tr < sr {
+ tr, sr = sr, tr
+ }
+ // ASCII only, sr/tr must be upper/lower case
+ if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
+ continue
+ }
+ return false
+ }
+ // Check if we've exhausted both strings.
+ return len(s) == len(t)
+
+hasUnicode:
+ s = s[i:]
+ t = t[i:]
+ for len(s) != 0 && len(t) != 0 {
+ // Extract first rune from each.
+ var sr, tr rune
+ if s[0] < utf8.RuneSelf {
+ sr, s = rune(s[0]), s[1:]
+ } else {
+ r, size := utf8.DecodeRune(s)
+ sr, s = r, s[size:]
+ }
+ if t[0] < utf8.RuneSelf {
+ tr, t = rune(t[0]), t[1:]
+ } else {
+ r, size := utf8.DecodeRune(t)
+ tr, t = r, t[size:]
+ }
+
+ // If they match, keep going; if not, return false.
+
+ // Easy case.
+ if tr == sr {
+ continue
+ }
+
+ // Make sr < tr to simplify what follows.
+ if tr < sr {
+ tr, sr = sr, tr
+ }
+ // Fast check for ASCII.
+ if tr < utf8.RuneSelf {
+ // ASCII only, sr/tr must be upper/lower case
+ if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
+ continue
+ }
+ return false
+ }
+
+ // General case. SimpleFold(x) returns the next equivalent rune > x
+ // or wraps around to smaller values.
+ r := unicode.SimpleFold(sr)
+ for r != sr && r < tr {
+ r = unicode.SimpleFold(r)
+ }
+ if r == tr {
+ continue
+ }
+ return false
+ }
+
+ // One string is empty. Are both?
+ return len(s) == len(t)
+}
+
+// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
+func Index(s, sep []byte) int {
+ n := len(sep)
+ switch {
+ case n == 0:
+ return 0
+ case n == 1:
+ return IndexByte(s, sep[0])
+ case n == len(s):
+ if Equal(sep, s) {
+ return 0
+ }
+ return -1
+ case n > len(s):
+ return -1
+ case n <= bytealg.MaxLen:
+ // Use brute force when s and sep both are small
+ if len(s) <= bytealg.MaxBruteForce {
+ return bytealg.Index(s, sep)
+ }
+ c0 := sep[0]
+ c1 := sep[1]
+ i := 0
+ t := len(s) - n + 1
+ fails := 0
+ for i < t {
+ if s[i] != c0 {
+ // IndexByte is faster than bytealg.Index, so use it as long as
+ // we're not getting lots of false positives.
+ o := IndexByte(s[i+1:t], c0)
+ if o < 0 {
+ return -1
+ }
+ i += o + 1
+ }
+ if s[i+1] == c1 && Equal(s[i:i+n], sep) {
+ return i
+ }
+ fails++
+ i++
+ // Switch to bytealg.Index when IndexByte produces too many false positives.
+ if fails > bytealg.Cutover(i) {
+ r := bytealg.Index(s[i:], sep)
+ if r >= 0 {
+ return r + i
+ }
+ return -1
+ }
+ }
+ return -1
+ }
+ c0 := sep[0]
+ c1 := sep[1]
+ i := 0
+ fails := 0
+ t := len(s) - n + 1
+ for i < t {
+ if s[i] != c0 {
+ o := IndexByte(s[i+1:t], c0)
+ if o < 0 {
+ break
+ }
+ i += o + 1
+ }
+ if s[i+1] == c1 && Equal(s[i:i+n], sep) {
+ return i
+ }
+ i++
+ fails++
+ if fails >= 4+i>>4 && i < t {
+ // Give up on IndexByte, it isn't skipping ahead
+ // far enough to be better than Rabin-Karp.
+ // Experiments (using IndexPeriodic) suggest
+ // the cutover is about 16 byte skips.
+ // TODO: if large prefixes of sep are matching
+ // we should cutover at even larger average skips,
+ // because Equal becomes that much more expensive.
+ // This code does not take that effect into account.
+ j := bytealg.IndexRabinKarp(s[i:], sep)
+ if j < 0 {
+ return -1
+ }
+ return i + j
+ }
+ }
+ return -1
+}
+
+// Cut slices s around the first instance of sep,
+// returning the text before and after sep.
+// The found result reports whether sep appears in s.
+// If sep does not appear in s, cut returns s, nil, false.
+//
+// Cut returns slices of the original slice s, not copies.
+func Cut(s, sep []byte) (before, after []byte, found bool) {
+ if i := Index(s, sep); i >= 0 {
+ return s[:i], s[i+len(sep):], true
+ }
+ return s, nil, false
+}
+
+// Clone returns a copy of b[:len(b)].
+// The result may have additional unused capacity.
+// Clone(nil) returns nil.
+func Clone(b []byte) []byte {
+ if b == nil {
+ return nil
+ }
+ return append([]byte{}, b...)
+}
+
+// CutPrefix returns s without the provided leading prefix byte slice
+// and reports whether it found the prefix.
+// If s doesn't start with prefix, CutPrefix returns s, false.
+// If prefix is the empty byte slice, CutPrefix returns s, true.
+//
+// CutPrefix returns slices of the original slice s, not copies.
+func CutPrefix(s, prefix []byte) (after []byte, found bool) {
+ if !HasPrefix(s, prefix) {
+ return s, false
+ }
+ return s[len(prefix):], true
+}
+
+// CutSuffix returns s without the provided ending suffix byte slice
+// and reports whether it found the suffix.
+// If s doesn't end with suffix, CutSuffix returns s, false.
+// If suffix is the empty byte slice, CutSuffix returns s, true.
+//
+// CutSuffix returns slices of the original slice s, not copies.
+func CutSuffix(s, suffix []byte) (before []byte, found bool) {
+ if !HasSuffix(s, suffix) {
+ return s, false
+ }
+ return s[:len(s)-len(suffix)], true
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/bytes_test.go b/platform/dbops/binaries/go/go/src/bytes/bytes_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0733edd3f447eb6d78ae1274f20f72191d2053c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/bytes_test.go
@@ -0,0 +1,2260 @@
+// 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 bytes_test
+
+import (
+ . "bytes"
+ "fmt"
+ "internal/testenv"
+ "math"
+ "math/rand"
+ "reflect"
+ "strings"
+ "testing"
+ "unicode"
+ "unicode/utf8"
+ "unsafe"
+)
+
+func eq(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := 0; i < len(a); i++ {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func sliceOfString(s [][]byte) []string {
+ result := make([]string, len(s))
+ for i, v := range s {
+ result[i] = string(v)
+ }
+ return result
+}
+
+// For ease of reading, the test cases use strings that are converted to byte
+// slices before invoking the functions.
+
+var abcd = "abcd"
+var faces = "☺☻☹"
+var commas = "1,2,3,4"
+var dots = "1....2....3....4"
+
+type BinOpTest struct {
+ a string
+ b string
+ i int
+}
+
+func TestEqual(t *testing.T) {
+ // Run the tests and check for allocation at the same time.
+ allocs := testing.AllocsPerRun(10, func() {
+ for _, tt := range compareTests {
+ eql := Equal(tt.a, tt.b)
+ if eql != (tt.i == 0) {
+ t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql)
+ }
+ }
+ })
+ if allocs > 0 {
+ t.Errorf("Equal allocated %v times", allocs)
+ }
+}
+
+func TestEqualExhaustive(t *testing.T) {
+ var size = 128
+ if testing.Short() {
+ size = 32
+ }
+ a := make([]byte, size)
+ b := make([]byte, size)
+ b_init := make([]byte, size)
+ // randomish but deterministic data
+ for i := 0; i < size; i++ {
+ a[i] = byte(17 * i)
+ b_init[i] = byte(23*i + 100)
+ }
+
+ for len := 0; len <= size; len++ {
+ for x := 0; x <= size-len; x++ {
+ for y := 0; y <= size-len; y++ {
+ copy(b, b_init)
+ copy(b[y:y+len], a[x:x+len])
+ if !Equal(a[x:x+len], b[y:y+len]) || !Equal(b[y:y+len], a[x:x+len]) {
+ t.Errorf("Equal(%d, %d, %d) = false", len, x, y)
+ }
+ }
+ }
+ }
+}
+
+// make sure Equal returns false for minimally different strings. The data
+// is all zeros except for a single one in one location.
+func TestNotEqual(t *testing.T) {
+ var size = 128
+ if testing.Short() {
+ size = 32
+ }
+ a := make([]byte, size)
+ b := make([]byte, size)
+
+ for len := 0; len <= size; len++ {
+ for x := 0; x <= size-len; x++ {
+ for y := 0; y <= size-len; y++ {
+ for diffpos := x; diffpos < x+len; diffpos++ {
+ a[diffpos] = 1
+ if Equal(a[x:x+len], b[y:y+len]) || Equal(b[y:y+len], a[x:x+len]) {
+ t.Errorf("NotEqual(%d, %d, %d, %d) = true", len, x, y, diffpos)
+ }
+ a[diffpos] = 0
+ }
+ }
+ }
+ }
+}
+
+var indexTests = []BinOpTest{
+ {"", "", 0},
+ {"", "a", -1},
+ {"", "foo", -1},
+ {"fo", "foo", -1},
+ {"foo", "baz", -1},
+ {"foo", "foo", 0},
+ {"oofofoofooo", "f", 2},
+ {"oofofoofooo", "foo", 4},
+ {"barfoobarfoo", "foo", 3},
+ {"foo", "", 0},
+ {"foo", "o", 1},
+ {"abcABCabc", "A", 3},
+ // cases with one byte strings - test IndexByte and special case in Index()
+ {"", "a", -1},
+ {"x", "a", -1},
+ {"x", "x", 0},
+ {"abc", "a", 0},
+ {"abc", "b", 1},
+ {"abc", "c", 2},
+ {"abc", "x", -1},
+ {"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33},
+ {"fofofofooofoboo", "oo", 7},
+ {"fofofofofofoboo", "ob", 11},
+ {"fofofofofofoboo", "boo", 12},
+ {"fofofofofofoboo", "oboo", 11},
+ {"fofofofofoooboo", "fooo", 8},
+ {"fofofofofofoboo", "foboo", 10},
+ {"fofofofofofoboo", "fofob", 8},
+ {"fofofofofofofoffofoobarfoo", "foffof", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffof", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofo", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofo", 13},
+ {"fofofofofoofofoffofoobarfoo", "foffofoo", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoo", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofoob", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoob", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofooba", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofooba", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofoobar", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoobar", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarf", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoobarf", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarfo", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoobarfo", 12},
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarfoo", 13},
+ {"fofofofofofofoffofoobarfoo", "foffofoobarfoo", 12},
+ {"fofofofofoofofoffofoobarfoo", "ofoffofoobarfoo", 12},
+ {"fofofofofofofoffofoobarfoo", "ofoffofoobarfoo", 11},
+ {"fofofofofoofofoffofoobarfoo", "fofoffofoobarfoo", 11},
+ {"fofofofofofofoffofoobarfoo", "fofoffofoobarfoo", 10},
+ {"fofofofofoofofoffofoobarfoo", "foobars", -1},
+ {"foofyfoobarfoobar", "y", 4},
+ {"oooooooooooooooooooooo", "r", -1},
+ {"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
+ {"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
+ // test fallback to Rabin-Karp.
+ {"000000000000000000000000000000000000000000000000000000000000000000000001", "0000000000000000000000000000000000000000000000000000000000000000001", 5},
+}
+
+var lastIndexTests = []BinOpTest{
+ {"", "", 0},
+ {"", "a", -1},
+ {"", "foo", -1},
+ {"fo", "foo", -1},
+ {"foo", "foo", 0},
+ {"foo", "f", 0},
+ {"oofofoofooo", "f", 7},
+ {"oofofoofooo", "foo", 7},
+ {"barfoobarfoo", "foo", 9},
+ {"foo", "", 3},
+ {"foo", "o", 2},
+ {"abcABCabc", "A", 3},
+ {"abcABCabc", "a", 6},
+}
+
+var indexAnyTests = []BinOpTest{
+ {"", "", -1},
+ {"", "a", -1},
+ {"", "abc", -1},
+ {"a", "", -1},
+ {"a", "a", 0},
+ {"\x80", "\xffb", 0},
+ {"aaa", "a", 0},
+ {"abc", "xyz", -1},
+ {"abc", "xcz", 2},
+ {"ab☺c", "x☺yz", 2},
+ {"a☺b☻c☹d", "cx", len("a☺b☻")},
+ {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
+ {"aRegExp*", ".(|)*+?^$[]", 7},
+ {dots + dots + dots, " ", -1},
+ {"012abcba210", "\xffb", 4},
+ {"012\x80bcb\x80210", "\xffb", 3},
+ {"0123456\xcf\x80abc", "\xcfb\x80", 10},
+}
+
+var lastIndexAnyTests = []BinOpTest{
+ {"", "", -1},
+ {"", "a", -1},
+ {"", "abc", -1},
+ {"a", "", -1},
+ {"a", "a", 0},
+ {"\x80", "\xffb", 0},
+ {"aaa", "a", 2},
+ {"abc", "xyz", -1},
+ {"abc", "ab", 1},
+ {"ab☺c", "x☺yz", 2},
+ {"a☺b☻c☹d", "cx", len("a☺b☻")},
+ {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
+ {"a.RegExp*", ".(|)*+?^$[]", 8},
+ {dots + dots + dots, " ", -1},
+ {"012abcba210", "\xffb", 6},
+ {"012\x80bcb\x80210", "\xffb", 7},
+ {"0123456\xcf\x80abc", "\xcfb\x80", 10},
+}
+
+// Execute f on each test case. funcName should be the name of f; it's used
+// in failure reports.
+func runIndexTests(t *testing.T, f func(s, sep []byte) int, funcName string, testCases []BinOpTest) {
+ for _, test := range testCases {
+ a := []byte(test.a)
+ b := []byte(test.b)
+ actual := f(a, b)
+ if actual != test.i {
+ t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, b, actual, test.i)
+ }
+ }
+ var allocTests = []struct {
+ a []byte
+ b []byte
+ i int
+ }{
+ // case for function Index.
+ {[]byte("000000000000000000000000000000000000000000000000000000000000000000000001"), []byte("0000000000000000000000000000000000000000000000000000000000000000001"), 5},
+ // case for function LastIndex.
+ {[]byte("000000000000000000000000000000000000000000000000000000000000000010000"), []byte("00000000000000000000000000000000000000000000000000000000000001"), 3},
+ }
+ allocs := testing.AllocsPerRun(100, func() {
+ if i := Index(allocTests[1].a, allocTests[1].b); i != allocTests[1].i {
+ t.Errorf("Index([]byte(%q), []byte(%q)) = %v; want %v", allocTests[1].a, allocTests[1].b, i, allocTests[1].i)
+ }
+ if i := LastIndex(allocTests[0].a, allocTests[0].b); i != allocTests[0].i {
+ t.Errorf("LastIndex([]byte(%q), []byte(%q)) = %v; want %v", allocTests[0].a, allocTests[0].b, i, allocTests[0].i)
+ }
+ })
+ if allocs != 0 {
+ t.Errorf("expected no allocations, got %f", allocs)
+ }
+}
+
+func runIndexAnyTests(t *testing.T, f func(s []byte, chars string) int, funcName string, testCases []BinOpTest) {
+ for _, test := range testCases {
+ a := []byte(test.a)
+ actual := f(a, test.b)
+ if actual != test.i {
+ t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, test.b, actual, test.i)
+ }
+ }
+}
+
+func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) }
+func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
+func TestIndexAny(t *testing.T) { runIndexAnyTests(t, IndexAny, "IndexAny", indexAnyTests) }
+func TestLastIndexAny(t *testing.T) {
+ runIndexAnyTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests)
+}
+
+func TestIndexByte(t *testing.T) {
+ for _, tt := range indexTests {
+ if len(tt.b) != 1 {
+ continue
+ }
+ a := []byte(tt.a)
+ b := tt.b[0]
+ pos := IndexByte(a, b)
+ if pos != tt.i {
+ t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos)
+ }
+ posp := IndexBytePortable(a, b)
+ if posp != tt.i {
+ t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp)
+ }
+ }
+}
+
+func TestLastIndexByte(t *testing.T) {
+ testCases := []BinOpTest{
+ {"", "q", -1},
+ {"abcdef", "q", -1},
+ {"abcdefabcdef", "a", len("abcdef")}, // something in the middle
+ {"abcdefabcdef", "f", len("abcdefabcde")}, // last byte
+ {"zabcdefabcdef", "z", 0}, // first byte
+ {"a☺b☻c☹d", "b", len("a☺")}, // non-ascii
+ }
+ for _, test := range testCases {
+ actual := LastIndexByte([]byte(test.a), test.b[0])
+ if actual != test.i {
+ t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.a, test.b[0], actual, test.i)
+ }
+ }
+}
+
+// test a larger buffer with different sizes and alignments
+func TestIndexByteBig(t *testing.T) {
+ var n = 1024
+ if testing.Short() {
+ n = 128
+ }
+ b := make([]byte, n)
+ for i := 0; i < n; i++ {
+ // different start alignments
+ b1 := b[i:]
+ for j := 0; j < len(b1); j++ {
+ b1[j] = 'x'
+ pos := IndexByte(b1, 'x')
+ if pos != j {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ b1[j] = 0
+ pos = IndexByte(b1, 'x')
+ if pos != -1 {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ }
+ // different end alignments
+ b1 = b[:i]
+ for j := 0; j < len(b1); j++ {
+ b1[j] = 'x'
+ pos := IndexByte(b1, 'x')
+ if pos != j {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ b1[j] = 0
+ pos = IndexByte(b1, 'x')
+ if pos != -1 {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ }
+ // different start and end alignments
+ b1 = b[i/2 : n-(i+1)/2]
+ for j := 0; j < len(b1); j++ {
+ b1[j] = 'x'
+ pos := IndexByte(b1, 'x')
+ if pos != j {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ b1[j] = 0
+ pos = IndexByte(b1, 'x')
+ if pos != -1 {
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
+ }
+ }
+ }
+}
+
+// test a small index across all page offsets
+func TestIndexByteSmall(t *testing.T) {
+ b := make([]byte, 5015) // bigger than a page
+ // Make sure we find the correct byte even when straddling a page.
+ for i := 0; i <= len(b)-15; i++ {
+ for j := 0; j < 15; j++ {
+ b[i+j] = byte(100 + j)
+ }
+ for j := 0; j < 15; j++ {
+ p := IndexByte(b[i:i+15], byte(100+j))
+ if p != j {
+ t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 100+j, p)
+ }
+ }
+ for j := 0; j < 15; j++ {
+ b[i+j] = 0
+ }
+ }
+ // Make sure matches outside the slice never trigger.
+ for i := 0; i <= len(b)-15; i++ {
+ for j := 0; j < 15; j++ {
+ b[i+j] = 1
+ }
+ for j := 0; j < 15; j++ {
+ p := IndexByte(b[i:i+15], byte(0))
+ if p != -1 {
+ t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 0, p)
+ }
+ }
+ for j := 0; j < 15; j++ {
+ b[i+j] = 0
+ }
+ }
+}
+
+func TestIndexRune(t *testing.T) {
+ tests := []struct {
+ in string
+ rune rune
+ want int
+ }{
+ {"", 'a', -1},
+ {"", '☺', -1},
+ {"foo", '☹', -1},
+ {"foo", 'o', 1},
+ {"foo☺bar", '☺', 3},
+ {"foo☺☻☹bar", '☹', 9},
+ {"a A x", 'A', 2},
+ {"some_text=some_value", '=', 9},
+ {"☺a", 'a', 3},
+ {"a☻☺b", '☺', 4},
+
+ // RuneError should match any invalid UTF-8 byte sequence.
+ {"�", '�', 0},
+ {"\xff", '�', 0},
+ {"☻x�", '�', len("☻x")},
+ {"☻x\xe2\x98", '�', len("☻x")},
+ {"☻x\xe2\x98�", '�', len("☻x")},
+ {"☻x\xe2\x98x", '�', len("☻x")},
+
+ // Invalid rune values should never match.
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
+ }
+ for _, tt := range tests {
+ if got := IndexRune([]byte(tt.in), tt.rune); got != tt.want {
+ t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
+ }
+ }
+
+ haystack := []byte("test世界")
+ allocs := testing.AllocsPerRun(1000, func() {
+ if i := IndexRune(haystack, 's'); i != 2 {
+ t.Fatalf("'s' at %d; want 2", i)
+ }
+ if i := IndexRune(haystack, '世'); i != 4 {
+ t.Fatalf("'世' at %d; want 4", i)
+ }
+ })
+ if allocs != 0 {
+ t.Errorf("expected no allocations, got %f", allocs)
+ }
+}
+
+// test count of a single byte across page offsets
+func TestCountByte(t *testing.T) {
+ b := make([]byte, 5015) // bigger than a page
+ windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
+ testCountWindow := func(i, window int) {
+ for j := 0; j < window; j++ {
+ b[i+j] = byte(100)
+ p := Count(b[i:i+window], []byte{100})
+ if p != j+1 {
+ t.Errorf("TestCountByte.Count(%q, 100) = %d", b[i:i+window], p)
+ }
+ }
+ }
+
+ maxWnd := windows[len(windows)-1]
+
+ for i := 0; i <= 2*maxWnd; i++ {
+ for _, window := range windows {
+ if window > len(b[i:]) {
+ window = len(b[i:])
+ }
+ testCountWindow(i, window)
+ for j := 0; j < window; j++ {
+ b[i+j] = byte(0)
+ }
+ }
+ }
+ for i := 4096 - (maxWnd + 1); i < len(b); i++ {
+ for _, window := range windows {
+ if window > len(b[i:]) {
+ window = len(b[i:])
+ }
+ testCountWindow(i, window)
+ for j := 0; j < window; j++ {
+ b[i+j] = byte(0)
+ }
+ }
+ }
+}
+
+// Make sure we don't count bytes outside our window
+func TestCountByteNoMatch(t *testing.T) {
+ b := make([]byte, 5015)
+ windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
+ for i := 0; i <= len(b); i++ {
+ for _, window := range windows {
+ if window > len(b[i:]) {
+ window = len(b[i:])
+ }
+ // Fill the window with non-match
+ for j := 0; j < window; j++ {
+ b[i+j] = byte(100)
+ }
+ // Try to find something that doesn't exist
+ p := Count(b[i:i+window], []byte{0})
+ if p != 0 {
+ t.Errorf("TestCountByteNoMatch(%q, 0) = %d", b[i:i+window], p)
+ }
+ for j := 0; j < window; j++ {
+ b[i+j] = byte(0)
+ }
+ }
+ }
+}
+
+var bmbuf []byte
+
+func valName(x int) string {
+ if s := x >> 20; s<<20 == x {
+ return fmt.Sprintf("%dM", s)
+ }
+ if s := x >> 10; s<<10 == x {
+ return fmt.Sprintf("%dK", s)
+ }
+ return fmt.Sprint(x)
+}
+
+func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
+ for _, n := range sizes {
+ if isRaceBuilder && n > 4<<10 {
+ continue
+ }
+ b.Run(valName(n), func(b *testing.B) {
+ if len(bmbuf) < n {
+ bmbuf = make([]byte, n)
+ }
+ b.SetBytes(int64(n))
+ f(b, n)
+ })
+ }
+}
+
+var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
+
+var isRaceBuilder = strings.HasSuffix(testenv.Builder(), "-race")
+
+func BenchmarkIndexByte(b *testing.B) {
+ benchBytes(b, indexSizes, bmIndexByte(IndexByte))
+}
+
+func BenchmarkIndexBytePortable(b *testing.B) {
+ benchBytes(b, indexSizes, bmIndexByte(IndexBytePortable))
+}
+
+func bmIndexByte(index func([]byte, byte) int) func(b *testing.B, n int) {
+ return func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := index(buf, 'x')
+ if j != n-1 {
+ b.Fatal("bad index", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ }
+}
+
+func BenchmarkIndexRune(b *testing.B) {
+ benchBytes(b, indexSizes, bmIndexRune(IndexRune))
+}
+
+func BenchmarkIndexRuneASCII(b *testing.B) {
+ benchBytes(b, indexSizes, bmIndexRuneASCII(IndexRune))
+}
+
+func bmIndexRuneASCII(index func([]byte, rune) int) func(b *testing.B, n int) {
+ return func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := index(buf, 'x')
+ if j != n-1 {
+ b.Fatal("bad index", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ }
+}
+
+func bmIndexRune(index func([]byte, rune) int) func(b *testing.B, n int) {
+ return func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ utf8.EncodeRune(buf[n-3:], '世')
+ for i := 0; i < b.N; i++ {
+ j := index(buf, '世')
+ if j != n-3 {
+ b.Fatal("bad index", j)
+ }
+ }
+ buf[n-3] = '\x00'
+ buf[n-2] = '\x00'
+ buf[n-1] = '\x00'
+ }
+}
+
+func BenchmarkEqual(b *testing.B) {
+ b.Run("0", func(b *testing.B) {
+ var buf [4]byte
+ buf1 := buf[0:0]
+ buf2 := buf[1:1]
+ for i := 0; i < b.N; i++ {
+ eq := Equal(buf1, buf2)
+ if !eq {
+ b.Fatal("bad equal")
+ }
+ }
+ })
+
+ sizes := []int{1, 6, 9, 15, 16, 20, 32, 4 << 10, 4 << 20, 64 << 20}
+ benchBytes(b, sizes, bmEqual(Equal))
+}
+
+func bmEqual(equal func([]byte, []byte) bool) func(b *testing.B, n int) {
+ return func(b *testing.B, n int) {
+ if len(bmbuf) < 2*n {
+ bmbuf = make([]byte, 2*n)
+ }
+ buf1 := bmbuf[0:n]
+ buf2 := bmbuf[n : 2*n]
+ buf1[n-1] = 'x'
+ buf2[n-1] = 'x'
+ for i := 0; i < b.N; i++ {
+ eq := equal(buf1, buf2)
+ if !eq {
+ b.Fatal("bad equal")
+ }
+ }
+ buf1[n-1] = '\x00'
+ buf2[n-1] = '\x00'
+ }
+}
+
+func BenchmarkEqualBothUnaligned(b *testing.B) {
+ sizes := []int{64, 4 << 10}
+ if !isRaceBuilder {
+ sizes = append(sizes, []int{4 << 20, 64 << 20}...)
+ }
+ maxSize := 2 * (sizes[len(sizes)-1] + 8)
+ if len(bmbuf) < maxSize {
+ bmbuf = make([]byte, maxSize)
+ }
+
+ for _, n := range sizes {
+ for _, off := range []int{0, 1, 4, 7} {
+ buf1 := bmbuf[off : off+n]
+ buf2Start := (len(bmbuf) / 2) + off
+ buf2 := bmbuf[buf2Start : buf2Start+n]
+ buf1[n-1] = 'x'
+ buf2[n-1] = 'x'
+ b.Run(fmt.Sprint(n, off), func(b *testing.B) {
+ b.SetBytes(int64(n))
+ for i := 0; i < b.N; i++ {
+ eq := Equal(buf1, buf2)
+ if !eq {
+ b.Fatal("bad equal")
+ }
+ }
+ })
+ buf1[n-1] = '\x00'
+ buf2[n-1] = '\x00'
+ }
+ }
+}
+
+func BenchmarkIndex(b *testing.B) {
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := Index(buf, buf[n-7:])
+ if j != n-7 {
+ b.Fatal("bad index", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ })
+}
+
+func BenchmarkIndexEasy(b *testing.B) {
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ buf[n-7] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := Index(buf, buf[n-7:])
+ if j != n-7 {
+ b.Fatal("bad index", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ buf[n-7] = '\x00'
+ })
+}
+
+func BenchmarkCount(b *testing.B) {
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := Count(buf, buf[n-7:])
+ if j != 1 {
+ b.Fatal("bad count", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ })
+}
+
+func BenchmarkCountEasy(b *testing.B) {
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
+ buf[n-7] = 'x'
+ for i := 0; i < b.N; i++ {
+ j := Count(buf, buf[n-7:])
+ if j != 1 {
+ b.Fatal("bad count", j)
+ }
+ }
+ buf[n-1] = '\x00'
+ buf[n-7] = '\x00'
+ })
+}
+
+func BenchmarkCountSingle(b *testing.B) {
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
+ buf := bmbuf[0:n]
+ step := 8
+ for i := 0; i < len(buf); i += step {
+ buf[i] = 1
+ }
+ expect := (len(buf) + (step - 1)) / step
+ for i := 0; i < b.N; i++ {
+ j := Count(buf, []byte{1})
+ if j != expect {
+ b.Fatal("bad count", j, expect)
+ }
+ }
+ for i := 0; i < len(buf); i++ {
+ buf[i] = 0
+ }
+ })
+}
+
+type SplitTest struct {
+ s string
+ sep string
+ n int
+ a []string
+}
+
+var splittests = []SplitTest{
+ {"", "", -1, []string{}},
+ {abcd, "a", 0, nil},
+ {abcd, "", 2, []string{"a", "bcd"}},
+ {abcd, "a", -1, []string{"", "bcd"}},
+ {abcd, "z", -1, []string{"abcd"}},
+ {abcd, "", -1, []string{"a", "b", "c", "d"}},
+ {commas, ",", -1, []string{"1", "2", "3", "4"}},
+ {dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
+ {faces, "☹", -1, []string{"☺☻", ""}},
+ {faces, "~", -1, []string{faces}},
+ {faces, "", -1, []string{"☺", "☻", "☹"}},
+ {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
+ {"1 2", " ", 3, []string{"1", "2"}},
+ {"123", "", 2, []string{"1", "23"}},
+ {"123", "", 17, []string{"1", "2", "3"}},
+ {"bT", "T", math.MaxInt / 4, []string{"b", ""}},
+ {"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}},
+ {"\xff-\xff", "-", -1, []string{"\xff", "\xff"}},
+}
+
+func TestSplit(t *testing.T) {
+ for _, tt := range splittests {
+ a := SplitN([]byte(tt.s), []byte(tt.sep), tt.n)
+
+ // Appending to the results should not change future results.
+ var x []byte
+ for _, v := range a {
+ x = append(v, 'z')
+ }
+
+ result := sliceOfString(a)
+ if !eq(result, tt.a) {
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
+ continue
+ }
+ if tt.n == 0 || len(a) == 0 {
+ continue
+ }
+
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
+ t.Errorf("last appended result was %s; want %s", x, want)
+ }
+
+ s := Join(a, []byte(tt.sep))
+ if string(s) != tt.s {
+ t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
+ }
+ if tt.n < 0 {
+ b := Split([]byte(tt.s), []byte(tt.sep))
+ if !reflect.DeepEqual(a, b) {
+ t.Errorf("Split disagrees withSplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
+ }
+ }
+ if len(a) > 0 {
+ in, out := a[0], s
+ if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
+ t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep)
+ }
+ }
+ }
+}
+
+var splitaftertests = []SplitTest{
+ {abcd, "a", -1, []string{"a", "bcd"}},
+ {abcd, "z", -1, []string{"abcd"}},
+ {abcd, "", -1, []string{"a", "b", "c", "d"}},
+ {commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
+ {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
+ {faces, "☹", -1, []string{"☺☻☹", ""}},
+ {faces, "~", -1, []string{faces}},
+ {faces, "", -1, []string{"☺", "☻", "☹"}},
+ {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
+ {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
+ {"1 2", " ", 3, []string{"1 ", "2"}},
+ {"123", "", 2, []string{"1", "23"}},
+ {"123", "", 17, []string{"1", "2", "3"}},
+}
+
+func TestSplitAfter(t *testing.T) {
+ for _, tt := range splitaftertests {
+ a := SplitAfterN([]byte(tt.s), []byte(tt.sep), tt.n)
+
+ // Appending to the results should not change future results.
+ var x []byte
+ for _, v := range a {
+ x = append(v, 'z')
+ }
+
+ result := sliceOfString(a)
+ if !eq(result, tt.a) {
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
+ continue
+ }
+
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
+ t.Errorf("last appended result was %s; want %s", x, want)
+ }
+
+ s := Join(a, nil)
+ if string(s) != tt.s {
+ t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
+ }
+ if tt.n < 0 {
+ b := SplitAfter([]byte(tt.s), []byte(tt.sep))
+ if !reflect.DeepEqual(a, b) {
+ t.Errorf("SplitAfter disagrees withSplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
+ }
+ }
+ }
+}
+
+type FieldsTest struct {
+ s string
+ a []string
+}
+
+var fieldstests = []FieldsTest{
+ {"", []string{}},
+ {" ", []string{}},
+ {" \t ", []string{}},
+ {" abc ", []string{"abc"}},
+ {"1 2 3 4", []string{"1", "2", "3", "4"}},
+ {"1 2 3 4", []string{"1", "2", "3", "4"}},
+ {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
+ {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
+ {"\u2000\u2001\u2002", []string{}},
+ {"\n™\t™\n", []string{"™", "™"}},
+ {faces, []string{faces}},
+}
+
+func TestFields(t *testing.T) {
+ for _, tt := range fieldstests {
+ b := []byte(tt.s)
+ a := Fields(b)
+
+ // Appending to the results should not change future results.
+ var x []byte
+ for _, v := range a {
+ x = append(v, 'z')
+ }
+
+ result := sliceOfString(a)
+ if !eq(result, tt.a) {
+ t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
+ continue
+ }
+
+ if string(b) != tt.s {
+ t.Errorf("slice changed to %s; want %s", string(b), tt.s)
+ }
+ if len(tt.a) > 0 {
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
+ t.Errorf("last appended result was %s; want %s", x, want)
+ }
+ }
+ }
+}
+
+func TestFieldsFunc(t *testing.T) {
+ for _, tt := range fieldstests {
+ a := FieldsFunc([]byte(tt.s), unicode.IsSpace)
+ result := sliceOfString(a)
+ if !eq(result, tt.a) {
+ t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
+ continue
+ }
+ }
+ pred := func(c rune) bool { return c == 'X' }
+ var fieldsFuncTests = []FieldsTest{
+ {"", []string{}},
+ {"XX", []string{}},
+ {"XXhiXXX", []string{"hi"}},
+ {"aXXbXXXcX", []string{"a", "b", "c"}},
+ }
+ for _, tt := range fieldsFuncTests {
+ b := []byte(tt.s)
+ a := FieldsFunc(b, pred)
+
+ // Appending to the results should not change future results.
+ var x []byte
+ for _, v := range a {
+ x = append(v, 'z')
+ }
+
+ result := sliceOfString(a)
+ if !eq(result, tt.a) {
+ t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
+ }
+
+ if string(b) != tt.s {
+ t.Errorf("slice changed to %s; want %s", b, tt.s)
+ }
+ if len(tt.a) > 0 {
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
+ t.Errorf("last appended result was %s; want %s", x, want)
+ }
+ }
+ }
+}
+
+// Test case for any function which accepts and returns a byte slice.
+// For ease of creation, we write the input byte slice as a string.
+type StringTest struct {
+ in string
+ out []byte
+}
+
+var upperTests = []StringTest{
+ {"", []byte("")},
+ {"ONLYUPPER", []byte("ONLYUPPER")},
+ {"abc", []byte("ABC")},
+ {"AbC123", []byte("ABC123")},
+ {"azAZ09_", []byte("AZAZ09_")},
+ {"longStrinGwitHmixofsmaLLandcAps", []byte("LONGSTRINGWITHMIXOFSMALLANDCAPS")},
+ {"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", []byte("LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS")},
+ {"\u0250\u0250\u0250\u0250\u0250", []byte("\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F")}, // grows one byte per char
+ {"a\u0080\U0010FFFF", []byte("A\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune
+}
+
+var lowerTests = []StringTest{
+ {"", []byte("")},
+ {"abc", []byte("abc")},
+ {"AbC123", []byte("abc123")},
+ {"azAZ09_", []byte("azaz09_")},
+ {"longStrinGwitHmixofsmaLLandcAps", []byte("longstringwithmixofsmallandcaps")},
+ {"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", []byte("long\u0250string\u0250with\u0250nonascii\u0250chars")},
+ {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", []byte("\u0251\u0251\u0251\u0251\u0251")}, // shrinks one byte per char
+ {"A\u0080\U0010FFFF", []byte("a\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune
+}
+
+const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
+
+var trimSpaceTests = []StringTest{
+ {"", nil},
+ {" a", []byte("a")},
+ {"b ", []byte("b")},
+ {"abc", []byte("abc")},
+ {space + "abc" + space, []byte("abc")},
+ {" ", nil},
+ {"\u3000 ", nil},
+ {" \u3000", nil},
+ {" \t\r\n \t\t\r\r\n\n ", nil},
+ {" \t\r\n x\t\t\r\r\n\n ", []byte("x")},
+ {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", []byte("x\t\t\r\r\ny")},
+ {"1 \t\r\n2", []byte("1 \t\r\n2")},
+ {" x\x80", []byte("x\x80")},
+ {" x\xc0", []byte("x\xc0")},
+ {"x \xc0\xc0 ", []byte("x \xc0\xc0")},
+ {"x \xc0", []byte("x \xc0")},
+ {"x \xc0 ", []byte("x \xc0")},
+ {"x \xc0\xc0 ", []byte("x \xc0\xc0")},
+ {"x ☺\xc0\xc0 ", []byte("x ☺\xc0\xc0")},
+ {"x ☺ ", []byte("x ☺")},
+}
+
+// Execute f on each test case. funcName should be the name of f; it's used
+// in failure reports.
+func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) {
+ for _, tc := range testCases {
+ actual := f([]byte(tc.in))
+ if actual == nil && tc.out != nil {
+ t.Errorf("%s(%q) = nil; want %q", funcName, tc.in, tc.out)
+ }
+ if actual != nil && tc.out == nil {
+ t.Errorf("%s(%q) = %q; want nil", funcName, tc.in, actual)
+ }
+ if !Equal(actual, tc.out) {
+ t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
+ }
+ }
+}
+
+func tenRunes(r rune) string {
+ runes := make([]rune, 10)
+ for i := range runes {
+ runes[i] = r
+ }
+ return string(runes)
+}
+
+// User-defined self-inverse mapping function
+func rot13(r rune) rune {
+ const step = 13
+ if r >= 'a' && r <= 'z' {
+ return ((r - 'a' + step) % 26) + 'a'
+ }
+ if r >= 'A' && r <= 'Z' {
+ return ((r - 'A' + step) % 26) + 'A'
+ }
+ return r
+}
+
+func TestMap(t *testing.T) {
+ // Run a couple of awful growth/shrinkage tests
+ a := tenRunes('a')
+
+ // 1. Grow. This triggers two reallocations in Map.
+ maxRune := func(r rune) rune { return unicode.MaxRune }
+ m := Map(maxRune, []byte(a))
+ expect := tenRunes(unicode.MaxRune)
+ if string(m) != expect {
+ t.Errorf("growing: expected %q got %q", expect, m)
+ }
+
+ // 2. Shrink
+ minRune := func(r rune) rune { return 'a' }
+ m = Map(minRune, []byte(tenRunes(unicode.MaxRune)))
+ expect = a
+ if string(m) != expect {
+ t.Errorf("shrinking: expected %q got %q", expect, m)
+ }
+
+ // 3. Rot13
+ m = Map(rot13, []byte("a to zed"))
+ expect = "n gb mrq"
+ if string(m) != expect {
+ t.Errorf("rot13: expected %q got %q", expect, m)
+ }
+
+ // 4. Rot13^2
+ m = Map(rot13, Map(rot13, []byte("a to zed")))
+ expect = "a to zed"
+ if string(m) != expect {
+ t.Errorf("rot13: expected %q got %q", expect, m)
+ }
+
+ // 5. Drop
+ dropNotLatin := func(r rune) rune {
+ if unicode.Is(unicode.Latin, r) {
+ return r
+ }
+ return -1
+ }
+ m = Map(dropNotLatin, []byte("Hello, 세계"))
+ expect = "Hello"
+ if string(m) != expect {
+ t.Errorf("drop: expected %q got %q", expect, m)
+ }
+
+ // 6. Invalid rune
+ invalidRune := func(r rune) rune {
+ return utf8.MaxRune + 1
+ }
+ m = Map(invalidRune, []byte("x"))
+ expect = "\uFFFD"
+ if string(m) != expect {
+ t.Errorf("invalidRune: expected %q got %q", expect, m)
+ }
+}
+
+func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
+
+func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
+
+func BenchmarkToUpper(b *testing.B) {
+ for _, tc := range upperTests {
+ tin := []byte(tc.in)
+ b.Run(tc.in, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ actual := ToUpper(tin)
+ if !Equal(actual, tc.out) {
+ b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkToLower(b *testing.B) {
+ for _, tc := range lowerTests {
+ tin := []byte(tc.in)
+ b.Run(tc.in, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ actual := ToLower(tin)
+ if !Equal(actual, tc.out) {
+ b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out)
+ }
+ }
+ })
+ }
+}
+
+var toValidUTF8Tests = []struct {
+ in string
+ repl string
+ out string
+}{
+ {"", "\uFFFD", ""},
+ {"abc", "\uFFFD", "abc"},
+ {"\uFDDD", "\uFFFD", "\uFDDD"},
+ {"a\xffb", "\uFFFD", "a\uFFFDb"},
+ {"a\xffb\uFFFD", "X", "aXb\uFFFD"},
+ {"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"},
+ {"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"},
+ {"\xC0\xAF", "\uFFFD", "\uFFFD"},
+ {"\xE0\x80\xAF", "\uFFFD", "\uFFFD"},
+ {"\xed\xa0\x80", "abc", "abc"},
+ {"\xed\xbf\xbf", "\uFFFD", "\uFFFD"},
+ {"\xF0\x80\x80\xaf", "☺", "☺"},
+ {"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
+ {"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
+}
+
+func TestToValidUTF8(t *testing.T) {
+ for _, tc := range toValidUTF8Tests {
+ got := ToValidUTF8([]byte(tc.in), []byte(tc.repl))
+ if !Equal(got, []byte(tc.out)) {
+ t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out)
+ }
+ }
+}
+
+func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
+
+type RepeatTest struct {
+ in, out string
+ count int
+}
+
+var longString = "a" + string(make([]byte, 1<<16)) + "z"
+
+var RepeatTests = []RepeatTest{
+ {"", "", 0},
+ {"", "", 1},
+ {"", "", 2},
+ {"-", "", 0},
+ {"-", "-", 1},
+ {"-", "----------", 10},
+ {"abc ", "abc abc abc ", 3},
+ // Tests for results over the chunkLimit
+ {string(rune(0)), string(make([]byte, 1<<16)), 1 << 16},
+ {longString, longString + longString, 2},
+}
+
+func TestRepeat(t *testing.T) {
+ for _, tt := range RepeatTests {
+ tin := []byte(tt.in)
+ tout := []byte(tt.out)
+ a := Repeat(tin, tt.count)
+ if !Equal(a, tout) {
+ t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout)
+ continue
+ }
+ }
+}
+
+func repeat(b []byte, count int) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ switch v := r.(type) {
+ case error:
+ err = v
+ default:
+ err = fmt.Errorf("%s", v)
+ }
+ }
+ }()
+
+ Repeat(b, count)
+
+ return
+}
+
+// See Issue golang.org/issue/16237
+func TestRepeatCatchesOverflow(t *testing.T) {
+ tests := [...]struct {
+ s string
+ count int
+ errStr string
+ }{
+ 0: {"--", -2147483647, "negative"},
+ 1: {"", int(^uint(0) >> 1), ""},
+ 2: {"-", 10, ""},
+ 3: {"gopher", 0, ""},
+ 4: {"-", -1, "negative"},
+ 5: {"--", -102, "negative"},
+ 6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
+ }
+
+ for i, tt := range tests {
+ err := repeat([]byte(tt.s), tt.count)
+ if tt.errStr == "" {
+ if err != nil {
+ t.Errorf("#%d panicked %v", i, err)
+ }
+ continue
+ }
+
+ if err == nil || !strings.Contains(err.Error(), tt.errStr) {
+ t.Errorf("#%d expected %q got %q", i, tt.errStr, err)
+ }
+ }
+}
+
+func runesEqual(a, b []rune) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i, r := range a {
+ if r != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+type RunesTest struct {
+ in string
+ out []rune
+ lossy bool
+}
+
+var RunesTests = []RunesTest{
+ {"", []rune{}, false},
+ {" ", []rune{32}, false},
+ {"ABC", []rune{65, 66, 67}, false},
+ {"abc", []rune{97, 98, 99}, false},
+ {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
+ {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
+ {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
+}
+
+func TestRunes(t *testing.T) {
+ for _, tt := range RunesTests {
+ tin := []byte(tt.in)
+ a := Runes(tin)
+ if !runesEqual(a, tt.out) {
+ t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out)
+ continue
+ }
+ if !tt.lossy {
+ // can only test reassembly if we didn't lose information
+ s := string(a)
+ if s != tt.in {
+ t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin)
+ }
+ }
+ }
+}
+
+type TrimTest struct {
+ f string
+ in, arg, out string
+}
+
+var trimTests = []TrimTest{
+ {"Trim", "abba", "a", "bb"},
+ {"Trim", "abba", "ab", ""},
+ {"TrimLeft", "abba", "ab", ""},
+ {"TrimRight", "abba", "ab", ""},
+ {"TrimLeft", "abba", "a", "bba"},
+ {"TrimLeft", "abba", "b", "abba"},
+ {"TrimRight", "abba", "a", "abb"},
+ {"TrimRight", "abba", "b", "abba"},
+ {"Trim", "", "<>", "tag"},
+ {"Trim", "* listitem", " *", "listitem"},
+ {"Trim", `"quote"`, `"`, "quote"},
+ {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
+ {"Trim", "\x80test\xff", "\xff", "test"},
+ {"Trim", " Ġ ", " ", "Ġ"},
+ {"Trim", " Ġİ0", "0 ", "Ġİ"},
+ //empty string tests
+ {"Trim", "abba", "", "abba"},
+ {"Trim", "", "123", ""},
+ {"Trim", "", "", ""},
+ {"TrimLeft", "abba", "", "abba"},
+ {"TrimLeft", "", "123", ""},
+ {"TrimLeft", "", "", ""},
+ {"TrimRight", "abba", "", "abba"},
+ {"TrimRight", "", "123", ""},
+ {"TrimRight", "", "", ""},
+ {"TrimRight", "☺\xc0", "☺", "☺\xc0"},
+ {"TrimPrefix", "aabb", "a", "abb"},
+ {"TrimPrefix", "aabb", "b", "aabb"},
+ {"TrimSuffix", "aabb", "a", "aabb"},
+ {"TrimSuffix", "aabb", "b", "aab"},
+}
+
+type TrimNilTest struct {
+ f string
+ in []byte
+ arg string
+ out []byte
+}
+
+var trimNilTests = []TrimNilTest{
+ {"Trim", nil, "", nil},
+ {"Trim", []byte{}, "", nil},
+ {"Trim", []byte{'a'}, "a", nil},
+ {"Trim", []byte{'a', 'a'}, "a", nil},
+ {"Trim", []byte{'a'}, "ab", nil},
+ {"Trim", []byte{'a', 'b'}, "ab", nil},
+ {"Trim", []byte("☺"), "☺", nil},
+ {"TrimLeft", nil, "", nil},
+ {"TrimLeft", []byte{}, "", nil},
+ {"TrimLeft", []byte{'a'}, "a", nil},
+ {"TrimLeft", []byte{'a', 'a'}, "a", nil},
+ {"TrimLeft", []byte{'a'}, "ab", nil},
+ {"TrimLeft", []byte{'a', 'b'}, "ab", nil},
+ {"TrimLeft", []byte("☺"), "☺", nil},
+ {"TrimRight", nil, "", nil},
+ {"TrimRight", []byte{}, "", []byte{}},
+ {"TrimRight", []byte{'a'}, "a", []byte{}},
+ {"TrimRight", []byte{'a', 'a'}, "a", []byte{}},
+ {"TrimRight", []byte{'a'}, "ab", []byte{}},
+ {"TrimRight", []byte{'a', 'b'}, "ab", []byte{}},
+ {"TrimRight", []byte("☺"), "☺", []byte{}},
+ {"TrimPrefix", nil, "", nil},
+ {"TrimPrefix", []byte{}, "", []byte{}},
+ {"TrimPrefix", []byte{'a'}, "a", []byte{}},
+ {"TrimPrefix", []byte("☺"), "☺", []byte{}},
+ {"TrimSuffix", nil, "", nil},
+ {"TrimSuffix", []byte{}, "", []byte{}},
+ {"TrimSuffix", []byte{'a'}, "a", []byte{}},
+ {"TrimSuffix", []byte("☺"), "☺", []byte{}},
+}
+
+func TestTrim(t *testing.T) {
+ toFn := func(name string) (func([]byte, string) []byte, func([]byte, []byte) []byte) {
+ switch name {
+ case "Trim":
+ return Trim, nil
+ case "TrimLeft":
+ return TrimLeft, nil
+ case "TrimRight":
+ return TrimRight, nil
+ case "TrimPrefix":
+ return nil, TrimPrefix
+ case "TrimSuffix":
+ return nil, TrimSuffix
+ default:
+ t.Errorf("Undefined trim function %s", name)
+ return nil, nil
+ }
+ }
+
+ for _, tc := range trimTests {
+ name := tc.f
+ f, fb := toFn(name)
+ if f == nil && fb == nil {
+ continue
+ }
+ var actual string
+ if f != nil {
+ actual = string(f([]byte(tc.in), tc.arg))
+ } else {
+ actual = string(fb([]byte(tc.in), []byte(tc.arg)))
+ }
+ if actual != tc.out {
+ t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
+ }
+ }
+
+ for _, tc := range trimNilTests {
+ name := tc.f
+ f, fb := toFn(name)
+ if f == nil && fb == nil {
+ continue
+ }
+ var actual []byte
+ if f != nil {
+ actual = f(tc.in, tc.arg)
+ } else {
+ actual = fb(tc.in, []byte(tc.arg))
+ }
+ report := func(s []byte) string {
+ if s == nil {
+ return "nil"
+ } else {
+ return fmt.Sprintf("%q", s)
+ }
+ }
+ if len(actual) != 0 {
+ t.Errorf("%s(%s, %q) returned non-empty value", name, report(tc.in), tc.arg)
+ } else {
+ actualNil := actual == nil
+ outNil := tc.out == nil
+ if actualNil != outNil {
+ t.Errorf("%s(%s, %q) got nil %t; want nil %t", name, report(tc.in), tc.arg, actualNil, outNil)
+ }
+ }
+ }
+}
+
+type predicate struct {
+ f func(r rune) bool
+ name string
+}
+
+var isSpace = predicate{unicode.IsSpace, "IsSpace"}
+var isDigit = predicate{unicode.IsDigit, "IsDigit"}
+var isUpper = predicate{unicode.IsUpper, "IsUpper"}
+var isValidRune = predicate{
+ func(r rune) bool {
+ return r != utf8.RuneError
+ },
+ "IsValidRune",
+}
+
+type TrimFuncTest struct {
+ f predicate
+ in string
+ trimOut []byte
+ leftOut []byte
+ rightOut []byte
+}
+
+func not(p predicate) predicate {
+ return predicate{
+ func(r rune) bool {
+ return !p.f(r)
+ },
+ "not " + p.name,
+ }
+}
+
+var trimFuncTests = []TrimFuncTest{
+ {isSpace, space + " hello " + space,
+ []byte("hello"),
+ []byte("hello " + space),
+ []byte(space + " hello")},
+ {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51",
+ []byte("hello"),
+ []byte("hello34\u0e50\u0e51"),
+ []byte("\u0e50\u0e5212hello")},
+ {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
+ []byte("hello"),
+ []byte("helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F"),
+ []byte("\u2C6F\u2C6F\u2C6F\u2C6FABCDhello")},
+ {not(isSpace), "hello" + space + "hello",
+ []byte(space),
+ []byte(space + "hello"),
+ []byte("hello" + space)},
+ {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo",
+ []byte("\u0e50\u0e521234\u0e50\u0e51"),
+ []byte("\u0e50\u0e521234\u0e50\u0e51helo"),
+ []byte("hello\u0e50\u0e521234\u0e50\u0e51")},
+ {isValidRune, "ab\xc0a\xc0cd",
+ []byte("\xc0a\xc0"),
+ []byte("\xc0a\xc0cd"),
+ []byte("ab\xc0a\xc0")},
+ {not(isValidRune), "\xc0a\xc0",
+ []byte("a"),
+ []byte("a\xc0"),
+ []byte("\xc0a")},
+ // The nils returned by TrimLeftFunc are odd behavior, but we need
+ // to preserve backwards compatibility.
+ {isSpace, "",
+ nil,
+ nil,
+ []byte("")},
+ {isSpace, " ",
+ nil,
+ nil,
+ []byte("")},
+}
+
+func TestTrimFunc(t *testing.T) {
+ for _, tc := range trimFuncTests {
+ trimmers := []struct {
+ name string
+ trim func(s []byte, f func(r rune) bool) []byte
+ out []byte
+ }{
+ {"TrimFunc", TrimFunc, tc.trimOut},
+ {"TrimLeftFunc", TrimLeftFunc, tc.leftOut},
+ {"TrimRightFunc", TrimRightFunc, tc.rightOut},
+ }
+ for _, trimmer := range trimmers {
+ actual := trimmer.trim([]byte(tc.in), tc.f.f)
+ if actual == nil && trimmer.out != nil {
+ t.Errorf("%s(%q, %q) = nil; want %q", trimmer.name, tc.in, tc.f.name, trimmer.out)
+ }
+ if actual != nil && trimmer.out == nil {
+ t.Errorf("%s(%q, %q) = %q; want nil", trimmer.name, tc.in, tc.f.name, actual)
+ }
+ if !Equal(actual, trimmer.out) {
+ t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out)
+ }
+ }
+ }
+}
+
+type IndexFuncTest struct {
+ in string
+ f predicate
+ first, last int
+}
+
+var indexFuncTests = []IndexFuncTest{
+ {"", isValidRune, -1, -1},
+ {"abc", isDigit, -1, -1},
+ {"0123", isDigit, 0, 3},
+ {"a1b", isDigit, 1, 1},
+ {space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes
+ {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
+ {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
+ {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
+
+ // tests of invalid UTF-8
+ {"\x801", isDigit, 1, 1},
+ {"\x80abc", isDigit, -1, -1},
+ {"\xc0a\xc0", isValidRune, 1, 1},
+ {"\xc0a\xc0", not(isValidRune), 0, 2},
+ {"\xc0☺\xc0", not(isValidRune), 0, 4},
+ {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
+ {"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
+ {"a\xe0\x80cd", not(isValidRune), 1, 2},
+}
+
+func TestIndexFunc(t *testing.T) {
+ for _, tc := range indexFuncTests {
+ first := IndexFunc([]byte(tc.in), tc.f.f)
+ if first != tc.first {
+ t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
+ }
+ last := LastIndexFunc([]byte(tc.in), tc.f.f)
+ if last != tc.last {
+ t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
+ }
+ }
+}
+
+type ReplaceTest struct {
+ in string
+ old, new string
+ n int
+ out string
+}
+
+var ReplaceTests = []ReplaceTest{
+ {"hello", "l", "L", 0, "hello"},
+ {"hello", "l", "L", -1, "heLLo"},
+ {"hello", "x", "X", -1, "hello"},
+ {"", "x", "X", -1, ""},
+ {"radar", "r", "", -1, "ada"},
+ {"", "", "<>", -1, "<>"},
+ {"banana", "a", "<>", -1, "b<>n<>n<>"},
+ {"banana", "a", "<>", 1, "b<>nana"},
+ {"banana", "a", "<>", 1000, "b<>n<>n<>"},
+ {"banana", "an", "<>", -1, "b<><>a"},
+ {"banana", "ana", "<>", -1, "b<>na"},
+ {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
+ {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
+ {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
+ {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
+ {"banana", "", "<>", 1, "<>banana"},
+ {"banana", "a", "a", -1, "banana"},
+ {"banana", "a", "a", 1, "banana"},
+ {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
+}
+
+func TestReplace(t *testing.T) {
+ for _, tt := range ReplaceTests {
+ in := append([]byte(tt.in), ""...)
+ in = in[:len(tt.in)]
+ out := Replace(in, []byte(tt.old), []byte(tt.new), tt.n)
+ if s := string(out); s != tt.out {
+ t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
+ }
+ if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
+ t.Errorf("Replace(%q, %q, %q, %d) didn't copy", tt.in, tt.old, tt.new, tt.n)
+ }
+ if tt.n == -1 {
+ out := ReplaceAll(in, []byte(tt.old), []byte(tt.new))
+ if s := string(out); s != tt.out {
+ t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out)
+ }
+ }
+ }
+}
+
+type TitleTest struct {
+ in, out string
+}
+
+var TitleTests = []TitleTest{
+ {"", ""},
+ {"a", "A"},
+ {" aaa aaa aaa ", " Aaa Aaa Aaa "},
+ {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
+ {"123a456", "123a456"},
+ {"double-blind", "Double-Blind"},
+ {"ÿøû", "Ÿøû"},
+ {"with_underscore", "With_underscore"},
+ {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
+}
+
+func TestTitle(t *testing.T) {
+ for _, tt := range TitleTests {
+ if s := string(Title([]byte(tt.in))); s != tt.out {
+ t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
+ }
+ }
+}
+
+var ToTitleTests = []TitleTest{
+ {"", ""},
+ {"a", "A"},
+ {" aaa aaa aaa ", " AAA AAA AAA "},
+ {" Aaa Aaa Aaa ", " AAA AAA AAA "},
+ {"123a456", "123A456"},
+ {"double-blind", "DOUBLE-BLIND"},
+ {"ÿøû", "ŸØÛ"},
+}
+
+func TestToTitle(t *testing.T) {
+ for _, tt := range ToTitleTests {
+ if s := string(ToTitle([]byte(tt.in))); s != tt.out {
+ t.Errorf("ToTitle(%q) = %q, want %q", tt.in, s, tt.out)
+ }
+ }
+}
+
+var EqualFoldTests = []struct {
+ s, t string
+ out bool
+}{
+ {"abc", "abc", true},
+ {"ABcd", "ABcd", true},
+ {"123abc", "123ABC", true},
+ {"αβδ", "ΑΒΔ", true},
+ {"abc", "xyz", false},
+ {"abc", "XYZ", false},
+ {"abcdefghijk", "abcdefghijX", false},
+ {"abcdefghijk", "abcdefghij\u212A", true},
+ {"abcdefghijK", "abcdefghij\u212A", true},
+ {"abcdefghijkz", "abcdefghij\u212Ay", false},
+ {"abcdefghijKz", "abcdefghij\u212Ay", false},
+}
+
+func TestEqualFold(t *testing.T) {
+ for _, tt := range EqualFoldTests {
+ if out := EqualFold([]byte(tt.s), []byte(tt.t)); out != tt.out {
+ t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
+ }
+ if out := EqualFold([]byte(tt.t), []byte(tt.s)); out != tt.out {
+ t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
+ }
+ }
+}
+
+var cutTests = []struct {
+ s, sep string
+ before, after string
+ found bool
+}{
+ {"abc", "b", "a", "c", true},
+ {"abc", "a", "", "bc", true},
+ {"abc", "c", "ab", "", true},
+ {"abc", "abc", "", "", true},
+ {"abc", "", "", "abc", true},
+ {"abc", "d", "abc", "", false},
+ {"", "d", "", "", false},
+ {"", "", "", "", true},
+}
+
+func TestCut(t *testing.T) {
+ for _, tt := range cutTests {
+ if before, after, found := Cut([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(after) != tt.after || found != tt.found {
+ t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
+ }
+ }
+}
+
+var cutPrefixTests = []struct {
+ s, sep string
+ after string
+ found bool
+}{
+ {"abc", "a", "bc", true},
+ {"abc", "abc", "", true},
+ {"abc", "", "abc", true},
+ {"abc", "d", "abc", false},
+ {"", "d", "", false},
+ {"", "", "", true},
+}
+
+func TestCutPrefix(t *testing.T) {
+ for _, tt := range cutPrefixTests {
+ if after, found := CutPrefix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found {
+ t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
+ }
+ }
+}
+
+var cutSuffixTests = []struct {
+ s, sep string
+ before string
+ found bool
+}{
+ {"abc", "bc", "a", true},
+ {"abc", "abc", "", true},
+ {"abc", "", "abc", true},
+ {"abc", "d", "abc", false},
+ {"", "d", "", false},
+ {"", "", "", true},
+}
+
+func TestCutSuffix(t *testing.T) {
+ for _, tt := range cutSuffixTests {
+ if before, found := CutSuffix([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || found != tt.found {
+ t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found)
+ }
+ }
+}
+
+func TestBufferGrowNegative(t *testing.T) {
+ defer func() {
+ if err := recover(); err == nil {
+ t.Fatal("Grow(-1) should have panicked")
+ }
+ }()
+ var b Buffer
+ b.Grow(-1)
+}
+
+func TestBufferTruncateNegative(t *testing.T) {
+ defer func() {
+ if err := recover(); err == nil {
+ t.Fatal("Truncate(-1) should have panicked")
+ }
+ }()
+ var b Buffer
+ b.Truncate(-1)
+}
+
+func TestBufferTruncateOutOfRange(t *testing.T) {
+ defer func() {
+ if err := recover(); err == nil {
+ t.Fatal("Truncate(20) should have panicked")
+ }
+ }()
+ var b Buffer
+ b.Write(make([]byte, 10))
+ b.Truncate(20)
+}
+
+var containsTests = []struct {
+ b, subslice []byte
+ want bool
+}{
+ {[]byte("hello"), []byte("hel"), true},
+ {[]byte("日本語"), []byte("日本"), true},
+ {[]byte("hello"), []byte("Hello, world"), false},
+ {[]byte("東京"), []byte("京東"), false},
+}
+
+func TestContains(t *testing.T) {
+ for _, tt := range containsTests {
+ if got := Contains(tt.b, tt.subslice); got != tt.want {
+ t.Errorf("Contains(%q, %q) = %v, want %v", tt.b, tt.subslice, got, tt.want)
+ }
+ }
+}
+
+var ContainsAnyTests = []struct {
+ b []byte
+ substr string
+ expected bool
+}{
+ {[]byte(""), "", false},
+ {[]byte(""), "a", false},
+ {[]byte(""), "abc", false},
+ {[]byte("a"), "", false},
+ {[]byte("a"), "a", true},
+ {[]byte("aaa"), "a", true},
+ {[]byte("abc"), "xyz", false},
+ {[]byte("abc"), "xcz", true},
+ {[]byte("a☺b☻c☹d"), "uvw☻xyz", true},
+ {[]byte("aRegExp*"), ".(|)*+?^$[]", true},
+ {[]byte(dots + dots + dots), " ", false},
+}
+
+func TestContainsAny(t *testing.T) {
+ for _, ct := range ContainsAnyTests {
+ if ContainsAny(ct.b, ct.substr) != ct.expected {
+ t.Errorf("ContainsAny(%s, %s) = %v, want %v",
+ ct.b, ct.substr, !ct.expected, ct.expected)
+ }
+ }
+}
+
+var ContainsRuneTests = []struct {
+ b []byte
+ r rune
+ expected bool
+}{
+ {[]byte(""), 'a', false},
+ {[]byte("a"), 'a', true},
+ {[]byte("aaa"), 'a', true},
+ {[]byte("abc"), 'y', false},
+ {[]byte("abc"), 'c', true},
+ {[]byte("a☺b☻c☹d"), 'x', false},
+ {[]byte("a☺b☻c☹d"), '☻', true},
+ {[]byte("aRegExp*"), '*', true},
+}
+
+func TestContainsRune(t *testing.T) {
+ for _, ct := range ContainsRuneTests {
+ if ContainsRune(ct.b, ct.r) != ct.expected {
+ t.Errorf("ContainsRune(%q, %q) = %v, want %v",
+ ct.b, ct.r, !ct.expected, ct.expected)
+ }
+ }
+}
+
+func TestContainsFunc(t *testing.T) {
+ for _, ct := range ContainsRuneTests {
+ if ContainsFunc(ct.b, func(r rune) bool {
+ return ct.r == r
+ }) != ct.expected {
+ t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v",
+ ct.b, ct.r, !ct.expected, ct.expected)
+ }
+ }
+}
+
+var makeFieldsInput = func() []byte {
+ x := make([]byte, 1<<20)
+ // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.
+ for i := range x {
+ switch rand.Intn(10) {
+ case 0:
+ x[i] = ' '
+ case 1:
+ if i > 0 && x[i-1] == 'x' {
+ copy(x[i-1:], "χ")
+ break
+ }
+ fallthrough
+ default:
+ x[i] = 'x'
+ }
+ }
+ return x
+}
+
+var makeFieldsInputASCII = func() []byte {
+ x := make([]byte, 1<<20)
+ // Input is ~10% space, rest ASCII non-space.
+ for i := range x {
+ if rand.Intn(10) == 0 {
+ x[i] = ' '
+ } else {
+ x[i] = 'x'
+ }
+ }
+ return x
+}
+
+var bytesdata = []struct {
+ name string
+ data []byte
+}{
+ {"ASCII", makeFieldsInputASCII()},
+ {"Mixed", makeFieldsInput()},
+}
+
+func BenchmarkFields(b *testing.B) {
+ for _, sd := range bytesdata {
+ b.Run(sd.name, func(b *testing.B) {
+ for j := 1 << 4; j <= 1<<20; j <<= 4 {
+ b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(j))
+ data := sd.data[:j]
+ for i := 0; i < b.N; i++ {
+ Fields(data)
+ }
+ })
+ }
+ })
+ }
+}
+
+func BenchmarkFieldsFunc(b *testing.B) {
+ for _, sd := range bytesdata {
+ b.Run(sd.name, func(b *testing.B) {
+ for j := 1 << 4; j <= 1<<20; j <<= 4 {
+ b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(j))
+ data := sd.data[:j]
+ for i := 0; i < b.N; i++ {
+ FieldsFunc(data, unicode.IsSpace)
+ }
+ })
+ }
+ })
+ }
+}
+
+func BenchmarkTrimSpace(b *testing.B) {
+ tests := []struct {
+ name string
+ input []byte
+ }{
+ {"NoTrim", []byte("typical")},
+ {"ASCII", []byte(" foo bar ")},
+ {"SomeNonASCII", []byte(" \u2000\t\r\n x\t\t\r\r\ny\n \u3000 ")},
+ {"JustNonASCII", []byte("\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000")},
+ }
+ for _, test := range tests {
+ b.Run(test.name, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ TrimSpace(test.input)
+ }
+ })
+ }
+}
+
+func BenchmarkToValidUTF8(b *testing.B) {
+ tests := []struct {
+ name string
+ input []byte
+ }{
+ {"Valid", []byte("typical")},
+ {"InvalidASCII", []byte("foo\xffbar")},
+ {"InvalidNonASCII", []byte("日本語\xff日本語")},
+ }
+ replacement := []byte("\uFFFD")
+ b.ResetTimer()
+ for _, test := range tests {
+ b.Run(test.name, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ ToValidUTF8(test.input, replacement)
+ }
+ })
+ }
+}
+
+func makeBenchInputHard() []byte {
+ tokens := [...]string{
+ "", "", "", "",
+ "
", "
", "", "",
+ "hello", "world",
+ }
+ x := make([]byte, 0, 1<<20)
+ for {
+ i := rand.Intn(len(tokens))
+ if len(x)+len(tokens[i]) >= 1<<20 {
+ break
+ }
+ x = append(x, tokens[i]...)
+ }
+ return x
+}
+
+var benchInputHard = makeBenchInputHard()
+
+func benchmarkIndexHard(b *testing.B, sep []byte) {
+ for i := 0; i < b.N; i++ {
+ Index(benchInputHard, sep)
+ }
+}
+
+func benchmarkLastIndexHard(b *testing.B, sep []byte) {
+ for i := 0; i < b.N; i++ {
+ LastIndex(benchInputHard, sep)
+ }
+}
+
+func benchmarkCountHard(b *testing.B, sep []byte) {
+ for i := 0; i < b.N; i++ {
+ Count(benchInputHard, sep)
+ }
+}
+
+func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, []byte("<>")) }
+func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, []byte("")) }
+func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, []byte("hello world")) }
+func BenchmarkIndexHard4(b *testing.B) {
+ benchmarkIndexHard(b, []byte("helloworld
"))
+}
+
+func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, []byte("<>")) }
+func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, []byte("")) }
+func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, []byte("hello world")) }
+
+func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, []byte("<>")) }
+func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, []byte("")) }
+func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, []byte("hello world")) }
+
+func BenchmarkSplitEmptySeparator(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Split(benchInputHard, nil)
+ }
+}
+
+func BenchmarkSplitSingleByteSeparator(b *testing.B) {
+ sep := []byte("/")
+ for i := 0; i < b.N; i++ {
+ Split(benchInputHard, sep)
+ }
+}
+
+func BenchmarkSplitMultiByteSeparator(b *testing.B) {
+ sep := []byte("hello")
+ for i := 0; i < b.N; i++ {
+ Split(benchInputHard, sep)
+ }
+}
+
+func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
+ sep := []byte("/")
+ for i := 0; i < b.N; i++ {
+ SplitN(benchInputHard, sep, 10)
+ }
+}
+
+func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
+ sep := []byte("hello")
+ for i := 0; i < b.N; i++ {
+ SplitN(benchInputHard, sep, 10)
+ }
+}
+
+func BenchmarkRepeat(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ Repeat([]byte("-"), 80)
+ }
+}
+
+func BenchmarkRepeatLarge(b *testing.B) {
+ s := Repeat([]byte("@"), 8*1024)
+ for j := 8; j <= 30; j++ {
+ for _, k := range []int{1, 16, 4097} {
+ s := s[:k]
+ n := (1 << j) / k
+ if n == 0 {
+ continue
+ }
+ b.Run(fmt.Sprintf("%d/%d", 1< b[:1] failed")
+ }
+}
+
+func TestCompareBytes(t *testing.T) {
+ lengths := make([]int, 0) // lengths to test in ascending order
+ for i := 0; i <= 128; i++ {
+ lengths = append(lengths, i)
+ }
+ lengths = append(lengths, 256, 512, 1024, 1333, 4095, 4096, 4097)
+
+ if !testing.Short() {
+ lengths = append(lengths, 65535, 65536, 65537, 99999)
+ }
+
+ n := lengths[len(lengths)-1]
+ a := make([]byte, n+1)
+ b := make([]byte, n+1)
+ for _, len := range lengths {
+ // randomish but deterministic data. No 0 or 255.
+ for i := 0; i < len; i++ {
+ a[i] = byte(1 + 31*i%254)
+ b[i] = byte(1 + 31*i%254)
+ }
+ // data past the end is different
+ for i := len; i <= n; i++ {
+ a[i] = 8
+ b[i] = 9
+ }
+ cmp := Compare(a[:len], b[:len])
+ if cmp != 0 {
+ t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
+ }
+ if len > 0 {
+ cmp = Compare(a[:len-1], b[:len])
+ if cmp != -1 {
+ t.Errorf(`CompareAshorter(%d) = %d`, len, cmp)
+ }
+ cmp = Compare(a[:len], b[:len-1])
+ if cmp != 1 {
+ t.Errorf(`CompareBshorter(%d) = %d`, len, cmp)
+ }
+ }
+ for k := 0; k < len; k++ {
+ b[k] = a[k] - 1
+ cmp = Compare(a[:len], b[:len])
+ if cmp != 1 {
+ t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
+ }
+ b[k] = a[k] + 1
+ cmp = Compare(a[:len], b[:len])
+ if cmp != -1 {
+ t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)
+ }
+ b[k] = a[k]
+ }
+ }
+}
+
+func TestEndianBaseCompare(t *testing.T) {
+ // This test compares byte slices that are almost identical, except one
+ // difference that for some j, a[j]>b[j] and a[j+1] b2 failed")
+ }
+ }
+}
+
+func BenchmarkCompareBytesEmpty(b *testing.B) {
+ b1 := []byte("")
+ b2 := b1
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+}
+
+func BenchmarkCompareBytesIdentical(b *testing.B) {
+ b1 := []byte("Hello Gophers!")
+ b2 := b1
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+}
+
+func BenchmarkCompareBytesSameLength(b *testing.B) {
+ b1 := []byte("Hello Gophers!")
+ b2 := []byte("Hello, Gophers")
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != -1 {
+ b.Fatal("b1 < b2 failed")
+ }
+ }
+}
+
+func BenchmarkCompareBytesDifferentLength(b *testing.B) {
+ b1 := []byte("Hello Gophers!")
+ b2 := []byte("Hello, Gophers!")
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != -1 {
+ b.Fatal("b1 < b2 failed")
+ }
+ }
+}
+
+func benchmarkCompareBytesBigUnaligned(b *testing.B, offset int) {
+ b.StopTimer()
+ b1 := make([]byte, 0, 1<<20)
+ for len(b1) < 1<<20 {
+ b1 = append(b1, "Hello Gophers!"...)
+ }
+ b2 := append([]byte("12345678")[:offset], b1...)
+ b.StartTimer()
+ for j := 0; j < b.N; j++ {
+ if Compare(b1, b2[offset:]) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+ b.SetBytes(int64(len(b1)))
+}
+
+func BenchmarkCompareBytesBigUnaligned(b *testing.B) {
+ for i := 1; i < 8; i++ {
+ b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) {
+ benchmarkCompareBytesBigUnaligned(b, i)
+ })
+ }
+}
+
+func benchmarkCompareBytesBigBothUnaligned(b *testing.B, offset int) {
+ b.StopTimer()
+ pattern := []byte("Hello Gophers!")
+ b1 := make([]byte, 0, 1<<20+len(pattern))
+ for len(b1) < 1<<20 {
+ b1 = append(b1, pattern...)
+ }
+ b2 := make([]byte, len(b1))
+ copy(b2, b1)
+ b.StartTimer()
+ for j := 0; j < b.N; j++ {
+ if Compare(b1[offset:], b2[offset:]) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+ b.SetBytes(int64(len(b1[offset:])))
+}
+
+func BenchmarkCompareBytesBigBothUnaligned(b *testing.B) {
+ for i := 0; i < 8; i++ {
+ b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) {
+ benchmarkCompareBytesBigBothUnaligned(b, i)
+ })
+ }
+}
+
+func BenchmarkCompareBytesBig(b *testing.B) {
+ b.StopTimer()
+ b1 := make([]byte, 0, 1<<20)
+ for len(b1) < 1<<20 {
+ b1 = append(b1, "Hello Gophers!"...)
+ }
+ b2 := append([]byte{}, b1...)
+ b.StartTimer()
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+ b.SetBytes(int64(len(b1)))
+}
+
+func BenchmarkCompareBytesBigIdentical(b *testing.B) {
+ b.StopTimer()
+ b1 := make([]byte, 0, 1<<20)
+ for len(b1) < 1<<20 {
+ b1 = append(b1, "Hello Gophers!"...)
+ }
+ b2 := b1
+ b.StartTimer()
+ for i := 0; i < b.N; i++ {
+ if Compare(b1, b2) != 0 {
+ b.Fatal("b1 != b2")
+ }
+ }
+ b.SetBytes(int64(len(b1)))
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/example_test.go b/platform/dbops/binaries/go/go/src/bytes/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5a66b1e43695948fbad95d555181a57c52bcaf68
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/example_test.go
@@ -0,0 +1,633 @@
+// 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 bytes_test
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "strconv"
+ "unicode"
+)
+
+func ExampleBuffer() {
+ var b bytes.Buffer // A Buffer needs no initialization.
+ b.Write([]byte("Hello "))
+ fmt.Fprintf(&b, "world!")
+ b.WriteTo(os.Stdout)
+ // Output: Hello world!
+}
+
+func ExampleBuffer_reader() {
+ // A Buffer can turn a string or a []byte into an io.Reader.
+ buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
+ dec := base64.NewDecoder(base64.StdEncoding, buf)
+ io.Copy(os.Stdout, dec)
+ // Output: Gophers rule!
+}
+
+func ExampleBuffer_Bytes() {
+ buf := bytes.Buffer{}
+ buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
+ os.Stdout.Write(buf.Bytes())
+ // Output: hello world
+}
+
+func ExampleBuffer_AvailableBuffer() {
+ var buf bytes.Buffer
+ for i := 0; i < 4; i++ {
+ b := buf.AvailableBuffer()
+ b = strconv.AppendInt(b, int64(i), 10)
+ b = append(b, ' ')
+ buf.Write(b)
+ }
+ os.Stdout.Write(buf.Bytes())
+ // Output: 0 1 2 3
+}
+
+func ExampleBuffer_Cap() {
+ buf1 := bytes.NewBuffer(make([]byte, 10))
+ buf2 := bytes.NewBuffer(make([]byte, 0, 10))
+ fmt.Println(buf1.Cap())
+ fmt.Println(buf2.Cap())
+ // Output:
+ // 10
+ // 10
+}
+
+func ExampleBuffer_Grow() {
+ var b bytes.Buffer
+ b.Grow(64)
+ bb := b.Bytes()
+ b.Write([]byte("64 bytes or fewer"))
+ fmt.Printf("%q", bb[:b.Len()])
+ // Output: "64 bytes or fewer"
+}
+
+func ExampleBuffer_Len() {
+ var b bytes.Buffer
+ b.Grow(64)
+ b.Write([]byte("abcde"))
+ fmt.Printf("%d", b.Len())
+ // Output: 5
+}
+
+func ExampleBuffer_Next() {
+ var b bytes.Buffer
+ b.Grow(64)
+ b.Write([]byte("abcde"))
+ fmt.Printf("%s\n", b.Next(2))
+ fmt.Printf("%s\n", b.Next(2))
+ fmt.Printf("%s", b.Next(2))
+ // Output:
+ // ab
+ // cd
+ // e
+}
+
+func ExampleBuffer_Read() {
+ var b bytes.Buffer
+ b.Grow(64)
+ b.Write([]byte("abcde"))
+ rdbuf := make([]byte, 1)
+ n, err := b.Read(rdbuf)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(n)
+ fmt.Println(b.String())
+ fmt.Println(string(rdbuf))
+ // Output
+ // 1
+ // bcde
+ // a
+}
+
+func ExampleBuffer_ReadByte() {
+ var b bytes.Buffer
+ b.Grow(64)
+ b.Write([]byte("abcde"))
+ c, err := b.ReadByte()
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(c)
+ fmt.Println(b.String())
+ // Output
+ // 97
+ // bcde
+}
+
+func ExampleClone() {
+ b := []byte("abc")
+ clone := bytes.Clone(b)
+ fmt.Printf("%s\n", clone)
+ clone[0] = 'd'
+ fmt.Printf("%s\n", b)
+ fmt.Printf("%s\n", clone)
+ // Output:
+ // abc
+ // abc
+ // dbc
+}
+
+func ExampleCompare() {
+ // Interpret Compare's result by comparing it to zero.
+ var a, b []byte
+ if bytes.Compare(a, b) < 0 {
+ // a less b
+ }
+ if bytes.Compare(a, b) <= 0 {
+ // a less or equal b
+ }
+ if bytes.Compare(a, b) > 0 {
+ // a greater b
+ }
+ if bytes.Compare(a, b) >= 0 {
+ // a greater or equal b
+ }
+
+ // Prefer Equal to Compare for equality comparisons.
+ if bytes.Equal(a, b) {
+ // a equal b
+ }
+ if !bytes.Equal(a, b) {
+ // a not equal b
+ }
+}
+
+func ExampleCompare_search() {
+ // Binary search to find a matching byte slice.
+ var needle []byte
+ var haystack [][]byte // Assume sorted
+ i := sort.Search(len(haystack), func(i int) bool {
+ // Return haystack[i] >= needle.
+ return bytes.Compare(haystack[i], needle) >= 0
+ })
+ if i < len(haystack) && bytes.Equal(haystack[i], needle) {
+ // Found it!
+ }
+}
+
+func ExampleContains() {
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
+ fmt.Println(bytes.Contains([]byte(""), []byte("")))
+ // Output:
+ // true
+ // false
+ // true
+ // true
+}
+
+func ExampleContainsAny() {
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
+ fmt.Println(bytes.ContainsAny([]byte(""), ""))
+ // Output:
+ // true
+ // true
+ // false
+ // false
+}
+
+func ExampleContainsRune() {
+ fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
+ fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
+ fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
+ fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
+ fmt.Println(bytes.ContainsRune([]byte(""), '@'))
+ // Output:
+ // true
+ // false
+ // true
+ // true
+ // false
+}
+
+func ExampleContainsFunc() {
+ f := func(r rune) bool {
+ return r >= 'a' && r <= 'z'
+ }
+ fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
+ fmt.Println(bytes.ContainsFunc([]byte("World"), f))
+ // Output:
+ // false
+ // true
+}
+
+func ExampleCount() {
+ fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
+ fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
+ // Output:
+ // 3
+ // 5
+}
+
+func ExampleCut() {
+ show := func(s, sep string) {
+ before, after, found := bytes.Cut([]byte(s), []byte(sep))
+ fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
+ }
+ show("Gopher", "Go")
+ show("Gopher", "ph")
+ show("Gopher", "er")
+ show("Gopher", "Badger")
+ // Output:
+ // Cut("Gopher", "Go") = "", "pher", true
+ // Cut("Gopher", "ph") = "Go", "er", true
+ // Cut("Gopher", "er") = "Goph", "", true
+ // Cut("Gopher", "Badger") = "Gopher", "", false
+}
+
+func ExampleCutPrefix() {
+ show := func(s, sep string) {
+ after, found := bytes.CutPrefix([]byte(s), []byte(sep))
+ fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
+ }
+ show("Gopher", "Go")
+ show("Gopher", "ph")
+ // Output:
+ // CutPrefix("Gopher", "Go") = "pher", true
+ // CutPrefix("Gopher", "ph") = "Gopher", false
+}
+
+func ExampleCutSuffix() {
+ show := func(s, sep string) {
+ before, found := bytes.CutSuffix([]byte(s), []byte(sep))
+ fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found)
+ }
+ show("Gopher", "Go")
+ show("Gopher", "er")
+ // Output:
+ // CutSuffix("Gopher", "Go") = "Gopher", false
+ // CutSuffix("Gopher", "er") = "Goph", true
+}
+
+func ExampleEqual() {
+ fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
+ fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
+ // Output:
+ // true
+ // false
+}
+
+func ExampleEqualFold() {
+ fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
+ // Output: true
+}
+
+func ExampleFields() {
+ fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz ")))
+ // Output: Fields are: ["foo" "bar" "baz"]
+}
+
+func ExampleFieldsFunc() {
+ f := func(c rune) bool {
+ return !unicode.IsLetter(c) && !unicode.IsNumber(c)
+ }
+ fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f))
+ // Output: Fields are: ["foo1" "bar2" "baz3"]
+}
+
+func ExampleHasPrefix() {
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
+ // Output:
+ // true
+ // false
+ // true
+}
+
+func ExampleHasSuffix() {
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
+ // Output:
+ // true
+ // false
+ // false
+ // true
+}
+
+func ExampleIndex() {
+ fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
+ fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
+ // Output:
+ // 4
+ // -1
+}
+
+func ExampleIndexByte() {
+ fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
+ fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
+ // Output:
+ // 4
+ // -1
+}
+
+func ExampleIndexFunc() {
+ f := func(c rune) bool {
+ return unicode.Is(unicode.Han, c)
+ }
+ fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
+ fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
+ // Output:
+ // 7
+ // -1
+}
+
+func ExampleIndexAny() {
+ fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
+ fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
+ // Output:
+ // 2
+ // -1
+}
+
+func ExampleIndexRune() {
+ fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
+ fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
+ // Output:
+ // 4
+ // -1
+}
+
+func ExampleJoin() {
+ s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
+ fmt.Printf("%s", bytes.Join(s, []byte(", ")))
+ // Output: foo, bar, baz
+}
+
+func ExampleLastIndex() {
+ fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
+ fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
+ fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
+ // Output:
+ // 0
+ // 3
+ // -1
+}
+
+func ExampleLastIndexAny() {
+ fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
+ fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
+ fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
+ // Output:
+ // 5
+ // 3
+ // -1
+}
+
+func ExampleLastIndexByte() {
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
+ // Output:
+ // 3
+ // 8
+ // -1
+}
+
+func ExampleLastIndexFunc() {
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
+ // Output:
+ // 8
+ // 9
+ // -1
+}
+
+func ExampleMap() {
+ rot13 := func(r rune) rune {
+ switch {
+ case r >= 'A' && r <= 'Z':
+ return 'A' + (r-'A'+13)%26
+ case r >= 'a' && r <= 'z':
+ return 'a' + (r-'a'+13)%26
+ }
+ return r
+ }
+ fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
+ // Output:
+ // 'Gjnf oevyyvt naq gur fyvgul tbcure...
+}
+
+func ExampleReader_Len() {
+ fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
+ fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
+ // Output:
+ // 3
+ // 16
+}
+
+func ExampleRepeat() {
+ fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
+ // Output: banana
+}
+
+func ExampleReplace() {
+ fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
+ fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
+ // Output:
+ // oinky oinky oink
+ // moo moo moo
+}
+
+func ExampleReplaceAll() {
+ fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
+ // Output:
+ // moo moo moo
+}
+
+func ExampleRunes() {
+ rs := bytes.Runes([]byte("go gopher"))
+ for _, r := range rs {
+ fmt.Printf("%#U\n", r)
+ }
+ // Output:
+ // U+0067 'g'
+ // U+006F 'o'
+ // U+0020 ' '
+ // U+0067 'g'
+ // U+006F 'o'
+ // U+0070 'p'
+ // U+0068 'h'
+ // U+0065 'e'
+ // U+0072 'r'
+}
+
+func ExampleSplit() {
+ fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
+ fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
+ fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
+ fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
+ // Output:
+ // ["a" "b" "c"]
+ // ["" "man " "plan " "canal panama"]
+ // [" " "x" "y" "z" " "]
+ // [""]
+}
+
+func ExampleSplitN() {
+ fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
+ z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
+ fmt.Printf("%q (nil = %v)\n", z, z == nil)
+ // Output:
+ // ["a" "b,c"]
+ // [] (nil = true)
+}
+
+func ExampleSplitAfter() {
+ fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
+ // Output: ["a," "b," "c"]
+}
+
+func ExampleSplitAfterN() {
+ fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
+ // Output: ["a," "b,c"]
+}
+
+func ExampleTitle() {
+ fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
+ // Output: Her Royal Highness
+}
+
+func ExampleToTitle() {
+ fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
+ fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))
+ // Output:
+ // LOUD NOISES
+ // ХЛЕБ
+}
+
+func ExampleToTitleSpecial() {
+ str := []byte("ahoj vývojári golang")
+ totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
+ fmt.Println("Original : " + string(str))
+ fmt.Println("ToTitle : " + string(totitle))
+ // Output:
+ // Original : ahoj vývojári golang
+ // ToTitle : AHOJ VÝVOJÁRİ GOLANG
+}
+
+func ExampleToValidUTF8() {
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
+ // Output:
+ // abc
+ // abc
+ // abc
+}
+
+func ExampleTrim() {
+ fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
+ // Output: ["Achtung! Achtung"]
+}
+
+func ExampleTrimFunc() {
+ fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
+ fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
+ fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
+ fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+ // Output:
+ // -gopher!
+ // "go-gopher!"
+ // go-gopher
+ // go-gopher!
+}
+
+func ExampleTrimLeft() {
+ fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
+ // Output:
+ // gopher8257
+}
+
+func ExampleTrimLeftFunc() {
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+ // Output:
+ // -gopher
+ // go-gopher!
+ // go-gopher!567
+}
+
+func ExampleTrimPrefix() {
+ var b = []byte("Goodbye,, world!")
+ b = bytes.TrimPrefix(b, []byte("Goodbye,"))
+ b = bytes.TrimPrefix(b, []byte("See ya,"))
+ fmt.Printf("Hello%s", b)
+ // Output: Hello, world!
+}
+
+func ExampleTrimSpace() {
+ fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
+ // Output: a lone gopher
+}
+
+func ExampleTrimSuffix() {
+ var b = []byte("Hello, goodbye, etc!")
+ b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
+ b = bytes.TrimSuffix(b, []byte("gopher"))
+ b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
+ os.Stdout.Write(b)
+ // Output: Hello, world!
+}
+
+func ExampleTrimRight() {
+ fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
+ // Output:
+ // 453gopher
+}
+
+func ExampleTrimRightFunc() {
+ fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
+ fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
+ fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
+ // Output:
+ // go-
+ // go-gopher
+ // 1234go-gopher!
+}
+
+func ExampleToLower() {
+ fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
+ // Output: gopher
+}
+
+func ExampleToLowerSpecial() {
+ str := []byte("AHOJ VÝVOJÁRİ GOLANG")
+ totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
+ fmt.Println("Original : " + string(str))
+ fmt.Println("ToLower : " + string(totitle))
+ // Output:
+ // Original : AHOJ VÝVOJÁRİ GOLANG
+ // ToLower : ahoj vývojári golang
+}
+
+func ExampleToUpper() {
+ fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
+ // Output: GOPHER
+}
+
+func ExampleToUpperSpecial() {
+ str := []byte("ahoj vývojári golang")
+ totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
+ fmt.Println("Original : " + string(str))
+ fmt.Println("ToUpper : " + string(totitle))
+ // Output:
+ // Original : ahoj vývojári golang
+ // ToUpper : AHOJ VÝVOJÁRİ GOLANG
+}
diff --git a/platform/dbops/binaries/go/go/src/bytes/export_test.go b/platform/dbops/binaries/go/go/src/bytes/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b65428d9ce84894e05ecd063fa2a53b803a2c9f8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/export_test.go
@@ -0,0 +1,8 @@
+// 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 bytes
+
+// Export func for testing
+var IndexBytePortable = indexBytePortable
diff --git a/platform/dbops/binaries/go/go/src/bytes/reader.go b/platform/dbops/binaries/go/go/src/bytes/reader.go
new file mode 100644
index 0000000000000000000000000000000000000000..9ef49014edfa98b3d33b8b56732d9c5373d9416f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/reader.go
@@ -0,0 +1,159 @@
+// 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 bytes
+
+import (
+ "errors"
+ "io"
+ "unicode/utf8"
+)
+
+// A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker,
+// io.ByteScanner, and io.RuneScanner interfaces by reading from
+// a byte slice.
+// Unlike a [Buffer], a Reader is read-only and supports seeking.
+// The zero value for Reader operates like a Reader of an empty slice.
+type Reader struct {
+ s []byte
+ i int64 // current reading index
+ prevRune int // index of previous rune; or < 0
+}
+
+// Len returns the number of bytes of the unread portion of the
+// slice.
+func (r *Reader) Len() int {
+ if r.i >= int64(len(r.s)) {
+ return 0
+ }
+ return int(int64(len(r.s)) - r.i)
+}
+
+// Size returns the original length of the underlying byte slice.
+// Size is the number of bytes available for reading via [Reader.ReadAt].
+// The result is unaffected by any method calls except [Reader.Reset].
+func (r *Reader) Size() int64 { return int64(len(r.s)) }
+
+// Read implements the [io.Reader] interface.
+func (r *Reader) Read(b []byte) (n int, err error) {
+ if r.i >= int64(len(r.s)) {
+ return 0, io.EOF
+ }
+ r.prevRune = -1
+ n = copy(b, r.s[r.i:])
+ r.i += int64(n)
+ return
+}
+
+// ReadAt implements the [io.ReaderAt] interface.
+func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) {
+ // cannot modify state - see io.ReaderAt
+ if off < 0 {
+ return 0, errors.New("bytes.Reader.ReadAt: negative offset")
+ }
+ if off >= int64(len(r.s)) {
+ return 0, io.EOF
+ }
+ n = copy(b, r.s[off:])
+ if n < len(b) {
+ err = io.EOF
+ }
+ return
+}
+
+// ReadByte implements the [io.ByteReader] interface.
+func (r *Reader) ReadByte() (byte, error) {
+ r.prevRune = -1
+ if r.i >= int64(len(r.s)) {
+ return 0, io.EOF
+ }
+ b := r.s[r.i]
+ r.i++
+ return b, nil
+}
+
+// UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface.
+func (r *Reader) UnreadByte() error {
+ if r.i <= 0 {
+ return errors.New("bytes.Reader.UnreadByte: at beginning of slice")
+ }
+ r.prevRune = -1
+ r.i--
+ return nil
+}
+
+// ReadRune implements the [io.RuneReader] interface.
+func (r *Reader) ReadRune() (ch rune, size int, err error) {
+ if r.i >= int64(len(r.s)) {
+ r.prevRune = -1
+ return 0, 0, io.EOF
+ }
+ r.prevRune = int(r.i)
+ if c := r.s[r.i]; c < utf8.RuneSelf {
+ r.i++
+ return rune(c), 1, nil
+ }
+ ch, size = utf8.DecodeRune(r.s[r.i:])
+ r.i += int64(size)
+ return
+}
+
+// UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface.
+func (r *Reader) UnreadRune() error {
+ if r.i <= 0 {
+ return errors.New("bytes.Reader.UnreadRune: at beginning of slice")
+ }
+ if r.prevRune < 0 {
+ return errors.New("bytes.Reader.UnreadRune: previous operation was not ReadRune")
+ }
+ r.i = int64(r.prevRune)
+ r.prevRune = -1
+ return nil
+}
+
+// Seek implements the [io.Seeker] interface.
+func (r *Reader) Seek(offset int64, whence int) (int64, error) {
+ r.prevRune = -1
+ var abs int64
+ switch whence {
+ case io.SeekStart:
+ abs = offset
+ case io.SeekCurrent:
+ abs = r.i + offset
+ case io.SeekEnd:
+ abs = int64(len(r.s)) + offset
+ default:
+ return 0, errors.New("bytes.Reader.Seek: invalid whence")
+ }
+ if abs < 0 {
+ return 0, errors.New("bytes.Reader.Seek: negative position")
+ }
+ r.i = abs
+ return abs, nil
+}
+
+// WriteTo implements the [io.WriterTo] interface.
+func (r *Reader) WriteTo(w io.Writer) (n int64, err error) {
+ r.prevRune = -1
+ if r.i >= int64(len(r.s)) {
+ return 0, nil
+ }
+ b := r.s[r.i:]
+ m, err := w.Write(b)
+ if m > len(b) {
+ panic("bytes.Reader.WriteTo: invalid Write count")
+ }
+ r.i += int64(m)
+ n = int64(m)
+ if m != len(b) && err == nil {
+ err = io.ErrShortWrite
+ }
+ return
+}
+
+// Reset resets the [Reader.Reader] to be reading from b.
+func (r *Reader) Reset(b []byte) { *r = Reader{b, 0, -1} }
+
+// NewReader returns a new [Reader.Reader] reading from b.
+func NewReader(b []byte) *Reader { return &Reader{b, 0, -1} }
diff --git a/platform/dbops/binaries/go/go/src/bytes/reader_test.go b/platform/dbops/binaries/go/go/src/bytes/reader_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9119c944ace4783ebb9fb3295beb7be23336e009
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/bytes/reader_test.go
@@ -0,0 +1,319 @@
+// 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 bytes_test
+
+import (
+ . "bytes"
+ "fmt"
+ "io"
+ "sync"
+ "testing"
+)
+
+func TestReader(t *testing.T) {
+ r := NewReader([]byte("0123456789"))
+ tests := []struct {
+ off int64
+ seek int
+ n int
+ want string
+ wantpos int64
+ readerr error
+ seekerr string
+ }{
+ {seek: io.SeekStart, off: 0, n: 20, want: "0123456789"},
+ {seek: io.SeekStart, off: 1, n: 1, want: "1"},
+ {seek: io.SeekCurrent, off: 1, wantpos: 3, n: 2, want: "34"},
+ {seek: io.SeekStart, off: -1, seekerr: "bytes.Reader.Seek: negative position"},
+ {seek: io.SeekStart, off: 1 << 33, wantpos: 1 << 33, readerr: io.EOF},
+ {seek: io.SeekCurrent, off: 1, wantpos: 1<<33 + 1, readerr: io.EOF},
+ {seek: io.SeekStart, n: 5, want: "01234"},
+ {seek: io.SeekCurrent, n: 5, want: "56789"},
+ {seek: io.SeekEnd, off: -1, n: 1, wantpos: 9, want: "9"},
+ }
+
+ for i, tt := range tests {
+ pos, err := r.Seek(tt.off, tt.seek)
+ if err == nil && tt.seekerr != "" {
+ t.Errorf("%d. want seek error %q", i, tt.seekerr)
+ continue
+ }
+ if err != nil && err.Error() != tt.seekerr {
+ t.Errorf("%d. seek error = %q; want %q", i, err.Error(), tt.seekerr)
+ continue
+ }
+ if tt.wantpos != 0 && tt.wantpos != pos {
+ t.Errorf("%d. pos = %d, want %d", i, pos, tt.wantpos)
+ }
+ buf := make([]byte, tt.n)
+ n, err := r.Read(buf)
+ if err != tt.readerr {
+ t.Errorf("%d. read = %v; want %v", i, err, tt.readerr)
+ continue
+ }
+ got := string(buf[:n])
+ if got != tt.want {
+ t.Errorf("%d. got %q; want %q", i, got, tt.want)
+ }
+ }
+}
+
+func TestReadAfterBigSeek(t *testing.T) {
+ r := NewReader([]byte("0123456789"))
+ if _, err := r.Seek(1<<31+5, io.SeekStart); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := r.Read(make([]byte, 10)); n != 0 || err != io.EOF {
+ t.Errorf("Read = %d, %v; want 0, EOF", n, err)
+ }
+}
+
+func TestReaderAt(t *testing.T) {
+ r := NewReader([]byte("0123456789"))
+ tests := []struct {
+ off int64
+ n int
+ want string
+ wanterr any
+ }{
+ {0, 10, "0123456789", nil},
+ {1, 10, "123456789", io.EOF},
+ {1, 9, "123456789", nil},
+ {11, 10, "", io.EOF},
+ {0, 0, "", nil},
+ {-1, 0, "", "bytes.Reader.ReadAt: negative offset"},
+ }
+ for i, tt := range tests {
+ b := make([]byte, tt.n)
+ rn, err := r.ReadAt(b, tt.off)
+ got := string(b[:rn])
+ if got != tt.want {
+ t.Errorf("%d. got %q; want %q", i, got, tt.want)
+ }
+ if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", tt.wanterr) {
+ t.Errorf("%d. got error = %v; want %v", i, err, tt.wanterr)
+ }
+ }
+}
+
+func TestReaderAtConcurrent(t *testing.T) {
+ // Test for the race detector, to verify ReadAt doesn't mutate
+ // any state.
+ r := NewReader([]byte("0123456789"))
+ var wg sync.WaitGroup
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ var buf [1]byte
+ r.ReadAt(buf[:], int64(i))
+ }(i)
+ }
+ wg.Wait()
+}
+
+func TestEmptyReaderConcurrent(t *testing.T) {
+ // Test for the race detector, to verify a Read that doesn't yield any bytes
+ // is okay to use from multiple goroutines. This was our historic behavior.
+ // See golang.org/issue/7856
+ r := NewReader([]byte{})
+ var wg sync.WaitGroup
+ for i := 0; i < 5; i++ {
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ var buf [1]byte
+ r.Read(buf[:])
+ }()
+ go func() {
+ defer wg.Done()
+ r.Read(nil)
+ }()
+ }
+ wg.Wait()
+}
+
+func TestReaderWriteTo(t *testing.T) {
+ for i := 0; i < 30; i += 3 {
+ var l int
+ if i > 0 {
+ l = len(testString) / i
+ }
+ s := testString[:l]
+ r := NewReader(testBytes[:l])
+ var b Buffer
+ n, err := r.WriteTo(&b)
+ if expect := int64(len(s)); n != expect {
+ t.Errorf("got %v; want %v", n, expect)
+ }
+ if err != nil {
+ t.Errorf("for length %d: got error = %v; want nil", l, err)
+ }
+ if b.String() != s {
+ t.Errorf("got string %q; want %q", b.String(), s)
+ }
+ if r.Len() != 0 {
+ t.Errorf("reader contains %v bytes; want 0", r.Len())
+ }
+ }
+}
+
+func TestReaderLen(t *testing.T) {
+ const data = "hello world"
+ r := NewReader([]byte(data))
+ if got, want := r.Len(), 11; got != want {
+ t.Errorf("r.Len(): got %d, want %d", got, want)
+ }
+ if n, err := r.Read(make([]byte, 10)); err != nil || n != 10 {
+ t.Errorf("Read failed: read %d %v", n, err)
+ }
+ if got, want := r.Len(), 1; got != want {
+ t.Errorf("r.Len(): got %d, want %d", got, want)
+ }
+ if n, err := r.Read(make([]byte, 1)); err != nil || n != 1 {
+ t.Errorf("Read failed: read %d %v; want 1, nil", n, err)
+ }
+ if got, want := r.Len(), 0; got != want {
+ t.Errorf("r.Len(): got %d, want %d", got, want)
+ }
+}
+
+var UnreadRuneErrorTests = []struct {
+ name string
+ f func(*Reader)
+}{
+ {"Read", func(r *Reader) { r.Read([]byte{0}) }},
+ {"ReadByte", func(r *Reader) { r.ReadByte() }},
+ {"UnreadRune", func(r *Reader) { r.UnreadRune() }},
+ {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }},
+ {"WriteTo", func(r *Reader) { r.WriteTo(&Buffer{}) }},
+}
+
+func TestUnreadRuneError(t *testing.T) {
+ for _, tt := range UnreadRuneErrorTests {
+ reader := NewReader([]byte("0123456789"))
+ if _, _, err := reader.ReadRune(); err != nil {
+ // should not happen
+ t.Fatal(err)
+ }
+ tt.f(reader)
+ err := reader.UnreadRune()
+ if err == nil {
+ t.Errorf("Unreading after %s: expected error", tt.name)
+ }
+ }
+}
+
+func TestReaderDoubleUnreadRune(t *testing.T) {
+ buf := NewBuffer([]byte("groucho"))
+ if _, _, err := buf.ReadRune(); err != nil {
+ // should not happen
+ t.Fatal(err)
+ }
+ if err := buf.UnreadByte(); err != nil {
+ // should not happen
+ t.Fatal(err)
+ }
+ if err := buf.UnreadByte(); err == nil {
+ t.Fatal("UnreadByte: expected error, got nil")
+ }
+}
+
+// verify that copying from an empty reader always has the same results,
+// regardless of the presence of a WriteTo method.
+func TestReaderCopyNothing(t *testing.T) {
+ type nErr struct {
+ n int64
+ err error
+ }
+ type justReader struct {
+ io.Reader
+ }
+ type justWriter struct {
+ io.Writer
+ }
+ discard := justWriter{io.Discard} // hide ReadFrom
+
+ var with, withOut nErr
+ with.n, with.err = io.Copy(discard, NewReader(nil))
+ withOut.n, withOut.err = io.Copy(discard, justReader{NewReader(nil)})
+ if with != withOut {
+ t.Errorf("behavior differs: with = %#v; without: %#v", with, withOut)
+ }
+}
+
+// tests that Len is affected by reads, but Size is not.
+func TestReaderLenSize(t *testing.T) {
+ r := NewReader([]byte("abc"))
+ io.CopyN(io.Discard, r, 1)
+ if r.Len() != 2 {
+ t.Errorf("Len = %d; want 2", r.Len())
+ }
+ if r.Size() != 3 {
+ t.Errorf("Size = %d; want 3", r.Size())
+ }
+}
+
+func TestReaderReset(t *testing.T) {
+ r := NewReader([]byte("世界"))
+ if _, _, err := r.ReadRune(); err != nil {
+ t.Errorf("ReadRune: unexpected error: %v", err)
+ }
+
+ const want = "abcdef"
+ r.Reset([]byte(want))
+ if err := r.UnreadRune(); err == nil {
+ t.Errorf("UnreadRune: expected error, got nil")
+ }
+ buf, err := io.ReadAll(r)
+ if err != nil {
+ t.Errorf("ReadAll: unexpected error: %v", err)
+ }
+ if got := string(buf); got != want {
+ t.Errorf("ReadAll: got %q, want %q", got, want)
+ }
+}
+
+func TestReaderZero(t *testing.T) {
+ if l := (&Reader{}).Len(); l != 0 {
+ t.Errorf("Len: got %d, want 0", l)
+ }
+
+ if n, err := (&Reader{}).Read(nil); n != 0 || err != io.EOF {
+ t.Errorf("Read: got %d, %v; want 0, io.EOF", n, err)
+ }
+
+ if n, err := (&Reader{}).ReadAt(nil, 11); n != 0 || err != io.EOF {
+ t.Errorf("ReadAt: got %d, %v; want 0, io.EOF", n, err)
+ }
+
+ if b, err := (&Reader{}).ReadByte(); b != 0 || err != io.EOF {
+ t.Errorf("ReadByte: got %d, %v; want 0, io.EOF", b, err)
+ }
+
+ if ch, size, err := (&Reader{}).ReadRune(); ch != 0 || size != 0 || err != io.EOF {
+ t.Errorf("ReadRune: got %d, %d, %v; want 0, 0, io.EOF", ch, size, err)
+ }
+
+ if offset, err := (&Reader{}).Seek(11, io.SeekStart); offset != 11 || err != nil {
+ t.Errorf("Seek: got %d, %v; want 11, nil", offset, err)
+ }
+
+ if s := (&Reader{}).Size(); s != 0 {
+ t.Errorf("Size: got %d, want 0", s)
+ }
+
+ if (&Reader{}).UnreadByte() == nil {
+ t.Errorf("UnreadByte: got nil, want error")
+ }
+
+ if (&Reader{}).UnreadRune() == nil {
+ t.Errorf("UnreadRune: got nil, want error")
+ }
+
+ if n, err := (&Reader{}).WriteTo(io.Discard); n != 0 || err != nil {
+ t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/cmd/README.vendor b/platform/dbops/binaries/go/go/src/cmd/README.vendor
new file mode 100644
index 0000000000000000000000000000000000000000..ac0df5e9257124ba06492f523eeed3706041fa1c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/cmd/README.vendor
@@ -0,0 +1,2 @@
+See src/README.vendor for information on loading vendored packages
+and updating the vendor directory.
diff --git a/platform/dbops/binaries/go/go/src/cmd/go.mod b/platform/dbops/binaries/go/go/src/cmd/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7a426887b48cb0df8195e47f8a4e08b71e7f2811
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/cmd/go.mod
@@ -0,0 +1,15 @@
+module cmd
+
+go 1.22
+
+require (
+ github.com/google/pprof v0.0.0-20230811205829-9131a7e9cc17
+ golang.org/x/arch v0.6.0
+ golang.org/x/mod v0.14.0
+ golang.org/x/sync v0.5.0
+ golang.org/x/sys v0.15.0
+ golang.org/x/term v0.15.0
+ golang.org/x/tools v0.16.2-0.20231218185909-83bceaf2424d
+)
+
+require github.com/ianlancetaylor/demangle v0.0.0-20230524184225-eabc099b10ab // indirect
diff --git a/platform/dbops/binaries/go/go/src/cmd/go.sum b/platform/dbops/binaries/go/go/src/cmd/go.sum
new file mode 100644
index 0000000000000000000000000000000000000000..8ea3d75bd1518d96b781d469681e314f35acf23e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/cmd/go.sum
@@ -0,0 +1,16 @@
+github.com/google/pprof v0.0.0-20230811205829-9131a7e9cc17 h1:0h35ESZ02+hN/MFZb7XZOXg+Rl9+Rk8fBIf5YLws9gA=
+github.com/google/pprof v0.0.0-20230811205829-9131a7e9cc17/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA=
+github.com/ianlancetaylor/demangle v0.0.0-20230524184225-eabc099b10ab h1:BA4a7pe6ZTd9F8kXETBoijjFJ/ntaa//1wiH9BZu4zU=
+github.com/ianlancetaylor/demangle v0.0.0-20230524184225-eabc099b10ab/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
+golang.org/x/arch v0.6.0 h1:S0JTfE48HbRj80+4tbvZDYsJ3tGv6BUU3XxyZ7CirAc=
+golang.org/x/arch v0.6.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
+golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
+golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
+golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
+golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
+golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
+golang.org/x/tools v0.16.2-0.20231218185909-83bceaf2424d h1:9YOyUBubvYqtjjtZBnI62JT9/QB9jfPwOQ7xLeyuOIU=
+golang.org/x/tools v0.16.2-0.20231218185909-83bceaf2424d/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
diff --git a/platform/dbops/binaries/go/go/src/cmp/cmp.go b/platform/dbops/binaries/go/go/src/cmp/cmp.go
new file mode 100644
index 0000000000000000000000000000000000000000..4d1af6a98c4e46ee3f839196bf7a463d0cc6ce48
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/cmp/cmp.go
@@ -0,0 +1,71 @@
+// 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 cmp provides types and functions related to comparing
+// ordered values.
+package cmp
+
+// Ordered is a constraint that permits any ordered type: any type
+// that supports the operators < <= >= >.
+// If future releases of Go add new ordered types,
+// this constraint will be modified to include them.
+//
+// Note that floating-point types may contain NaN ("not-a-number") values.
+// An operator such as == or < will always report false when
+// comparing a NaN value with any other value, NaN or not.
+// See the [Compare] function for a consistent way to compare NaN values.
+type Ordered interface {
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
+ ~float32 | ~float64 |
+ ~string
+}
+
+// Less reports whether x is less than y.
+// For floating-point types, a NaN is considered less than any non-NaN,
+// and -0.0 is not less than (is equal to) 0.0.
+func Less[T Ordered](x, y T) bool {
+ return (isNaN(x) && !isNaN(y)) || x < y
+}
+
+// Compare returns
+//
+// -1 if x is less than y,
+// 0 if x equals y,
+// +1 if x is greater than y.
+//
+// For floating-point types, a NaN is considered less than any non-NaN,
+// a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
+func Compare[T Ordered](x, y T) int {
+ xNaN := isNaN(x)
+ yNaN := isNaN(y)
+ if xNaN && yNaN {
+ return 0
+ }
+ if xNaN || x < y {
+ return -1
+ }
+ if yNaN || x > y {
+ return +1
+ }
+ return 0
+}
+
+// isNaN reports whether x is a NaN without requiring the math package.
+// This will always return false if T is not floating-point.
+func isNaN[T Ordered](x T) bool {
+ return x != x
+}
+
+// Or returns the first of its arguments that is not equal to the zero value.
+// If no argument is non-zero, it returns the zero value.
+func Or[T comparable](vals ...T) T {
+ var zero T
+ for _, val := range vals {
+ if val != zero {
+ return val
+ }
+ }
+ return zero
+}
diff --git a/platform/dbops/binaries/go/go/src/cmp/cmp_test.go b/platform/dbops/binaries/go/go/src/cmp/cmp_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..e265464f4f0fd71a2ba59996320fdc0ddbc763b5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/cmp/cmp_test.go
@@ -0,0 +1,177 @@
+// 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 cmp_test
+
+import (
+ "cmp"
+ "fmt"
+ "math"
+ "slices"
+ "sort"
+ "testing"
+ "unsafe"
+)
+
+var negzero = math.Copysign(0, -1)
+var nonnilptr uintptr = uintptr(unsafe.Pointer(&negzero))
+var nilptr uintptr = uintptr(unsafe.Pointer(nil))
+
+var tests = []struct {
+ x, y any
+ compare int
+}{
+ {1, 2, -1},
+ {1, 1, 0},
+ {2, 1, +1},
+ {"a", "aa", -1},
+ {"a", "a", 0},
+ {"aa", "a", +1},
+ {1.0, 1.1, -1},
+ {1.1, 1.1, 0},
+ {1.1, 1.0, +1},
+ {math.Inf(1), math.Inf(1), 0},
+ {math.Inf(-1), math.Inf(-1), 0},
+ {math.Inf(-1), 1.0, -1},
+ {1.0, math.Inf(-1), +1},
+ {math.Inf(1), 1.0, +1},
+ {1.0, math.Inf(1), -1},
+ {math.NaN(), math.NaN(), 0},
+ {0.0, math.NaN(), +1},
+ {math.NaN(), 0.0, -1},
+ {math.NaN(), math.Inf(-1), -1},
+ {math.Inf(-1), math.NaN(), +1},
+ {0.0, 0.0, 0},
+ {negzero, negzero, 0},
+ {negzero, 0.0, 0},
+ {0.0, negzero, 0},
+ {negzero, 1.0, -1},
+ {negzero, -1.0, +1},
+ {nilptr, nonnilptr, -1},
+ {nonnilptr, nilptr, 1},
+ {nonnilptr, nonnilptr, 0},
+}
+
+func TestLess(t *testing.T) {
+ for _, test := range tests {
+ var b bool
+ switch test.x.(type) {
+ case int:
+ b = cmp.Less(test.x.(int), test.y.(int))
+ case string:
+ b = cmp.Less(test.x.(string), test.y.(string))
+ case float64:
+ b = cmp.Less(test.x.(float64), test.y.(float64))
+ case uintptr:
+ b = cmp.Less(test.x.(uintptr), test.y.(uintptr))
+ }
+ if b != (test.compare < 0) {
+ t.Errorf("Less(%v, %v) == %t, want %t", test.x, test.y, b, test.compare < 0)
+ }
+ }
+}
+
+func TestCompare(t *testing.T) {
+ for _, test := range tests {
+ var c int
+ switch test.x.(type) {
+ case int:
+ c = cmp.Compare(test.x.(int), test.y.(int))
+ case string:
+ c = cmp.Compare(test.x.(string), test.y.(string))
+ case float64:
+ c = cmp.Compare(test.x.(float64), test.y.(float64))
+ case uintptr:
+ c = cmp.Compare(test.x.(uintptr), test.y.(uintptr))
+ }
+ if c != test.compare {
+ t.Errorf("Compare(%v, %v) == %d, want %d", test.x, test.y, c, test.compare)
+ }
+ }
+}
+
+func TestSort(t *testing.T) {
+ // Test that our comparison function is consistent with
+ // sort.Float64s.
+ input := []float64{1.0, 0.0, negzero, math.Inf(1), math.Inf(-1), math.NaN()}
+ sort.Float64s(input)
+ for i := 0; i < len(input)-1; i++ {
+ if cmp.Less(input[i+1], input[i]) {
+ t.Errorf("Less sort mismatch at %d in %v", i, input)
+ }
+ if cmp.Compare(input[i], input[i+1]) > 0 {
+ t.Errorf("Compare sort mismatch at %d in %v", i, input)
+ }
+ }
+}
+
+func TestOr(t *testing.T) {
+ cases := []struct {
+ in []int
+ want int
+ }{
+ {nil, 0},
+ {[]int{0}, 0},
+ {[]int{1}, 1},
+ {[]int{0, 2}, 2},
+ {[]int{3, 0}, 3},
+ {[]int{4, 5}, 4},
+ {[]int{0, 6, 7}, 6},
+ }
+ for _, tc := range cases {
+ if got := cmp.Or(tc.in...); got != tc.want {
+ t.Errorf("cmp.Or(%v) = %v; want %v", tc.in, got, tc.want)
+ }
+ }
+}
+
+func ExampleOr() {
+ // Suppose we have some user input
+ // that may or may not be an empty string
+ userInput1 := ""
+ userInput2 := "some text"
+
+ fmt.Println(cmp.Or(userInput1, "default"))
+ fmt.Println(cmp.Or(userInput2, "default"))
+ fmt.Println(cmp.Or(userInput1, userInput2, "default"))
+ // Output:
+ // default
+ // some text
+ // some text
+}
+
+func ExampleOr_sort() {
+ type Order struct {
+ Product string
+ Customer string
+ Price float64
+ }
+ orders := []Order{
+ {"foo", "alice", 1.00},
+ {"bar", "bob", 3.00},
+ {"baz", "carol", 4.00},
+ {"foo", "alice", 2.00},
+ {"bar", "carol", 1.00},
+ {"foo", "bob", 4.00},
+ }
+ // Sort by customer first, product second, and last by higher price
+ slices.SortFunc(orders, func(a, b Order) int {
+ return cmp.Or(
+ cmp.Compare(a.Customer, b.Customer),
+ cmp.Compare(a.Product, b.Product),
+ cmp.Compare(b.Price, a.Price),
+ )
+ })
+ for _, order := range orders {
+ fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
+ }
+
+ // Output:
+ // foo alice 2.00
+ // foo alice 1.00
+ // bar bob 3.00
+ // foo bob 4.00
+ // bar carol 1.00
+ // baz carol 4.00
+}
diff --git a/platform/dbops/binaries/go/go/src/context/afterfunc_test.go b/platform/dbops/binaries/go/go/src/context/afterfunc_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b75295eb4dab03363efee1f56fbfa693edeca78
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/afterfunc_test.go
@@ -0,0 +1,143 @@
+// 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 context_test
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+)
+
+// afterFuncContext is a context that's not one of the types
+// defined in context.go, that supports registering AfterFuncs.
+type afterFuncContext struct {
+ mu sync.Mutex
+ afterFuncs map[*byte]func()
+ done chan struct{}
+ err error
+}
+
+func newAfterFuncContext() context.Context {
+ return &afterFuncContext{}
+}
+
+func (c *afterFuncContext) Deadline() (time.Time, bool) {
+ return time.Time{}, false
+}
+
+func (c *afterFuncContext) Done() <-chan struct{} {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.done == nil {
+ c.done = make(chan struct{})
+ }
+ return c.done
+}
+
+func (c *afterFuncContext) Err() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.err
+}
+
+func (c *afterFuncContext) Value(key any) any {
+ return nil
+}
+
+func (c *afterFuncContext) AfterFunc(f func()) func() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ k := new(byte)
+ if c.afterFuncs == nil {
+ c.afterFuncs = make(map[*byte]func())
+ }
+ c.afterFuncs[k] = f
+ return func() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ _, ok := c.afterFuncs[k]
+ delete(c.afterFuncs, k)
+ return ok
+ }
+}
+
+func (c *afterFuncContext) cancel(err error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return
+ }
+ c.err = err
+ for _, f := range c.afterFuncs {
+ go f()
+ }
+ c.afterFuncs = nil
+}
+
+func TestCustomContextAfterFuncCancel(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ ctx1, cancel := context.WithCancel(ctx0)
+ defer cancel()
+ ctx0.cancel(context.Canceled)
+ <-ctx1.Done()
+}
+
+func TestCustomContextAfterFuncTimeout(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ ctx1, cancel := context.WithTimeout(ctx0, veryLongDuration)
+ defer cancel()
+ ctx0.cancel(context.Canceled)
+ <-ctx1.Done()
+}
+
+func TestCustomContextAfterFuncAfterFunc(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ donec := make(chan struct{})
+ stop := context.AfterFunc(ctx0, func() {
+ close(donec)
+ })
+ defer stop()
+ ctx0.cancel(context.Canceled)
+ <-donec
+}
+
+func TestCustomContextAfterFuncUnregisterCancel(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ _, cancel1 := context.WithCancel(ctx0)
+ _, cancel2 := context.WithCancel(ctx0)
+ if got, want := len(ctx0.afterFuncs), 2; got != want {
+ t.Errorf("after WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+ cancel1()
+ cancel2()
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
+ t.Errorf("after canceling WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+}
+
+func TestCustomContextAfterFuncUnregisterTimeout(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ _, cancel := context.WithTimeout(ctx0, veryLongDuration)
+ if got, want := len(ctx0.afterFuncs), 1; got != want {
+ t.Errorf("after WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+ cancel()
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
+ t.Errorf("after canceling WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+}
+
+func TestCustomContextAfterFuncUnregisterAfterFunc(t *testing.T) {
+ ctx0 := &afterFuncContext{}
+ stop := context.AfterFunc(ctx0, func() {})
+ if got, want := len(ctx0.afterFuncs), 1; got != want {
+ t.Errorf("after AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+ stop()
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
+ t.Errorf("after stopping AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/context/benchmark_test.go b/platform/dbops/binaries/go/go/src/context/benchmark_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..144f473a4448166892aa66c8d214e8db64848069
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/benchmark_test.go
@@ -0,0 +1,190 @@
+// 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 context_test
+
+import (
+ . "context"
+ "fmt"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+)
+
+func BenchmarkCommonParentCancel(b *testing.B) {
+ root := WithValue(Background(), "key", "value")
+ shared, sharedcancel := WithCancel(root)
+ defer sharedcancel()
+
+ b.ResetTimer()
+ b.RunParallel(func(pb *testing.PB) {
+ x := 0
+ for pb.Next() {
+ ctx, cancel := WithCancel(shared)
+ if ctx.Value("key").(string) != "value" {
+ b.Fatal("should not be reached")
+ }
+ for i := 0; i < 100; i++ {
+ x /= x + 1
+ }
+ cancel()
+ for i := 0; i < 100; i++ {
+ x /= x + 1
+ }
+ }
+ })
+}
+
+func BenchmarkWithTimeout(b *testing.B) {
+ for concurrency := 40; concurrency <= 4e5; concurrency *= 100 {
+ name := fmt.Sprintf("concurrency=%d", concurrency)
+ b.Run(name, func(b *testing.B) {
+ benchmarkWithTimeout(b, concurrency)
+ })
+ }
+}
+
+func benchmarkWithTimeout(b *testing.B, concurrentContexts int) {
+ gomaxprocs := runtime.GOMAXPROCS(0)
+ perPContexts := concurrentContexts / gomaxprocs
+ root := Background()
+
+ // Generate concurrent contexts.
+ var wg sync.WaitGroup
+ ccf := make([][]CancelFunc, gomaxprocs)
+ for i := range ccf {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ cf := make([]CancelFunc, perPContexts)
+ for j := range cf {
+ _, cf[j] = WithTimeout(root, time.Hour)
+ }
+ ccf[i] = cf
+ }(i)
+ }
+ wg.Wait()
+
+ b.ResetTimer()
+ b.RunParallel(func(pb *testing.PB) {
+ wcf := make([]CancelFunc, 10)
+ for pb.Next() {
+ for i := range wcf {
+ _, wcf[i] = WithTimeout(root, time.Hour)
+ }
+ for _, f := range wcf {
+ f()
+ }
+ }
+ })
+ b.StopTimer()
+
+ for _, cf := range ccf {
+ for _, f := range cf {
+ f()
+ }
+ }
+}
+
+func BenchmarkCancelTree(b *testing.B) {
+ depths := []int{1, 10, 100, 1000}
+ for _, d := range depths {
+ b.Run(fmt.Sprintf("depth=%d", d), func(b *testing.B) {
+ b.Run("Root=Background", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ buildContextTree(Background(), d)
+ }
+ })
+ b.Run("Root=OpenCanceler", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ ctx, cancel := WithCancel(Background())
+ buildContextTree(ctx, d)
+ cancel()
+ }
+ })
+ b.Run("Root=ClosedCanceler", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ ctx, cancel := WithCancel(Background())
+ cancel()
+ buildContextTree(ctx, d)
+ }
+ })
+ })
+ }
+}
+
+func buildContextTree(root Context, depth int) {
+ for d := 0; d < depth; d++ {
+ root, _ = WithCancel(root)
+ }
+}
+
+func BenchmarkCheckCanceled(b *testing.B) {
+ ctx, cancel := WithCancel(Background())
+ cancel()
+ b.Run("Err", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ ctx.Err()
+ }
+ })
+ b.Run("Done", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ select {
+ case <-ctx.Done():
+ default:
+ }
+ }
+ })
+}
+
+func BenchmarkContextCancelDone(b *testing.B) {
+ ctx, cancel := WithCancel(Background())
+ defer cancel()
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ select {
+ case <-ctx.Done():
+ default:
+ }
+ }
+ })
+}
+
+func BenchmarkDeepValueNewGoRoutine(b *testing.B) {
+ for _, depth := range []int{10, 20, 30, 50, 100} {
+ ctx := Background()
+ for i := 0; i < depth; i++ {
+ ctx = WithValue(ctx, i, i)
+ }
+
+ b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ctx.Value(-1)
+ }()
+ wg.Wait()
+ }
+ })
+ }
+}
+
+func BenchmarkDeepValueSameGoRoutine(b *testing.B) {
+ for _, depth := range []int{10, 20, 30, 50, 100} {
+ ctx := Background()
+ for i := 0; i < depth; i++ {
+ ctx = WithValue(ctx, i, i)
+ }
+
+ b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ ctx.Value(-1)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/context/context.go b/platform/dbops/binaries/go/go/src/context/context.go
new file mode 100644
index 0000000000000000000000000000000000000000..80e1787576364967f99dfd207d739361b130c593
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/context.go
@@ -0,0 +1,790 @@
+// 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 context defines the Context type, which carries deadlines,
+// cancellation signals, and other request-scoped values across API boundaries
+// and between processes.
+//
+// Incoming requests to a server should create a [Context], and outgoing
+// calls to servers should accept a Context. The chain of function
+// calls between them must propagate the Context, optionally replacing
+// it with a derived Context created using [WithCancel], [WithDeadline],
+// [WithTimeout], or [WithValue]. When a Context is canceled, all
+// Contexts derived from it are also canceled.
+//
+// The [WithCancel], [WithDeadline], and [WithTimeout] functions take a
+// Context (the parent) and return a derived Context (the child) and a
+// [CancelFunc]. Calling the CancelFunc cancels the child and its
+// children, removes the parent's reference to the child, and stops
+// any associated timers. Failing to call the CancelFunc leaks the
+// child and its children until the parent is canceled or the timer
+// fires. The go vet tool checks that CancelFuncs are used on all
+// control-flow paths.
+//
+// The [WithCancelCause] function returns a [CancelCauseFunc], which
+// takes an error and records it as the cancellation cause. Calling
+// [Cause] on the canceled context or any of its children retrieves
+// the cause. If no cause is specified, Cause(ctx) returns the same
+// value as ctx.Err().
+//
+// Programs that use Contexts should follow these rules to keep interfaces
+// consistent across packages and enable static analysis tools to check context
+// propagation:
+//
+// Do not store Contexts inside a struct type; instead, pass a Context
+// explicitly to each function that needs it. The Context should be the first
+// parameter, typically named ctx:
+//
+// func DoSomething(ctx context.Context, arg Arg) error {
+// // ... use ctx ...
+// }
+//
+// Do not pass a nil [Context], even if a function permits it. Pass [context.TODO]
+// if you are unsure about which Context to use.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+//
+// The same Context may be passed to functions running in different goroutines;
+// Contexts are safe for simultaneous use by multiple goroutines.
+//
+// See https://blog.golang.org/context for example code for a server that uses
+// Contexts.
+package context
+
+import (
+ "errors"
+ "internal/reflectlite"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// A Context carries a deadline, a cancellation signal, and other values across
+// API boundaries.
+//
+// Context's methods may be called by multiple goroutines simultaneously.
+type Context interface {
+ // Deadline returns the time when work done on behalf of this context
+ // should be canceled. Deadline returns ok==false when no deadline is
+ // set. Successive calls to Deadline return the same results.
+ Deadline() (deadline time.Time, ok bool)
+
+ // Done returns a channel that's closed when work done on behalf of this
+ // context should be canceled. Done may return nil if this context can
+ // never be canceled. Successive calls to Done return the same value.
+ // The close of the Done channel may happen asynchronously,
+ // after the cancel function returns.
+ //
+ // WithCancel arranges for Done to be closed when cancel is called;
+ // WithDeadline arranges for Done to be closed when the deadline
+ // expires; WithTimeout arranges for Done to be closed when the timeout
+ // elapses.
+ //
+ // Done is provided for use in select statements:
+ //
+ // // Stream generates values with DoSomething and sends them to out
+ // // until DoSomething returns an error or ctx.Done is closed.
+ // func Stream(ctx context.Context, out chan<- Value) error {
+ // for {
+ // v, err := DoSomething(ctx)
+ // if err != nil {
+ // return err
+ // }
+ // select {
+ // case <-ctx.Done():
+ // return ctx.Err()
+ // case out <- v:
+ // }
+ // }
+ // }
+ //
+ // See https://blog.golang.org/pipelines for more examples of how to use
+ // a Done channel for cancellation.
+ Done() <-chan struct{}
+
+ // If Done is not yet closed, Err returns nil.
+ // If Done is closed, Err returns a non-nil error explaining why:
+ // Canceled if the context was canceled
+ // or DeadlineExceeded if the context's deadline passed.
+ // After Err returns a non-nil error, successive calls to Err return the same error.
+ Err() error
+
+ // Value returns the value associated with this context for key, or nil
+ // if no value is associated with key. Successive calls to Value with
+ // the same key returns the same result.
+ //
+ // Use context values only for request-scoped data that transits
+ // processes and API boundaries, not for passing optional parameters to
+ // functions.
+ //
+ // A key identifies a specific value in a Context. Functions that wish
+ // to store values in Context typically allocate a key in a global
+ // variable then use that key as the argument to context.WithValue and
+ // Context.Value. A key can be any type that supports equality;
+ // packages should define keys as an unexported type to avoid
+ // collisions.
+ //
+ // Packages that define a Context key should provide type-safe accessors
+ // for the values stored using that key:
+ //
+ // // Package user defines a User type that's stored in Contexts.
+ // package user
+ //
+ // import "context"
+ //
+ // // User is the type of value stored in the Contexts.
+ // type User struct {...}
+ //
+ // // key is an unexported type for keys defined in this package.
+ // // This prevents collisions with keys defined in other packages.
+ // type key int
+ //
+ // // userKey is the key for user.User values in Contexts. It is
+ // // unexported; clients use user.NewContext and user.FromContext
+ // // instead of using this key directly.
+ // var userKey key
+ //
+ // // NewContext returns a new Context that carries value u.
+ // func NewContext(ctx context.Context, u *User) context.Context {
+ // return context.WithValue(ctx, userKey, u)
+ // }
+ //
+ // // FromContext returns the User value stored in ctx, if any.
+ // func FromContext(ctx context.Context) (*User, bool) {
+ // u, ok := ctx.Value(userKey).(*User)
+ // return u, ok
+ // }
+ Value(key any) any
+}
+
+// Canceled is the error returned by [Context.Err] when the context is canceled.
+var Canceled = errors.New("context canceled")
+
+// DeadlineExceeded is the error returned by [Context.Err] when the context's
+// deadline passes.
+var DeadlineExceeded error = deadlineExceededError{}
+
+type deadlineExceededError struct{}
+
+func (deadlineExceededError) Error() string { return "context deadline exceeded" }
+func (deadlineExceededError) Timeout() bool { return true }
+func (deadlineExceededError) Temporary() bool { return true }
+
+// An emptyCtx is never canceled, has no values, and has no deadline.
+// It is the common base of backgroundCtx and todoCtx.
+type emptyCtx struct{}
+
+func (emptyCtx) Deadline() (deadline time.Time, ok bool) {
+ return
+}
+
+func (emptyCtx) Done() <-chan struct{} {
+ return nil
+}
+
+func (emptyCtx) Err() error {
+ return nil
+}
+
+func (emptyCtx) Value(key any) any {
+ return nil
+}
+
+type backgroundCtx struct{ emptyCtx }
+
+func (backgroundCtx) String() string {
+ return "context.Background"
+}
+
+type todoCtx struct{ emptyCtx }
+
+func (todoCtx) String() string {
+ return "context.TODO"
+}
+
+// Background returns a non-nil, empty [Context]. It is never canceled, has no
+// values, and has no deadline. It is typically used by the main function,
+// initialization, and tests, and as the top-level Context for incoming
+// requests.
+func Background() Context {
+ return backgroundCtx{}
+}
+
+// TODO returns a non-nil, empty [Context]. Code should use context.TODO when
+// it's unclear which Context to use or it is not yet available (because the
+// surrounding function has not yet been extended to accept a Context
+// parameter).
+func TODO() Context {
+ return todoCtx{}
+}
+
+// A CancelFunc tells an operation to abandon its work.
+// A CancelFunc does not wait for the work to stop.
+// A CancelFunc may be called by multiple goroutines simultaneously.
+// After the first call, subsequent calls to a CancelFunc do nothing.
+type CancelFunc func()
+
+// WithCancel returns a copy of parent with a new Done channel. The returned
+// context's Done channel is closed when the returned cancel function is called
+// or when the parent context's Done channel is closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
+ c := withCancel(parent)
+ return c, func() { c.cancel(true, Canceled, nil) }
+}
+
+// A CancelCauseFunc behaves like a [CancelFunc] but additionally sets the cancellation cause.
+// This cause can be retrieved by calling [Cause] on the canceled Context or on
+// any of its derived Contexts.
+//
+// If the context has already been canceled, CancelCauseFunc does not set the cause.
+// For example, if childContext is derived from parentContext:
+// - if parentContext is canceled with cause1 before childContext is canceled with cause2,
+// then Cause(parentContext) == Cause(childContext) == cause1
+// - if childContext is canceled with cause2 before parentContext is canceled with cause1,
+// then Cause(parentContext) == cause1 and Cause(childContext) == cause2
+type CancelCauseFunc func(cause error)
+
+// WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc].
+// Calling cancel with a non-nil error (the "cause") records that error in ctx;
+// it can then be retrieved using Cause(ctx).
+// Calling cancel with nil sets the cause to Canceled.
+//
+// Example use:
+//
+// ctx, cancel := context.WithCancelCause(parent)
+// cancel(myError)
+// ctx.Err() // returns context.Canceled
+// context.Cause(ctx) // returns myError
+func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) {
+ c := withCancel(parent)
+ return c, func(cause error) { c.cancel(true, Canceled, cause) }
+}
+
+func withCancel(parent Context) *cancelCtx {
+ if parent == nil {
+ panic("cannot create context from nil parent")
+ }
+ c := &cancelCtx{}
+ c.propagateCancel(parent, c)
+ return c
+}
+
+// Cause returns a non-nil error explaining why c was canceled.
+// The first cancellation of c or one of its parents sets the cause.
+// If that cancellation happened via a call to CancelCauseFunc(err),
+// then [Cause] returns err.
+// Otherwise Cause(c) returns the same value as c.Err().
+// Cause returns nil if c has not been canceled yet.
+func Cause(c Context) error {
+ if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.cause
+ }
+ // There is no cancelCtxKey value, so we know that c is
+ // not a descendant of some Context created by WithCancelCause.
+ // Therefore, there is no specific cause to return.
+ // If this is not one of the standard Context types,
+ // it might still have an error even though it won't have a cause.
+ return c.Err()
+}
+
+// AfterFunc arranges to call f in its own goroutine after ctx is done
+// (cancelled or timed out).
+// If ctx is already done, AfterFunc calls f immediately in its own goroutine.
+//
+// Multiple calls to AfterFunc on a context operate independently;
+// one does not replace another.
+//
+// Calling the returned stop function stops the association of ctx with f.
+// It returns true if the call stopped f from being run.
+// If stop returns false,
+// either the context is done and f has been started in its own goroutine;
+// or f was already stopped.
+// The stop function does not wait for f to complete before returning.
+// If the caller needs to know whether f is completed,
+// it must coordinate with f explicitly.
+//
+// If ctx has a "AfterFunc(func()) func() bool" method,
+// AfterFunc will use it to schedule the call.
+func AfterFunc(ctx Context, f func()) (stop func() bool) {
+ a := &afterFuncCtx{
+ f: f,
+ }
+ a.cancelCtx.propagateCancel(ctx, a)
+ return func() bool {
+ stopped := false
+ a.once.Do(func() {
+ stopped = true
+ })
+ if stopped {
+ a.cancel(true, Canceled, nil)
+ }
+ return stopped
+ }
+}
+
+type afterFuncer interface {
+ AfterFunc(func()) func() bool
+}
+
+type afterFuncCtx struct {
+ cancelCtx
+ once sync.Once // either starts running f or stops f from running
+ f func()
+}
+
+func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error) {
+ a.cancelCtx.cancel(false, err, cause)
+ if removeFromParent {
+ removeChild(a.Context, a)
+ }
+ a.once.Do(func() {
+ go a.f()
+ })
+}
+
+// A stopCtx is used as the parent context of a cancelCtx when
+// an AfterFunc has been registered with the parent.
+// It holds the stop function used to unregister the AfterFunc.
+type stopCtx struct {
+ Context
+ stop func() bool
+}
+
+// goroutines counts the number of goroutines ever created; for testing.
+var goroutines atomic.Int32
+
+// &cancelCtxKey is the key that a cancelCtx returns itself for.
+var cancelCtxKey int
+
+// parentCancelCtx returns the underlying *cancelCtx for parent.
+// It does this by looking up parent.Value(&cancelCtxKey) to find
+// the innermost enclosing *cancelCtx and then checking whether
+// parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
+// has been wrapped in a custom implementation providing a
+// different done channel, in which case we should not bypass it.)
+func parentCancelCtx(parent Context) (*cancelCtx, bool) {
+ done := parent.Done()
+ if done == closedchan || done == nil {
+ return nil, false
+ }
+ p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
+ if !ok {
+ return nil, false
+ }
+ pdone, _ := p.done.Load().(chan struct{})
+ if pdone != done {
+ return nil, false
+ }
+ return p, true
+}
+
+// removeChild removes a context from its parent.
+func removeChild(parent Context, child canceler) {
+ if s, ok := parent.(stopCtx); ok {
+ s.stop()
+ return
+ }
+ p, ok := parentCancelCtx(parent)
+ if !ok {
+ return
+ }
+ p.mu.Lock()
+ if p.children != nil {
+ delete(p.children, child)
+ }
+ p.mu.Unlock()
+}
+
+// A canceler is a context type that can be canceled directly. The
+// implementations are *cancelCtx and *timerCtx.
+type canceler interface {
+ cancel(removeFromParent bool, err, cause error)
+ Done() <-chan struct{}
+}
+
+// closedchan is a reusable closed channel.
+var closedchan = make(chan struct{})
+
+func init() {
+ close(closedchan)
+}
+
+// A cancelCtx can be canceled. When canceled, it also cancels any children
+// that implement canceler.
+type cancelCtx struct {
+ Context
+
+ mu sync.Mutex // protects following fields
+ done atomic.Value // of chan struct{}, created lazily, closed by first cancel call
+ children map[canceler]struct{} // set to nil by the first cancel call
+ err error // set to non-nil by the first cancel call
+ cause error // set to non-nil by the first cancel call
+}
+
+func (c *cancelCtx) Value(key any) any {
+ if key == &cancelCtxKey {
+ return c
+ }
+ return value(c.Context, key)
+}
+
+func (c *cancelCtx) Done() <-chan struct{} {
+ d := c.done.Load()
+ if d != nil {
+ return d.(chan struct{})
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ d = c.done.Load()
+ if d == nil {
+ d = make(chan struct{})
+ c.done.Store(d)
+ }
+ return d.(chan struct{})
+}
+
+func (c *cancelCtx) Err() error {
+ c.mu.Lock()
+ err := c.err
+ c.mu.Unlock()
+ return err
+}
+
+// propagateCancel arranges for child to be canceled when parent is.
+// It sets the parent context of cancelCtx.
+func (c *cancelCtx) propagateCancel(parent Context, child canceler) {
+ c.Context = parent
+
+ done := parent.Done()
+ if done == nil {
+ return // parent is never canceled
+ }
+
+ select {
+ case <-done:
+ // parent is already canceled
+ child.cancel(false, parent.Err(), Cause(parent))
+ return
+ default:
+ }
+
+ if p, ok := parentCancelCtx(parent); ok {
+ // parent is a *cancelCtx, or derives from one.
+ p.mu.Lock()
+ if p.err != nil {
+ // parent has already been canceled
+ child.cancel(false, p.err, p.cause)
+ } else {
+ if p.children == nil {
+ p.children = make(map[canceler]struct{})
+ }
+ p.children[child] = struct{}{}
+ }
+ p.mu.Unlock()
+ return
+ }
+
+ if a, ok := parent.(afterFuncer); ok {
+ // parent implements an AfterFunc method.
+ c.mu.Lock()
+ stop := a.AfterFunc(func() {
+ child.cancel(false, parent.Err(), Cause(parent))
+ })
+ c.Context = stopCtx{
+ Context: parent,
+ stop: stop,
+ }
+ c.mu.Unlock()
+ return
+ }
+
+ goroutines.Add(1)
+ go func() {
+ select {
+ case <-parent.Done():
+ child.cancel(false, parent.Err(), Cause(parent))
+ case <-child.Done():
+ }
+ }()
+}
+
+type stringer interface {
+ String() string
+}
+
+func contextName(c Context) string {
+ if s, ok := c.(stringer); ok {
+ return s.String()
+ }
+ return reflectlite.TypeOf(c).String()
+}
+
+func (c *cancelCtx) String() string {
+ return contextName(c.Context) + ".WithCancel"
+}
+
+// cancel closes c.done, cancels each of c's children, and, if
+// removeFromParent is true, removes c from its parent's children.
+// cancel sets c.cause to cause if this is the first time c is canceled.
+func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {
+ if err == nil {
+ panic("context: internal error: missing cancel error")
+ }
+ if cause == nil {
+ cause = err
+ }
+ c.mu.Lock()
+ if c.err != nil {
+ c.mu.Unlock()
+ return // already canceled
+ }
+ c.err = err
+ c.cause = cause
+ d, _ := c.done.Load().(chan struct{})
+ if d == nil {
+ c.done.Store(closedchan)
+ } else {
+ close(d)
+ }
+ for child := range c.children {
+ // NOTE: acquiring the child's lock while holding parent's lock.
+ child.cancel(false, err, cause)
+ }
+ c.children = nil
+ c.mu.Unlock()
+
+ if removeFromParent {
+ removeChild(c.Context, c)
+ }
+}
+
+// WithoutCancel returns a copy of parent that is not canceled when parent is canceled.
+// The returned context returns no Deadline or Err, and its Done channel is nil.
+// Calling [Cause] on the returned context returns nil.
+func WithoutCancel(parent Context) Context {
+ if parent == nil {
+ panic("cannot create context from nil parent")
+ }
+ return withoutCancelCtx{parent}
+}
+
+type withoutCancelCtx struct {
+ c Context
+}
+
+func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) {
+ return
+}
+
+func (withoutCancelCtx) Done() <-chan struct{} {
+ return nil
+}
+
+func (withoutCancelCtx) Err() error {
+ return nil
+}
+
+func (c withoutCancelCtx) Value(key any) any {
+ return value(c, key)
+}
+
+func (c withoutCancelCtx) String() string {
+ return contextName(c.c) + ".WithoutCancel"
+}
+
+// WithDeadline returns a copy of the parent context with the deadline adjusted
+// to be no later than d. If the parent's deadline is already earlier than d,
+// WithDeadline(parent, d) is semantically equivalent to parent. The returned
+// [Context.Done] channel is closed when the deadline expires, when the returned
+// cancel function is called, or when the parent context's Done channel is
+// closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this [Context] complete.
+func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
+ return WithDeadlineCause(parent, d, nil)
+}
+
+// WithDeadlineCause behaves like [WithDeadline] but also sets the cause of the
+// returned Context when the deadline is exceeded. The returned [CancelFunc] does
+// not set the cause.
+func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {
+ if parent == nil {
+ panic("cannot create context from nil parent")
+ }
+ if cur, ok := parent.Deadline(); ok && cur.Before(d) {
+ // The current deadline is already sooner than the new one.
+ return WithCancel(parent)
+ }
+ c := &timerCtx{
+ deadline: d,
+ }
+ c.cancelCtx.propagateCancel(parent, c)
+ dur := time.Until(d)
+ if dur <= 0 {
+ c.cancel(true, DeadlineExceeded, cause) // deadline has already passed
+ return c, func() { c.cancel(false, Canceled, nil) }
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err == nil {
+ c.timer = time.AfterFunc(dur, func() {
+ c.cancel(true, DeadlineExceeded, cause)
+ })
+ }
+ return c, func() { c.cancel(true, Canceled, nil) }
+}
+
+// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
+// implement Done and Err. It implements cancel by stopping its timer then
+// delegating to cancelCtx.cancel.
+type timerCtx struct {
+ cancelCtx
+ timer *time.Timer // Under cancelCtx.mu.
+
+ deadline time.Time
+}
+
+func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
+ return c.deadline, true
+}
+
+func (c *timerCtx) String() string {
+ return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
+ c.deadline.String() + " [" +
+ time.Until(c.deadline).String() + "])"
+}
+
+func (c *timerCtx) cancel(removeFromParent bool, err, cause error) {
+ c.cancelCtx.cancel(false, err, cause)
+ if removeFromParent {
+ // Remove this timerCtx from its parent cancelCtx's children.
+ removeChild(c.cancelCtx.Context, c)
+ }
+ c.mu.Lock()
+ if c.timer != nil {
+ c.timer.Stop()
+ c.timer = nil
+ }
+ c.mu.Unlock()
+}
+
+// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this [Context] complete:
+//
+// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+// defer cancel() // releases resources if slowOperation completes before timeout elapses
+// return slowOperation(ctx)
+// }
+func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
+ return WithDeadline(parent, time.Now().Add(timeout))
+}
+
+// WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the
+// returned Context when the timeout expires. The returned [CancelFunc] does
+// not set the cause.
+func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) {
+ return WithDeadlineCause(parent, time.Now().Add(timeout), cause)
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+//
+// The provided key must be comparable and should not be of type
+// string or any other built-in type to avoid collisions between
+// packages using context. Users of WithValue should define their own
+// types for keys. To avoid allocating when assigning to an
+// interface{}, context keys often have concrete type
+// struct{}. Alternatively, exported context key variables' static
+// type should be a pointer or interface.
+func WithValue(parent Context, key, val any) Context {
+ if parent == nil {
+ panic("cannot create context from nil parent")
+ }
+ if key == nil {
+ panic("nil key")
+ }
+ if !reflectlite.TypeOf(key).Comparable() {
+ panic("key is not comparable")
+ }
+ return &valueCtx{parent, key, val}
+}
+
+// A valueCtx carries a key-value pair. It implements Value for that key and
+// delegates all other calls to the embedded Context.
+type valueCtx struct {
+ Context
+ key, val any
+}
+
+// stringify tries a bit to stringify v, without using fmt, since we don't
+// want context depending on the unicode tables. This is only used by
+// *valueCtx.String().
+func stringify(v any) string {
+ switch s := v.(type) {
+ case stringer:
+ return s.String()
+ case string:
+ return s
+ }
+ return ""
+}
+
+func (c *valueCtx) String() string {
+ return contextName(c.Context) + ".WithValue(type " +
+ reflectlite.TypeOf(c.key).String() +
+ ", val " + stringify(c.val) + ")"
+}
+
+func (c *valueCtx) Value(key any) any {
+ if c.key == key {
+ return c.val
+ }
+ return value(c.Context, key)
+}
+
+func value(c Context, key any) any {
+ for {
+ switch ctx := c.(type) {
+ case *valueCtx:
+ if key == ctx.key {
+ return ctx.val
+ }
+ c = ctx.Context
+ case *cancelCtx:
+ if key == &cancelCtxKey {
+ return c
+ }
+ c = ctx.Context
+ case withoutCancelCtx:
+ if key == &cancelCtxKey {
+ // This implements Cause(ctx) == nil
+ // when ctx is created using WithoutCancel.
+ return nil
+ }
+ c = ctx.c
+ case *timerCtx:
+ if key == &cancelCtxKey {
+ return &ctx.cancelCtx
+ }
+ c = ctx.Context
+ case backgroundCtx, todoCtx:
+ return nil
+ default:
+ return c.Value(key)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/context/context_test.go b/platform/dbops/binaries/go/go/src/context/context_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..57066c968596f631f63b811f35e84d97b3570ca6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/context_test.go
@@ -0,0 +1,297 @@
+// 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 context
+
+// Tests in package context cannot depend directly on package testing due to an import cycle.
+// If your test does requires access to unexported members of the context package,
+// add your test below as `func XTestFoo(t testingT)` and add a `TestFoo` to x_test.go
+// that calls it. Otherwise, write a regular test in a test.go file in package context_test.
+
+import (
+ "time"
+)
+
+type testingT interface {
+ Deadline() (time.Time, bool)
+ Error(args ...any)
+ Errorf(format string, args ...any)
+ Fail()
+ FailNow()
+ Failed() bool
+ Fatal(args ...any)
+ Fatalf(format string, args ...any)
+ Helper()
+ Log(args ...any)
+ Logf(format string, args ...any)
+ Name() string
+ Parallel()
+ Skip(args ...any)
+ SkipNow()
+ Skipf(format string, args ...any)
+ Skipped() bool
+}
+
+const veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time
+
+func contains(m map[canceler]struct{}, key canceler) bool {
+ _, ret := m[key]
+ return ret
+}
+
+func XTestParentFinishesChild(t testingT) {
+ // Context tree:
+ // parent -> cancelChild
+ // parent -> valueChild -> timerChild
+ // parent -> afterChild
+ parent, cancel := WithCancel(Background())
+ cancelChild, stop := WithCancel(parent)
+ defer stop()
+ valueChild := WithValue(parent, "key", "value")
+ timerChild, stop := WithTimeout(valueChild, veryLongDuration)
+ defer stop()
+ afterStop := AfterFunc(parent, func() {})
+ defer afterStop()
+
+ select {
+ case x := <-parent.Done():
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
+ case x := <-cancelChild.Done():
+ t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x)
+ case x := <-timerChild.Done():
+ t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x)
+ case x := <-valueChild.Done():
+ t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+
+ // The parent's children should contain the three cancelable children.
+ pc := parent.(*cancelCtx)
+ cc := cancelChild.(*cancelCtx)
+ tc := timerChild.(*timerCtx)
+ pc.mu.Lock()
+ var ac *afterFuncCtx
+ for c := range pc.children {
+ if a, ok := c.(*afterFuncCtx); ok {
+ ac = a
+ break
+ }
+ }
+ if len(pc.children) != 3 || !contains(pc.children, cc) || !contains(pc.children, tc) || ac == nil {
+ t.Errorf("bad linkage: pc.children = %v, want %v, %v, and an afterFunc",
+ pc.children, cc, tc)
+ }
+ pc.mu.Unlock()
+
+ if p, ok := parentCancelCtx(cc.Context); !ok || p != pc {
+ t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc)
+ }
+ if p, ok := parentCancelCtx(tc.Context); !ok || p != pc {
+ t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc)
+ }
+ if p, ok := parentCancelCtx(ac.Context); !ok || p != pc {
+ t.Errorf("bad linkage: parentCancelCtx(afterChild.Context) = %v, %v want %v, true", p, ok, pc)
+ }
+
+ cancel()
+
+ pc.mu.Lock()
+ if len(pc.children) != 0 {
+ t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children)
+ }
+ pc.mu.Unlock()
+
+ // parent and children should all be finished.
+ check := func(ctx Context, name string) {
+ select {
+ case <-ctx.Done():
+ default:
+ t.Errorf("<-%s.Done() blocked, but shouldn't have", name)
+ }
+ if e := ctx.Err(); e != Canceled {
+ t.Errorf("%s.Err() == %v want %v", name, e, Canceled)
+ }
+ }
+ check(parent, "parent")
+ check(cancelChild, "cancelChild")
+ check(valueChild, "valueChild")
+ check(timerChild, "timerChild")
+
+ // WithCancel should return a canceled context on a canceled parent.
+ precanceledChild := WithValue(parent, "key", "value")
+ select {
+ case <-precanceledChild.Done():
+ default:
+ t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have")
+ }
+ if e := precanceledChild.Err(); e != Canceled {
+ t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled)
+ }
+}
+
+func XTestChildFinishesFirst(t testingT) {
+ cancelable, stop := WithCancel(Background())
+ defer stop()
+ for _, parent := range []Context{Background(), cancelable} {
+ child, cancel := WithCancel(parent)
+
+ select {
+ case x := <-parent.Done():
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
+ case x := <-child.Done():
+ t.Errorf("<-child.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+
+ cc := child.(*cancelCtx)
+ pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background()
+ if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) {
+ t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok)
+ }
+
+ if pcok {
+ pc.mu.Lock()
+ if len(pc.children) != 1 || !contains(pc.children, cc) {
+ t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc)
+ }
+ pc.mu.Unlock()
+ }
+
+ cancel()
+
+ if pcok {
+ pc.mu.Lock()
+ if len(pc.children) != 0 {
+ t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children)
+ }
+ pc.mu.Unlock()
+ }
+
+ // child should be finished.
+ select {
+ case <-child.Done():
+ default:
+ t.Errorf("<-child.Done() blocked, but shouldn't have")
+ }
+ if e := child.Err(); e != Canceled {
+ t.Errorf("child.Err() == %v want %v", e, Canceled)
+ }
+
+ // parent should not be finished.
+ select {
+ case x := <-parent.Done():
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+ if e := parent.Err(); e != nil {
+ t.Errorf("parent.Err() == %v want nil", e)
+ }
+ }
+}
+
+func XTestCancelRemoves(t testingT) {
+ checkChildren := func(when string, ctx Context, want int) {
+ if got := len(ctx.(*cancelCtx).children); got != want {
+ t.Errorf("%s: context has %d children, want %d", when, got, want)
+ }
+ }
+
+ ctx, _ := WithCancel(Background())
+ checkChildren("after creation", ctx, 0)
+ _, cancel := WithCancel(ctx)
+ checkChildren("with WithCancel child ", ctx, 1)
+ cancel()
+ checkChildren("after canceling WithCancel child", ctx, 0)
+
+ ctx, _ = WithCancel(Background())
+ checkChildren("after creation", ctx, 0)
+ _, cancel = WithTimeout(ctx, 60*time.Minute)
+ checkChildren("with WithTimeout child ", ctx, 1)
+ cancel()
+ checkChildren("after canceling WithTimeout child", ctx, 0)
+
+ ctx, _ = WithCancel(Background())
+ checkChildren("after creation", ctx, 0)
+ stop := AfterFunc(ctx, func() {})
+ checkChildren("with AfterFunc child ", ctx, 1)
+ stop()
+ checkChildren("after stopping AfterFunc child ", ctx, 0)
+}
+
+type myCtx struct {
+ Context
+}
+
+type myDoneCtx struct {
+ Context
+}
+
+func (d *myDoneCtx) Done() <-chan struct{} {
+ c := make(chan struct{})
+ return c
+}
+func XTestCustomContextGoroutines(t testingT) {
+ g := goroutines.Load()
+ checkNoGoroutine := func() {
+ t.Helper()
+ now := goroutines.Load()
+ if now != g {
+ t.Fatalf("%d goroutines created", now-g)
+ }
+ }
+ checkCreatedGoroutine := func() {
+ t.Helper()
+ now := goroutines.Load()
+ if now != g+1 {
+ t.Fatalf("%d goroutines created, want 1", now-g)
+ }
+ g = now
+ }
+
+ _, cancel0 := WithCancel(&myDoneCtx{Background()})
+ cancel0()
+ checkCreatedGoroutine()
+
+ _, cancel0 = WithTimeout(&myDoneCtx{Background()}, veryLongDuration)
+ cancel0()
+ checkCreatedGoroutine()
+
+ checkNoGoroutine()
+ defer checkNoGoroutine()
+
+ ctx1, cancel1 := WithCancel(Background())
+ defer cancel1()
+ checkNoGoroutine()
+
+ ctx2 := &myCtx{ctx1}
+ ctx3, cancel3 := WithCancel(ctx2)
+ defer cancel3()
+ checkNoGoroutine()
+
+ _, cancel3b := WithCancel(&myDoneCtx{ctx2})
+ defer cancel3b()
+ checkCreatedGoroutine() // ctx1 is not providing Done, must not be used
+
+ ctx4, cancel4 := WithTimeout(ctx3, veryLongDuration)
+ defer cancel4()
+ checkNoGoroutine()
+
+ ctx5, cancel5 := WithCancel(ctx4)
+ defer cancel5()
+ checkNoGoroutine()
+
+ cancel5()
+ checkNoGoroutine()
+
+ _, cancel6 := WithTimeout(ctx5, veryLongDuration)
+ defer cancel6()
+ checkNoGoroutine()
+
+ // Check applied to canceled context.
+ cancel6()
+ cancel1()
+ _, cancel7 := WithCancel(ctx5)
+ defer cancel7()
+ checkNoGoroutine()
+}
diff --git a/platform/dbops/binaries/go/go/src/context/example_test.go b/platform/dbops/binaries/go/go/src/context/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..03333b5ccae9599eb2d0cd179312d32830081e9b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/example_test.go
@@ -0,0 +1,263 @@
+// 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 context_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "sync"
+ "time"
+)
+
+var neverReady = make(chan struct{}) // never closed
+
+// This example demonstrates the use of a cancelable context to prevent a
+// goroutine leak. By the end of the example function, the goroutine started
+// by gen will return without leaking.
+func ExampleWithCancel() {
+ // gen generates integers in a separate goroutine and
+ // sends them to the returned channel.
+ // The callers of gen need to cancel the context once
+ // they are done consuming generated integers not to leak
+ // the internal goroutine started by gen.
+ gen := func(ctx context.Context) <-chan int {
+ dst := make(chan int)
+ n := 1
+ go func() {
+ for {
+ select {
+ case <-ctx.Done():
+ return // returning not to leak the goroutine
+ case dst <- n:
+ n++
+ }
+ }
+ }()
+ return dst
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel() // cancel when we are finished consuming integers
+
+ for n := range gen(ctx) {
+ fmt.Println(n)
+ if n == 5 {
+ break
+ }
+ }
+ // Output:
+ // 1
+ // 2
+ // 3
+ // 4
+ // 5
+}
+
+// This example passes a context with an arbitrary deadline to tell a blocking
+// function that it should abandon its work as soon as it gets to it.
+func ExampleWithDeadline() {
+ d := time.Now().Add(shortDuration)
+ ctx, cancel := context.WithDeadline(context.Background(), d)
+
+ // Even though ctx will be expired, it is good practice to call its
+ // cancellation function in any case. Failure to do so may keep the
+ // context and its parent alive longer than necessary.
+ defer cancel()
+
+ select {
+ case <-neverReady:
+ fmt.Println("ready")
+ case <-ctx.Done():
+ fmt.Println(ctx.Err())
+ }
+
+ // Output:
+ // context deadline exceeded
+}
+
+// This example passes a context with a timeout to tell a blocking function that
+// it should abandon its work after the timeout elapses.
+func ExampleWithTimeout() {
+ // Pass a context with a timeout to tell a blocking function that it
+ // should abandon its work after the timeout elapses.
+ ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
+ defer cancel()
+
+ select {
+ case <-neverReady:
+ fmt.Println("ready")
+ case <-ctx.Done():
+ fmt.Println(ctx.Err()) // prints "context deadline exceeded"
+ }
+
+ // Output:
+ // context deadline exceeded
+}
+
+// This example demonstrates how a value can be passed to the context
+// and also how to retrieve it if it exists.
+func ExampleWithValue() {
+ type favContextKey string
+
+ f := func(ctx context.Context, k favContextKey) {
+ if v := ctx.Value(k); v != nil {
+ fmt.Println("found value:", v)
+ return
+ }
+ fmt.Println("key not found:", k)
+ }
+
+ k := favContextKey("language")
+ ctx := context.WithValue(context.Background(), k, "Go")
+
+ f(ctx, k)
+ f(ctx, favContextKey("color"))
+
+ // Output:
+ // found value: Go
+ // key not found: color
+}
+
+// This example uses AfterFunc to define a function which waits on a sync.Cond,
+// stopping the wait when a context is canceled.
+func ExampleAfterFunc_cond() {
+ waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error {
+ stopf := context.AfterFunc(ctx, func() {
+ // We need to acquire cond.L here to be sure that the Broadcast
+ // below won't occur before the call to Wait, which would result
+ // in a missed signal (and deadlock).
+ cond.L.Lock()
+ defer cond.L.Unlock()
+
+ // If multiple goroutines are waiting on cond simultaneously,
+ // we need to make sure we wake up exactly this one.
+ // That means that we need to Broadcast to all of the goroutines,
+ // which will wake them all up.
+ //
+ // If there are N concurrent calls to waitOnCond, each of the goroutines
+ // will spuriously wake up O(N) other goroutines that aren't ready yet,
+ // so this will cause the overall CPU cost to be O(N²).
+ cond.Broadcast()
+ })
+ defer stopf()
+
+ // Since the wakeups are using Broadcast instead of Signal, this call to
+ // Wait may unblock due to some other goroutine's context becoming done,
+ // so to be sure that ctx is actually done we need to check it in a loop.
+ for !conditionMet() {
+ cond.Wait()
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ }
+
+ return nil
+ }
+
+ cond := sync.NewCond(new(sync.Mutex))
+
+ var wg sync.WaitGroup
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
+ defer cancel()
+
+ cond.L.Lock()
+ defer cond.L.Unlock()
+
+ err := waitOnCond(ctx, cond, func() bool { return false })
+ fmt.Println(err)
+ }()
+ }
+ wg.Wait()
+
+ // Output:
+ // context deadline exceeded
+ // context deadline exceeded
+ // context deadline exceeded
+ // context deadline exceeded
+}
+
+// This example uses AfterFunc to define a function which reads from a net.Conn,
+// stopping the read when a context is canceled.
+func ExampleAfterFunc_connection() {
+ readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) {
+ stopc := make(chan struct{})
+ stop := context.AfterFunc(ctx, func() {
+ conn.SetReadDeadline(time.Now())
+ close(stopc)
+ })
+ n, err = conn.Read(b)
+ if !stop() {
+ // The AfterFunc was started.
+ // Wait for it to complete, and reset the Conn's deadline.
+ <-stopc
+ conn.SetReadDeadline(time.Time{})
+ return n, ctx.Err()
+ }
+ return n, err
+ }
+
+ listener, err := net.Listen("tcp", ":0")
+ if err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer listener.Close()
+
+ conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String())
+ if err != nil {
+ fmt.Println(err)
+ return
+ }
+ defer conn.Close()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
+ defer cancel()
+
+ b := make([]byte, 1024)
+ _, err = readFromConn(ctx, conn, b)
+ fmt.Println(err)
+
+ // Output:
+ // context deadline exceeded
+}
+
+// This example uses AfterFunc to define a function which combines
+// the cancellation signals of two Contexts.
+func ExampleAfterFunc_merge() {
+ // mergeCancel returns a context that contains the values of ctx,
+ // and which is canceled when either ctx or cancelCtx is canceled.
+ mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithCancelCause(ctx)
+ stop := context.AfterFunc(cancelCtx, func() {
+ cancel(context.Cause(cancelCtx))
+ })
+ return ctx, func() {
+ stop()
+ cancel(context.Canceled)
+ }
+ }
+
+ ctx1, cancel1 := context.WithCancelCause(context.Background())
+ defer cancel1(errors.New("ctx1 canceled"))
+
+ ctx2, cancel2 := context.WithCancelCause(context.Background())
+
+ mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2)
+ defer mergedCancel()
+
+ cancel2(errors.New("ctx2 canceled"))
+ <-mergedCtx.Done()
+ fmt.Println(context.Cause(mergedCtx))
+
+ // Output:
+ // ctx2 canceled
+}
diff --git a/platform/dbops/binaries/go/go/src/context/net_test.go b/platform/dbops/binaries/go/go/src/context/net_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a007689d363713a4c548623ef934c6bb83918ade
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/net_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 context_test
+
+import (
+ "context"
+ "net"
+ "testing"
+)
+
+func TestDeadlineExceededIsNetError(t *testing.T) {
+ err, ok := context.DeadlineExceeded.(net.Error)
+ if !ok {
+ t.Fatal("DeadlineExceeded does not implement net.Error")
+ }
+ if !err.Timeout() || !err.Temporary() {
+ t.Fatalf("Timeout() = %v, Temporary() = %v, want true, true", err.Timeout(), err.Temporary())
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/context/x_test.go b/platform/dbops/binaries/go/go/src/context/x_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b1012fad8758a405121149d7e5c36eaef227ee39
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/context/x_test.go
@@ -0,0 +1,1077 @@
+// 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 context_test
+
+import (
+ . "context"
+ "errors"
+ "fmt"
+ "math/rand"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// Each XTestFoo in context_test.go must be called from a TestFoo here to run.
+func TestParentFinishesChild(t *testing.T) {
+ XTestParentFinishesChild(t) // uses unexported context types
+}
+func TestChildFinishesFirst(t *testing.T) {
+ XTestChildFinishesFirst(t) // uses unexported context types
+}
+func TestCancelRemoves(t *testing.T) {
+ XTestCancelRemoves(t) // uses unexported context types
+}
+func TestCustomContextGoroutines(t *testing.T) {
+ XTestCustomContextGoroutines(t) // reads the context.goroutines counter
+}
+
+// The following are regular tests in package context_test.
+
+// otherContext is a Context that's not one of the types defined in context.go.
+// This lets us test code paths that differ based on the underlying type of the
+// Context.
+type otherContext struct {
+ Context
+}
+
+const (
+ shortDuration = 1 * time.Millisecond // a reasonable duration to block in a test
+ veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time
+)
+
+// quiescent returns an arbitrary duration by which the program should have
+// completed any remaining work and reached a steady (idle) state.
+func quiescent(t *testing.T) time.Duration {
+ deadline, ok := t.Deadline()
+ if !ok {
+ return 5 * time.Second
+ }
+
+ const arbitraryCleanupMargin = 1 * time.Second
+ return time.Until(deadline) - arbitraryCleanupMargin
+}
+func TestBackground(t *testing.T) {
+ c := Background()
+ if c == nil {
+ t.Fatalf("Background returned nil")
+ }
+ select {
+ case x := <-c.Done():
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+ if got, want := fmt.Sprint(c), "context.Background"; got != want {
+ t.Errorf("Background().String() = %q want %q", got, want)
+ }
+}
+
+func TestTODO(t *testing.T) {
+ c := TODO()
+ if c == nil {
+ t.Fatalf("TODO returned nil")
+ }
+ select {
+ case x := <-c.Done():
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+ if got, want := fmt.Sprint(c), "context.TODO"; got != want {
+ t.Errorf("TODO().String() = %q want %q", got, want)
+ }
+}
+
+func TestWithCancel(t *testing.T) {
+ c1, cancel := WithCancel(Background())
+
+ if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want {
+ t.Errorf("c1.String() = %q want %q", got, want)
+ }
+
+ o := otherContext{c1}
+ c2, _ := WithCancel(o)
+ contexts := []Context{c1, o, c2}
+
+ for i, c := range contexts {
+ if d := c.Done(); d == nil {
+ t.Errorf("c[%d].Done() == %v want non-nil", i, d)
+ }
+ if e := c.Err(); e != nil {
+ t.Errorf("c[%d].Err() == %v want nil", i, e)
+ }
+
+ select {
+ case x := <-c.Done():
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
+ default:
+ }
+ }
+
+ cancel() // Should propagate synchronously.
+ for i, c := range contexts {
+ select {
+ case <-c.Done():
+ default:
+ t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i)
+ }
+ if e := c.Err(); e != Canceled {
+ t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled)
+ }
+ }
+}
+
+func testDeadline(c Context, name string, t *testing.T) {
+ t.Helper()
+ d := quiescent(t)
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ t.Fatalf("%s: context not timed out after %v", name, d)
+ case <-c.Done():
+ }
+ if e := c.Err(); e != DeadlineExceeded {
+ t.Errorf("%s: c.Err() == %v; want %v", name, e, DeadlineExceeded)
+ }
+}
+
+func TestDeadline(t *testing.T) {
+ t.Parallel()
+
+ c, _ := WithDeadline(Background(), time.Now().Add(shortDuration))
+ if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
+ t.Errorf("c.String() = %q want prefix %q", got, prefix)
+ }
+ testDeadline(c, "WithDeadline", t)
+
+ c, _ = WithDeadline(Background(), time.Now().Add(shortDuration))
+ o := otherContext{c}
+ testDeadline(o, "WithDeadline+otherContext", t)
+
+ c, _ = WithDeadline(Background(), time.Now().Add(shortDuration))
+ o = otherContext{c}
+ c, _ = WithDeadline(o, time.Now().Add(veryLongDuration))
+ testDeadline(c, "WithDeadline+otherContext+WithDeadline", t)
+
+ c, _ = WithDeadline(Background(), time.Now().Add(-shortDuration))
+ testDeadline(c, "WithDeadline+inthepast", t)
+
+ c, _ = WithDeadline(Background(), time.Now())
+ testDeadline(c, "WithDeadline+now", t)
+}
+
+func TestTimeout(t *testing.T) {
+ t.Parallel()
+
+ c, _ := WithTimeout(Background(), shortDuration)
+ if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
+ t.Errorf("c.String() = %q want prefix %q", got, prefix)
+ }
+ testDeadline(c, "WithTimeout", t)
+
+ c, _ = WithTimeout(Background(), shortDuration)
+ o := otherContext{c}
+ testDeadline(o, "WithTimeout+otherContext", t)
+
+ c, _ = WithTimeout(Background(), shortDuration)
+ o = otherContext{c}
+ c, _ = WithTimeout(o, veryLongDuration)
+ testDeadline(c, "WithTimeout+otherContext+WithTimeout", t)
+}
+
+func TestCanceledTimeout(t *testing.T) {
+ c, _ := WithTimeout(Background(), time.Second)
+ o := otherContext{c}
+ c, cancel := WithTimeout(o, veryLongDuration)
+ cancel() // Should propagate synchronously.
+ select {
+ case <-c.Done():
+ default:
+ t.Errorf("<-c.Done() blocked, but shouldn't have")
+ }
+ if e := c.Err(); e != Canceled {
+ t.Errorf("c.Err() == %v want %v", e, Canceled)
+ }
+}
+
+type key1 int
+type key2 int
+
+var k1 = key1(1)
+var k2 = key2(1) // same int as k1, different type
+var k3 = key2(3) // same type as k2, different int
+
+func TestValues(t *testing.T) {
+ check := func(c Context, nm, v1, v2, v3 string) {
+ if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 {
+ t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0)
+ }
+ if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 {
+ t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0)
+ }
+ if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 {
+ t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0)
+ }
+ }
+
+ c0 := Background()
+ check(c0, "c0", "", "", "")
+
+ c1 := WithValue(Background(), k1, "c1k1")
+ check(c1, "c1", "c1k1", "", "")
+
+ if got, want := fmt.Sprint(c1), `context.Background.WithValue(type context_test.key1, val c1k1)`; got != want {
+ t.Errorf("c.String() = %q want %q", got, want)
+ }
+
+ c2 := WithValue(c1, k2, "c2k2")
+ check(c2, "c2", "c1k1", "c2k2", "")
+
+ c3 := WithValue(c2, k3, "c3k3")
+ check(c3, "c2", "c1k1", "c2k2", "c3k3")
+
+ c4 := WithValue(c3, k1, nil)
+ check(c4, "c4", "", "c2k2", "c3k3")
+
+ o0 := otherContext{Background()}
+ check(o0, "o0", "", "", "")
+
+ o1 := otherContext{WithValue(Background(), k1, "c1k1")}
+ check(o1, "o1", "c1k1", "", "")
+
+ o2 := WithValue(o1, k2, "o2k2")
+ check(o2, "o2", "c1k1", "o2k2", "")
+
+ o3 := otherContext{c4}
+ check(o3, "o3", "", "c2k2", "c3k3")
+
+ o4 := WithValue(o3, k3, nil)
+ check(o4, "o4", "", "c2k2", "")
+}
+
+func TestAllocs(t *testing.T) {
+ bg := Background()
+ for _, test := range []struct {
+ desc string
+ f func()
+ limit float64
+ gccgoLimit float64
+ }{
+ {
+ desc: "Background()",
+ f: func() { Background() },
+ limit: 0,
+ gccgoLimit: 0,
+ },
+ {
+ desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1),
+ f: func() {
+ c := WithValue(bg, k1, nil)
+ c.Value(k1)
+ },
+ limit: 3,
+ gccgoLimit: 3,
+ },
+ {
+ desc: "WithTimeout(bg, 1*time.Nanosecond)",
+ f: func() {
+ c, _ := WithTimeout(bg, 1*time.Nanosecond)
+ <-c.Done()
+ },
+ limit: 12,
+ gccgoLimit: 15,
+ },
+ {
+ desc: "WithCancel(bg)",
+ f: func() {
+ c, cancel := WithCancel(bg)
+ cancel()
+ <-c.Done()
+ },
+ limit: 5,
+ gccgoLimit: 8,
+ },
+ {
+ desc: "WithTimeout(bg, 5*time.Millisecond)",
+ f: func() {
+ c, cancel := WithTimeout(bg, 5*time.Millisecond)
+ cancel()
+ <-c.Done()
+ },
+ limit: 8,
+ gccgoLimit: 25,
+ },
+ } {
+ limit := test.limit
+ if runtime.Compiler == "gccgo" {
+ // gccgo does not yet do escape analysis.
+ // TODO(iant): Remove this when gccgo does do escape analysis.
+ limit = test.gccgoLimit
+ }
+ numRuns := 100
+ if testing.Short() {
+ numRuns = 10
+ }
+ if n := testing.AllocsPerRun(numRuns, test.f); n > limit {
+ t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit))
+ }
+ }
+}
+
+func TestSimultaneousCancels(t *testing.T) {
+ root, cancel := WithCancel(Background())
+ m := map[Context]CancelFunc{root: cancel}
+ q := []Context{root}
+ // Create a tree of contexts.
+ for len(q) != 0 && len(m) < 100 {
+ parent := q[0]
+ q = q[1:]
+ for i := 0; i < 4; i++ {
+ ctx, cancel := WithCancel(parent)
+ m[ctx] = cancel
+ q = append(q, ctx)
+ }
+ }
+ // Start all the cancels in a random order.
+ var wg sync.WaitGroup
+ wg.Add(len(m))
+ for _, cancel := range m {
+ go func(cancel CancelFunc) {
+ cancel()
+ wg.Done()
+ }(cancel)
+ }
+
+ d := quiescent(t)
+ stuck := make(chan struct{})
+ timer := time.AfterFunc(d, func() { close(stuck) })
+ defer timer.Stop()
+
+ // Wait on all the contexts in a random order.
+ for ctx := range m {
+ select {
+ case <-ctx.Done():
+ case <-stuck:
+ buf := make([]byte, 10<<10)
+ n := runtime.Stack(buf, true)
+ t.Fatalf("timed out after %v waiting for <-ctx.Done(); stacks:\n%s", d, buf[:n])
+ }
+ }
+ // Wait for all the cancel functions to return.
+ done := make(chan struct{})
+ go func() {
+ wg.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-stuck:
+ buf := make([]byte, 10<<10)
+ n := runtime.Stack(buf, true)
+ t.Fatalf("timed out after %v waiting for cancel functions; stacks:\n%s", d, buf[:n])
+ }
+}
+
+func TestInterlockedCancels(t *testing.T) {
+ parent, cancelParent := WithCancel(Background())
+ child, cancelChild := WithCancel(parent)
+ go func() {
+ <-parent.Done()
+ cancelChild()
+ }()
+ cancelParent()
+ d := quiescent(t)
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-child.Done():
+ case <-timer.C:
+ buf := make([]byte, 10<<10)
+ n := runtime.Stack(buf, true)
+ t.Fatalf("timed out after %v waiting for child.Done(); stacks:\n%s", d, buf[:n])
+ }
+}
+
+func TestLayersCancel(t *testing.T) {
+ testLayers(t, time.Now().UnixNano(), false)
+}
+
+func TestLayersTimeout(t *testing.T) {
+ testLayers(t, time.Now().UnixNano(), true)
+}
+
+func testLayers(t *testing.T, seed int64, testTimeout bool) {
+ t.Parallel()
+
+ r := rand.New(rand.NewSource(seed))
+ prefix := fmt.Sprintf("seed=%d", seed)
+ errorf := func(format string, a ...any) {
+ t.Errorf(prefix+format, a...)
+ }
+ const (
+ minLayers = 30
+ )
+ type value int
+ var (
+ vals []*value
+ cancels []CancelFunc
+ numTimers int
+ ctx = Background()
+ )
+ for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ {
+ switch r.Intn(3) {
+ case 0:
+ v := new(value)
+ ctx = WithValue(ctx, v, v)
+ vals = append(vals, v)
+ case 1:
+ var cancel CancelFunc
+ ctx, cancel = WithCancel(ctx)
+ cancels = append(cancels, cancel)
+ case 2:
+ var cancel CancelFunc
+ d := veryLongDuration
+ if testTimeout {
+ d = shortDuration
+ }
+ ctx, cancel = WithTimeout(ctx, d)
+ cancels = append(cancels, cancel)
+ numTimers++
+ }
+ }
+ checkValues := func(when string) {
+ for _, key := range vals {
+ if val := ctx.Value(key).(*value); key != val {
+ errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key)
+ }
+ }
+ }
+ if !testTimeout {
+ select {
+ case <-ctx.Done():
+ errorf("ctx should not be canceled yet")
+ default:
+ }
+ }
+ if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) {
+ t.Errorf("ctx.String() = %q want prefix %q", s, prefix)
+ }
+ t.Log(ctx)
+ checkValues("before cancel")
+ if testTimeout {
+ d := quiescent(t)
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ case <-timer.C:
+ errorf("ctx should have timed out after %v", d)
+ }
+ checkValues("after timeout")
+ } else {
+ cancel := cancels[r.Intn(len(cancels))]
+ cancel()
+ select {
+ case <-ctx.Done():
+ default:
+ errorf("ctx should be canceled")
+ }
+ checkValues("after cancel")
+ }
+}
+
+func TestWithCancelCanceledParent(t *testing.T) {
+ parent, pcancel := WithCancelCause(Background())
+ cause := fmt.Errorf("Because!")
+ pcancel(cause)
+
+ c, _ := WithCancel(parent)
+ select {
+ case <-c.Done():
+ default:
+ t.Errorf("child not done immediately upon construction")
+ }
+ if got, want := c.Err(), Canceled; got != want {
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
+ }
+ if got, want := Cause(c), cause; got != want {
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
+ }
+}
+
+func TestWithCancelSimultaneouslyCanceledParent(t *testing.T) {
+ // Cancel the parent goroutine concurrently with creating a child.
+ for i := 0; i < 100; i++ {
+ parent, pcancel := WithCancelCause(Background())
+ cause := fmt.Errorf("Because!")
+ go pcancel(cause)
+
+ c, _ := WithCancel(parent)
+ <-c.Done()
+ if got, want := c.Err(), Canceled; got != want {
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
+ }
+ if got, want := Cause(c), cause; got != want {
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
+ }
+ }
+}
+
+func TestWithValueChecksKey(t *testing.T) {
+ panicVal := recoveredValue(func() { _ = WithValue(Background(), []byte("foo"), "bar") })
+ if panicVal == nil {
+ t.Error("expected panic")
+ }
+ panicVal = recoveredValue(func() { _ = WithValue(Background(), nil, "bar") })
+ if got, want := fmt.Sprint(panicVal), "nil key"; got != want {
+ t.Errorf("panic = %q; want %q", got, want)
+ }
+}
+
+func TestInvalidDerivedFail(t *testing.T) {
+ panicVal := recoveredValue(func() { _, _ = WithCancel(nil) })
+ if panicVal == nil {
+ t.Error("expected panic")
+ }
+ panicVal = recoveredValue(func() { _, _ = WithDeadline(nil, time.Now().Add(shortDuration)) })
+ if panicVal == nil {
+ t.Error("expected panic")
+ }
+ panicVal = recoveredValue(func() { _ = WithValue(nil, "foo", "bar") })
+ if panicVal == nil {
+ t.Error("expected panic")
+ }
+}
+
+func recoveredValue(fn func()) (v any) {
+ defer func() { v = recover() }()
+ fn()
+ return
+}
+
+func TestDeadlineExceededSupportsTimeout(t *testing.T) {
+ i, ok := DeadlineExceeded.(interface {
+ Timeout() bool
+ })
+ if !ok {
+ t.Fatal("DeadlineExceeded does not support Timeout interface")
+ }
+ if !i.Timeout() {
+ t.Fatal("wrong value for timeout")
+ }
+}
+func TestCause(t *testing.T) {
+ var (
+ forever = 1e6 * time.Second
+ parentCause = fmt.Errorf("parentCause")
+ childCause = fmt.Errorf("childCause")
+ tooSlow = fmt.Errorf("tooSlow")
+ finishedEarly = fmt.Errorf("finishedEarly")
+ )
+ for _, test := range []struct {
+ name string
+ ctx func() Context
+ err error
+ cause error
+ }{
+ {
+ name: "Background",
+ ctx: Background,
+ err: nil,
+ cause: nil,
+ },
+ {
+ name: "TODO",
+ ctx: TODO,
+ err: nil,
+ cause: nil,
+ },
+ {
+ name: "WithCancel",
+ ctx: func() Context {
+ ctx, cancel := WithCancel(Background())
+ cancel()
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithCancelCause",
+ ctx: func() Context {
+ ctx, cancel := WithCancelCause(Background())
+ cancel(parentCause)
+ return ctx
+ },
+ err: Canceled,
+ cause: parentCause,
+ },
+ {
+ name: "WithCancelCause nil",
+ ctx: func() Context {
+ ctx, cancel := WithCancelCause(Background())
+ cancel(nil)
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithCancelCause: parent cause before child",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancelCause(Background())
+ ctx, cancelChild := WithCancelCause(ctx)
+ cancelParent(parentCause)
+ cancelChild(childCause)
+ return ctx
+ },
+ err: Canceled,
+ cause: parentCause,
+ },
+ {
+ name: "WithCancelCause: parent cause after child",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancelCause(Background())
+ ctx, cancelChild := WithCancelCause(ctx)
+ cancelChild(childCause)
+ cancelParent(parentCause)
+ return ctx
+ },
+ err: Canceled,
+ cause: childCause,
+ },
+ {
+ name: "WithCancelCause: parent cause before nil",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancelCause(Background())
+ ctx, cancelChild := WithCancel(ctx)
+ cancelParent(parentCause)
+ cancelChild()
+ return ctx
+ },
+ err: Canceled,
+ cause: parentCause,
+ },
+ {
+ name: "WithCancelCause: parent cause after nil",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancelCause(Background())
+ ctx, cancelChild := WithCancel(ctx)
+ cancelChild()
+ cancelParent(parentCause)
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithCancelCause: child cause after nil",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancel(Background())
+ ctx, cancelChild := WithCancelCause(ctx)
+ cancelParent()
+ cancelChild(childCause)
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithCancelCause: child cause before nil",
+ ctx: func() Context {
+ ctx, cancelParent := WithCancel(Background())
+ ctx, cancelChild := WithCancelCause(ctx)
+ cancelChild(childCause)
+ cancelParent()
+ return ctx
+ },
+ err: Canceled,
+ cause: childCause,
+ },
+ {
+ name: "WithTimeout",
+ ctx: func() Context {
+ ctx, cancel := WithTimeout(Background(), 0)
+ cancel()
+ return ctx
+ },
+ err: DeadlineExceeded,
+ cause: DeadlineExceeded,
+ },
+ {
+ name: "WithTimeout canceled",
+ ctx: func() Context {
+ ctx, cancel := WithTimeout(Background(), forever)
+ cancel()
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithTimeoutCause",
+ ctx: func() Context {
+ ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow)
+ cancel()
+ return ctx
+ },
+ err: DeadlineExceeded,
+ cause: tooSlow,
+ },
+ {
+ name: "WithTimeoutCause canceled",
+ ctx: func() Context {
+ ctx, cancel := WithTimeoutCause(Background(), forever, tooSlow)
+ cancel()
+ return ctx
+ },
+ err: Canceled,
+ cause: Canceled,
+ },
+ {
+ name: "WithTimeoutCause stacked",
+ ctx: func() Context {
+ ctx, cancel := WithCancelCause(Background())
+ ctx, _ = WithTimeoutCause(ctx, 0, tooSlow)
+ cancel(finishedEarly)
+ return ctx
+ },
+ err: DeadlineExceeded,
+ cause: tooSlow,
+ },
+ {
+ name: "WithTimeoutCause stacked canceled",
+ ctx: func() Context {
+ ctx, cancel := WithCancelCause(Background())
+ ctx, _ = WithTimeoutCause(ctx, forever, tooSlow)
+ cancel(finishedEarly)
+ return ctx
+ },
+ err: Canceled,
+ cause: finishedEarly,
+ },
+ {
+ name: "WithoutCancel",
+ ctx: func() Context {
+ return WithoutCancel(Background())
+ },
+ err: nil,
+ cause: nil,
+ },
+ {
+ name: "WithoutCancel canceled",
+ ctx: func() Context {
+ ctx, cancel := WithCancelCause(Background())
+ ctx = WithoutCancel(ctx)
+ cancel(finishedEarly)
+ return ctx
+ },
+ err: nil,
+ cause: nil,
+ },
+ {
+ name: "WithoutCancel timeout",
+ ctx: func() Context {
+ ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow)
+ ctx = WithoutCancel(ctx)
+ cancel()
+ return ctx
+ },
+ err: nil,
+ cause: nil,
+ },
+ } {
+ test := test
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+ ctx := test.ctx()
+ if got, want := ctx.Err(), test.err; want != got {
+ t.Errorf("ctx.Err() = %v want %v", got, want)
+ }
+ if got, want := Cause(ctx), test.cause; want != got {
+ t.Errorf("Cause(ctx) = %v want %v", got, want)
+ }
+ })
+ }
+}
+
+func TestCauseRace(t *testing.T) {
+ cause := errors.New("TestCauseRace")
+ ctx, cancel := WithCancelCause(Background())
+ go func() {
+ cancel(cause)
+ }()
+ for {
+ // Poll Cause, rather than waiting for Done, to test that
+ // access to the underlying cause is synchronized properly.
+ if err := Cause(ctx); err != nil {
+ if err != cause {
+ t.Errorf("Cause returned %v, want %v", err, cause)
+ }
+ break
+ }
+ runtime.Gosched()
+ }
+}
+
+func TestWithoutCancel(t *testing.T) {
+ key, value := "key", "value"
+ ctx := WithValue(Background(), key, value)
+ ctx = WithoutCancel(ctx)
+ if d, ok := ctx.Deadline(); !d.IsZero() || ok != false {
+ t.Errorf("ctx.Deadline() = %v, %v want zero, false", d, ok)
+ }
+ if done := ctx.Done(); done != nil {
+ t.Errorf("ctx.Deadline() = %v want nil", done)
+ }
+ if err := ctx.Err(); err != nil {
+ t.Errorf("ctx.Err() = %v want nil", err)
+ }
+ if v := ctx.Value(key); v != value {
+ t.Errorf("ctx.Value(%q) = %q want %q", key, v, value)
+ }
+}
+
+type customDoneContext struct {
+ Context
+ donec chan struct{}
+}
+
+func (c *customDoneContext) Done() <-chan struct{} {
+ return c.donec
+}
+
+func TestCustomContextPropagation(t *testing.T) {
+ cause := errors.New("TestCustomContextPropagation")
+ donec := make(chan struct{})
+ ctx1, cancel1 := WithCancelCause(Background())
+ ctx2 := &customDoneContext{
+ Context: ctx1,
+ donec: donec,
+ }
+ ctx3, cancel3 := WithCancel(ctx2)
+ defer cancel3()
+
+ cancel1(cause)
+ close(donec)
+
+ <-ctx3.Done()
+ if got, want := ctx3.Err(), Canceled; got != want {
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
+ }
+ if got, want := Cause(ctx3), cause; got != want {
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
+ }
+}
+
+// customCauseContext is a custom Context used to test context.Cause.
+type customCauseContext struct {
+ mu sync.Mutex
+ done chan struct{}
+ err error
+
+ cancelChild CancelFunc
+}
+
+func (ccc *customCauseContext) Deadline() (deadline time.Time, ok bool) {
+ return
+}
+
+func (ccc *customCauseContext) Done() <-chan struct{} {
+ ccc.mu.Lock()
+ defer ccc.mu.Unlock()
+ return ccc.done
+}
+
+func (ccc *customCauseContext) Err() error {
+ ccc.mu.Lock()
+ defer ccc.mu.Unlock()
+ return ccc.err
+}
+
+func (ccc *customCauseContext) Value(key any) any {
+ return nil
+}
+
+func (ccc *customCauseContext) cancel() {
+ ccc.mu.Lock()
+ ccc.err = Canceled
+ close(ccc.done)
+ cancelChild := ccc.cancelChild
+ ccc.mu.Unlock()
+
+ if cancelChild != nil {
+ cancelChild()
+ }
+}
+
+func (ccc *customCauseContext) setCancelChild(cancelChild CancelFunc) {
+ ccc.cancelChild = cancelChild
+}
+
+func TestCustomContextCause(t *testing.T) {
+ // Test if we cancel a custom context, Err and Cause return Canceled.
+ ccc := &customCauseContext{
+ done: make(chan struct{}),
+ }
+ ccc.cancel()
+ if got := ccc.Err(); got != Canceled {
+ t.Errorf("ccc.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ccc); got != Canceled {
+ t.Errorf("Cause(ccc) = %v, want %v", got, Canceled)
+ }
+
+ // Test that if we pass a custom context to WithCancelCause,
+ // and then cancel that child context with a cause,
+ // that the cause of the child canceled context is correct
+ // but that the parent custom context is not canceled.
+ ccc = &customCauseContext{
+ done: make(chan struct{}),
+ }
+ ctx, causeFunc := WithCancelCause(ccc)
+ cause := errors.New("TestCustomContextCause")
+ causeFunc(cause)
+ if got := ctx.Err(); got != Canceled {
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ctx); got != cause {
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause)
+ }
+ if got := ccc.Err(); got != nil {
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, nil)
+ }
+ if got := Cause(ccc); got != nil {
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, nil)
+ }
+
+ // Test that if we now cancel the parent custom context,
+ // the cause of the child canceled context is still correct,
+ // and the parent custom context is canceled without a cause.
+ ccc.cancel()
+ if got := ctx.Err(); got != Canceled {
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ctx); got != cause {
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause)
+ }
+ if got := ccc.Err(); got != Canceled {
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ccc); got != Canceled {
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled)
+ }
+
+ // Test that if we associate a custom context with a child,
+ // then canceling the custom context cancels the child.
+ ccc = &customCauseContext{
+ done: make(chan struct{}),
+ }
+ ctx, cancelFunc := WithCancel(ccc)
+ ccc.setCancelChild(cancelFunc)
+ ccc.cancel()
+ if got := ctx.Err(); got != Canceled {
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ctx); got != Canceled {
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, Canceled)
+ }
+ if got := ccc.Err(); got != Canceled {
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled)
+ }
+ if got := Cause(ccc); got != Canceled {
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled)
+ }
+}
+
+func TestAfterFuncCalledAfterCancel(t *testing.T) {
+ ctx, cancel := WithCancel(Background())
+ donec := make(chan struct{})
+ stop := AfterFunc(ctx, func() {
+ close(donec)
+ })
+ select {
+ case <-donec:
+ t.Fatalf("AfterFunc called before context is done")
+ case <-time.After(shortDuration):
+ }
+ cancel()
+ select {
+ case <-donec:
+ case <-time.After(veryLongDuration):
+ t.Fatalf("AfterFunc not called after context is canceled")
+ }
+ if stop() {
+ t.Fatalf("stop() = true, want false")
+ }
+}
+
+func TestAfterFuncCalledAfterTimeout(t *testing.T) {
+ ctx, cancel := WithTimeout(Background(), shortDuration)
+ defer cancel()
+ donec := make(chan struct{})
+ AfterFunc(ctx, func() {
+ close(donec)
+ })
+ select {
+ case <-donec:
+ case <-time.After(veryLongDuration):
+ t.Fatalf("AfterFunc not called after context is canceled")
+ }
+}
+
+func TestAfterFuncCalledImmediately(t *testing.T) {
+ ctx, cancel := WithCancel(Background())
+ cancel()
+ donec := make(chan struct{})
+ AfterFunc(ctx, func() {
+ close(donec)
+ })
+ select {
+ case <-donec:
+ case <-time.After(veryLongDuration):
+ t.Fatalf("AfterFunc not called for already-canceled context")
+ }
+}
+
+func TestAfterFuncNotCalledAfterStop(t *testing.T) {
+ ctx, cancel := WithCancel(Background())
+ donec := make(chan struct{})
+ stop := AfterFunc(ctx, func() {
+ close(donec)
+ })
+ if !stop() {
+ t.Fatalf("stop() = false, want true")
+ }
+ cancel()
+ select {
+ case <-donec:
+ t.Fatalf("AfterFunc called for already-canceled context")
+ case <-time.After(shortDuration):
+ }
+ if stop() {
+ t.Fatalf("stop() = true, want false")
+ }
+}
+
+// This test verifies that cancelling a context does not block waiting for AfterFuncs to finish.
+func TestAfterFuncCalledAsynchronously(t *testing.T) {
+ ctx, cancel := WithCancel(Background())
+ donec := make(chan struct{})
+ stop := AfterFunc(ctx, func() {
+ // The channel send blocks until donec is read from.
+ donec <- struct{}{}
+ })
+ defer stop()
+ cancel()
+ // After cancel returns, read from donec and unblock the AfterFunc.
+ select {
+ case <-donec:
+ case <-time.After(veryLongDuration):
+ t.Fatalf("AfterFunc not called after context is canceled")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/crypto/crypto.go b/platform/dbops/binaries/go/go/src/crypto/crypto.go
new file mode 100644
index 0000000000000000000000000000000000000000..2774a6b6815fdf0173e646bf7b3b1e92ec59b298
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/crypto/crypto.go
@@ -0,0 +1,223 @@
+// 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 crypto collects common cryptographic constants.
+package crypto
+
+import (
+ "hash"
+ "io"
+ "strconv"
+)
+
+// Hash identifies a cryptographic hash function that is implemented in another
+// package.
+type Hash uint
+
+// HashFunc simply returns the value of h so that [Hash] implements [SignerOpts].
+func (h Hash) HashFunc() Hash {
+ return h
+}
+
+func (h Hash) String() string {
+ switch h {
+ case MD4:
+ return "MD4"
+ case MD5:
+ return "MD5"
+ case SHA1:
+ return "SHA-1"
+ case SHA224:
+ return "SHA-224"
+ case SHA256:
+ return "SHA-256"
+ case SHA384:
+ return "SHA-384"
+ case SHA512:
+ return "SHA-512"
+ case MD5SHA1:
+ return "MD5+SHA1"
+ case RIPEMD160:
+ return "RIPEMD-160"
+ case SHA3_224:
+ return "SHA3-224"
+ case SHA3_256:
+ return "SHA3-256"
+ case SHA3_384:
+ return "SHA3-384"
+ case SHA3_512:
+ return "SHA3-512"
+ case SHA512_224:
+ return "SHA-512/224"
+ case SHA512_256:
+ return "SHA-512/256"
+ case BLAKE2s_256:
+ return "BLAKE2s-256"
+ case BLAKE2b_256:
+ return "BLAKE2b-256"
+ case BLAKE2b_384:
+ return "BLAKE2b-384"
+ case BLAKE2b_512:
+ return "BLAKE2b-512"
+ default:
+ return "unknown hash value " + strconv.Itoa(int(h))
+ }
+}
+
+const (
+ MD4 Hash = 1 + iota // import golang.org/x/crypto/md4
+ MD5 // import crypto/md5
+ SHA1 // import crypto/sha1
+ SHA224 // import crypto/sha256
+ SHA256 // import crypto/sha256
+ SHA384 // import crypto/sha512
+ SHA512 // import crypto/sha512
+ MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA
+ RIPEMD160 // import golang.org/x/crypto/ripemd160
+ SHA3_224 // import golang.org/x/crypto/sha3
+ SHA3_256 // import golang.org/x/crypto/sha3
+ SHA3_384 // import golang.org/x/crypto/sha3
+ SHA3_512 // import golang.org/x/crypto/sha3
+ SHA512_224 // import crypto/sha512
+ SHA512_256 // import crypto/sha512
+ BLAKE2s_256 // import golang.org/x/crypto/blake2s
+ BLAKE2b_256 // import golang.org/x/crypto/blake2b
+ BLAKE2b_384 // import golang.org/x/crypto/blake2b
+ BLAKE2b_512 // import golang.org/x/crypto/blake2b
+ maxHash
+)
+
+var digestSizes = []uint8{
+ MD4: 16,
+ MD5: 16,
+ SHA1: 20,
+ SHA224: 28,
+ SHA256: 32,
+ SHA384: 48,
+ SHA512: 64,
+ SHA512_224: 28,
+ SHA512_256: 32,
+ SHA3_224: 28,
+ SHA3_256: 32,
+ SHA3_384: 48,
+ SHA3_512: 64,
+ MD5SHA1: 36,
+ RIPEMD160: 20,
+ BLAKE2s_256: 32,
+ BLAKE2b_256: 32,
+ BLAKE2b_384: 48,
+ BLAKE2b_512: 64,
+}
+
+// Size returns the length, in bytes, of a digest resulting from the given hash
+// function. It doesn't require that the hash function in question be linked
+// into the program.
+func (h Hash) Size() int {
+ if h > 0 && h < maxHash {
+ return int(digestSizes[h])
+ }
+ panic("crypto: Size of unknown hash function")
+}
+
+var hashes = make([]func() hash.Hash, maxHash)
+
+// New returns a new hash.Hash calculating the given hash function. New panics
+// if the hash function is not linked into the binary.
+func (h Hash) New() hash.Hash {
+ if h > 0 && h < maxHash {
+ f := hashes[h]
+ if f != nil {
+ return f()
+ }
+ }
+ panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable")
+}
+
+// Available reports whether the given hash function is linked into the binary.
+func (h Hash) Available() bool {
+ return h < maxHash && hashes[h] != nil
+}
+
+// RegisterHash registers a function that returns a new instance of the given
+// hash function. This is intended to be called from the init function in
+// packages that implement hash functions.
+func RegisterHash(h Hash, f func() hash.Hash) {
+ if h >= maxHash {
+ panic("crypto: RegisterHash of unknown hash function")
+ }
+ hashes[h] = f
+}
+
+// PublicKey represents a public key using an unspecified algorithm.
+//
+// Although this type is an empty interface for backwards compatibility reasons,
+// all public key types in the standard library implement the following interface
+//
+// interface{
+// Equal(x crypto.PublicKey) bool
+// }
+//
+// which can be used for increased type safety within applications.
+type PublicKey any
+
+// PrivateKey represents a private key using an unspecified algorithm.
+//
+// Although this type is an empty interface for backwards compatibility reasons,
+// all private key types in the standard library implement the following interface
+//
+// interface{
+// Public() crypto.PublicKey
+// Equal(x crypto.PrivateKey) bool
+// }
+//
+// as well as purpose-specific interfaces such as [Signer] and [Decrypter], which
+// can be used for increased type safety within applications.
+type PrivateKey any
+
+// Signer is an interface for an opaque private key that can be used for
+// signing operations. For example, an RSA key kept in a hardware module.
+type Signer interface {
+ // Public returns the public key corresponding to the opaque,
+ // private key.
+ Public() PublicKey
+
+ // Sign signs digest with the private key, possibly using entropy from
+ // rand. For an RSA key, the resulting signature should be either a
+ // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
+ // key, it should be a DER-serialised, ASN.1 signature structure.
+ //
+ // Hash implements the SignerOpts interface and, in most cases, one can
+ // simply pass in the hash function used as opts. Sign may also attempt
+ // to type assert opts to other types in order to obtain algorithm
+ // specific values. See the documentation in each package for details.
+ //
+ // Note that when a signature of a hash of a larger message is needed,
+ // the caller is responsible for hashing the larger message and passing
+ // the hash (as digest) and the hash function (as opts) to Sign.
+ Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
+}
+
+// SignerOpts contains options for signing with a [Signer].
+type SignerOpts interface {
+ // HashFunc returns an identifier for the hash function used to produce
+ // the message passed to Signer.Sign, or else zero to indicate that no
+ // hashing was done.
+ HashFunc() Hash
+}
+
+// Decrypter is an interface for an opaque private key that can be used for
+// asymmetric decryption operations. An example would be an RSA key
+// kept in a hardware module.
+type Decrypter interface {
+ // Public returns the public key corresponding to the opaque,
+ // private key.
+ Public() PublicKey
+
+ // Decrypt decrypts msg. The opts argument should be appropriate for
+ // the primitive used. See the documentation in each implementation for
+ // details.
+ Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
+}
+
+type DecrypterOpts any
diff --git a/platform/dbops/binaries/go/go/src/crypto/issue21104_test.go b/platform/dbops/binaries/go/go/src/crypto/issue21104_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..466208879991e1a12ecf92d34b53d71885ed1b08
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/crypto/issue21104_test.go
@@ -0,0 +1,61 @@
+// 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 crypto_test
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rc4"
+ "testing"
+)
+
+func TestRC4OutOfBoundsWrite(t *testing.T) {
+ // This cipherText is encrypted "0123456789"
+ cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63}
+ cipher, err := rc4.NewCipher([]byte{0})
+ if err != nil {
+ panic(err)
+ }
+ test(t, "RC4", cipherText, cipher.XORKeyStream)
+}
+func TestCTROutOfBoundsWrite(t *testing.T) {
+ testBlock(t, "CTR", cipher.NewCTR)
+}
+func TestOFBOutOfBoundsWrite(t *testing.T) {
+ testBlock(t, "OFB", cipher.NewOFB)
+}
+func TestCFBEncryptOutOfBoundsWrite(t *testing.T) {
+ testBlock(t, "CFB Encrypt", cipher.NewCFBEncrypter)
+}
+func TestCFBDecryptOutOfBoundsWrite(t *testing.T) {
+ testBlock(t, "CFB Decrypt", cipher.NewCFBDecrypter)
+}
+func testBlock(t *testing.T, name string, newCipher func(cipher.Block, []byte) cipher.Stream) {
+ // This cipherText is encrypted "0123456789"
+ cipherText := []byte{86, 216, 121, 231, 219, 191, 26, 12, 176, 117}
+ var iv, key [16]byte
+ block, err := aes.NewCipher(key[:])
+ if err != nil {
+ panic(err)
+ }
+ stream := newCipher(block, iv[:])
+ test(t, name, cipherText, stream.XORKeyStream)
+}
+func test(t *testing.T, name string, cipherText []byte, xor func([]byte, []byte)) {
+ want := "abcdefghij"
+ plainText := []byte(want)
+ shorterLen := len(cipherText) / 2
+ defer func() {
+ err := recover()
+ if err == nil {
+ t.Errorf("%v XORKeyStream expected to panic on len(dst) < len(src), but didn't", name)
+ }
+ const plain = "0123456789"
+ if plainText[shorterLen] == plain[shorterLen] {
+ t.Errorf("%v XORKeyStream did out of bounds write, want %v, got %v", name, want, string(plainText))
+ }
+ }()
+ xor(plainText[:shorterLen], cipherText)
+}
diff --git a/platform/dbops/binaries/go/go/src/embed/embed.go b/platform/dbops/binaries/go/go/src/embed/embed.go
new file mode 100644
index 0000000000000000000000000000000000000000..b7bb16099e56a1944adc88b17dda8acf54571f4d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/embed/embed.go
@@ -0,0 +1,448 @@
+// 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 embed provides access to files embedded in the running Go program.
+//
+// Go source files that import "embed" can use the //go:embed directive
+// to initialize a variable of type string, []byte, or [FS] with the contents of
+// files read from the package directory or subdirectories at compile time.
+//
+// For example, here are three ways to embed a file named hello.txt
+// and then print its contents at run time.
+//
+// Embedding one file into a string:
+//
+// import _ "embed"
+//
+// //go:embed hello.txt
+// var s string
+// print(s)
+//
+// Embedding one file into a slice of bytes:
+//
+// import _ "embed"
+//
+// //go:embed hello.txt
+// var b []byte
+// print(string(b))
+//
+// Embedded one or more files into a file system:
+//
+// import "embed"
+//
+// //go:embed hello.txt
+// var f embed.FS
+// data, _ := f.ReadFile("hello.txt")
+// print(string(data))
+//
+// # Directives
+//
+// A //go:embed directive above a variable declaration specifies which files to embed,
+// using one or more path.Match patterns.
+//
+// The directive must immediately precede a line containing the declaration of a single variable.
+// Only blank lines and ‘//’ line comments are permitted between the directive and the declaration.
+//
+// The type of the variable must be a string type, or a slice of a byte type,
+// or [FS] (or an alias of [FS]).
+//
+// For example:
+//
+// package server
+//
+// import "embed"
+//
+// // content holds our static web server content.
+// //go:embed image/* template/*
+// //go:embed html/index.html
+// var content embed.FS
+//
+// The Go build system will recognize the directives and arrange for the declared variable
+// (in the example above, content) to be populated with the matching files from the file system.
+//
+// The //go:embed directive accepts multiple space-separated patterns for
+// brevity, but it can also be repeated, to avoid very long lines when there are
+// many patterns. The patterns are interpreted relative to the package directory
+// containing the source file. The path separator is a forward slash, even on
+// Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements,
+// nor may they begin or end with a slash. To match everything in the current
+// directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in
+// their names, patterns can be written as Go double-quoted or back-quoted
+// string literals.
+//
+// If a pattern names a directory, all files in the subtree rooted at that directory are
+// embedded (recursively), except that files with names beginning with ‘.’ or ‘_’
+// are excluded. So the variable in the above example is almost equivalent to:
+//
+// // content is our static web server content.
+// //go:embed image template html/index.html
+// var content embed.FS
+//
+// The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not.
+// Neither embeds ‘image/dir/.tempfile’.
+//
+// If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed
+// to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds
+// both ‘image/.tempfile’ and ‘image/dir/.tempfile’.
+//
+// The //go:embed directive can be used with both exported and unexported variables,
+// depending on whether the package wants to make the data available to other packages.
+// It can only be used with variables at package scope, not with local variables.
+//
+// Patterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links.
+// Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :.
+// Matches for empty directories are ignored. After that, each pattern in a //go:embed line
+// must match at least one file or non-empty directory.
+//
+// If any patterns are invalid or have invalid matches, the build will fail.
+//
+// # Strings and Bytes
+//
+// The //go:embed line for a variable of type string or []byte can have only a single pattern,
+// and that pattern can match only a single file. The string or []byte is initialized with
+// the contents of that file.
+//
+// The //go:embed directive requires importing "embed", even when using a string or []byte.
+// In source files that don't refer to [embed.FS], use a blank import (import _ "embed").
+//
+// # File Systems
+//
+// For embedding a single file, a variable of type string or []byte is often best.
+// The [FS] type enables embedding a tree of files, such as a directory of static
+// web server content, as in the example above.
+//
+// FS implements the [io/fs] package's [FS] interface, so it can be used with any package that
+// understands file systems, including [net/http], [text/template], and [html/template].
+//
+// For example, given the content variable in the example above, we can write:
+//
+// http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
+//
+// template.ParseFS(content, "*.tmpl")
+//
+// # Tools
+//
+// To support tools that analyze Go packages, the patterns found in //go:embed lines
+// are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns,
+// and XTestEmbedPatterns fields in the “go help list” output.
+package embed
+
+import (
+ "errors"
+ "io"
+ "io/fs"
+ "time"
+)
+
+// An FS is a read-only collection of files, usually initialized with a //go:embed directive.
+// When declared without a //go:embed directive, an FS is an empty file system.
+//
+// An FS is a read-only value, so it is safe to use from multiple goroutines
+// simultaneously and also safe to assign values of type FS to each other.
+//
+// FS implements fs.FS, so it can be used with any package that understands
+// file system interfaces, including net/http, text/template, and html/template.
+//
+// See the package documentation for more details about initializing an FS.
+type FS struct {
+ // The compiler knows the layout of this struct.
+ // See cmd/compile/internal/staticdata's WriteEmbed.
+ //
+ // The files list is sorted by name but not by simple string comparison.
+ // Instead, each file's name takes the form "dir/elem" or "dir/elem/".
+ // The optional trailing slash indicates that the file is itself a directory.
+ // The files list is sorted first by dir (if dir is missing, it is taken to be ".")
+ // and then by base, so this list of files:
+ //
+ // p
+ // q/
+ // q/r
+ // q/s/
+ // q/s/t
+ // q/s/u
+ // q/v
+ // w
+ //
+ // is actually sorted as:
+ //
+ // p # dir=. elem=p
+ // q/ # dir=. elem=q
+ // w/ # dir=. elem=w
+ // q/r # dir=q elem=r
+ // q/s/ # dir=q elem=s
+ // q/v # dir=q elem=v
+ // q/s/t # dir=q/s elem=t
+ // q/s/u # dir=q/s elem=u
+ //
+ // This order brings directory contents together in contiguous sections
+ // of the list, allowing a directory read to use binary search to find
+ // the relevant sequence of entries.
+ files *[]file
+}
+
+// split splits the name into dir and elem as described in the
+// comment in the FS struct above. isDir reports whether the
+// final trailing slash was present, indicating that name is a directory.
+func split(name string) (dir, elem string, isDir bool) {
+ if name[len(name)-1] == '/' {
+ isDir = true
+ name = name[:len(name)-1]
+ }
+ i := len(name) - 1
+ for i >= 0 && name[i] != '/' {
+ i--
+ }
+ if i < 0 {
+ return ".", name, isDir
+ }
+ return name[:i], name[i+1:], isDir
+}
+
+// trimSlash trims a trailing slash from name, if present,
+// returning the possibly shortened name.
+func trimSlash(name string) string {
+ if len(name) > 0 && name[len(name)-1] == '/' {
+ return name[:len(name)-1]
+ }
+ return name
+}
+
+var (
+ _ fs.ReadDirFS = FS{}
+ _ fs.ReadFileFS = FS{}
+)
+
+// A file is a single file in the FS.
+// It implements fs.FileInfo and fs.DirEntry.
+type file struct {
+ // The compiler knows the layout of this struct.
+ // See cmd/compile/internal/staticdata's WriteEmbed.
+ name string
+ data string
+ hash [16]byte // truncated SHA256 hash
+}
+
+var (
+ _ fs.FileInfo = (*file)(nil)
+ _ fs.DirEntry = (*file)(nil)
+)
+
+func (f *file) Name() string { _, elem, _ := split(f.name); return elem }
+func (f *file) Size() int64 { return int64(len(f.data)) }
+func (f *file) ModTime() time.Time { return time.Time{} }
+func (f *file) IsDir() bool { _, _, isDir := split(f.name); return isDir }
+func (f *file) Sys() any { return nil }
+func (f *file) Type() fs.FileMode { return f.Mode().Type() }
+func (f *file) Info() (fs.FileInfo, error) { return f, nil }
+
+func (f *file) Mode() fs.FileMode {
+ if f.IsDir() {
+ return fs.ModeDir | 0555
+ }
+ return 0444
+}
+
+func (f *file) String() string {
+ return fs.FormatFileInfo(f)
+}
+
+// dotFile is a file for the root directory,
+// which is omitted from the files list in a FS.
+var dotFile = &file{name: "./"}
+
+// lookup returns the named file, or nil if it is not present.
+func (f FS) lookup(name string) *file {
+ if !fs.ValidPath(name) {
+ // The compiler should never emit a file with an invalid name,
+ // so this check is not strictly necessary (if name is invalid,
+ // we shouldn't find a match below), but it's a good backstop anyway.
+ return nil
+ }
+ if name == "." {
+ return dotFile
+ }
+ if f.files == nil {
+ return nil
+ }
+
+ // Binary search to find where name would be in the list,
+ // and then check if name is at that position.
+ dir, elem, _ := split(name)
+ files := *f.files
+ i := sortSearch(len(files), func(i int) bool {
+ idir, ielem, _ := split(files[i].name)
+ return idir > dir || idir == dir && ielem >= elem
+ })
+ if i < len(files) && trimSlash(files[i].name) == name {
+ return &files[i]
+ }
+ return nil
+}
+
+// readDir returns the list of files corresponding to the directory dir.
+func (f FS) readDir(dir string) []file {
+ if f.files == nil {
+ return nil
+ }
+ // Binary search to find where dir starts and ends in the list
+ // and then return that slice of the list.
+ files := *f.files
+ i := sortSearch(len(files), func(i int) bool {
+ idir, _, _ := split(files[i].name)
+ return idir >= dir
+ })
+ j := sortSearch(len(files), func(j int) bool {
+ jdir, _, _ := split(files[j].name)
+ return jdir > dir
+ })
+ return files[i:j]
+}
+
+// Open opens the named file for reading and returns it as an [fs.File].
+//
+// The returned file implements [io.Seeker] and [io.ReaderAt] when the file is not a directory.
+func (f FS) Open(name string) (fs.File, error) {
+ file := f.lookup(name)
+ if file == nil {
+ return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
+ }
+ if file.IsDir() {
+ return &openDir{file, f.readDir(name), 0}, nil
+ }
+ return &openFile{file, 0}, nil
+}
+
+// ReadDir reads and returns the entire named directory.
+func (f FS) ReadDir(name string) ([]fs.DirEntry, error) {
+ file, err := f.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ dir, ok := file.(*openDir)
+ if !ok {
+ return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("not a directory")}
+ }
+ list := make([]fs.DirEntry, len(dir.files))
+ for i := range list {
+ list[i] = &dir.files[i]
+ }
+ return list, nil
+}
+
+// ReadFile reads and returns the content of the named file.
+func (f FS) ReadFile(name string) ([]byte, error) {
+ file, err := f.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ ofile, ok := file.(*openFile)
+ if !ok {
+ return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("is a directory")}
+ }
+ return []byte(ofile.f.data), nil
+}
+
+// An openFile is a regular file open for reading.
+type openFile struct {
+ f *file // the file itself
+ offset int64 // current read offset
+}
+
+var (
+ _ io.Seeker = (*openFile)(nil)
+ _ io.ReaderAt = (*openFile)(nil)
+)
+
+func (f *openFile) Close() error { return nil }
+func (f *openFile) Stat() (fs.FileInfo, error) { return f.f, nil }
+
+func (f *openFile) Read(b []byte) (int, error) {
+ if f.offset >= int64(len(f.f.data)) {
+ return 0, io.EOF
+ }
+ if f.offset < 0 {
+ return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid}
+ }
+ n := copy(b, f.f.data[f.offset:])
+ f.offset += int64(n)
+ return n, nil
+}
+
+func (f *openFile) Seek(offset int64, whence int) (int64, error) {
+ switch whence {
+ case 0:
+ // offset += 0
+ case 1:
+ offset += f.offset
+ case 2:
+ offset += int64(len(f.f.data))
+ }
+ if offset < 0 || offset > int64(len(f.f.data)) {
+ return 0, &fs.PathError{Op: "seek", Path: f.f.name, Err: fs.ErrInvalid}
+ }
+ f.offset = offset
+ return offset, nil
+}
+
+func (f *openFile) ReadAt(b []byte, offset int64) (int, error) {
+ if offset < 0 || offset > int64(len(f.f.data)) {
+ return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid}
+ }
+ n := copy(b, f.f.data[offset:])
+ if n < len(b) {
+ return n, io.EOF
+ }
+ return n, nil
+}
+
+// An openDir is a directory open for reading.
+type openDir struct {
+ f *file // the directory file itself
+ files []file // the directory contents
+ offset int // the read offset, an index into the files slice
+}
+
+func (d *openDir) Close() error { return nil }
+func (d *openDir) Stat() (fs.FileInfo, error) { return d.f, nil }
+
+func (d *openDir) Read([]byte) (int, error) {
+ return 0, &fs.PathError{Op: "read", Path: d.f.name, Err: errors.New("is a directory")}
+}
+
+func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) {
+ n := len(d.files) - d.offset
+ if n == 0 {
+ if count <= 0 {
+ return nil, nil
+ }
+ return nil, io.EOF
+ }
+ if count > 0 && n > count {
+ n = count
+ }
+ list := make([]fs.DirEntry, n)
+ for i := range list {
+ list[i] = &d.files[d.offset+i]
+ }
+ d.offset += n
+ return list, nil
+}
+
+// sortSearch is like sort.Search, avoiding an import.
+func sortSearch(n int, f func(int) bool) int {
+ // Define f(-1) == false and f(n) == true.
+ // Invariant: f(i-1) == false, f(j) == true.
+ i, j := 0, n
+ for i < j {
+ h := int(uint(i+j) >> 1) // avoid overflow when computing h
+ // i ≤ h < j
+ if !f(h) {
+ i = h + 1 // preserves f(i-1) == false
+ } else {
+ j = h // preserves f(j) == true
+ }
+ }
+ // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
+ return i
+}
diff --git a/platform/dbops/binaries/go/go/src/embed/example_test.go b/platform/dbops/binaries/go/go/src/embed/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b92eb520092013f4c33e897701c99d0941aec9cb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/embed/example_test.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.
+
+package embed_test
+
+import (
+ "embed"
+ "log"
+ "net/http"
+)
+
+//go:embed internal/embedtest/testdata/*.txt
+var content embed.FS
+
+func Example() {
+ mux := http.NewServeMux()
+ mux.Handle("/", http.FileServer(http.FS(content)))
+ err := http.ListenAndServe(":8080", mux)
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/encoding/encoding.go b/platform/dbops/binaries/go/go/src/encoding/encoding.go
new file mode 100644
index 0000000000000000000000000000000000000000..50acf3c23a10138229288204e6a4c03e13907f86
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/encoding/encoding.go
@@ -0,0 +1,54 @@
+// 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 encoding defines interfaces shared by other packages that
+// convert data to and from byte-level and textual representations.
+// Packages that check for these interfaces include encoding/gob,
+// encoding/json, and encoding/xml. As a result, implementing an
+// interface once can make a type useful in multiple encodings.
+// Standard types that implement these interfaces include time.Time and net.IP.
+// The interfaces come in pairs that produce and consume encoded data.
+//
+// Adding encoding/decoding methods to existing types may constitute a breaking change,
+// as they can be used for serialization in communicating with programs
+// written with different library versions.
+// The policy for packages maintained by the Go project is to only allow
+// the addition of marshaling functions if no existing, reasonable marshaling exists.
+package encoding
+
+// BinaryMarshaler is the interface implemented by an object that can
+// marshal itself into a binary form.
+//
+// MarshalBinary encodes the receiver into a binary form and returns the result.
+type BinaryMarshaler interface {
+ MarshalBinary() (data []byte, err error)
+}
+
+// BinaryUnmarshaler is the interface implemented by an object that can
+// unmarshal a binary representation of itself.
+//
+// UnmarshalBinary must be able to decode the form generated by MarshalBinary.
+// UnmarshalBinary must copy the data if it wishes to retain the data
+// after returning.
+type BinaryUnmarshaler interface {
+ UnmarshalBinary(data []byte) error
+}
+
+// TextMarshaler is the interface implemented by an object that can
+// marshal itself into a textual form.
+//
+// MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
+type TextMarshaler interface {
+ MarshalText() (text []byte, err error)
+}
+
+// TextUnmarshaler is the interface implemented by an object that can
+// unmarshal a textual representation of itself.
+//
+// UnmarshalText must be able to decode the form generated by MarshalText.
+// UnmarshalText must copy the text if it wishes to retain the text
+// after returning.
+type TextUnmarshaler interface {
+ UnmarshalText(text []byte) error
+}
diff --git a/platform/dbops/binaries/go/go/src/errors/errors.go b/platform/dbops/binaries/go/go/src/errors/errors.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e3860aaa9946fb526ee7de12b9b735511e3e3b3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/errors.go
@@ -0,0 +1,87 @@
+// 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 errors implements functions to manipulate errors.
+//
+// The [New] function creates errors whose only content is a text message.
+//
+// An error e wraps another error if e's type has one of the methods
+//
+// Unwrap() error
+// Unwrap() []error
+//
+// If e.Unwrap() returns a non-nil error w or a slice containing w,
+// then we say that e wraps w. A nil error returned from e.Unwrap()
+// indicates that e does not wrap any error. It is invalid for an
+// Unwrap method to return an []error containing a nil error value.
+//
+// An easy way to create wrapped errors is to call [fmt.Errorf] and apply
+// the %w verb to the error argument:
+//
+// wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
+//
+// Successive unwrapping of an error creates a tree. The [Is] and [As]
+// functions inspect an error's tree by examining first the error
+// itself followed by the tree of each of its children in turn
+// (pre-order, depth-first traversal).
+//
+// [Is] examines the tree of its first argument looking for an error that
+// matches the second. It reports whether it finds a match. It should be
+// used in preference to simple equality checks:
+//
+// if errors.Is(err, fs.ErrExist)
+//
+// is preferable to
+//
+// if err == fs.ErrExist
+//
+// because the former will succeed if err wraps [io/fs.ErrExist].
+//
+// [As] examines the tree of its first argument looking for an error that can be
+// assigned to its second argument, which must be a pointer. If it succeeds, it
+// performs the assignment and returns true. Otherwise, it returns false. The form
+//
+// var perr *fs.PathError
+// if errors.As(err, &perr) {
+// fmt.Println(perr.Path)
+// }
+//
+// is preferable to
+//
+// if perr, ok := err.(*fs.PathError); ok {
+// fmt.Println(perr.Path)
+// }
+//
+// because the former will succeed if err wraps an [*io/fs.PathError].
+package errors
+
+// New returns an error that formats as the given text.
+// Each call to New returns a distinct error value even if the text is identical.
+func New(text string) error {
+ return &errorString{text}
+}
+
+// errorString is a trivial implementation of error.
+type errorString struct {
+ s string
+}
+
+func (e *errorString) Error() string {
+ return e.s
+}
+
+// ErrUnsupported indicates that a requested operation cannot be performed,
+// because it is unsupported. For example, a call to [os.Link] when using a
+// file system that does not support hard links.
+//
+// Functions and methods should not return this error but should instead
+// return an error including appropriate context that satisfies
+//
+// errors.Is(err, errors.ErrUnsupported)
+//
+// either by directly wrapping ErrUnsupported or by implementing an [Is] method.
+//
+// Functions and methods should document the cases in which an error
+// wrapping this will be returned.
+var ErrUnsupported = New("unsupported operation")
diff --git a/platform/dbops/binaries/go/go/src/errors/errors_test.go b/platform/dbops/binaries/go/go/src/errors/errors_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..08ed54e041cf03ab83ffe9146c6f08c0cb5daf05
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/errors_test.go
@@ -0,0 +1,33 @@
+// 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 errors_test
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestNewEqual(t *testing.T) {
+ // Different allocations should not be equal.
+ if errors.New("abc") == errors.New("abc") {
+ t.Errorf(`New("abc") == New("abc")`)
+ }
+ if errors.New("abc") == errors.New("xyz") {
+ t.Errorf(`New("abc") == New("xyz")`)
+ }
+
+ // Same allocation should be equal to itself (not crash).
+ err := errors.New("jkl")
+ if err != err {
+ t.Errorf(`err != err`)
+ }
+}
+
+func TestErrorMethod(t *testing.T) {
+ err := errors.New("abc")
+ if err.Error() != "abc" {
+ t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/errors/example_test.go b/platform/dbops/binaries/go/go/src/errors/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1976f05afa7e9fbeac0639a63f6170331c11e176
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/example_test.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.
+
+package errors_test
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "time"
+)
+
+// MyError is an error implementation that includes a time and message.
+type MyError struct {
+ When time.Time
+ What string
+}
+
+func (e MyError) Error() string {
+ return fmt.Sprintf("%v: %v", e.When, e.What)
+}
+
+func oops() error {
+ return MyError{
+ time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
+ "the file system has gone away",
+ }
+}
+
+func Example() {
+ if err := oops(); err != nil {
+ fmt.Println(err)
+ }
+ // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
+}
+
+func ExampleNew() {
+ err := errors.New("emit macho dwarf: elf header corrupted")
+ if err != nil {
+ fmt.Print(err)
+ }
+ // Output: emit macho dwarf: elf header corrupted
+}
+
+// The fmt package's Errorf function lets us use the package's formatting
+// features to create descriptive error messages.
+func ExampleNew_errorf() {
+ const name, id = "bimmler", 17
+ err := fmt.Errorf("user %q (id %d) not found", name, id)
+ if err != nil {
+ fmt.Print(err)
+ }
+ // Output: user "bimmler" (id 17) not found
+}
+
+func ExampleJoin() {
+ err1 := errors.New("err1")
+ err2 := errors.New("err2")
+ err := errors.Join(err1, err2)
+ fmt.Println(err)
+ if errors.Is(err, err1) {
+ fmt.Println("err is err1")
+ }
+ if errors.Is(err, err2) {
+ fmt.Println("err is err2")
+ }
+ // Output:
+ // err1
+ // err2
+ // err is err1
+ // err is err2
+}
+
+func ExampleIs() {
+ if _, err := os.Open("non-existing"); err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ fmt.Println("file does not exist")
+ } else {
+ fmt.Println(err)
+ }
+ }
+
+ // Output:
+ // file does not exist
+}
+
+func ExampleAs() {
+ if _, err := os.Open("non-existing"); err != nil {
+ var pathError *fs.PathError
+ if errors.As(err, &pathError) {
+ fmt.Println("Failed at path:", pathError.Path)
+ } else {
+ fmt.Println(err)
+ }
+ }
+
+ // Output:
+ // Failed at path: non-existing
+}
+
+func ExampleUnwrap() {
+ err1 := errors.New("error1")
+ err2 := fmt.Errorf("error2: [%w]", err1)
+ fmt.Println(err2)
+ fmt.Println(errors.Unwrap(err2))
+ // Output:
+ // error2: [error1]
+ // error1
+}
diff --git a/platform/dbops/binaries/go/go/src/errors/join.go b/platform/dbops/binaries/go/go/src/errors/join.go
new file mode 100644
index 0000000000000000000000000000000000000000..349fc06ed9f75c3323a9d65c2e519713a9b33e7e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/join.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 errors
+
+import (
+ "unsafe"
+)
+
+// Join returns an error that wraps the given errors.
+// Any nil error values are discarded.
+// Join returns nil if every value in errs is nil.
+// The error formats as the concatenation of the strings obtained
+// by calling the Error method of each element of errs, with a newline
+// between each string.
+//
+// A non-nil error returned by Join implements the Unwrap() []error method.
+func Join(errs ...error) error {
+ n := 0
+ for _, err := range errs {
+ if err != nil {
+ n++
+ }
+ }
+ if n == 0 {
+ return nil
+ }
+ e := &joinError{
+ errs: make([]error, 0, n),
+ }
+ for _, err := range errs {
+ if err != nil {
+ e.errs = append(e.errs, err)
+ }
+ }
+ return e
+}
+
+type joinError struct {
+ errs []error
+}
+
+func (e *joinError) Error() string {
+ // Since Join returns nil if every value in errs is nil,
+ // e.errs cannot be empty.
+ if len(e.errs) == 1 {
+ return e.errs[0].Error()
+ }
+
+ b := []byte(e.errs[0].Error())
+ for _, err := range e.errs[1:] {
+ b = append(b, '\n')
+ b = append(b, err.Error()...)
+ }
+ // At this point, b has at least one byte '\n'.
+ return unsafe.String(&b[0], len(b))
+}
+
+func (e *joinError) Unwrap() []error {
+ return e.errs
+}
diff --git a/platform/dbops/binaries/go/go/src/errors/join_test.go b/platform/dbops/binaries/go/go/src/errors/join_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4828dc4d755fd678d0b3ca31f7fdebc5e1dcaeaf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/join_test.go
@@ -0,0 +1,72 @@
+// 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 errors_test
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func TestJoinReturnsNil(t *testing.T) {
+ if err := errors.Join(); err != nil {
+ t.Errorf("errors.Join() = %v, want nil", err)
+ }
+ if err := errors.Join(nil); err != nil {
+ t.Errorf("errors.Join(nil) = %v, want nil", err)
+ }
+ if err := errors.Join(nil, nil); err != nil {
+ t.Errorf("errors.Join(nil, nil) = %v, want nil", err)
+ }
+}
+
+func TestJoin(t *testing.T) {
+ err1 := errors.New("err1")
+ err2 := errors.New("err2")
+ for _, test := range []struct {
+ errs []error
+ want []error
+ }{{
+ errs: []error{err1},
+ want: []error{err1},
+ }, {
+ errs: []error{err1, err2},
+ want: []error{err1, err2},
+ }, {
+ errs: []error{err1, nil, err2},
+ want: []error{err1, err2},
+ }} {
+ got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap()
+ if !reflect.DeepEqual(got, test.want) {
+ t.Errorf("Join(%v) = %v; want %v", test.errs, got, test.want)
+ }
+ if len(got) != cap(got) {
+ t.Errorf("Join(%v) returns errors with len=%v, cap=%v; want len==cap", test.errs, len(got), cap(got))
+ }
+ }
+}
+
+func TestJoinErrorMethod(t *testing.T) {
+ err1 := errors.New("err1")
+ err2 := errors.New("err2")
+ for _, test := range []struct {
+ errs []error
+ want string
+ }{{
+ errs: []error{err1},
+ want: "err1",
+ }, {
+ errs: []error{err1, err2},
+ want: "err1\nerr2",
+ }, {
+ errs: []error{err1, nil, err2},
+ want: "err1\nerr2",
+ }} {
+ got := errors.Join(test.errs...).Error()
+ if got != test.want {
+ t.Errorf("Join(%v).Error() = %q; want %q", test.errs, got, test.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/errors/wrap.go b/platform/dbops/binaries/go/go/src/errors/wrap.go
new file mode 100644
index 0000000000000000000000000000000000000000..88ee0a9281f2f13b6e2bcaeb77163a4760497725
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/wrap.go
@@ -0,0 +1,147 @@
+// 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 errors
+
+import (
+ "internal/reflectlite"
+)
+
+// Unwrap returns the result of calling the Unwrap method on err, if err's
+// type contains an Unwrap method returning error.
+// Otherwise, Unwrap returns nil.
+//
+// Unwrap only calls a method of the form "Unwrap() error".
+// In particular Unwrap does not unwrap errors returned by [Join].
+func Unwrap(err error) error {
+ u, ok := err.(interface {
+ Unwrap() error
+ })
+ if !ok {
+ return nil
+ }
+ return u.Unwrap()
+}
+
+// Is reports whether any error in err's tree matches target.
+//
+// The tree consists of err itself, followed by the errors obtained by repeatedly
+// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
+// errors, Is examines err followed by a depth-first traversal of its children.
+//
+// An error is considered to match a target if it is equal to that target or if
+// it implements a method Is(error) bool such that Is(target) returns true.
+//
+// An error type might provide an Is method so it can be treated as equivalent
+// to an existing error. For example, if MyError defines
+//
+// func (m MyError) Is(target error) bool { return target == fs.ErrExist }
+//
+// then Is(MyError{}, fs.ErrExist) returns true. See [syscall.Errno.Is] for
+// an example in the standard library. An Is method should only shallowly
+// compare err and the target and not call [Unwrap] on either.
+func Is(err, target error) bool {
+ if target == nil {
+ return err == target
+ }
+
+ isComparable := reflectlite.TypeOf(target).Comparable()
+ return is(err, target, isComparable)
+}
+
+func is(err, target error, targetComparable bool) bool {
+ for {
+ if targetComparable && err == target {
+ return true
+ }
+ if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
+ return true
+ }
+ switch x := err.(type) {
+ case interface{ Unwrap() error }:
+ err = x.Unwrap()
+ if err == nil {
+ return false
+ }
+ case interface{ Unwrap() []error }:
+ for _, err := range x.Unwrap() {
+ if is(err, target, targetComparable) {
+ return true
+ }
+ }
+ return false
+ default:
+ return false
+ }
+ }
+}
+
+// As finds the first error in err's tree that matches target, and if one is found, sets
+// target to that error value and returns true. Otherwise, it returns false.
+//
+// The tree consists of err itself, followed by the errors obtained by repeatedly
+// calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
+// errors, As examines err followed by a depth-first traversal of its children.
+//
+// An error matches target if the error's concrete value is assignable to the value
+// pointed to by target, or if the error has a method As(interface{}) bool such that
+// As(target) returns true. In the latter case, the As method is responsible for
+// setting target.
+//
+// An error type might provide an As method so it can be treated as if it were a
+// different error type.
+//
+// As panics if target is not a non-nil pointer to either a type that implements
+// error, or to any interface type.
+func As(err error, target any) bool {
+ if err == nil {
+ return false
+ }
+ if target == nil {
+ panic("errors: target cannot be nil")
+ }
+ val := reflectlite.ValueOf(target)
+ typ := val.Type()
+ if typ.Kind() != reflectlite.Ptr || val.IsNil() {
+ panic("errors: target must be a non-nil pointer")
+ }
+ targetType := typ.Elem()
+ if targetType.Kind() != reflectlite.Interface && !targetType.Implements(errorType) {
+ panic("errors: *target must be interface or implement error")
+ }
+ return as(err, target, val, targetType)
+}
+
+func as(err error, target any, targetVal reflectlite.Value, targetType reflectlite.Type) bool {
+ for {
+ if reflectlite.TypeOf(err).AssignableTo(targetType) {
+ targetVal.Elem().Set(reflectlite.ValueOf(err))
+ return true
+ }
+ if x, ok := err.(interface{ As(any) bool }); ok && x.As(target) {
+ return true
+ }
+ switch x := err.(type) {
+ case interface{ Unwrap() error }:
+ err = x.Unwrap()
+ if err == nil {
+ return false
+ }
+ case interface{ Unwrap() []error }:
+ for _, err := range x.Unwrap() {
+ if err == nil {
+ continue
+ }
+ if as(err, target, targetVal, targetType) {
+ return true
+ }
+ }
+ return false
+ default:
+ return false
+ }
+ }
+}
+
+var errorType = reflectlite.TypeOf((*error)(nil)).Elem()
diff --git a/platform/dbops/binaries/go/go/src/errors/wrap_test.go b/platform/dbops/binaries/go/go/src/errors/wrap_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0a7bc5d16a1344c87cb7c802cd5c9fb6726dd1c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/errors/wrap_test.go
@@ -0,0 +1,311 @@
+// 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 errors_test
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "reflect"
+ "testing"
+)
+
+func TestIs(t *testing.T) {
+ err1 := errors.New("1")
+ erra := wrapped{"wrap 2", err1}
+ errb := wrapped{"wrap 3", erra}
+
+ err3 := errors.New("3")
+
+ poser := &poser{"either 1 or 3", func(err error) bool {
+ return err == err1 || err == err3
+ }}
+
+ testCases := []struct {
+ err error
+ target error
+ match bool
+ }{
+ {nil, nil, true},
+ {err1, nil, false},
+ {err1, err1, true},
+ {erra, err1, true},
+ {errb, err1, true},
+ {err1, err3, false},
+ {erra, err3, false},
+ {errb, err3, false},
+ {poser, err1, true},
+ {poser, err3, true},
+ {poser, erra, false},
+ {poser, errb, false},
+ {errorUncomparable{}, errorUncomparable{}, true},
+ {errorUncomparable{}, &errorUncomparable{}, false},
+ {&errorUncomparable{}, errorUncomparable{}, true},
+ {&errorUncomparable{}, &errorUncomparable{}, false},
+ {errorUncomparable{}, err1, false},
+ {&errorUncomparable{}, err1, false},
+ {multiErr{}, err1, false},
+ {multiErr{err1, err3}, err1, true},
+ {multiErr{err3, err1}, err1, true},
+ {multiErr{err1, err3}, errors.New("x"), false},
+ {multiErr{err3, errb}, errb, true},
+ {multiErr{err3, errb}, erra, true},
+ {multiErr{err3, errb}, err1, true},
+ {multiErr{errb, err3}, err1, true},
+ {multiErr{poser}, err1, true},
+ {multiErr{poser}, err3, true},
+ {multiErr{nil}, nil, false},
+ }
+ for _, tc := range testCases {
+ t.Run("", func(t *testing.T) {
+ if got := errors.Is(tc.err, tc.target); got != tc.match {
+ t.Errorf("Is(%v, %v) = %v, want %v", tc.err, tc.target, got, tc.match)
+ }
+ })
+ }
+}
+
+type poser struct {
+ msg string
+ f func(error) bool
+}
+
+var poserPathErr = &fs.PathError{Op: "poser"}
+
+func (p *poser) Error() string { return p.msg }
+func (p *poser) Is(err error) bool { return p.f(err) }
+func (p *poser) As(err any) bool {
+ switch x := err.(type) {
+ case **poser:
+ *x = p
+ case *errorT:
+ *x = errorT{"poser"}
+ case **fs.PathError:
+ *x = poserPathErr
+ default:
+ return false
+ }
+ return true
+}
+
+func TestAs(t *testing.T) {
+ var errT errorT
+ var errP *fs.PathError
+ var timeout interface{ Timeout() bool }
+ var p *poser
+ _, errF := os.Open("non-existing")
+ poserErr := &poser{"oh no", nil}
+
+ testCases := []struct {
+ err error
+ target any
+ match bool
+ want any // value of target on match
+ }{{
+ nil,
+ &errP,
+ false,
+ nil,
+ }, {
+ wrapped{"pitied the fool", errorT{"T"}},
+ &errT,
+ true,
+ errorT{"T"},
+ }, {
+ errF,
+ &errP,
+ true,
+ errF,
+ }, {
+ errorT{},
+ &errP,
+ false,
+ nil,
+ }, {
+ wrapped{"wrapped", nil},
+ &errT,
+ false,
+ nil,
+ }, {
+ &poser{"error", nil},
+ &errT,
+ true,
+ errorT{"poser"},
+ }, {
+ &poser{"path", nil},
+ &errP,
+ true,
+ poserPathErr,
+ }, {
+ poserErr,
+ &p,
+ true,
+ poserErr,
+ }, {
+ errors.New("err"),
+ &timeout,
+ false,
+ nil,
+ }, {
+ errF,
+ &timeout,
+ true,
+ errF,
+ }, {
+ wrapped{"path error", errF},
+ &timeout,
+ true,
+ errF,
+ }, {
+ multiErr{},
+ &errT,
+ false,
+ nil,
+ }, {
+ multiErr{errors.New("a"), errorT{"T"}},
+ &errT,
+ true,
+ errorT{"T"},
+ }, {
+ multiErr{errorT{"T"}, errors.New("a")},
+ &errT,
+ true,
+ errorT{"T"},
+ }, {
+ multiErr{errorT{"a"}, errorT{"b"}},
+ &errT,
+ true,
+ errorT{"a"},
+ }, {
+ multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}},
+ &errT,
+ true,
+ errorT{"a"},
+ }, {
+ multiErr{wrapped{"path error", errF}},
+ &timeout,
+ true,
+ errF,
+ }, {
+ multiErr{nil},
+ &errT,
+ false,
+ nil,
+ }}
+ for i, tc := range testCases {
+ name := fmt.Sprintf("%d:As(Errorf(..., %v), %v)", i, tc.err, tc.target)
+ // Clear the target pointer, in case it was set in a previous test.
+ rtarget := reflect.ValueOf(tc.target)
+ rtarget.Elem().Set(reflect.Zero(reflect.TypeOf(tc.target).Elem()))
+ t.Run(name, func(t *testing.T) {
+ match := errors.As(tc.err, tc.target)
+ if match != tc.match {
+ t.Fatalf("match: got %v; want %v", match, tc.match)
+ }
+ if !match {
+ return
+ }
+ if got := rtarget.Elem().Interface(); got != tc.want {
+ t.Fatalf("got %#v, want %#v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestAsValidation(t *testing.T) {
+ var s string
+ testCases := []any{
+ nil,
+ (*int)(nil),
+ "error",
+ &s,
+ }
+ err := errors.New("error")
+ for _, tc := range testCases {
+ t.Run(fmt.Sprintf("%T(%v)", tc, tc), func(t *testing.T) {
+ defer func() {
+ recover()
+ }()
+ if errors.As(err, tc) {
+ t.Errorf("As(err, %T(%v)) = true, want false", tc, tc)
+ return
+ }
+ t.Errorf("As(err, %T(%v)) did not panic", tc, tc)
+ })
+ }
+}
+
+func BenchmarkIs(b *testing.B) {
+ err1 := errors.New("1")
+ err2 := multiErr{multiErr{multiErr{err1, errorT{"a"}}, errorT{"b"}}}
+
+ for i := 0; i < b.N; i++ {
+ if !errors.Is(err2, err1) {
+ b.Fatal("Is failed")
+ }
+ }
+}
+
+func BenchmarkAs(b *testing.B) {
+ err := multiErr{multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}}
+ for i := 0; i < b.N; i++ {
+ var target errorT
+ if !errors.As(err, &target) {
+ b.Fatal("As failed")
+ }
+ }
+}
+
+func TestUnwrap(t *testing.T) {
+ err1 := errors.New("1")
+ erra := wrapped{"wrap 2", err1}
+
+ testCases := []struct {
+ err error
+ want error
+ }{
+ {nil, nil},
+ {wrapped{"wrapped", nil}, nil},
+ {err1, nil},
+ {erra, err1},
+ {wrapped{"wrap 3", erra}, erra},
+ }
+ for _, tc := range testCases {
+ if got := errors.Unwrap(tc.err); got != tc.want {
+ t.Errorf("Unwrap(%v) = %v, want %v", tc.err, got, tc.want)
+ }
+ }
+}
+
+type errorT struct{ s string }
+
+func (e errorT) Error() string { return fmt.Sprintf("errorT(%s)", e.s) }
+
+type wrapped struct {
+ msg string
+ err error
+}
+
+func (e wrapped) Error() string { return e.msg }
+func (e wrapped) Unwrap() error { return e.err }
+
+type multiErr []error
+
+func (m multiErr) Error() string { return "multiError" }
+func (m multiErr) Unwrap() []error { return []error(m) }
+
+type errorUncomparable struct {
+ f []string
+}
+
+func (errorUncomparable) Error() string {
+ return "uncomparable error"
+}
+
+func (errorUncomparable) Is(target error) bool {
+ _, ok := target.(errorUncomparable)
+ return ok
+}
diff --git a/platform/dbops/binaries/go/go/src/expvar/expvar.go b/platform/dbops/binaries/go/go/src/expvar/expvar.go
new file mode 100644
index 0000000000000000000000000000000000000000..954d63d17f52b10ec1de8a6cb227c5993b981b26
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/expvar/expvar.go
@@ -0,0 +1,416 @@
+// 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 expvar provides a standardized interface to public variables, such
+// as operation counters in servers. It exposes these variables via HTTP at
+// /debug/vars in JSON format.
+//
+// Operations to set or modify these public variables are atomic.
+//
+// In addition to adding the HTTP handler, this package registers the
+// following variables:
+//
+// cmdline os.Args
+// memstats runtime.Memstats
+//
+// The package is sometimes only imported for the side effect of
+// registering its HTTP handler and the above variables. To use it
+// this way, link this package into your program:
+//
+// import _ "expvar"
+package expvar
+
+import (
+ "encoding/json"
+ "log"
+ "math"
+ "net/http"
+ "os"
+ "runtime"
+ "sort"
+ "strconv"
+ "sync"
+ "sync/atomic"
+ "unicode/utf8"
+)
+
+// Var is an abstract type for all exported variables.
+type Var interface {
+ // String returns a valid JSON value for the variable.
+ // Types with String methods that do not return valid JSON
+ // (such as time.Time) must not be used as a Var.
+ String() string
+}
+
+type jsonVar interface {
+ // appendJSON appends the JSON representation of the receiver to b.
+ appendJSON(b []byte) []byte
+}
+
+// Int is a 64-bit integer variable that satisfies the [Var] interface.
+type Int struct {
+ i atomic.Int64
+}
+
+func (v *Int) Value() int64 {
+ return v.i.Load()
+}
+
+func (v *Int) String() string {
+ return string(v.appendJSON(nil))
+}
+
+func (v *Int) appendJSON(b []byte) []byte {
+ return strconv.AppendInt(b, v.i.Load(), 10)
+}
+
+func (v *Int) Add(delta int64) {
+ v.i.Add(delta)
+}
+
+func (v *Int) Set(value int64) {
+ v.i.Store(value)
+}
+
+// Float is a 64-bit float variable that satisfies the [Var] interface.
+type Float struct {
+ f atomic.Uint64
+}
+
+func (v *Float) Value() float64 {
+ return math.Float64frombits(v.f.Load())
+}
+
+func (v *Float) String() string {
+ return string(v.appendJSON(nil))
+}
+
+func (v *Float) appendJSON(b []byte) []byte {
+ return strconv.AppendFloat(b, math.Float64frombits(v.f.Load()), 'g', -1, 64)
+}
+
+// Add adds delta to v.
+func (v *Float) Add(delta float64) {
+ for {
+ cur := v.f.Load()
+ curVal := math.Float64frombits(cur)
+ nxtVal := curVal + delta
+ nxt := math.Float64bits(nxtVal)
+ if v.f.CompareAndSwap(cur, nxt) {
+ return
+ }
+ }
+}
+
+// Set sets v to value.
+func (v *Float) Set(value float64) {
+ v.f.Store(math.Float64bits(value))
+}
+
+// Map is a string-to-Var map variable that satisfies the [Var] interface.
+type Map struct {
+ m sync.Map // map[string]Var
+ keysMu sync.RWMutex
+ keys []string // sorted
+}
+
+// KeyValue represents a single entry in a [Map].
+type KeyValue struct {
+ Key string
+ Value Var
+}
+
+func (v *Map) String() string {
+ return string(v.appendJSON(nil))
+}
+
+func (v *Map) appendJSON(b []byte) []byte {
+ return v.appendJSONMayExpand(b, false)
+}
+
+func (v *Map) appendJSONMayExpand(b []byte, expand bool) []byte {
+ afterCommaDelim := byte(' ')
+ mayAppendNewline := func(b []byte) []byte { return b }
+ if expand {
+ afterCommaDelim = '\n'
+ mayAppendNewline = func(b []byte) []byte { return append(b, '\n') }
+ }
+
+ b = append(b, '{')
+ b = mayAppendNewline(b)
+ first := true
+ v.Do(func(kv KeyValue) {
+ if !first {
+ b = append(b, ',', afterCommaDelim)
+ }
+ first = false
+ b = appendJSONQuote(b, kv.Key)
+ b = append(b, ':', ' ')
+ switch v := kv.Value.(type) {
+ case nil:
+ b = append(b, "null"...)
+ case jsonVar:
+ b = v.appendJSON(b)
+ default:
+ b = append(b, v.String()...)
+ }
+ })
+ b = mayAppendNewline(b)
+ b = append(b, '}')
+ b = mayAppendNewline(b)
+ return b
+}
+
+// Init removes all keys from the map.
+func (v *Map) Init() *Map {
+ v.keysMu.Lock()
+ defer v.keysMu.Unlock()
+ v.keys = v.keys[:0]
+ v.m.Range(func(k, _ any) bool {
+ v.m.Delete(k)
+ return true
+ })
+ return v
+}
+
+// addKey updates the sorted list of keys in v.keys.
+func (v *Map) addKey(key string) {
+ v.keysMu.Lock()
+ defer v.keysMu.Unlock()
+ // Using insertion sort to place key into the already-sorted v.keys.
+ if i := sort.SearchStrings(v.keys, key); i >= len(v.keys) {
+ v.keys = append(v.keys, key)
+ } else if v.keys[i] != key {
+ v.keys = append(v.keys, "")
+ copy(v.keys[i+1:], v.keys[i:])
+ v.keys[i] = key
+ }
+}
+
+func (v *Map) Get(key string) Var {
+ i, _ := v.m.Load(key)
+ av, _ := i.(Var)
+ return av
+}
+
+func (v *Map) Set(key string, av Var) {
+ // Before we store the value, check to see whether the key is new. Try a Load
+ // before LoadOrStore: LoadOrStore causes the key interface to escape even on
+ // the Load path.
+ if _, ok := v.m.Load(key); !ok {
+ if _, dup := v.m.LoadOrStore(key, av); !dup {
+ v.addKey(key)
+ return
+ }
+ }
+
+ v.m.Store(key, av)
+}
+
+// Add adds delta to the *[Int] value stored under the given map key.
+func (v *Map) Add(key string, delta int64) {
+ i, ok := v.m.Load(key)
+ if !ok {
+ var dup bool
+ i, dup = v.m.LoadOrStore(key, new(Int))
+ if !dup {
+ v.addKey(key)
+ }
+ }
+
+ // Add to Int; ignore otherwise.
+ if iv, ok := i.(*Int); ok {
+ iv.Add(delta)
+ }
+}
+
+// AddFloat adds delta to the *[Float] value stored under the given map key.
+func (v *Map) AddFloat(key string, delta float64) {
+ i, ok := v.m.Load(key)
+ if !ok {
+ var dup bool
+ i, dup = v.m.LoadOrStore(key, new(Float))
+ if !dup {
+ v.addKey(key)
+ }
+ }
+
+ // Add to Float; ignore otherwise.
+ if iv, ok := i.(*Float); ok {
+ iv.Add(delta)
+ }
+}
+
+// Delete deletes the given key from the map.
+func (v *Map) Delete(key string) {
+ v.keysMu.Lock()
+ defer v.keysMu.Unlock()
+ i := sort.SearchStrings(v.keys, key)
+ if i < len(v.keys) && key == v.keys[i] {
+ v.keys = append(v.keys[:i], v.keys[i+1:]...)
+ v.m.Delete(key)
+ }
+}
+
+// Do calls f for each entry in the map.
+// The map is locked during the iteration,
+// but existing entries may be concurrently updated.
+func (v *Map) Do(f func(KeyValue)) {
+ v.keysMu.RLock()
+ defer v.keysMu.RUnlock()
+ for _, k := range v.keys {
+ i, _ := v.m.Load(k)
+ val, _ := i.(Var)
+ f(KeyValue{k, val})
+ }
+}
+
+// String is a string variable, and satisfies the [Var] interface.
+type String struct {
+ s atomic.Value // string
+}
+
+func (v *String) Value() string {
+ p, _ := v.s.Load().(string)
+ return p
+}
+
+// String implements the [Var] interface. To get the unquoted string
+// use [String.Value].
+func (v *String) String() string {
+ return string(v.appendJSON(nil))
+}
+
+func (v *String) appendJSON(b []byte) []byte {
+ return appendJSONQuote(b, v.Value())
+}
+
+func (v *String) Set(value string) {
+ v.s.Store(value)
+}
+
+// Func implements [Var] by calling the function
+// and formatting the returned value using JSON.
+type Func func() any
+
+func (f Func) Value() any {
+ return f()
+}
+
+func (f Func) String() string {
+ v, _ := json.Marshal(f())
+ return string(v)
+}
+
+// All published variables.
+var vars Map
+
+// Publish declares a named exported variable. This should be called from a
+// package's init function when it creates its Vars. If the name is already
+// registered then this will log.Panic.
+func Publish(name string, v Var) {
+ if _, dup := vars.m.LoadOrStore(name, v); dup {
+ log.Panicln("Reuse of exported var name:", name)
+ }
+ vars.keysMu.Lock()
+ defer vars.keysMu.Unlock()
+ vars.keys = append(vars.keys, name)
+ sort.Strings(vars.keys)
+}
+
+// Get retrieves a named exported variable. It returns nil if the name has
+// not been registered.
+func Get(name string) Var {
+ return vars.Get(name)
+}
+
+// Convenience functions for creating new exported variables.
+
+func NewInt(name string) *Int {
+ v := new(Int)
+ Publish(name, v)
+ return v
+}
+
+func NewFloat(name string) *Float {
+ v := new(Float)
+ Publish(name, v)
+ return v
+}
+
+func NewMap(name string) *Map {
+ v := new(Map).Init()
+ Publish(name, v)
+ return v
+}
+
+func NewString(name string) *String {
+ v := new(String)
+ Publish(name, v)
+ return v
+}
+
+// Do calls f for each exported variable.
+// The global variable map is locked during the iteration,
+// but existing entries may be concurrently updated.
+func Do(f func(KeyValue)) {
+ vars.Do(f)
+}
+
+func expvarHandler(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Write(vars.appendJSONMayExpand(nil, true))
+}
+
+// Handler returns the expvar HTTP Handler.
+//
+// This is only needed to install the handler in a non-standard location.
+func Handler() http.Handler {
+ return http.HandlerFunc(expvarHandler)
+}
+
+func cmdline() any {
+ return os.Args
+}
+
+func memstats() any {
+ stats := new(runtime.MemStats)
+ runtime.ReadMemStats(stats)
+ return *stats
+}
+
+func init() {
+ http.HandleFunc("/debug/vars", expvarHandler)
+ Publish("cmdline", Func(cmdline))
+ Publish("memstats", Func(memstats))
+}
+
+// TODO: Use json.appendString instead.
+func appendJSONQuote(b []byte, s string) []byte {
+ const hex = "0123456789abcdef"
+ b = append(b, '"')
+ for _, r := range s {
+ switch {
+ case r < ' ' || r == '\\' || r == '"' || r == '<' || r == '>' || r == '&' || r == '\u2028' || r == '\u2029':
+ switch r {
+ case '\\', '"':
+ b = append(b, '\\', byte(r))
+ case '\n':
+ b = append(b, '\\', 'n')
+ case '\r':
+ b = append(b, '\\', 'r')
+ case '\t':
+ b = append(b, '\\', 't')
+ default:
+ b = append(b, '\\', 'u', hex[(r>>12)&0xf], hex[(r>>8)&0xf], hex[(r>>4)&0xf], hex[(r>>0)&0xf])
+ }
+ case r < utf8.RuneSelf:
+ b = append(b, byte(r))
+ default:
+ b = utf8.AppendRune(b, r)
+ }
+ }
+ b = append(b, '"')
+ return b
+}
diff --git a/platform/dbops/binaries/go/go/src/expvar/expvar_test.go b/platform/dbops/binaries/go/go/src/expvar/expvar_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b827c4d621b93966b7a959bfa70f5307963d3480
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/expvar/expvar_test.go
@@ -0,0 +1,663 @@
+// 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 expvar
+
+import (
+ "bytes"
+ "crypto/sha1"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http/httptest"
+ "reflect"
+ "runtime"
+ "strconv"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+// RemoveAll removes all exported variables.
+// This is for tests only.
+func RemoveAll() {
+ vars.keysMu.Lock()
+ defer vars.keysMu.Unlock()
+ for _, k := range vars.keys {
+ vars.m.Delete(k)
+ }
+ vars.keys = nil
+}
+
+func TestNil(t *testing.T) {
+ RemoveAll()
+ val := Get("missing")
+ if val != nil {
+ t.Errorf("got %v, want nil", val)
+ }
+}
+
+func TestInt(t *testing.T) {
+ RemoveAll()
+ reqs := NewInt("requests")
+ if i := reqs.Value(); i != 0 {
+ t.Errorf("reqs.Value() = %v, want 0", i)
+ }
+ if reqs != Get("requests").(*Int) {
+ t.Errorf("Get() failed.")
+ }
+
+ reqs.Add(1)
+ reqs.Add(3)
+ if i := reqs.Value(); i != 4 {
+ t.Errorf("reqs.Value() = %v, want 4", i)
+ }
+
+ if s := reqs.String(); s != "4" {
+ t.Errorf("reqs.String() = %q, want \"4\"", s)
+ }
+
+ reqs.Set(-2)
+ if i := reqs.Value(); i != -2 {
+ t.Errorf("reqs.Value() = %v, want -2", i)
+ }
+}
+
+func BenchmarkIntAdd(b *testing.B) {
+ var v Int
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ v.Add(1)
+ }
+ })
+}
+
+func BenchmarkIntSet(b *testing.B) {
+ var v Int
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ v.Set(1)
+ }
+ })
+}
+
+func TestFloat(t *testing.T) {
+ RemoveAll()
+ reqs := NewFloat("requests-float")
+ if reqs.f.Load() != 0.0 {
+ t.Errorf("reqs.f = %v, want 0", reqs.f.Load())
+ }
+ if reqs != Get("requests-float").(*Float) {
+ t.Errorf("Get() failed.")
+ }
+
+ reqs.Add(1.5)
+ reqs.Add(1.25)
+ if v := reqs.Value(); v != 2.75 {
+ t.Errorf("reqs.Value() = %v, want 2.75", v)
+ }
+
+ if s := reqs.String(); s != "2.75" {
+ t.Errorf("reqs.String() = %q, want \"4.64\"", s)
+ }
+
+ reqs.Add(-2)
+ if v := reqs.Value(); v != 0.75 {
+ t.Errorf("reqs.Value() = %v, want 0.75", v)
+ }
+}
+
+func BenchmarkFloatAdd(b *testing.B) {
+ var f Float
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ f.Add(1.0)
+ }
+ })
+}
+
+func BenchmarkFloatSet(b *testing.B) {
+ var f Float
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ f.Set(1.0)
+ }
+ })
+}
+
+func TestString(t *testing.T) {
+ RemoveAll()
+ name := NewString("my-name")
+ if s := name.Value(); s != "" {
+ t.Errorf(`NewString("my-name").Value() = %q, want ""`, s)
+ }
+
+ name.Set("Mike")
+ if s, want := name.String(), `"Mike"`; s != want {
+ t.Errorf(`after name.Set("Mike"), name.String() = %q, want %q`, s, want)
+ }
+ if s, want := name.Value(), "Mike"; s != want {
+ t.Errorf(`after name.Set("Mike"), name.Value() = %q, want %q`, s, want)
+ }
+
+ // Make sure we produce safe JSON output.
+ name.Set("<")
+ if s, want := name.String(), "\"\\u003c\""; s != want {
+ t.Errorf(`after name.Set("<"), name.String() = %q, want %q`, s, want)
+ }
+}
+
+func BenchmarkStringSet(b *testing.B) {
+ var s String
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ s.Set("red")
+ }
+ })
+}
+
+func TestMapInit(t *testing.T) {
+ RemoveAll()
+ colors := NewMap("bike-shed-colors")
+ colors.Add("red", 1)
+ colors.Add("blue", 1)
+ colors.Add("chartreuse", 1)
+
+ n := 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 3 {
+ t.Errorf("after three Add calls with distinct keys, Do should invoke f 3 times; got %v", n)
+ }
+
+ colors.Init()
+
+ n = 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 0 {
+ t.Errorf("after Init, Do should invoke f 0 times; got %v", n)
+ }
+}
+
+func TestMapDelete(t *testing.T) {
+ RemoveAll()
+ colors := NewMap("bike-shed-colors")
+
+ colors.Add("red", 1)
+ colors.Add("red", 2)
+ colors.Add("blue", 4)
+
+ n := 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 2 {
+ t.Errorf("after two Add calls with distinct keys, Do should invoke f 2 times; got %v", n)
+ }
+
+ colors.Delete("red")
+ n = 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 1 {
+ t.Errorf("removed red, Do should invoke f 1 times; got %v", n)
+ }
+
+ colors.Delete("notfound")
+ n = 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 1 {
+ t.Errorf("attempted to remove notfound, Do should invoke f 1 times; got %v", n)
+ }
+
+ colors.Delete("blue")
+ colors.Delete("blue")
+ n = 0
+ colors.Do(func(KeyValue) { n++ })
+ if n != 0 {
+ t.Errorf("all keys removed, Do should invoke f 0 times; got %v", n)
+ }
+}
+
+func TestMapCounter(t *testing.T) {
+ RemoveAll()
+ colors := NewMap("bike-shed-colors")
+
+ colors.Add("red", 1)
+ colors.Add("red", 2)
+ colors.Add("blue", 4)
+ colors.AddFloat(`green "midori"`, 4.125)
+ if x := colors.Get("red").(*Int).Value(); x != 3 {
+ t.Errorf("colors.m[\"red\"] = %v, want 3", x)
+ }
+ if x := colors.Get("blue").(*Int).Value(); x != 4 {
+ t.Errorf("colors.m[\"blue\"] = %v, want 4", x)
+ }
+ if x := colors.Get(`green "midori"`).(*Float).Value(); x != 4.125 {
+ t.Errorf("colors.m[`green \"midori\"] = %v, want 4.125", x)
+ }
+
+ // colors.String() should be '{"red":3, "blue":4}',
+ // though the order of red and blue could vary.
+ s := colors.String()
+ var j any
+ err := json.Unmarshal([]byte(s), &j)
+ if err != nil {
+ t.Errorf("colors.String() isn't valid JSON: %v", err)
+ }
+ m, ok := j.(map[string]any)
+ if !ok {
+ t.Error("colors.String() didn't produce a map.")
+ }
+ red := m["red"]
+ x, ok := red.(float64)
+ if !ok {
+ t.Error("red.Kind() is not a number.")
+ }
+ if x != 3 {
+ t.Errorf("red = %v, want 3", x)
+ }
+}
+
+func TestMapNil(t *testing.T) {
+ RemoveAll()
+ const key = "key"
+ m := NewMap("issue527719")
+ m.Set(key, nil)
+ s := m.String()
+ var j any
+ if err := json.Unmarshal([]byte(s), &j); err != nil {
+ t.Fatalf("m.String() == %q isn't valid JSON: %v", s, err)
+ }
+ m2, ok := j.(map[string]any)
+ if !ok {
+ t.Fatalf("m.String() produced %T, wanted a map", j)
+ }
+ v, ok := m2[key]
+ if !ok {
+ t.Fatalf("missing %q in %v", key, m2)
+ }
+ if v != nil {
+ t.Fatalf("m[%q] = %v, want nil", key, v)
+ }
+}
+
+func BenchmarkMapSet(b *testing.B) {
+ m := new(Map).Init()
+
+ v := new(Int)
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ m.Set("red", v)
+ }
+ })
+}
+
+func BenchmarkMapSetDifferent(b *testing.B) {
+ procKeys := make([][]string, runtime.GOMAXPROCS(0))
+ for i := range procKeys {
+ keys := make([]string, 4)
+ for j := range keys {
+ keys[j] = fmt.Sprint(i, j)
+ }
+ procKeys[i] = keys
+ }
+
+ m := new(Map).Init()
+ v := new(Int)
+ b.ResetTimer()
+
+ var n int32
+ b.RunParallel(func(pb *testing.PB) {
+ i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys)
+ keys := procKeys[i]
+
+ for pb.Next() {
+ for _, k := range keys {
+ m.Set(k, v)
+ }
+ }
+ })
+}
+
+// BenchmarkMapSetDifferentRandom simulates such a case where the concerned
+// keys of Map.Set are generated dynamically and as a result insertion is
+// out of order and the number of the keys may be large.
+func BenchmarkMapSetDifferentRandom(b *testing.B) {
+ keys := make([]string, 100)
+ for i := range keys {
+ keys[i] = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprint(i))))
+ }
+
+ v := new(Int)
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m := new(Map).Init()
+ for _, k := range keys {
+ m.Set(k, v)
+ }
+ }
+}
+
+func BenchmarkMapSetString(b *testing.B) {
+ m := new(Map).Init()
+
+ v := new(String)
+ v.Set("Hello, !")
+
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ m.Set("red", v)
+ }
+ })
+}
+
+func BenchmarkMapAddSame(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ m := new(Map).Init()
+ m.Add("red", 1)
+ m.Add("red", 1)
+ m.Add("red", 1)
+ m.Add("red", 1)
+ }
+ })
+}
+
+func BenchmarkMapAddDifferent(b *testing.B) {
+ procKeys := make([][]string, runtime.GOMAXPROCS(0))
+ for i := range procKeys {
+ keys := make([]string, 4)
+ for j := range keys {
+ keys[j] = fmt.Sprint(i, j)
+ }
+ procKeys[i] = keys
+ }
+
+ b.ResetTimer()
+
+ var n int32
+ b.RunParallel(func(pb *testing.PB) {
+ i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys)
+ keys := procKeys[i]
+
+ for pb.Next() {
+ m := new(Map).Init()
+ for _, k := range keys {
+ m.Add(k, 1)
+ }
+ }
+ })
+}
+
+// BenchmarkMapAddDifferentRandom simulates such a case where that the concerned
+// keys of Map.Add are generated dynamically and as a result insertion is out of
+// order and the number of the keys may be large.
+func BenchmarkMapAddDifferentRandom(b *testing.B) {
+ keys := make([]string, 100)
+ for i := range keys {
+ keys[i] = fmt.Sprintf("%x", sha1.Sum([]byte(fmt.Sprint(i))))
+ }
+
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m := new(Map).Init()
+ for _, k := range keys {
+ m.Add(k, 1)
+ }
+ }
+}
+
+func BenchmarkMapAddSameSteadyState(b *testing.B) {
+ m := new(Map).Init()
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ m.Add("red", 1)
+ }
+ })
+}
+
+func BenchmarkMapAddDifferentSteadyState(b *testing.B) {
+ procKeys := make([][]string, runtime.GOMAXPROCS(0))
+ for i := range procKeys {
+ keys := make([]string, 4)
+ for j := range keys {
+ keys[j] = fmt.Sprint(i, j)
+ }
+ procKeys[i] = keys
+ }
+
+ m := new(Map).Init()
+ b.ResetTimer()
+
+ var n int32
+ b.RunParallel(func(pb *testing.PB) {
+ i := int(atomic.AddInt32(&n, 1)-1) % len(procKeys)
+ keys := procKeys[i]
+
+ for pb.Next() {
+ for _, k := range keys {
+ m.Add(k, 1)
+ }
+ }
+ })
+}
+
+func TestFunc(t *testing.T) {
+ RemoveAll()
+ var x any = []string{"a", "b"}
+ f := Func(func() any { return x })
+ if s, exp := f.String(), `["a","b"]`; s != exp {
+ t.Errorf(`f.String() = %q, want %q`, s, exp)
+ }
+ if v := f.Value(); !reflect.DeepEqual(v, x) {
+ t.Errorf(`f.Value() = %q, want %q`, v, x)
+ }
+
+ x = 17
+ if s, exp := f.String(), `17`; s != exp {
+ t.Errorf(`f.String() = %q, want %q`, s, exp)
+ }
+}
+
+func TestHandler(t *testing.T) {
+ RemoveAll()
+ m := NewMap("map1")
+ m.Add("a", 1)
+ m.Add("z", 2)
+ m2 := NewMap("map2")
+ for i := 0; i < 9; i++ {
+ m2.Add(strconv.Itoa(i), int64(i))
+ }
+ rr := httptest.NewRecorder()
+ rr.Body = new(bytes.Buffer)
+ expvarHandler(rr, nil)
+ want := `{
+"map1": {"a": 1, "z": 2},
+"map2": {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8}
+}
+`
+ if got := rr.Body.String(); got != want {
+ t.Errorf("HTTP handler wrote:\n%s\nWant:\n%s", got, want)
+ }
+}
+
+func BenchmarkMapString(b *testing.B) {
+ var m, m1, m2 Map
+ m.Set("map1", &m1)
+ m1.Add("a", 1)
+ m1.Add("z", 2)
+ m.Set("map2", &m2)
+ for i := 0; i < 9; i++ {
+ m2.Add(strconv.Itoa(i), int64(i))
+ }
+ var s1, s2 String
+ m.Set("str1", &s1)
+ s1.Set("hello, world!")
+ m.Set("str2", &s2)
+ s2.Set("fizz buzz")
+ b.ResetTimer()
+
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ _ = m.String()
+ }
+}
+
+func BenchmarkRealworldExpvarUsage(b *testing.B) {
+ var (
+ bytesSent Int
+ bytesRead Int
+ )
+
+ // The benchmark creates GOMAXPROCS client/server pairs.
+ // Each pair creates 4 goroutines: client reader/writer and server reader/writer.
+ // The benchmark stresses concurrent reading and writing to the same connection.
+ // Such pattern is used in net/http and net/rpc.
+
+ b.StopTimer()
+
+ P := runtime.GOMAXPROCS(0)
+ N := b.N / P
+ W := 1000
+
+ // Setup P client/server connections.
+ clients := make([]net.Conn, P)
+ servers := make([]net.Conn, P)
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ b.Fatalf("Listen failed: %v", err)
+ }
+ defer ln.Close()
+ done := make(chan bool, 1)
+ go func() {
+ for p := 0; p < P; p++ {
+ s, err := ln.Accept()
+ if err != nil {
+ b.Errorf("Accept failed: %v", err)
+ done <- false
+ return
+ }
+ servers[p] = s
+ }
+ done <- true
+ }()
+ for p := 0; p < P; p++ {
+ c, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ <-done
+ b.Fatalf("Dial failed: %v", err)
+ }
+ clients[p] = c
+ }
+ if !<-done {
+ b.FailNow()
+ }
+
+ b.StartTimer()
+
+ var wg sync.WaitGroup
+ wg.Add(4 * P)
+ for p := 0; p < P; p++ {
+ // Client writer.
+ go func(c net.Conn) {
+ defer wg.Done()
+ var buf [1]byte
+ for i := 0; i < N; i++ {
+ v := byte(i)
+ for w := 0; w < W; w++ {
+ v *= v
+ }
+ buf[0] = v
+ n, err := c.Write(buf[:])
+ if err != nil {
+ b.Errorf("Write failed: %v", err)
+ return
+ }
+
+ bytesSent.Add(int64(n))
+ }
+ }(clients[p])
+
+ // Pipe between server reader and server writer.
+ pipe := make(chan byte, 128)
+
+ // Server reader.
+ go func(s net.Conn) {
+ defer wg.Done()
+ var buf [1]byte
+ for i := 0; i < N; i++ {
+ n, err := s.Read(buf[:])
+
+ if err != nil {
+ b.Errorf("Read failed: %v", err)
+ return
+ }
+
+ bytesRead.Add(int64(n))
+ pipe <- buf[0]
+ }
+ }(servers[p])
+
+ // Server writer.
+ go func(s net.Conn) {
+ defer wg.Done()
+ var buf [1]byte
+ for i := 0; i < N; i++ {
+ v := <-pipe
+ for w := 0; w < W; w++ {
+ v *= v
+ }
+ buf[0] = v
+ n, err := s.Write(buf[:])
+ if err != nil {
+ b.Errorf("Write failed: %v", err)
+ return
+ }
+
+ bytesSent.Add(int64(n))
+ }
+ s.Close()
+ }(servers[p])
+
+ // Client reader.
+ go func(c net.Conn) {
+ defer wg.Done()
+ var buf [1]byte
+ for i := 0; i < N; i++ {
+ n, err := c.Read(buf[:])
+
+ if err != nil {
+ b.Errorf("Read failed: %v", err)
+ return
+ }
+
+ bytesRead.Add(int64(n))
+ }
+ c.Close()
+ }(clients[p])
+ }
+ wg.Wait()
+}
+
+func TestAppendJSONQuote(t *testing.T) {
+ var b []byte
+ for i := 0; i < 128; i++ {
+ b = append(b, byte(i))
+ }
+ b = append(b, "\u2028\u2029"...)
+ got := string(appendJSONQuote(nil, string(b[:])))
+ want := `"` +
+ `\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\t\n\u000b\u000c\r\u000e\u000f` +
+ `\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f` +
+ ` !\"#$%\u0026'()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_` +
+ "`" + `abcdefghijklmnopqrstuvwxyz{|}~` + "\x7f" + `\u2028\u2029"`
+ if got != want {
+ t.Errorf("appendJSONQuote mismatch:\ngot %v\nwant %v", got, want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/example_func_test.go b/platform/dbops/binaries/go/go/src/flag/example_func_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ac9f9858dfa0013228006cd1bdcb85137a07390c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/example_func_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 flag_test
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "net"
+ "os"
+)
+
+func ExampleFunc() {
+ fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError)
+ fs.SetOutput(os.Stdout)
+ var ip net.IP
+ fs.Func("ip", "`IP address` to parse", func(s string) error {
+ ip = net.ParseIP(s)
+ if ip == nil {
+ return errors.New("could not parse IP")
+ }
+ return nil
+ })
+ fs.Parse([]string{"-ip", "127.0.0.1"})
+ fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+ // 256 is not a valid IPv4 component
+ fs.Parse([]string{"-ip", "256.0.0.1"})
+ fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
+
+ // Output:
+ // {ip: 127.0.0.1, loopback: true}
+ //
+ // invalid value "256.0.0.1" for flag -ip: could not parse IP
+ // Usage of ExampleFunc:
+ // -ip IP address
+ // IP address to parse
+ // {ip: , loopback: false}
+}
+
+func ExampleBoolFunc() {
+ fs := flag.NewFlagSet("ExampleBoolFunc", flag.ContinueOnError)
+ fs.SetOutput(os.Stdout)
+
+ fs.BoolFunc("log", "logs a dummy message", func(s string) error {
+ fmt.Println("dummy message:", s)
+ return nil
+ })
+ fs.Parse([]string{"-log"})
+ fs.Parse([]string{"-log=0"})
+
+ // Output:
+ // dummy message: true
+ // dummy message: 0
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/example_test.go b/platform/dbops/binaries/go/go/src/flag/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..088447d43f6195cec3b72c45ac20801c4776ba43
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/example_test.go
@@ -0,0 +1,85 @@
+// 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.
+
+// These examples demonstrate more intricate uses of the flag package.
+package flag_test
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "strings"
+ "time"
+)
+
+// Example 1: A single string flag called "species" with default value "gopher".
+var species = flag.String("species", "gopher", "the species we are studying")
+
+// Example 2: Two flags sharing a variable, so we can have a shorthand.
+// The order of initialization is undefined, so make sure both use the
+// same default value. They must be set up with an init function.
+var gopherType string
+
+func init() {
+ const (
+ defaultGopher = "pocket"
+ usage = "the variety of gopher"
+ )
+ flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
+ flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
+}
+
+// Example 3: A user-defined flag type, a slice of durations.
+type interval []time.Duration
+
+// String is the method to format the flag's value, part of the flag.Value interface.
+// The String method's output will be used in diagnostics.
+func (i *interval) String() string {
+ return fmt.Sprint(*i)
+}
+
+// Set is the method to set the flag value, part of the flag.Value interface.
+// Set's argument is a string to be parsed to set the flag.
+// It's a comma-separated list, so we split it.
+func (i *interval) Set(value string) error {
+ // If we wanted to allow the flag to be set multiple times,
+ // accumulating values, we would delete this if statement.
+ // That would permit usages such as
+ // -deltaT 10s -deltaT 15s
+ // and other combinations.
+ if len(*i) > 0 {
+ return errors.New("interval flag already set")
+ }
+ for _, dt := range strings.Split(value, ",") {
+ duration, err := time.ParseDuration(dt)
+ if err != nil {
+ return err
+ }
+ *i = append(*i, duration)
+ }
+ return nil
+}
+
+// Define a flag to accumulate durations. Because it has a special type,
+// we need to use the Var function and therefore create the flag during
+// init.
+
+var intervalFlag interval
+
+func init() {
+ // Tie the command-line flag to the intervalFlag variable and
+ // set a usage message.
+ flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
+}
+
+func Example() {
+ // All the interesting pieces are with the variables declared above, but
+ // to enable the flag package to see the flags defined there, one must
+ // execute, typically at the start of main (not init!):
+ // flag.Parse()
+ // We don't call it here because this code is a function called "Example"
+ // that is part of the testing suite for the package, which has already
+ // parsed the flags. When viewed at pkg.go.dev, however, the function is
+ // renamed to "main" and it could be run as a standalone example.
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/example_textvar_test.go b/platform/dbops/binaries/go/go/src/flag/example_textvar_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8b8cbf6b6c8f6b8040096d75edcd97a830512214
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/example_textvar_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 flag_test
+
+import (
+ "flag"
+ "fmt"
+ "net"
+ "os"
+)
+
+func ExampleTextVar() {
+ fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError)
+ fs.SetOutput(os.Stdout)
+ var ip net.IP
+ fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse")
+ fs.Parse([]string{"-ip", "127.0.0.1"})
+ fmt.Printf("{ip: %v}\n\n", ip)
+
+ // 256 is not a valid IPv4 component
+ ip = nil
+ fs.Parse([]string{"-ip", "256.0.0.1"})
+ fmt.Printf("{ip: %v}\n\n", ip)
+
+ // Output:
+ // {ip: 127.0.0.1}
+ //
+ // invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1
+ // Usage of ExampleTextVar:
+ // -ip IP address
+ // IP address to parse (default 192.168.0.100)
+ // {ip: }
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/example_value_test.go b/platform/dbops/binaries/go/go/src/flag/example_value_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d464c62e876b94a07fde8d8cb61b180826ae7c1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/example_value_test.go
@@ -0,0 +1,44 @@
+// 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 flag_test
+
+import (
+ "flag"
+ "fmt"
+ "net/url"
+)
+
+type URLValue struct {
+ URL *url.URL
+}
+
+func (v URLValue) String() string {
+ if v.URL != nil {
+ return v.URL.String()
+ }
+ return ""
+}
+
+func (v URLValue) Set(s string) error {
+ if u, err := url.Parse(s); err != nil {
+ return err
+ } else {
+ *v.URL = *u
+ }
+ return nil
+}
+
+var u = &url.URL{}
+
+func ExampleValue() {
+ fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
+ fs.Var(&URLValue{u}, "url", "URL to parse")
+
+ fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
+ fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
+
+ // Output:
+ // {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/export_test.go b/platform/dbops/binaries/go/go/src/flag/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9ef93ed6c5be1d0ea9949a150b7e92e6b3d59d44
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/export_test.go
@@ -0,0 +1,24 @@
+// 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 flag
+
+import (
+ "io"
+ "os"
+)
+
+// Additional routines compiled into the package only during testing.
+
+var DefaultUsage = Usage
+
+// ResetForTesting clears all flag state and sets the usage function as directed.
+// After calling ResetForTesting, parse errors in flag handling will not
+// exit the program.
+func ResetForTesting(usage func()) {
+ CommandLine = NewFlagSet(os.Args[0], ContinueOnError)
+ CommandLine.SetOutput(io.Discard)
+ CommandLine.Usage = commandLineUsage
+ Usage = usage
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/flag.go b/platform/dbops/binaries/go/go/src/flag/flag.go
new file mode 100644
index 0000000000000000000000000000000000000000..1669e9aca7f2f334bf2d987dcb6796d7f58c797a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/flag.go
@@ -0,0 +1,1231 @@
+// 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 flag implements command-line flag parsing.
+
+# Usage
+
+Define flags using [flag.String], [Bool], [Int], etc.
+
+This declares an integer flag, -n, stored in the pointer nFlag, with type *int:
+
+ import "flag"
+ var nFlag = flag.Int("n", 1234, "help message for flag n")
+
+If you like, you can bind the flag to a variable using the Var() functions.
+
+ var flagvar int
+ func init() {
+ flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
+ }
+
+Or you can create custom flags that satisfy the Value interface (with
+pointer receivers) and couple them to flag parsing by
+
+ flag.Var(&flagVal, "name", "help message for flagname")
+
+For such flags, the default value is just the initial value of the variable.
+
+After all flags are defined, call
+
+ flag.Parse()
+
+to parse the command line into the defined flags.
+
+Flags may then be used directly. If you're using the flags themselves,
+they are all pointers; if you bind to variables, they're values.
+
+ fmt.Println("ip has value ", *ip)
+ fmt.Println("flagvar has value ", flagvar)
+
+After parsing, the arguments following the flags are available as the
+slice [flag.Args] or individually as [flag.Arg](i).
+The arguments are indexed from 0 through [flag.NArg]-1.
+
+# Command line flag syntax
+
+The following forms are permitted:
+
+ -flag
+ --flag // double dashes are also permitted
+ -flag=x
+ -flag x // non-boolean flags only
+
+One or two dashes may be used; they are equivalent.
+The last form is not permitted for boolean flags because the
+meaning of the command
+
+ cmd -x *
+
+where * is a Unix shell wildcard, will change if there is a file
+called 0, false, etc. You must use the -flag=false form to turn
+off a boolean flag.
+
+Flag parsing stops just before the first non-flag argument
+("-" is a non-flag argument) or after the terminator "--".
+
+Integer flags accept 1234, 0664, 0x1234 and may be negative.
+Boolean flags may be:
+
+ 1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
+
+Duration flags accept any input valid for time.ParseDuration.
+
+The default set of command-line flags is controlled by
+top-level functions. The [FlagSet] type allows one to define
+independent sets of flags, such as to implement subcommands
+in a command-line interface. The methods of [FlagSet] are
+analogous to the top-level functions for the command-line
+flag set.
+*/
+package flag
+
+import (
+ "encoding"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// ErrHelp is the error returned if the -help or -h flag is invoked
+// but no such flag is defined.
+var ErrHelp = errors.New("flag: help requested")
+
+// errParse is returned by Set if a flag's value fails to parse, such as with an invalid integer for Int.
+// It then gets wrapped through failf to provide more information.
+var errParse = errors.New("parse error")
+
+// errRange is returned by Set if a flag's value is out of range.
+// It then gets wrapped through failf to provide more information.
+var errRange = errors.New("value out of range")
+
+func numError(err error) error {
+ ne, ok := err.(*strconv.NumError)
+ if !ok {
+ return err
+ }
+ if ne.Err == strconv.ErrSyntax {
+ return errParse
+ }
+ if ne.Err == strconv.ErrRange {
+ return errRange
+ }
+ return err
+}
+
+// -- bool Value
+type boolValue bool
+
+func newBoolValue(val bool, p *bool) *boolValue {
+ *p = val
+ return (*boolValue)(p)
+}
+
+func (b *boolValue) Set(s string) error {
+ v, err := strconv.ParseBool(s)
+ if err != nil {
+ err = errParse
+ }
+ *b = boolValue(v)
+ return err
+}
+
+func (b *boolValue) Get() any { return bool(*b) }
+
+func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
+
+func (b *boolValue) IsBoolFlag() bool { return true }
+
+// optional interface to indicate boolean flags that can be
+// supplied without "=value" text
+type boolFlag interface {
+ Value
+ IsBoolFlag() bool
+}
+
+// -- int Value
+type intValue int
+
+func newIntValue(val int, p *int) *intValue {
+ *p = val
+ return (*intValue)(p)
+}
+
+func (i *intValue) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, strconv.IntSize)
+ if err != nil {
+ err = numError(err)
+ }
+ *i = intValue(v)
+ return err
+}
+
+func (i *intValue) Get() any { return int(*i) }
+
+func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
+
+// -- int64 Value
+type int64Value int64
+
+func newInt64Value(val int64, p *int64) *int64Value {
+ *p = val
+ return (*int64Value)(p)
+}
+
+func (i *int64Value) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 64)
+ if err != nil {
+ err = numError(err)
+ }
+ *i = int64Value(v)
+ return err
+}
+
+func (i *int64Value) Get() any { return int64(*i) }
+
+func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
+
+// -- uint Value
+type uintValue uint
+
+func newUintValue(val uint, p *uint) *uintValue {
+ *p = val
+ return (*uintValue)(p)
+}
+
+func (i *uintValue) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, strconv.IntSize)
+ if err != nil {
+ err = numError(err)
+ }
+ *i = uintValue(v)
+ return err
+}
+
+func (i *uintValue) Get() any { return uint(*i) }
+
+func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+// -- uint64 Value
+type uint64Value uint64
+
+func newUint64Value(val uint64, p *uint64) *uint64Value {
+ *p = val
+ return (*uint64Value)(p)
+}
+
+func (i *uint64Value) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 64)
+ if err != nil {
+ err = numError(err)
+ }
+ *i = uint64Value(v)
+ return err
+}
+
+func (i *uint64Value) Get() any { return uint64(*i) }
+
+func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+// -- string Value
+type stringValue string
+
+func newStringValue(val string, p *string) *stringValue {
+ *p = val
+ return (*stringValue)(p)
+}
+
+func (s *stringValue) Set(val string) error {
+ *s = stringValue(val)
+ return nil
+}
+
+func (s *stringValue) Get() any { return string(*s) }
+
+func (s *stringValue) String() string { return string(*s) }
+
+// -- float64 Value
+type float64Value float64
+
+func newFloat64Value(val float64, p *float64) *float64Value {
+ *p = val
+ return (*float64Value)(p)
+}
+
+func (f *float64Value) Set(s string) error {
+ v, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ err = numError(err)
+ }
+ *f = float64Value(v)
+ return err
+}
+
+func (f *float64Value) Get() any { return float64(*f) }
+
+func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
+
+// -- time.Duration Value
+type durationValue time.Duration
+
+func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
+ *p = val
+ return (*durationValue)(p)
+}
+
+func (d *durationValue) Set(s string) error {
+ v, err := time.ParseDuration(s)
+ if err != nil {
+ err = errParse
+ }
+ *d = durationValue(v)
+ return err
+}
+
+func (d *durationValue) Get() any { return time.Duration(*d) }
+
+func (d *durationValue) String() string { return (*time.Duration)(d).String() }
+
+// -- encoding.TextUnmarshaler Value
+type textValue struct{ p encoding.TextUnmarshaler }
+
+func newTextValue(val encoding.TextMarshaler, p encoding.TextUnmarshaler) textValue {
+ ptrVal := reflect.ValueOf(p)
+ if ptrVal.Kind() != reflect.Ptr {
+ panic("variable value type must be a pointer")
+ }
+ defVal := reflect.ValueOf(val)
+ if defVal.Kind() == reflect.Ptr {
+ defVal = defVal.Elem()
+ }
+ if defVal.Type() != ptrVal.Type().Elem() {
+ panic(fmt.Sprintf("default type does not match variable type: %v != %v", defVal.Type(), ptrVal.Type().Elem()))
+ }
+ ptrVal.Elem().Set(defVal)
+ return textValue{p}
+}
+
+func (v textValue) Set(s string) error {
+ return v.p.UnmarshalText([]byte(s))
+}
+
+func (v textValue) Get() interface{} {
+ return v.p
+}
+
+func (v textValue) String() string {
+ if m, ok := v.p.(encoding.TextMarshaler); ok {
+ if b, err := m.MarshalText(); err == nil {
+ return string(b)
+ }
+ }
+ return ""
+}
+
+// -- func Value
+type funcValue func(string) error
+
+func (f funcValue) Set(s string) error { return f(s) }
+
+func (f funcValue) String() string { return "" }
+
+// -- boolFunc Value
+type boolFuncValue func(string) error
+
+func (f boolFuncValue) Set(s string) error { return f(s) }
+
+func (f boolFuncValue) String() string { return "" }
+
+func (f boolFuncValue) IsBoolFlag() bool { return true }
+
+// Value is the interface to the dynamic value stored in a flag.
+// (The default value is represented as a string.)
+//
+// If a Value has an IsBoolFlag() bool method returning true,
+// the command-line parser makes -name equivalent to -name=true
+// rather than using the next command-line argument.
+//
+// Set is called once, in command line order, for each flag present.
+// The flag package may call the [String] method with a zero-valued receiver,
+// such as a nil pointer.
+type Value interface {
+ String() string
+ Set(string) error
+}
+
+// Getter is an interface that allows the contents of a [Value] to be retrieved.
+// It wraps the [Value] interface, rather than being part of it, because it
+// appeared after Go 1 and its compatibility rules. All [Value] types provided
+// by this package satisfy the [Getter] interface, except the type used by [Func].
+type Getter interface {
+ Value
+ Get() any
+}
+
+// ErrorHandling defines how [FlagSet.Parse] behaves if the parse fails.
+type ErrorHandling int
+
+// These constants cause [FlagSet.Parse] to behave as described if the parse fails.
+const (
+ ContinueOnError ErrorHandling = iota // Return a descriptive error.
+ ExitOnError // Call os.Exit(2) or for -h/-help Exit(0).
+ PanicOnError // Call panic with a descriptive error.
+)
+
+// A FlagSet represents a set of defined flags. The zero value of a FlagSet
+// has no name and has [ContinueOnError] error handling.
+//
+// [Flag] names must be unique within a FlagSet. An attempt to define a flag whose
+// name is already in use will cause a panic.
+type FlagSet struct {
+ // Usage is the function called when an error occurs while parsing flags.
+ // The field is a function (not a method) that may be changed to point to
+ // a custom error handler. What happens after Usage is called depends
+ // on the ErrorHandling setting; for the command line, this defaults
+ // to ExitOnError, which exits the program after calling Usage.
+ Usage func()
+
+ name string
+ parsed bool
+ actual map[string]*Flag
+ formal map[string]*Flag
+ args []string // arguments after flags
+ errorHandling ErrorHandling
+ output io.Writer // nil means stderr; use Output() accessor
+ undef map[string]string // flags which didn't exist at the time of Set
+}
+
+// A Flag represents the state of a flag.
+type Flag struct {
+ Name string // name as it appears on command line
+ Usage string // help message
+ Value Value // value as set
+ DefValue string // default value (as text); for usage message
+}
+
+// sortFlags returns the flags as a slice in lexicographical sorted order.
+func sortFlags(flags map[string]*Flag) []*Flag {
+ result := make([]*Flag, len(flags))
+ i := 0
+ for _, f := range flags {
+ result[i] = f
+ i++
+ }
+ sort.Slice(result, func(i, j int) bool {
+ return result[i].Name < result[j].Name
+ })
+ return result
+}
+
+// Output returns the destination for usage and error messages. [os.Stderr] is returned if
+// output was not set or was set to nil.
+func (f *FlagSet) Output() io.Writer {
+ if f.output == nil {
+ return os.Stderr
+ }
+ return f.output
+}
+
+// Name returns the name of the flag set.
+func (f *FlagSet) Name() string {
+ return f.name
+}
+
+// ErrorHandling returns the error handling behavior of the flag set.
+func (f *FlagSet) ErrorHandling() ErrorHandling {
+ return f.errorHandling
+}
+
+// SetOutput sets the destination for usage and error messages.
+// If output is nil, [os.Stderr] is used.
+func (f *FlagSet) SetOutput(output io.Writer) {
+ f.output = output
+}
+
+// VisitAll visits the flags in lexicographical order, calling fn for each.
+// It visits all flags, even those not set.
+func (f *FlagSet) VisitAll(fn func(*Flag)) {
+ for _, flag := range sortFlags(f.formal) {
+ fn(flag)
+ }
+}
+
+// VisitAll visits the command-line flags in lexicographical order, calling
+// fn for each. It visits all flags, even those not set.
+func VisitAll(fn func(*Flag)) {
+ CommandLine.VisitAll(fn)
+}
+
+// Visit visits the flags in lexicographical order, calling fn for each.
+// It visits only those flags that have been set.
+func (f *FlagSet) Visit(fn func(*Flag)) {
+ for _, flag := range sortFlags(f.actual) {
+ fn(flag)
+ }
+}
+
+// Visit visits the command-line flags in lexicographical order, calling fn
+// for each. It visits only those flags that have been set.
+func Visit(fn func(*Flag)) {
+ CommandLine.Visit(fn)
+}
+
+// Lookup returns the [Flag] structure of the named flag, returning nil if none exists.
+func (f *FlagSet) Lookup(name string) *Flag {
+ return f.formal[name]
+}
+
+// Lookup returns the [Flag] structure of the named command-line flag,
+// returning nil if none exists.
+func Lookup(name string) *Flag {
+ return CommandLine.formal[name]
+}
+
+// Set sets the value of the named flag.
+func (f *FlagSet) Set(name, value string) error {
+ return f.set(name, value)
+}
+func (f *FlagSet) set(name, value string) error {
+ flag, ok := f.formal[name]
+ if !ok {
+ // Remember that a flag that isn't defined is being set.
+ // We return an error in this case, but in addition if
+ // subsequently that flag is defined, we want to panic
+ // at the definition point.
+ // This is a problem which occurs if both the definition
+ // and the Set call are in init code and for whatever
+ // reason the init code changes evaluation order.
+ // See issue 57411.
+ _, file, line, ok := runtime.Caller(2)
+ if !ok {
+ file = "?"
+ line = 0
+ }
+ if f.undef == nil {
+ f.undef = map[string]string{}
+ }
+ f.undef[name] = fmt.Sprintf("%s:%d", file, line)
+
+ return fmt.Errorf("no such flag -%v", name)
+ }
+ err := flag.Value.Set(value)
+ if err != nil {
+ return err
+ }
+ if f.actual == nil {
+ f.actual = make(map[string]*Flag)
+ }
+ f.actual[name] = flag
+ return nil
+}
+
+// Set sets the value of the named command-line flag.
+func Set(name, value string) error {
+ return CommandLine.set(name, value)
+}
+
+// isZeroValue determines whether the string represents the zero
+// value for a flag.
+func isZeroValue(flag *Flag, value string) (ok bool, err error) {
+ // Build a zero value of the flag's Value type, and see if the
+ // result of calling its String method equals the value passed in.
+ // This works unless the Value type is itself an interface type.
+ typ := reflect.TypeOf(flag.Value)
+ var z reflect.Value
+ if typ.Kind() == reflect.Pointer {
+ z = reflect.New(typ.Elem())
+ } else {
+ z = reflect.Zero(typ)
+ }
+ // Catch panics calling the String method, which shouldn't prevent the
+ // usage message from being printed, but that we should report to the
+ // user so that they know to fix their code.
+ defer func() {
+ if e := recover(); e != nil {
+ if typ.Kind() == reflect.Pointer {
+ typ = typ.Elem()
+ }
+ err = fmt.Errorf("panic calling String method on zero %v for flag %s: %v", typ, flag.Name, e)
+ }
+ }()
+ return value == z.Interface().(Value).String(), nil
+}
+
+// UnquoteUsage extracts a back-quoted name from the usage
+// string for a flag and returns it and the un-quoted usage.
+// Given "a `name` to show" it returns ("name", "a name to show").
+// If there are no back quotes, the name is an educated guess of the
+// type of the flag's value, or the empty string if the flag is boolean.
+func UnquoteUsage(flag *Flag) (name string, usage string) {
+ // Look for a back-quoted name, but avoid the strings package.
+ usage = flag.Usage
+ for i := 0; i < len(usage); i++ {
+ if usage[i] == '`' {
+ for j := i + 1; j < len(usage); j++ {
+ if usage[j] == '`' {
+ name = usage[i+1 : j]
+ usage = usage[:i] + name + usage[j+1:]
+ return name, usage
+ }
+ }
+ break // Only one back quote; use type name.
+ }
+ }
+ // No explicit name, so use type if we can find one.
+ name = "value"
+ switch fv := flag.Value.(type) {
+ case boolFlag:
+ if fv.IsBoolFlag() {
+ name = ""
+ }
+ case *durationValue:
+ name = "duration"
+ case *float64Value:
+ name = "float"
+ case *intValue, *int64Value:
+ name = "int"
+ case *stringValue:
+ name = "string"
+ case *uintValue, *uint64Value:
+ name = "uint"
+ }
+ return
+}
+
+// PrintDefaults prints, to standard error unless configured otherwise, the
+// default values of all defined command-line flags in the set. See the
+// documentation for the global function PrintDefaults for more information.
+func (f *FlagSet) PrintDefaults() {
+ var isZeroValueErrs []error
+ f.VisitAll(func(flag *Flag) {
+ var b strings.Builder
+ fmt.Fprintf(&b, " -%s", flag.Name) // Two spaces before -; see next two comments.
+ name, usage := UnquoteUsage(flag)
+ if len(name) > 0 {
+ b.WriteString(" ")
+ b.WriteString(name)
+ }
+ // Boolean flags of one ASCII letter are so common we
+ // treat them specially, putting their usage on the same line.
+ if b.Len() <= 4 { // space, space, '-', 'x'.
+ b.WriteString("\t")
+ } else {
+ // Four spaces before the tab triggers good alignment
+ // for both 4- and 8-space tab stops.
+ b.WriteString("\n \t")
+ }
+ b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
+
+ // Print the default value only if it differs to the zero value
+ // for this flag type.
+ if isZero, err := isZeroValue(flag, flag.DefValue); err != nil {
+ isZeroValueErrs = append(isZeroValueErrs, err)
+ } else if !isZero {
+ if _, ok := flag.Value.(*stringValue); ok {
+ // put quotes on the value
+ fmt.Fprintf(&b, " (default %q)", flag.DefValue)
+ } else {
+ fmt.Fprintf(&b, " (default %v)", flag.DefValue)
+ }
+ }
+ fmt.Fprint(f.Output(), b.String(), "\n")
+ })
+ // If calling String on any zero flag.Values triggered a panic, print
+ // the messages after the full set of defaults so that the programmer
+ // knows to fix the panic.
+ if errs := isZeroValueErrs; len(errs) > 0 {
+ fmt.Fprintln(f.Output())
+ for _, err := range errs {
+ fmt.Fprintln(f.Output(), err)
+ }
+ }
+}
+
+// PrintDefaults prints, to standard error unless configured otherwise,
+// a usage message showing the default settings of all defined
+// command-line flags.
+// For an integer valued flag x, the default output has the form
+//
+// -x int
+// usage-message-for-x (default 7)
+//
+// The usage message will appear on a separate line for anything but
+// a bool flag with a one-byte name. For bool flags, the type is
+// omitted and if the flag name is one byte the usage message appears
+// on the same line. The parenthetical default is omitted if the
+// default is the zero value for the type. The listed type, here int,
+// can be changed by placing a back-quoted name in the flag's usage
+// string; the first such item in the message is taken to be a parameter
+// name to show in the message and the back quotes are stripped from
+// the message when displayed. For instance, given
+//
+// flag.String("I", "", "search `directory` for include files")
+//
+// the output will be
+//
+// -I directory
+// search directory for include files.
+//
+// To change the destination for flag messages, call [CommandLine].SetOutput.
+func PrintDefaults() {
+ CommandLine.PrintDefaults()
+}
+
+// defaultUsage is the default function to print a usage message.
+func (f *FlagSet) defaultUsage() {
+ if f.name == "" {
+ fmt.Fprintf(f.Output(), "Usage:\n")
+ } else {
+ fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name)
+ }
+ f.PrintDefaults()
+}
+
+// NOTE: Usage is not just defaultUsage(CommandLine)
+// because it serves (via godoc flag Usage) as the example
+// for how to write your own usage function.
+
+// Usage prints a usage message documenting all defined command-line flags
+// to [CommandLine]'s output, which by default is [os.Stderr].
+// It is called when an error occurs while parsing flags.
+// The function is a variable that may be changed to point to a custom function.
+// By default it prints a simple header and calls [PrintDefaults]; for details about the
+// format of the output and how to control it, see the documentation for [PrintDefaults].
+// Custom usage functions may choose to exit the program; by default exiting
+// happens anyway as the command line's error handling strategy is set to
+// [ExitOnError].
+var Usage = func() {
+ fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
+ PrintDefaults()
+}
+
+// NFlag returns the number of flags that have been set.
+func (f *FlagSet) NFlag() int { return len(f.actual) }
+
+// NFlag returns the number of command-line flags that have been set.
+func NFlag() int { return len(CommandLine.actual) }
+
+// Arg returns the i'th argument. Arg(0) is the first remaining argument
+// after flags have been processed. Arg returns an empty string if the
+// requested element does not exist.
+func (f *FlagSet) Arg(i int) string {
+ if i < 0 || i >= len(f.args) {
+ return ""
+ }
+ return f.args[i]
+}
+
+// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
+// after flags have been processed. Arg returns an empty string if the
+// requested element does not exist.
+func Arg(i int) string {
+ return CommandLine.Arg(i)
+}
+
+// NArg is the number of arguments remaining after flags have been processed.
+func (f *FlagSet) NArg() int { return len(f.args) }
+
+// NArg is the number of arguments remaining after flags have been processed.
+func NArg() int { return len(CommandLine.args) }
+
+// Args returns the non-flag arguments.
+func (f *FlagSet) Args() []string { return f.args }
+
+// Args returns the non-flag command-line arguments.
+func Args() []string { return CommandLine.args }
+
+// BoolVar defines a bool flag with specified name, default value, and usage string.
+// The argument p points to a bool variable in which to store the value of the flag.
+func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
+ f.Var(newBoolValue(value, p), name, usage)
+}
+
+// BoolVar defines a bool flag with specified name, default value, and usage string.
+// The argument p points to a bool variable in which to store the value of the flag.
+func BoolVar(p *bool, name string, value bool, usage string) {
+ CommandLine.Var(newBoolValue(value, p), name, usage)
+}
+
+// Bool defines a bool flag with specified name, default value, and usage string.
+// The return value is the address of a bool variable that stores the value of the flag.
+func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
+ p := new(bool)
+ f.BoolVar(p, name, value, usage)
+ return p
+}
+
+// Bool defines a bool flag with specified name, default value, and usage string.
+// The return value is the address of a bool variable that stores the value of the flag.
+func Bool(name string, value bool, usage string) *bool {
+ return CommandLine.Bool(name, value, usage)
+}
+
+// IntVar defines an int flag with specified name, default value, and usage string.
+// The argument p points to an int variable in which to store the value of the flag.
+func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
+ f.Var(newIntValue(value, p), name, usage)
+}
+
+// IntVar defines an int flag with specified name, default value, and usage string.
+// The argument p points to an int variable in which to store the value of the flag.
+func IntVar(p *int, name string, value int, usage string) {
+ CommandLine.Var(newIntValue(value, p), name, usage)
+}
+
+// Int defines an int flag with specified name, default value, and usage string.
+// The return value is the address of an int variable that stores the value of the flag.
+func (f *FlagSet) Int(name string, value int, usage string) *int {
+ p := new(int)
+ f.IntVar(p, name, value, usage)
+ return p
+}
+
+// Int defines an int flag with specified name, default value, and usage string.
+// The return value is the address of an int variable that stores the value of the flag.
+func Int(name string, value int, usage string) *int {
+ return CommandLine.Int(name, value, usage)
+}
+
+// Int64Var defines an int64 flag with specified name, default value, and usage string.
+// The argument p points to an int64 variable in which to store the value of the flag.
+func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
+ f.Var(newInt64Value(value, p), name, usage)
+}
+
+// Int64Var defines an int64 flag with specified name, default value, and usage string.
+// The argument p points to an int64 variable in which to store the value of the flag.
+func Int64Var(p *int64, name string, value int64, usage string) {
+ CommandLine.Var(newInt64Value(value, p), name, usage)
+}
+
+// Int64 defines an int64 flag with specified name, default value, and usage string.
+// The return value is the address of an int64 variable that stores the value of the flag.
+func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
+ p := new(int64)
+ f.Int64Var(p, name, value, usage)
+ return p
+}
+
+// Int64 defines an int64 flag with specified name, default value, and usage string.
+// The return value is the address of an int64 variable that stores the value of the flag.
+func Int64(name string, value int64, usage string) *int64 {
+ return CommandLine.Int64(name, value, usage)
+}
+
+// UintVar defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
+ f.Var(newUintValue(value, p), name, usage)
+}
+
+// UintVar defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func UintVar(p *uint, name string, value uint, usage string) {
+ CommandLine.Var(newUintValue(value, p), name, usage)
+}
+
+// Uint defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
+ p := new(uint)
+ f.UintVar(p, name, value, usage)
+ return p
+}
+
+// Uint defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func Uint(name string, value uint, usage string) *uint {
+ return CommandLine.Uint(name, value, usage)
+}
+
+// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
+// The argument p points to a uint64 variable in which to store the value of the flag.
+func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
+ f.Var(newUint64Value(value, p), name, usage)
+}
+
+// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
+// The argument p points to a uint64 variable in which to store the value of the flag.
+func Uint64Var(p *uint64, name string, value uint64, usage string) {
+ CommandLine.Var(newUint64Value(value, p), name, usage)
+}
+
+// Uint64 defines a uint64 flag with specified name, default value, and usage string.
+// The return value is the address of a uint64 variable that stores the value of the flag.
+func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
+ p := new(uint64)
+ f.Uint64Var(p, name, value, usage)
+ return p
+}
+
+// Uint64 defines a uint64 flag with specified name, default value, and usage string.
+// The return value is the address of a uint64 variable that stores the value of the flag.
+func Uint64(name string, value uint64, usage string) *uint64 {
+ return CommandLine.Uint64(name, value, usage)
+}
+
+// StringVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a string variable in which to store the value of the flag.
+func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
+ f.Var(newStringValue(value, p), name, usage)
+}
+
+// StringVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a string variable in which to store the value of the flag.
+func StringVar(p *string, name string, value string, usage string) {
+ CommandLine.Var(newStringValue(value, p), name, usage)
+}
+
+// String defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a string variable that stores the value of the flag.
+func (f *FlagSet) String(name string, value string, usage string) *string {
+ p := new(string)
+ f.StringVar(p, name, value, usage)
+ return p
+}
+
+// String defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a string variable that stores the value of the flag.
+func String(name string, value string, usage string) *string {
+ return CommandLine.String(name, value, usage)
+}
+
+// Float64Var defines a float64 flag with specified name, default value, and usage string.
+// The argument p points to a float64 variable in which to store the value of the flag.
+func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
+ f.Var(newFloat64Value(value, p), name, usage)
+}
+
+// Float64Var defines a float64 flag with specified name, default value, and usage string.
+// The argument p points to a float64 variable in which to store the value of the flag.
+func Float64Var(p *float64, name string, value float64, usage string) {
+ CommandLine.Var(newFloat64Value(value, p), name, usage)
+}
+
+// Float64 defines a float64 flag with specified name, default value, and usage string.
+// The return value is the address of a float64 variable that stores the value of the flag.
+func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
+ p := new(float64)
+ f.Float64Var(p, name, value, usage)
+ return p
+}
+
+// Float64 defines a float64 flag with specified name, default value, and usage string.
+// The return value is the address of a float64 variable that stores the value of the flag.
+func Float64(name string, value float64, usage string) *float64 {
+ return CommandLine.Float64(name, value, usage)
+}
+
+// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
+// The argument p points to a time.Duration variable in which to store the value of the flag.
+// The flag accepts a value acceptable to time.ParseDuration.
+func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
+ f.Var(newDurationValue(value, p), name, usage)
+}
+
+// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
+// The argument p points to a time.Duration variable in which to store the value of the flag.
+// The flag accepts a value acceptable to time.ParseDuration.
+func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
+ CommandLine.Var(newDurationValue(value, p), name, usage)
+}
+
+// Duration defines a time.Duration flag with specified name, default value, and usage string.
+// The return value is the address of a time.Duration variable that stores the value of the flag.
+// The flag accepts a value acceptable to time.ParseDuration.
+func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
+ p := new(time.Duration)
+ f.DurationVar(p, name, value, usage)
+ return p
+}
+
+// Duration defines a time.Duration flag with specified name, default value, and usage string.
+// The return value is the address of a time.Duration variable that stores the value of the flag.
+// The flag accepts a value acceptable to time.ParseDuration.
+func Duration(name string, value time.Duration, usage string) *time.Duration {
+ return CommandLine.Duration(name, value, usage)
+}
+
+// TextVar defines a flag with a specified name, default value, and usage string.
+// The argument p must be a pointer to a variable that will hold the value
+// of the flag, and p must implement encoding.TextUnmarshaler.
+// If the flag is used, the flag value will be passed to p's UnmarshalText method.
+// The type of the default value must be the same as the type of p.
+func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) {
+ f.Var(newTextValue(value, p), name, usage)
+}
+
+// TextVar defines a flag with a specified name, default value, and usage string.
+// The argument p must be a pointer to a variable that will hold the value
+// of the flag, and p must implement encoding.TextUnmarshaler.
+// If the flag is used, the flag value will be passed to p's UnmarshalText method.
+// The type of the default value must be the same as the type of p.
+func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) {
+ CommandLine.Var(newTextValue(value, p), name, usage)
+}
+
+// Func defines a flag with the specified name and usage string.
+// Each time the flag is seen, fn is called with the value of the flag.
+// If fn returns a non-nil error, it will be treated as a flag value parsing error.
+func (f *FlagSet) Func(name, usage string, fn func(string) error) {
+ f.Var(funcValue(fn), name, usage)
+}
+
+// Func defines a flag with the specified name and usage string.
+// Each time the flag is seen, fn is called with the value of the flag.
+// If fn returns a non-nil error, it will be treated as a flag value parsing error.
+func Func(name, usage string, fn func(string) error) {
+ CommandLine.Func(name, usage, fn)
+}
+
+// BoolFunc defines a flag with the specified name and usage string without requiring values.
+// Each time the flag is seen, fn is called with the value of the flag.
+// If fn returns a non-nil error, it will be treated as a flag value parsing error.
+func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error) {
+ f.Var(boolFuncValue(fn), name, usage)
+}
+
+// BoolFunc defines a flag with the specified name and usage string without requiring values.
+// Each time the flag is seen, fn is called with the value of the flag.
+// If fn returns a non-nil error, it will be treated as a flag value parsing error.
+func BoolFunc(name, usage string, fn func(string) error) {
+ CommandLine.BoolFunc(name, usage, fn)
+}
+
+// Var defines a flag with the specified name and usage string. The type and
+// value of the flag are represented by the first argument, of type [Value], which
+// typically holds a user-defined implementation of [Value]. For instance, the
+// caller could create a flag that turns a comma-separated string into a slice
+// of strings by giving the slice the methods of [Value]; in particular, [Set] would
+// decompose the comma-separated string into the slice.
+func (f *FlagSet) Var(value Value, name string, usage string) {
+ // Flag must not begin "-" or contain "=".
+ if strings.HasPrefix(name, "-") {
+ panic(f.sprintf("flag %q begins with -", name))
+ } else if strings.Contains(name, "=") {
+ panic(f.sprintf("flag %q contains =", name))
+ }
+
+ // Remember the default value as a string; it won't change.
+ flag := &Flag{name, usage, value, value.String()}
+ _, alreadythere := f.formal[name]
+ if alreadythere {
+ var msg string
+ if f.name == "" {
+ msg = f.sprintf("flag redefined: %s", name)
+ } else {
+ msg = f.sprintf("%s flag redefined: %s", f.name, name)
+ }
+ panic(msg) // Happens only if flags are declared with identical names
+ }
+ if pos := f.undef[name]; pos != "" {
+ panic(fmt.Sprintf("flag %s set at %s before being defined", name, pos))
+ }
+ if f.formal == nil {
+ f.formal = make(map[string]*Flag)
+ }
+ f.formal[name] = flag
+}
+
+// Var defines a flag with the specified name and usage string. The type and
+// value of the flag are represented by the first argument, of type [Value], which
+// typically holds a user-defined implementation of [Value]. For instance, the
+// caller could create a flag that turns a comma-separated string into a slice
+// of strings by giving the slice the methods of [Value]; in particular, [Set] would
+// decompose the comma-separated string into the slice.
+func Var(value Value, name string, usage string) {
+ CommandLine.Var(value, name, usage)
+}
+
+// sprintf formats the message, prints it to output, and returns it.
+func (f *FlagSet) sprintf(format string, a ...any) string {
+ msg := fmt.Sprintf(format, a...)
+ fmt.Fprintln(f.Output(), msg)
+ return msg
+}
+
+// failf prints to standard error a formatted error and usage message and
+// returns the error.
+func (f *FlagSet) failf(format string, a ...any) error {
+ msg := f.sprintf(format, a...)
+ f.usage()
+ return errors.New(msg)
+}
+
+// usage calls the Usage method for the flag set if one is specified,
+// or the appropriate default usage function otherwise.
+func (f *FlagSet) usage() {
+ if f.Usage == nil {
+ f.defaultUsage()
+ } else {
+ f.Usage()
+ }
+}
+
+// parseOne parses one flag. It reports whether a flag was seen.
+func (f *FlagSet) parseOne() (bool, error) {
+ if len(f.args) == 0 {
+ return false, nil
+ }
+ s := f.args[0]
+ if len(s) < 2 || s[0] != '-' {
+ return false, nil
+ }
+ numMinuses := 1
+ if s[1] == '-' {
+ numMinuses++
+ if len(s) == 2 { // "--" terminates the flags
+ f.args = f.args[1:]
+ return false, nil
+ }
+ }
+ name := s[numMinuses:]
+ if len(name) == 0 || name[0] == '-' || name[0] == '=' {
+ return false, f.failf("bad flag syntax: %s", s)
+ }
+
+ // it's a flag. does it have an argument?
+ f.args = f.args[1:]
+ hasValue := false
+ value := ""
+ for i := 1; i < len(name); i++ { // equals cannot be first
+ if name[i] == '=' {
+ value = name[i+1:]
+ hasValue = true
+ name = name[0:i]
+ break
+ }
+ }
+
+ flag, ok := f.formal[name]
+ if !ok {
+ if name == "help" || name == "h" { // special case for nice help message.
+ f.usage()
+ return false, ErrHelp
+ }
+ return false, f.failf("flag provided but not defined: -%s", name)
+ }
+
+ if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
+ if hasValue {
+ if err := fv.Set(value); err != nil {
+ return false, f.failf("invalid boolean value %q for -%s: %v", value, name, err)
+ }
+ } else {
+ if err := fv.Set("true"); err != nil {
+ return false, f.failf("invalid boolean flag %s: %v", name, err)
+ }
+ }
+ } else {
+ // It must have a value, which might be the next argument.
+ if !hasValue && len(f.args) > 0 {
+ // value is the next arg
+ hasValue = true
+ value, f.args = f.args[0], f.args[1:]
+ }
+ if !hasValue {
+ return false, f.failf("flag needs an argument: -%s", name)
+ }
+ if err := flag.Value.Set(value); err != nil {
+ return false, f.failf("invalid value %q for flag -%s: %v", value, name, err)
+ }
+ }
+ if f.actual == nil {
+ f.actual = make(map[string]*Flag)
+ }
+ f.actual[name] = flag
+ return true, nil
+}
+
+// Parse parses flag definitions from the argument list, which should not
+// include the command name. Must be called after all flags in the [FlagSet]
+// are defined and before flags are accessed by the program.
+// The return value will be [ErrHelp] if -help or -h were set but not defined.
+func (f *FlagSet) Parse(arguments []string) error {
+ f.parsed = true
+ f.args = arguments
+ for {
+ seen, err := f.parseOne()
+ if seen {
+ continue
+ }
+ if err == nil {
+ break
+ }
+ switch f.errorHandling {
+ case ContinueOnError:
+ return err
+ case ExitOnError:
+ if err == ErrHelp {
+ os.Exit(0)
+ }
+ os.Exit(2)
+ case PanicOnError:
+ panic(err)
+ }
+ }
+ return nil
+}
+
+// Parsed reports whether f.Parse has been called.
+func (f *FlagSet) Parsed() bool {
+ return f.parsed
+}
+
+// Parse parses the command-line flags from [os.Args][1:]. Must be called
+// after all flags are defined and before flags are accessed by the program.
+func Parse() {
+ // Ignore errors; CommandLine is set for ExitOnError.
+ CommandLine.Parse(os.Args[1:])
+}
+
+// Parsed reports whether the command-line flags have been parsed.
+func Parsed() bool {
+ return CommandLine.Parsed()
+}
+
+// CommandLine is the default set of command-line flags, parsed from [os.Args].
+// The top-level functions such as [BoolVar], [Arg], and so on are wrappers for the
+// methods of CommandLine.
+var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
+
+func init() {
+ // Override generic FlagSet default Usage with call to global Usage.
+ // Note: This is not CommandLine.Usage = Usage,
+ // because we want any eventual call to use any updated value of Usage,
+ // not the value it has when this line is run.
+ CommandLine.Usage = commandLineUsage
+}
+
+func commandLineUsage() {
+ Usage()
+}
+
+// NewFlagSet returns a new, empty flag set with the specified name and
+// error handling property. If the name is not empty, it will be printed
+// in the default usage message and in error messages.
+func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
+ f := &FlagSet{
+ name: name,
+ errorHandling: errorHandling,
+ }
+ f.Usage = f.defaultUsage
+ return f
+}
+
+// Init sets the name and error handling property for a flag set.
+// By default, the zero [FlagSet] uses an empty name and the
+// [ContinueOnError] error handling policy.
+func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
+ f.name = name
+ f.errorHandling = errorHandling
+}
diff --git a/platform/dbops/binaries/go/go/src/flag/flag_test.go b/platform/dbops/binaries/go/go/src/flag/flag_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e9ae316fe0e7dbbe234d7b44992dec734ff9cc5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/flag/flag_test.go
@@ -0,0 +1,858 @@
+// 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 flag_test
+
+import (
+ "bytes"
+ . "flag"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "os"
+ "os/exec"
+ "regexp"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func boolString(s string) string {
+ if s == "0" {
+ return "false"
+ }
+ return "true"
+}
+
+func TestEverything(t *testing.T) {
+ ResetForTesting(nil)
+ Bool("test_bool", false, "bool value")
+ Int("test_int", 0, "int value")
+ Int64("test_int64", 0, "int64 value")
+ Uint("test_uint", 0, "uint value")
+ Uint64("test_uint64", 0, "uint64 value")
+ String("test_string", "0", "string value")
+ Float64("test_float64", 0, "float64 value")
+ Duration("test_duration", 0, "time.Duration value")
+ Func("test_func", "func value", func(string) error { return nil })
+ BoolFunc("test_boolfunc", "func", func(string) error { return nil })
+
+ m := make(map[string]*Flag)
+ desired := "0"
+ visitor := func(f *Flag) {
+ if len(f.Name) > 5 && f.Name[0:5] == "test_" {
+ m[f.Name] = f
+ ok := false
+ switch {
+ case f.Value.String() == desired:
+ ok = true
+ case f.Name == "test_bool" && f.Value.String() == boolString(desired):
+ ok = true
+ case f.Name == "test_duration" && f.Value.String() == desired+"s":
+ ok = true
+ case f.Name == "test_func" && f.Value.String() == "":
+ ok = true
+ case f.Name == "test_boolfunc" && f.Value.String() == "":
+ ok = true
+ }
+ if !ok {
+ t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
+ }
+ }
+ }
+ VisitAll(visitor)
+ if len(m) != 10 {
+ t.Error("VisitAll misses some flags")
+ for k, v := range m {
+ t.Log(k, *v)
+ }
+ }
+ m = make(map[string]*Flag)
+ Visit(visitor)
+ if len(m) != 0 {
+ t.Errorf("Visit sees unset flags")
+ for k, v := range m {
+ t.Log(k, *v)
+ }
+ }
+ // Now set all flags
+ Set("test_bool", "true")
+ Set("test_int", "1")
+ Set("test_int64", "1")
+ Set("test_uint", "1")
+ Set("test_uint64", "1")
+ Set("test_string", "1")
+ Set("test_float64", "1")
+ Set("test_duration", "1s")
+ Set("test_func", "1")
+ Set("test_boolfunc", "")
+ desired = "1"
+ Visit(visitor)
+ if len(m) != 10 {
+ t.Error("Visit fails after set")
+ for k, v := range m {
+ t.Log(k, *v)
+ }
+ }
+ // Now test they're visited in sort order.
+ var flagNames []string
+ Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
+ if !sort.StringsAreSorted(flagNames) {
+ t.Errorf("flag names not sorted: %v", flagNames)
+ }
+}
+
+func TestGet(t *testing.T) {
+ ResetForTesting(nil)
+ Bool("test_bool", true, "bool value")
+ Int("test_int", 1, "int value")
+ Int64("test_int64", 2, "int64 value")
+ Uint("test_uint", 3, "uint value")
+ Uint64("test_uint64", 4, "uint64 value")
+ String("test_string", "5", "string value")
+ Float64("test_float64", 6, "float64 value")
+ Duration("test_duration", 7, "time.Duration value")
+
+ visitor := func(f *Flag) {
+ if len(f.Name) > 5 && f.Name[0:5] == "test_" {
+ g, ok := f.Value.(Getter)
+ if !ok {
+ t.Errorf("Visit: value does not satisfy Getter: %T", f.Value)
+ return
+ }
+ switch f.Name {
+ case "test_bool":
+ ok = g.Get() == true
+ case "test_int":
+ ok = g.Get() == int(1)
+ case "test_int64":
+ ok = g.Get() == int64(2)
+ case "test_uint":
+ ok = g.Get() == uint(3)
+ case "test_uint64":
+ ok = g.Get() == uint64(4)
+ case "test_string":
+ ok = g.Get() == "5"
+ case "test_float64":
+ ok = g.Get() == float64(6)
+ case "test_duration":
+ ok = g.Get() == time.Duration(7)
+ }
+ if !ok {
+ t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), f.Name)
+ }
+ }
+ }
+ VisitAll(visitor)
+}
+
+func TestUsage(t *testing.T) {
+ called := false
+ ResetForTesting(func() { called = true })
+ if CommandLine.Parse([]string{"-x"}) == nil {
+ t.Error("parse did not fail for unknown flag")
+ }
+ if !called {
+ t.Error("did not call Usage for unknown flag")
+ }
+}
+
+func testParse(f *FlagSet, t *testing.T) {
+ if f.Parsed() {
+ t.Error("f.Parse() = true before Parse")
+ }
+ boolFlag := f.Bool("bool", false, "bool value")
+ bool2Flag := f.Bool("bool2", false, "bool2 value")
+ intFlag := f.Int("int", 0, "int value")
+ int64Flag := f.Int64("int64", 0, "int64 value")
+ uintFlag := f.Uint("uint", 0, "uint value")
+ uint64Flag := f.Uint64("uint64", 0, "uint64 value")
+ stringFlag := f.String("string", "0", "string value")
+ float64Flag := f.Float64("float64", 0, "float64 value")
+ durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
+ extra := "one-extra-argument"
+ args := []string{
+ "-bool",
+ "-bool2=true",
+ "--int", "22",
+ "--int64", "0x23",
+ "-uint", "24",
+ "--uint64", "25",
+ "-string", "hello",
+ "-float64", "2718e28",
+ "-duration", "2m",
+ extra,
+ }
+ if err := f.Parse(args); err != nil {
+ t.Fatal(err)
+ }
+ if !f.Parsed() {
+ t.Error("f.Parse() = false after Parse")
+ }
+ if *boolFlag != true {
+ t.Error("bool flag should be true, is ", *boolFlag)
+ }
+ if *bool2Flag != true {
+ t.Error("bool2 flag should be true, is ", *bool2Flag)
+ }
+ if *intFlag != 22 {
+ t.Error("int flag should be 22, is ", *intFlag)
+ }
+ if *int64Flag != 0x23 {
+ t.Error("int64 flag should be 0x23, is ", *int64Flag)
+ }
+ if *uintFlag != 24 {
+ t.Error("uint flag should be 24, is ", *uintFlag)
+ }
+ if *uint64Flag != 25 {
+ t.Error("uint64 flag should be 25, is ", *uint64Flag)
+ }
+ if *stringFlag != "hello" {
+ t.Error("string flag should be `hello`, is ", *stringFlag)
+ }
+ if *float64Flag != 2718e28 {
+ t.Error("float64 flag should be 2718e28, is ", *float64Flag)
+ }
+ if *durationFlag != 2*time.Minute {
+ t.Error("duration flag should be 2m, is ", *durationFlag)
+ }
+ if len(f.Args()) != 1 {
+ t.Error("expected one argument, got", len(f.Args()))
+ } else if f.Args()[0] != extra {
+ t.Errorf("expected argument %q got %q", extra, f.Args()[0])
+ }
+}
+
+func TestParse(t *testing.T) {
+ ResetForTesting(func() { t.Error("bad parse") })
+ testParse(CommandLine, t)
+}
+
+func TestFlagSetParse(t *testing.T) {
+ testParse(NewFlagSet("test", ContinueOnError), t)
+}
+
+// Declare a user-defined flag type.
+type flagVar []string
+
+func (f *flagVar) String() string {
+ return fmt.Sprint([]string(*f))
+}
+
+func (f *flagVar) Set(value string) error {
+ *f = append(*f, value)
+ return nil
+}
+
+func TestUserDefined(t *testing.T) {
+ var flags FlagSet
+ flags.Init("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ var v flagVar
+ flags.Var(&v, "v", "usage")
+ if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
+ t.Error(err)
+ }
+ if len(v) != 3 {
+ t.Fatal("expected 3 args; got ", len(v))
+ }
+ expect := "[1 2 3]"
+ if v.String() != expect {
+ t.Errorf("expected value %q got %q", expect, v.String())
+ }
+}
+
+func TestUserDefinedFunc(t *testing.T) {
+ flags := NewFlagSet("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ var ss []string
+ flags.Func("v", "usage", func(s string) error {
+ ss = append(ss, s)
+ return nil
+ })
+ if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
+ t.Error(err)
+ }
+ if len(ss) != 3 {
+ t.Fatal("expected 3 args; got ", len(ss))
+ }
+ expect := "[1 2 3]"
+ if got := fmt.Sprint(ss); got != expect {
+ t.Errorf("expected value %q got %q", expect, got)
+ }
+ // test usage
+ var buf strings.Builder
+ flags.SetOutput(&buf)
+ flags.Parse([]string{"-h"})
+ if usage := buf.String(); !strings.Contains(usage, "usage") {
+ t.Errorf("usage string not included: %q", usage)
+ }
+ // test Func error
+ flags = NewFlagSet("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ flags.Func("v", "usage", func(s string) error {
+ return fmt.Errorf("test error")
+ })
+ // flag not set, so no error
+ if err := flags.Parse(nil); err != nil {
+ t.Error(err)
+ }
+ // flag set, expect error
+ if err := flags.Parse([]string{"-v", "1"}); err == nil {
+ t.Error("expected error; got none")
+ } else if errMsg := err.Error(); !strings.Contains(errMsg, "test error") {
+ t.Errorf(`error should contain "test error"; got %q`, errMsg)
+ }
+}
+
+func TestUserDefinedForCommandLine(t *testing.T) {
+ const help = "HELP"
+ var result string
+ ResetForTesting(func() { result = help })
+ Usage()
+ if result != help {
+ t.Fatalf("got %q; expected %q", result, help)
+ }
+}
+
+// Declare a user-defined boolean flag type.
+type boolFlagVar struct {
+ count int
+}
+
+func (b *boolFlagVar) String() string {
+ return fmt.Sprintf("%d", b.count)
+}
+
+func (b *boolFlagVar) Set(value string) error {
+ if value == "true" {
+ b.count++
+ }
+ return nil
+}
+
+func (b *boolFlagVar) IsBoolFlag() bool {
+ return b.count < 4
+}
+
+func TestUserDefinedBool(t *testing.T) {
+ var flags FlagSet
+ flags.Init("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ var b boolFlagVar
+ var err error
+ flags.Var(&b, "b", "usage")
+ if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil {
+ if b.count < 4 {
+ t.Error(err)
+ }
+ }
+
+ if b.count != 4 {
+ t.Errorf("want: %d; got: %d", 4, b.count)
+ }
+
+ if err == nil {
+ t.Error("expected error; got none")
+ }
+}
+
+func TestUserDefinedBoolUsage(t *testing.T) {
+ var flags FlagSet
+ flags.Init("test", ContinueOnError)
+ var buf bytes.Buffer
+ flags.SetOutput(&buf)
+ var b boolFlagVar
+ flags.Var(&b, "b", "X")
+ b.count = 0
+ // b.IsBoolFlag() will return true and usage will look boolean.
+ flags.PrintDefaults()
+ got := buf.String()
+ want := " -b\tX\n"
+ if got != want {
+ t.Errorf("false: want %q; got %q", want, got)
+ }
+ b.count = 4
+ // b.IsBoolFlag() will return false and usage will look non-boolean.
+ flags.PrintDefaults()
+ got = buf.String()
+ want = " -b\tX\n -b value\n \tX\n"
+ if got != want {
+ t.Errorf("false: want %q; got %q", want, got)
+ }
+}
+
+func TestSetOutput(t *testing.T) {
+ var flags FlagSet
+ var buf strings.Builder
+ flags.SetOutput(&buf)
+ flags.Init("test", ContinueOnError)
+ flags.Parse([]string{"-unknown"})
+ if out := buf.String(); !strings.Contains(out, "-unknown") {
+ t.Logf("expected output mentioning unknown; got %q", out)
+ }
+}
+
+// This tests that one can reset the flags. This still works but not well, and is
+// superseded by FlagSet.
+func TestChangingArgs(t *testing.T) {
+ ResetForTesting(func() { t.Fatal("bad parse") })
+ oldArgs := os.Args
+ defer func() { os.Args = oldArgs }()
+ os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
+ before := Bool("before", false, "")
+ if err := CommandLine.Parse(os.Args[1:]); err != nil {
+ t.Fatal(err)
+ }
+ cmd := Arg(0)
+ os.Args = Args()
+ after := Bool("after", false, "")
+ Parse()
+ args := Args()
+
+ if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
+ t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
+ }
+}
+
+// Test that -help invokes the usage message and returns ErrHelp.
+func TestHelp(t *testing.T) {
+ var helpCalled = false
+ fs := NewFlagSet("help test", ContinueOnError)
+ fs.Usage = func() { helpCalled = true }
+ var flag bool
+ fs.BoolVar(&flag, "flag", false, "regular flag")
+ // Regular flag invocation should work
+ err := fs.Parse([]string{"-flag=true"})
+ if err != nil {
+ t.Fatal("expected no error; got ", err)
+ }
+ if !flag {
+ t.Error("flag was not set by -flag")
+ }
+ if helpCalled {
+ t.Error("help called for regular flag")
+ helpCalled = false // reset for next test
+ }
+ // Help flag should work as expected.
+ err = fs.Parse([]string{"-help"})
+ if err == nil {
+ t.Fatal("error expected")
+ }
+ if err != ErrHelp {
+ t.Fatal("expected ErrHelp; got ", err)
+ }
+ if !helpCalled {
+ t.Fatal("help was not called")
+ }
+ // If we define a help flag, that should override.
+ var help bool
+ fs.BoolVar(&help, "help", false, "help flag")
+ helpCalled = false
+ err = fs.Parse([]string{"-help"})
+ if err != nil {
+ t.Fatal("expected no error for defined -help; got ", err)
+ }
+ if helpCalled {
+ t.Fatal("help was called; should not have been for defined help flag")
+ }
+}
+
+// zeroPanicker is a flag.Value whose String method panics if its dontPanic
+// field is false.
+type zeroPanicker struct {
+ dontPanic bool
+ v string
+}
+
+func (f *zeroPanicker) Set(s string) error {
+ f.v = s
+ return nil
+}
+
+func (f *zeroPanicker) String() string {
+ if !f.dontPanic {
+ panic("panic!")
+ }
+ return f.v
+}
+
+const defaultOutput = ` -A for bootstrapping, allow 'any' type
+ -Alongflagname
+ disable bounds checking
+ -C a boolean defaulting to true (default true)
+ -D path
+ set relative path for local imports
+ -E string
+ issue 23543 (default "0")
+ -F number
+ a non-zero number (default 2.7)
+ -G float
+ a float that defaults to zero
+ -M string
+ a multiline
+ help
+ string
+ -N int
+ a non-zero int (default 27)
+ -O a flag
+ multiline help string (default true)
+ -V list
+ a list of strings (default [a b])
+ -Z int
+ an int that defaults to zero
+ -ZP0 value
+ a flag whose String method panics when it is zero
+ -ZP1 value
+ a flag whose String method panics when it is zero
+ -maxT timeout
+ set timeout for dial
+
+panic calling String method on zero flag_test.zeroPanicker for flag ZP0: panic!
+panic calling String method on zero flag_test.zeroPanicker for flag ZP1: panic!
+`
+
+func TestPrintDefaults(t *testing.T) {
+ fs := NewFlagSet("print defaults test", ContinueOnError)
+ var buf strings.Builder
+ fs.SetOutput(&buf)
+ fs.Bool("A", false, "for bootstrapping, allow 'any' type")
+ fs.Bool("Alongflagname", false, "disable bounds checking")
+ fs.Bool("C", true, "a boolean defaulting to true")
+ fs.String("D", "", "set relative `path` for local imports")
+ fs.String("E", "0", "issue 23543")
+ fs.Float64("F", 2.7, "a non-zero `number`")
+ fs.Float64("G", 0, "a float that defaults to zero")
+ fs.String("M", "", "a multiline\nhelp\nstring")
+ fs.Int("N", 27, "a non-zero int")
+ fs.Bool("O", true, "a flag\nmultiline help string")
+ fs.Var(&flagVar{"a", "b"}, "V", "a `list` of strings")
+ fs.Int("Z", 0, "an int that defaults to zero")
+ fs.Var(&zeroPanicker{true, ""}, "ZP0", "a flag whose String method panics when it is zero")
+ fs.Var(&zeroPanicker{true, "something"}, "ZP1", "a flag whose String method panics when it is zero")
+ fs.Duration("maxT", 0, "set `timeout` for dial")
+ fs.PrintDefaults()
+ got := buf.String()
+ if got != defaultOutput {
+ t.Errorf("got:\n%q\nwant:\n%q", got, defaultOutput)
+ }
+}
+
+// Issue 19230: validate range of Int and Uint flag values.
+func TestIntFlagOverflow(t *testing.T) {
+ if strconv.IntSize != 32 {
+ return
+ }
+ ResetForTesting(nil)
+ Int("i", 0, "")
+ Uint("u", 0, "")
+ if err := Set("i", "2147483648"); err == nil {
+ t.Error("unexpected success setting Int")
+ }
+ if err := Set("u", "4294967296"); err == nil {
+ t.Error("unexpected success setting Uint")
+ }
+}
+
+// Issue 20998: Usage should respect CommandLine.output.
+func TestUsageOutput(t *testing.T) {
+ ResetForTesting(DefaultUsage)
+ var buf strings.Builder
+ CommandLine.SetOutput(&buf)
+ defer func(old []string) { os.Args = old }(os.Args)
+ os.Args = []string{"app", "-i=1", "-unknown"}
+ Parse()
+ const want = "flag provided but not defined: -i\nUsage of app:\n"
+ if got := buf.String(); got != want {
+ t.Errorf("output = %q; want %q", got, want)
+ }
+}
+
+func TestGetters(t *testing.T) {
+ expectedName := "flag set"
+ expectedErrorHandling := ContinueOnError
+ expectedOutput := io.Writer(os.Stderr)
+ fs := NewFlagSet(expectedName, expectedErrorHandling)
+
+ if fs.Name() != expectedName {
+ t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
+ }
+ if fs.ErrorHandling() != expectedErrorHandling {
+ t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
+ }
+ if fs.Output() != expectedOutput {
+ t.Errorf("unexpected output: got %#v, expected %#v", fs.Output(), expectedOutput)
+ }
+
+ expectedName = "gopher"
+ expectedErrorHandling = ExitOnError
+ expectedOutput = os.Stdout
+ fs.Init(expectedName, expectedErrorHandling)
+ fs.SetOutput(expectedOutput)
+
+ if fs.Name() != expectedName {
+ t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
+ }
+ if fs.ErrorHandling() != expectedErrorHandling {
+ t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
+ }
+ if fs.Output() != expectedOutput {
+ t.Errorf("unexpected output: got %v, expected %v", fs.Output(), expectedOutput)
+ }
+}
+
+func TestParseError(t *testing.T) {
+ for _, typ := range []string{"bool", "int", "int64", "uint", "uint64", "float64", "duration"} {
+ fs := NewFlagSet("parse error test", ContinueOnError)
+ fs.SetOutput(io.Discard)
+ _ = fs.Bool("bool", false, "")
+ _ = fs.Int("int", 0, "")
+ _ = fs.Int64("int64", 0, "")
+ _ = fs.Uint("uint", 0, "")
+ _ = fs.Uint64("uint64", 0, "")
+ _ = fs.Float64("float64", 0, "")
+ _ = fs.Duration("duration", 0, "")
+ // Strings cannot give errors.
+ args := []string{"-" + typ + "=x"}
+ err := fs.Parse(args) // x is not a valid setting for any flag.
+ if err == nil {
+ t.Errorf("Parse(%q)=%v; expected parse error", args, err)
+ continue
+ }
+ if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "parse error") {
+ t.Errorf("Parse(%q)=%v; expected parse error", args, err)
+ }
+ }
+}
+
+func TestRangeError(t *testing.T) {
+ bad := []string{
+ "-int=123456789012345678901",
+ "-int64=123456789012345678901",
+ "-uint=123456789012345678901",
+ "-uint64=123456789012345678901",
+ "-float64=1e1000",
+ }
+ for _, arg := range bad {
+ fs := NewFlagSet("parse error test", ContinueOnError)
+ fs.SetOutput(io.Discard)
+ _ = fs.Int("int", 0, "")
+ _ = fs.Int64("int64", 0, "")
+ _ = fs.Uint("uint", 0, "")
+ _ = fs.Uint64("uint64", 0, "")
+ _ = fs.Float64("float64", 0, "")
+ // Strings cannot give errors, and bools and durations do not return strconv.NumError.
+ err := fs.Parse([]string{arg})
+ if err == nil {
+ t.Errorf("Parse(%q)=%v; expected range error", arg, err)
+ continue
+ }
+ if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "value out of range") {
+ t.Errorf("Parse(%q)=%v; expected range error", arg, err)
+ }
+ }
+}
+
+func TestExitCode(t *testing.T) {
+ testenv.MustHaveExec(t)
+
+ magic := 123
+ if os.Getenv("GO_CHILD_FLAG") != "" {
+ fs := NewFlagSet("test", ExitOnError)
+ if os.Getenv("GO_CHILD_FLAG_HANDLE") != "" {
+ var b bool
+ fs.BoolVar(&b, os.Getenv("GO_CHILD_FLAG_HANDLE"), false, "")
+ }
+ fs.Parse([]string{os.Getenv("GO_CHILD_FLAG")})
+ os.Exit(magic)
+ }
+
+ tests := []struct {
+ flag string
+ flagHandle string
+ expectExit int
+ }{
+ {
+ flag: "-h",
+ expectExit: 0,
+ },
+ {
+ flag: "-help",
+ expectExit: 0,
+ },
+ {
+ flag: "-undefined",
+ expectExit: 2,
+ },
+ {
+ flag: "-h",
+ flagHandle: "h",
+ expectExit: magic,
+ },
+ {
+ flag: "-help",
+ flagHandle: "help",
+ expectExit: magic,
+ },
+ }
+
+ for _, test := range tests {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestExitCode$")
+ cmd.Env = append(
+ os.Environ(),
+ "GO_CHILD_FLAG="+test.flag,
+ "GO_CHILD_FLAG_HANDLE="+test.flagHandle,
+ )
+ cmd.Run()
+ got := cmd.ProcessState.ExitCode()
+ // ExitCode is either 0 or 1 on Plan 9.
+ if runtime.GOOS == "plan9" && test.expectExit != 0 {
+ test.expectExit = 1
+ }
+ if got != test.expectExit {
+ t.Errorf("unexpected exit code for test case %+v \n: got %d, expect %d",
+ test, got, test.expectExit)
+ }
+ }
+}
+
+func mustPanic(t *testing.T, testName string, expected string, f func()) {
+ t.Helper()
+ defer func() {
+ switch msg := recover().(type) {
+ case nil:
+ t.Errorf("%s\n: expected panic(%q), but did not panic", testName, expected)
+ case string:
+ if ok, _ := regexp.MatchString(expected, msg); !ok {
+ t.Errorf("%s\n: expected panic(%q), but got panic(%q)", testName, expected, msg)
+ }
+ default:
+ t.Errorf("%s\n: expected panic(%q), but got panic(%T%v)", testName, expected, msg, msg)
+ }
+ }()
+ f()
+}
+
+func TestInvalidFlags(t *testing.T) {
+ tests := []struct {
+ flag string
+ errorMsg string
+ }{
+ {
+ flag: "-foo",
+ errorMsg: "flag \"-foo\" begins with -",
+ },
+ {
+ flag: "foo=bar",
+ errorMsg: "flag \"foo=bar\" contains =",
+ },
+ }
+
+ for _, test := range tests {
+ testName := fmt.Sprintf("FlagSet.Var(&v, %q, \"\")", test.flag)
+
+ fs := NewFlagSet("", ContinueOnError)
+ buf := &strings.Builder{}
+ fs.SetOutput(buf)
+
+ mustPanic(t, testName, test.errorMsg, func() {
+ var v flagVar
+ fs.Var(&v, test.flag, "")
+ })
+ if msg := test.errorMsg + "\n"; msg != buf.String() {
+ t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf)
+ }
+ }
+}
+
+func TestRedefinedFlags(t *testing.T) {
+ tests := []struct {
+ flagSetName string
+ errorMsg string
+ }{
+ {
+ flagSetName: "",
+ errorMsg: "flag redefined: foo",
+ },
+ {
+ flagSetName: "fs",
+ errorMsg: "fs flag redefined: foo",
+ },
+ }
+
+ for _, test := range tests {
+ testName := fmt.Sprintf("flag redefined in FlagSet(%q)", test.flagSetName)
+
+ fs := NewFlagSet(test.flagSetName, ContinueOnError)
+ buf := &strings.Builder{}
+ fs.SetOutput(buf)
+
+ var v flagVar
+ fs.Var(&v, "foo", "")
+
+ mustPanic(t, testName, test.errorMsg, func() {
+ fs.Var(&v, "foo", "")
+ })
+ if msg := test.errorMsg + "\n"; msg != buf.String() {
+ t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf)
+ }
+ }
+}
+
+func TestUserDefinedBoolFunc(t *testing.T) {
+ flags := NewFlagSet("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ var ss []string
+ flags.BoolFunc("v", "usage", func(s string) error {
+ ss = append(ss, s)
+ return nil
+ })
+ if err := flags.Parse([]string{"-v", "", "-v", "1", "-v=2"}); err != nil {
+ t.Error(err)
+ }
+ if len(ss) != 1 {
+ t.Fatalf("got %d args; want 1 arg", len(ss))
+ }
+ want := "[true]"
+ if got := fmt.Sprint(ss); got != want {
+ t.Errorf("got %q; want %q", got, want)
+ }
+ // test usage
+ var buf strings.Builder
+ flags.SetOutput(&buf)
+ flags.Parse([]string{"-h"})
+ if usage := buf.String(); !strings.Contains(usage, "usage") {
+ t.Errorf("usage string not included: %q", usage)
+ }
+ // test BoolFunc error
+ flags = NewFlagSet("test", ContinueOnError)
+ flags.SetOutput(io.Discard)
+ flags.BoolFunc("v", "usage", func(s string) error {
+ return fmt.Errorf("test error")
+ })
+ // flag not set, so no error
+ if err := flags.Parse(nil); err != nil {
+ t.Error(err)
+ }
+ // flag set, expect error
+ if err := flags.Parse([]string{"-v", ""}); err == nil {
+ t.Error("got err == nil; want err != nil")
+ } else if errMsg := err.Error(); !strings.Contains(errMsg, "test error") {
+ t.Errorf(`got %q; error should contain "test error"`, errMsg)
+ }
+}
+
+func TestDefineAfterSet(t *testing.T) {
+ flags := NewFlagSet("test", ContinueOnError)
+ // Set by itself doesn't panic.
+ flags.Set("myFlag", "value")
+
+ // Define-after-set panics.
+ mustPanic(t, "DefineAfterSet", "flag myFlag set at .*/flag_test.go:.* before being defined", func() {
+ _ = flags.String("myFlag", "default", "usage")
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/doc.go b/platform/dbops/binaries/go/go/src/fmt/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..1cda484d8ab274b0738763364854b0d9a0009a6a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/doc.go
@@ -0,0 +1,384 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+/*
+Package fmt implements formatted I/O with functions analogous
+to C's printf and scanf. The format 'verbs' are derived from C's but
+are simpler.
+
+# Printing
+
+The verbs:
+
+General:
+
+ %v the value in a default format
+ when printing structs, the plus flag (%+v) adds field names
+ %#v a Go-syntax representation of the value
+ %T a Go-syntax representation of the type of the value
+ %% a literal percent sign; consumes no value
+
+Boolean:
+
+ %t the word true or false
+
+Integer:
+
+ %b base 2
+ %c the character represented by the corresponding Unicode code point
+ %d base 10
+ %o base 8
+ %O base 8 with 0o prefix
+ %q a single-quoted character literal safely escaped with Go syntax.
+ %x base 16, with lower-case letters for a-f
+ %X base 16, with upper-case letters for A-F
+ %U Unicode format: U+1234; same as "U+%04X"
+
+Floating-point and complex constituents:
+
+ %b decimalless scientific notation with exponent a power of two,
+ in the manner of strconv.FormatFloat with the 'b' format,
+ e.g. -123456p-78
+ %e scientific notation, e.g. -1.234456e+78
+ %E scientific notation, e.g. -1.234456E+78
+ %f decimal point but no exponent, e.g. 123.456
+ %F synonym for %f
+ %g %e for large exponents, %f otherwise. Precision is discussed below.
+ %G %E for large exponents, %F otherwise
+ %x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
+ %X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20
+
+String and slice of bytes (treated equivalently with these verbs):
+
+ %s the uninterpreted bytes of the string or slice
+ %q a double-quoted string safely escaped with Go syntax
+ %x base 16, lower-case, two characters per byte
+ %X base 16, upper-case, two characters per byte
+
+Slice:
+
+ %p address of 0th element in base 16 notation, with leading 0x
+
+Pointer:
+
+ %p base 16 notation, with leading 0x
+ The %b, %d, %o, %x and %X verbs also work with pointers,
+ formatting the value exactly as if it were an integer.
+
+The default format for %v is:
+
+ bool: %t
+ int, int8 etc.: %d
+ uint, uint8 etc.: %d, %#x if printed with %#v
+ float32, complex64, etc: %g
+ string: %s
+ chan: %p
+ pointer: %p
+
+For compound objects, the elements are printed using these rules, recursively,
+laid out like this:
+
+ struct: {field0 field1 ...}
+ array, slice: [elem0 elem1 ...]
+ maps: map[key1:value1 key2:value2 ...]
+ pointer to above: &{}, &[], &map[]
+
+Width is specified by an optional decimal number immediately preceding the verb.
+If absent, the width is whatever is necessary to represent the value.
+Precision is specified after the (optional) width by a period followed by a
+decimal number. If no period is present, a default precision is used.
+A period with no following number specifies a precision of zero.
+Examples:
+
+ %f default width, default precision
+ %9f width 9, default precision
+ %.2f default width, precision 2
+ %9.2f width 9, precision 2
+ %9.f width 9, precision 0
+
+Width and precision are measured in units of Unicode code points,
+that is, runes. (This differs from C's printf where the
+units are always measured in bytes.) Either or both of the flags
+may be replaced with the character '*', causing their values to be
+obtained from the next operand (preceding the one to format),
+which must be of type int.
+
+For most values, width is the minimum number of runes to output,
+padding the formatted form with spaces if necessary.
+
+For strings, byte slices and byte arrays, however, precision
+limits the length of the input to be formatted (not the size of
+the output), truncating if necessary. Normally it is measured in
+runes, but for these types when formatted with the %x or %X format
+it is measured in bytes.
+
+For floating-point values, width sets the minimum width of the field and
+precision sets the number of places after the decimal, if appropriate,
+except that for %g/%G precision sets the maximum number of significant
+digits (trailing zeros are removed). For example, given 12.345 the format
+%6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f
+and %#g is 6; for %g it is the smallest number of digits necessary to identify
+the value uniquely.
+
+For complex numbers, the width and precision apply to the two
+components independently and the result is parenthesized, so %f applied
+to 1.2+3.4i produces (1.200000+3.400000i).
+
+When formatting a single integer code point or a rune string (type []rune)
+with %q, invalid Unicode code points are changed to the Unicode replacement
+character, U+FFFD, as in strconv.QuoteRune.
+
+Other flags:
+
+ '+' always print a sign for numeric values;
+ guarantee ASCII-only output for %q (%+q)
+ '-' pad with spaces on the right rather than the left (left-justify the field)
+ '#' alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
+ 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
+ for %q, print a raw (backquoted) string if strconv.CanBackquote
+ returns true;
+ always print a decimal point for %e, %E, %f, %F, %g and %G;
+ do not remove trailing zeros for %g and %G;
+ write e.g. U+0078 'x' if the character is printable for %U (%#U).
+ ' ' (space) leave a space for elided sign in numbers (% d);
+ put spaces between bytes printing strings or slices in hex (% x, % X)
+ '0' pad with leading zeros rather than spaces;
+ for numbers, this moves the padding after the sign;
+ ignored for strings, byte slices and byte arrays
+
+Flags are ignored by verbs that do not expect them.
+For example there is no alternate decimal format, so %#d and %d
+behave identically.
+
+For each Printf-like function, there is also a Print function
+that takes no format and is equivalent to saying %v for every
+operand. Another variant Println inserts blanks between
+operands and appends a newline.
+
+Regardless of the verb, if an operand is an interface value,
+the internal concrete value is used, not the interface itself.
+Thus:
+
+ var i interface{} = 23
+ fmt.Printf("%v\n", i)
+
+will print 23.
+
+Except when printed using the verbs %T and %p, special
+formatting considerations apply for operands that implement
+certain interfaces. In order of application:
+
+1. If the operand is a reflect.Value, the operand is replaced by the
+concrete value that it holds, and printing continues with the next rule.
+
+2. If an operand implements the Formatter interface, it will
+be invoked. In this case the interpretation of verbs and flags is
+controlled by that implementation.
+
+3. If the %v verb is used with the # flag (%#v) and the operand
+implements the GoStringer interface, that will be invoked.
+
+If the format (which is implicitly %v for Println etc.) is valid
+for a string (%s %q %x %X), or is %v but not %#v,
+the following two rules apply:
+
+4. If an operand implements the error interface, the Error method
+will be invoked to convert the object to a string, which will then
+be formatted as required by the verb (if any).
+
+5. If an operand implements method String() string, that method
+will be invoked to convert the object to a string, which will then
+be formatted as required by the verb (if any).
+
+For compound operands such as slices and structs, the format
+applies to the elements of each operand, recursively, not to the
+operand as a whole. Thus %q will quote each element of a slice
+of strings, and %6.2f will control formatting for each element
+of a floating-point array.
+
+However, when printing a byte slice with a string-like verb
+(%s %q %x %X), it is treated identically to a string, as a single item.
+
+To avoid recursion in cases such as
+
+ type X string
+ func (x X) String() string { return Sprintf("<%s>", x) }
+
+convert the value before recurring:
+
+ func (x X) String() string { return Sprintf("<%s>", string(x)) }
+
+Infinite recursion can also be triggered by self-referential data
+structures, such as a slice that contains itself as an element, if
+that type has a String method. Such pathologies are rare, however,
+and the package does not protect against them.
+
+When printing a struct, fmt cannot and therefore does not invoke
+formatting methods such as Error or String on unexported fields.
+
+# Explicit argument indexes
+
+In Printf, Sprintf, and Fprintf, the default behavior is for each
+formatting verb to format successive arguments passed in the call.
+However, the notation [n] immediately before the verb indicates that the
+nth one-indexed argument is to be formatted instead. The same notation
+before a '*' for a width or precision selects the argument index holding
+the value. After processing a bracketed expression [n], subsequent verbs
+will use arguments n+1, n+2, etc. unless otherwise directed.
+
+For example,
+
+ fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
+
+will yield "22 11", while
+
+ fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)
+
+equivalent to
+
+ fmt.Sprintf("%6.2f", 12.0)
+
+will yield " 12.00". Because an explicit index affects subsequent verbs,
+this notation can be used to print the same values multiple times
+by resetting the index for the first argument to be repeated:
+
+ fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
+
+will yield "16 17 0x10 0x11".
+
+# Format errors
+
+If an invalid argument is given for a verb, such as providing
+a string to %d, the generated string will contain a
+description of the problem, as in these examples:
+
+ Wrong type or unknown verb: %!verb(type=value)
+ Printf("%d", "hi"): %!d(string=hi)
+ Too many arguments: %!(EXTRA type=value)
+ Printf("hi", "guys"): hi%!(EXTRA string=guys)
+ Too few arguments: %!verb(MISSING)
+ Printf("hi%d"): hi%!d(MISSING)
+ Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
+ Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi
+ Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
+ Invalid or invalid use of argument index: %!(BADINDEX)
+ Printf("%*[2]d", 7): %!d(BADINDEX)
+ Printf("%.[2]d", 7): %!d(BADINDEX)
+
+All errors begin with the string "%!" followed sometimes
+by a single character (the verb) and end with a parenthesized
+description.
+
+If an Error or String method triggers a panic when called by a
+print routine, the fmt package reformats the error message
+from the panic, decorating it with an indication that it came
+through the fmt package. For example, if a String method
+calls panic("bad"), the resulting formatted message will look
+like
+
+ %!s(PANIC=bad)
+
+The %!s just shows the print verb in use when the failure
+occurred. If the panic is caused by a nil receiver to an Error
+or String method, however, the output is the undecorated
+string, "".
+
+# Scanning
+
+An analogous set of functions scans formatted text to yield
+values. Scan, Scanf and Scanln read from os.Stdin; Fscan,
+Fscanf and Fscanln read from a specified io.Reader; Sscan,
+Sscanf and Sscanln read from an argument string.
+
+Scan, Fscan, Sscan treat newlines in the input as spaces.
+
+Scanln, Fscanln and Sscanln stop scanning at a newline and
+require that the items be followed by a newline or EOF.
+
+Scanf, Fscanf, and Sscanf parse the arguments according to a
+format string, analogous to that of Printf. In the text that
+follows, 'space' means any Unicode whitespace character
+except newline.
+
+In the format string, a verb introduced by the % character
+consumes and parses input; these verbs are described in more
+detail below. A character other than %, space, or newline in
+the format consumes exactly that input character, which must
+be present. A newline with zero or more spaces before it in
+the format string consumes zero or more spaces in the input
+followed by a single newline or the end of the input. A space
+following a newline in the format string consumes zero or more
+spaces in the input. Otherwise, any run of one or more spaces
+in the format string consumes as many spaces as possible in
+the input. Unless the run of spaces in the format string
+appears adjacent to a newline, the run must consume at least
+one space from the input or find the end of the input.
+
+The handling of spaces and newlines differs from that of C's
+scanf family: in C, newlines are treated as any other space,
+and it is never an error when a run of spaces in the format
+string finds no spaces to consume in the input.
+
+The verbs behave analogously to those of Printf.
+For example, %x will scan an integer as a hexadecimal number,
+and %v will scan the default representation format for the value.
+The Printf verbs %p and %T and the flags # and + are not implemented.
+For floating-point and complex values, all valid formatting verbs
+(%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept
+both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8")
+and digit-separating underscores (for example: "3.14159_26535_89793").
+
+Input processed by verbs is implicitly space-delimited: the
+implementation of every verb except %c starts by discarding
+leading spaces from the remaining input, and the %s verb
+(and %v reading into a string) stops consuming input at the first
+space or newline character.
+
+The familiar base-setting prefixes 0b (binary), 0o and 0 (octal),
+and 0x (hexadecimal) are accepted when scanning integers
+without a format or with the %v verb, as are digit-separating
+underscores.
+
+Width is interpreted in the input text but there is no
+syntax for scanning with a precision (no %5.2f, just %5f).
+If width is provided, it applies after leading spaces are
+trimmed and specifies the maximum number of runes to read
+to satisfy the verb. For example,
+
+ Sscanf(" 1234567 ", "%5s%d", &s, &i)
+
+will set s to "12345" and i to 67 while
+
+ Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
+
+will set s to "12" and i to 34.
+
+In all the scanning functions, a carriage return followed
+immediately by a newline is treated as a plain newline
+(\r\n means the same as \n).
+
+In all the scanning functions, if an operand implements method
+Scan (that is, it implements the Scanner interface) that
+method will be used to scan the text for that operand. Also,
+if the number of arguments scanned is less than the number of
+arguments provided, an error is returned.
+
+All arguments to be scanned must be either pointers to basic
+types or implementations of the Scanner interface.
+
+Like Scanf and Fscanf, Sscanf need not consume its entire input.
+There is no way to recover how much of the input string Sscanf used.
+
+Note: Fscan etc. can read one character (rune) past the input
+they return, which means that a loop calling a scan routine
+may skip some of the input. This is usually a problem only
+when there is no space between input values. If the reader
+provided to Fscan implements ReadRune, that method will be used
+to read characters. If the reader also implements UnreadRune,
+that method will be used to save the character and successive
+calls will not lose data. To attach ReadRune and UnreadRune
+methods to a reader without that capability, use
+bufio.NewReader.
+*/
+package fmt
diff --git a/platform/dbops/binaries/go/go/src/fmt/errors.go b/platform/dbops/binaries/go/go/src/fmt/errors.go
new file mode 100644
index 0000000000000000000000000000000000000000..1fbd39f8f17bf3601cff438202e4c875de073b1a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/errors.go
@@ -0,0 +1,78 @@
+// 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 fmt
+
+import (
+ "errors"
+ "sort"
+)
+
+// Errorf formats according to a format specifier and returns the string as a
+// value that satisfies error.
+//
+// If the format specifier includes a %w verb with an error operand,
+// the returned error will implement an Unwrap method returning the operand.
+// If there is more than one %w verb, the returned error will implement an
+// Unwrap method returning a []error containing all the %w operands in the
+// order they appear in the arguments.
+// It is invalid to supply the %w verb with an operand that does not implement
+// the error interface. The %w verb is otherwise a synonym for %v.
+func Errorf(format string, a ...any) error {
+ p := newPrinter()
+ p.wrapErrs = true
+ p.doPrintf(format, a)
+ s := string(p.buf)
+ var err error
+ switch len(p.wrappedErrs) {
+ case 0:
+ err = errors.New(s)
+ case 1:
+ w := &wrapError{msg: s}
+ w.err, _ = a[p.wrappedErrs[0]].(error)
+ err = w
+ default:
+ if p.reordered {
+ sort.Ints(p.wrappedErrs)
+ }
+ var errs []error
+ for i, argNum := range p.wrappedErrs {
+ if i > 0 && p.wrappedErrs[i-1] == argNum {
+ continue
+ }
+ if e, ok := a[argNum].(error); ok {
+ errs = append(errs, e)
+ }
+ }
+ err = &wrapErrors{s, errs}
+ }
+ p.free()
+ return err
+}
+
+type wrapError struct {
+ msg string
+ err error
+}
+
+func (e *wrapError) Error() string {
+ return e.msg
+}
+
+func (e *wrapError) Unwrap() error {
+ return e.err
+}
+
+type wrapErrors struct {
+ msg string
+ errs []error
+}
+
+func (e *wrapErrors) Error() string {
+ return e.msg
+}
+
+func (e *wrapErrors) Unwrap() []error {
+ return e.errs
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/errors_test.go b/platform/dbops/binaries/go/go/src/fmt/errors_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4eb55faffe7a181777ae1961d35f3a9f66a5042b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/errors_test.go
@@ -0,0 +1,107 @@
+// 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 fmt_test
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "testing"
+)
+
+func TestErrorf(t *testing.T) {
+ // noVetErrorf is an alias for fmt.Errorf that does not trigger vet warnings for
+ // %w format strings.
+ noVetErrorf := fmt.Errorf
+
+ wrapped := errors.New("inner error")
+ for _, test := range []struct {
+ err error
+ wantText string
+ wantUnwrap error
+ wantSplit []error
+ }{{
+ err: fmt.Errorf("%w", wrapped),
+ wantText: "inner error",
+ wantUnwrap: wrapped,
+ }, {
+ err: fmt.Errorf("added context: %w", wrapped),
+ wantText: "added context: inner error",
+ wantUnwrap: wrapped,
+ }, {
+ err: fmt.Errorf("%w with added context", wrapped),
+ wantText: "inner error with added context",
+ wantUnwrap: wrapped,
+ }, {
+ err: fmt.Errorf("%s %w %v", "prefix", wrapped, "suffix"),
+ wantText: "prefix inner error suffix",
+ wantUnwrap: wrapped,
+ }, {
+ err: fmt.Errorf("%[2]s: %[1]w", wrapped, "positional verb"),
+ wantText: "positional verb: inner error",
+ wantUnwrap: wrapped,
+ }, {
+ err: fmt.Errorf("%v", wrapped),
+ wantText: "inner error",
+ }, {
+ err: fmt.Errorf("added context: %v", wrapped),
+ wantText: "added context: inner error",
+ }, {
+ err: fmt.Errorf("%v with added context", wrapped),
+ wantText: "inner error with added context",
+ }, {
+ err: noVetErrorf("%w is not an error", "not-an-error"),
+ wantText: "%!w(string=not-an-error) is not an error",
+ }, {
+ err: noVetErrorf("wrapped two errors: %w %w", errString("1"), errString("2")),
+ wantText: "wrapped two errors: 1 2",
+ wantSplit: []error{errString("1"), errString("2")},
+ }, {
+ err: noVetErrorf("wrapped three errors: %w %w %w", errString("1"), errString("2"), errString("3")),
+ wantText: "wrapped three errors: 1 2 3",
+ wantSplit: []error{errString("1"), errString("2"), errString("3")},
+ }, {
+ err: noVetErrorf("wrapped nil error: %w %w %w", errString("1"), nil, errString("2")),
+ wantText: "wrapped nil error: 1 %!w() 2",
+ wantSplit: []error{errString("1"), errString("2")},
+ }, {
+ err: noVetErrorf("wrapped one non-error: %w %w %w", errString("1"), "not-an-error", errString("3")),
+ wantText: "wrapped one non-error: 1 %!w(string=not-an-error) 3",
+ wantSplit: []error{errString("1"), errString("3")},
+ }, {
+ err: fmt.Errorf("wrapped errors out of order: %[3]w %[2]w %[1]w", errString("1"), errString("2"), errString("3")),
+ wantText: "wrapped errors out of order: 3 2 1",
+ wantSplit: []error{errString("1"), errString("2"), errString("3")},
+ }, {
+ err: fmt.Errorf("wrapped several times: %[1]w %[1]w %[2]w %[1]w", errString("1"), errString("2")),
+ wantText: "wrapped several times: 1 1 2 1",
+ wantSplit: []error{errString("1"), errString("2")},
+ }, {
+ err: fmt.Errorf("%w", nil),
+ wantText: "%!w()",
+ wantUnwrap: nil, // still nil
+ }} {
+ if got, want := errors.Unwrap(test.err), test.wantUnwrap; got != want {
+ t.Errorf("Formatted error: %v\nerrors.Unwrap() = %v, want %v", test.err, got, want)
+ }
+ if got, want := splitErr(test.err), test.wantSplit; !reflect.DeepEqual(got, want) {
+ t.Errorf("Formatted error: %v\nUnwrap() []error = %v, want %v", test.err, got, want)
+ }
+ if got, want := test.err.Error(), test.wantText; got != want {
+ t.Errorf("err.Error() = %q, want %q", got, want)
+ }
+ }
+}
+
+func splitErr(err error) []error {
+ if e, ok := err.(interface{ Unwrap() []error }); ok {
+ return e.Unwrap()
+ }
+ return nil
+}
+
+type errString string
+
+func (e errString) Error() string { return string(e) }
diff --git a/platform/dbops/binaries/go/go/src/fmt/example_test.go b/platform/dbops/binaries/go/go/src/fmt/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5962834226b9d58564eafa1b240a9ff4e99171fc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/example_test.go
@@ -0,0 +1,365 @@
+// 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 fmt_test
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "strings"
+ "time"
+)
+
+// The Errorf function lets us use formatting features
+// to create descriptive error messages.
+func ExampleErrorf() {
+ const name, id = "bueller", 17
+ err := fmt.Errorf("user %q (id %d) not found", name, id)
+ fmt.Println(err.Error())
+
+ // Output: user "bueller" (id 17) not found
+}
+
+func ExampleFscanf() {
+ var (
+ i int
+ b bool
+ s string
+ )
+ r := strings.NewReader("5 true gophers")
+ n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
+ }
+ fmt.Println(i, b, s)
+ fmt.Println(n)
+ // Output:
+ // 5 true gophers
+ // 3
+}
+
+func ExampleFscanln() {
+ s := `dmr 1771 1.61803398875
+ ken 271828 3.14159`
+ r := strings.NewReader(s)
+ var a string
+ var b int
+ var c float64
+ for {
+ n, err := fmt.Fscanln(r, &a, &b, &c)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ panic(err)
+ }
+ fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
+ }
+ // Output:
+ // 3: dmr, 1771, 1.618034
+ // 3: ken, 271828, 3.141590
+}
+
+func ExampleSscanf() {
+ var name string
+ var age int
+ n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Printf("%d: %s, %d\n", n, name, age)
+
+ // Output:
+ // 2: Kim, 22
+}
+
+func ExamplePrint() {
+ const name, age = "Kim", 22
+ fmt.Print(name, " is ", age, " years old.\n")
+
+ // It is conventional not to worry about any
+ // error returned by Print.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExamplePrintln() {
+ const name, age = "Kim", 22
+ fmt.Println(name, "is", age, "years old.")
+
+ // It is conventional not to worry about any
+ // error returned by Println.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExamplePrintf() {
+ const name, age = "Kim", 22
+ fmt.Printf("%s is %d years old.\n", name, age)
+
+ // It is conventional not to worry about any
+ // error returned by Printf.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExampleSprint() {
+ const name, age = "Kim", 22
+ s := fmt.Sprint(name, " is ", age, " years old.\n")
+
+ io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExampleSprintln() {
+ const name, age = "Kim", 22
+ s := fmt.Sprintln(name, "is", age, "years old.")
+
+ io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExampleSprintf() {
+ const name, age = "Kim", 22
+ s := fmt.Sprintf("%s is %d years old.\n", name, age)
+
+ io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
+
+ // Output:
+ // Kim is 22 years old.
+}
+
+func ExampleFprint() {
+ const name, age = "Kim", 22
+ n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")
+
+ // The n and err return values from Fprint are
+ // those returned by the underlying io.Writer.
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
+ }
+ fmt.Print(n, " bytes written.\n")
+
+ // Output:
+ // Kim is 22 years old.
+ // 21 bytes written.
+}
+
+func ExampleFprintln() {
+ const name, age = "Kim", 22
+ n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")
+
+ // The n and err return values from Fprintln are
+ // those returned by the underlying io.Writer.
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
+ }
+ fmt.Println(n, "bytes written.")
+
+ // Output:
+ // Kim is 22 years old.
+ // 21 bytes written.
+}
+
+func ExampleFprintf() {
+ const name, age = "Kim", 22
+ n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
+
+ // The n and err return values from Fprintf are
+ // those returned by the underlying io.Writer.
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
+ }
+ fmt.Printf("%d bytes written.\n", n)
+
+ // Output:
+ // Kim is 22 years old.
+ // 21 bytes written.
+}
+
+// Print, Println, and Printf lay out their arguments differently. In this example
+// we can compare their behaviors. Println always adds blanks between the items it
+// prints, while Print adds blanks only between non-string arguments and Printf
+// does exactly what it is told.
+// Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same as
+// their corresponding Print, Println, and Printf functions shown here.
+func Example_printers() {
+ a, b := 3.0, 4.0
+ h := math.Hypot(a, b)
+
+ // Print inserts blanks between arguments when neither is a string.
+ // It does not add a newline to the output, so we add one explicitly.
+ fmt.Print("The vector (", a, b, ") has length ", h, ".\n")
+
+ // Println always inserts spaces between its arguments,
+ // so it cannot be used to produce the same output as Print in this case;
+ // its output has extra spaces.
+ // Also, Println always adds a newline to the output.
+ fmt.Println("The vector (", a, b, ") has length", h, ".")
+
+ // Printf provides complete control but is more complex to use.
+ // It does not add a newline to the output, so we add one explicitly
+ // at the end of the format specifier string.
+ fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h)
+
+ // Output:
+ // The vector (3 4) has length 5.
+ // The vector ( 3 4 ) has length 5 .
+ // The vector (3 4) has length 5.
+}
+
+// These examples demonstrate the basics of printing using a format string. Printf,
+// Sprintf, and Fprintf all take a format string that specifies how to format the
+// subsequent arguments. For example, %d (we call that a 'verb') says to print the
+// corresponding argument, which must be an integer (or something containing an
+// integer, such as a slice of ints) in decimal. The verb %v ('v' for 'value')
+// always formats the argument in its default form, just how Print or Println would
+// show it. The special verb %T ('T' for 'Type') prints the type of the argument
+// rather than its value. The examples are not exhaustive; see the package comment
+// for all the details.
+func Example_formats() {
+ // A basic set of examples showing that %v is the default format, in this
+ // case decimal for integers, which can be explicitly requested with %d;
+ // the output is just what Println generates.
+ integer := 23
+ // Each of these prints "23" (without the quotes).
+ fmt.Println(integer)
+ fmt.Printf("%v\n", integer)
+ fmt.Printf("%d\n", integer)
+
+ // The special verb %T shows the type of an item rather than its value.
+ fmt.Printf("%T %T\n", integer, &integer)
+ // Result: int *int
+
+ // Println(x) is the same as Printf("%v\n", x) so we will use only Printf
+ // in the following examples. Each one demonstrates how to format values of
+ // a particular type, such as integers or strings. We start each format
+ // string with %v to show the default output and follow that with one or
+ // more custom formats.
+
+ // Booleans print as "true" or "false" with %v or %t.
+ truth := true
+ fmt.Printf("%v %t\n", truth, truth)
+ // Result: true true
+
+ // Integers print as decimals with %v and %d,
+ // or in hex with %x, octal with %o, or binary with %b.
+ answer := 42
+ fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
+ // Result: 42 42 2a 52 101010
+
+ // Floats have multiple formats: %v and %g print a compact representation,
+ // while %f prints a decimal point and %e uses exponential notation. The
+ // format %6.2f used here shows how to set the width and precision to
+ // control the appearance of a floating-point value. In this instance, 6 is
+ // the total width of the printed text for the value (note the extra spaces
+ // in the output) and 2 is the number of decimal places to show.
+ pi := math.Pi
+ fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
+ // Result: 3.141592653589793 3.141592653589793 3.14 ( 3.14) 3.141593e+00
+
+ // Complex numbers format as parenthesized pairs of floats, with an 'i'
+ // after the imaginary part.
+ point := 110.7 + 22.5i
+ fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
+ // Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
+
+ // Runes are integers but when printed with %c show the character with that
+ // Unicode value. The %q verb shows them as quoted characters, %U as a
+ // hex Unicode code point, and %#U as both a code point and a quoted
+ // printable form if the rune is printable.
+ smile := '😀'
+ fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
+ // Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
+
+ // Strings are formatted with %v and %s as-is, with %q as quoted strings,
+ // and %#q as backquoted strings.
+ placeholders := `foo "bar"`
+ fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
+ // Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
+
+ // Maps formatted with %v show keys and values in their default formats.
+ // The %#v form (the # is called a "flag" in this context) shows the map in
+ // the Go source format. Maps are printed in a consistent order, sorted
+ // by the values of the keys.
+ isLegume := map[string]bool{
+ "peanut": true,
+ "dachshund": false,
+ }
+ fmt.Printf("%v %#v\n", isLegume, isLegume)
+ // Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
+
+ // Structs formatted with %v show field values in their default formats.
+ // The %+v form shows the fields by name, while %#v formats the struct in
+ // Go source format.
+ person := struct {
+ Name string
+ Age int
+ }{"Kim", 22}
+ fmt.Printf("%v %+v %#v\n", person, person, person)
+ // Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
+
+ // The default format for a pointer shows the underlying value preceded by
+ // an ampersand. The %p verb prints the pointer value in hex. We use a
+ // typed nil for the argument to %p here because the value of any non-nil
+ // pointer would change from run to run; run the commented-out Printf
+ // call yourself to see.
+ pointer := &person
+ fmt.Printf("%v %p\n", pointer, (*int)(nil))
+ // Result: &{Kim 22} 0x0
+ // fmt.Printf("%v %p\n", pointer, pointer)
+ // Result: &{Kim 22} 0x010203 // See comment above.
+
+ // Arrays and slices are formatted by applying the format to each element.
+ greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
+ fmt.Printf("%v %q\n", greats, greats)
+ // Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
+
+ kGreats := greats[:3]
+ fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
+ // Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
+
+ // Byte slices are special. Integer verbs like %d print the elements in
+ // that format. The %s and %q forms treat the slice like a string. The %x
+ // verb has a special form with the space flag that puts a space between
+ // the bytes.
+ cmd := []byte("a⌘")
+ fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
+ // Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
+
+ // Types that implement Stringer are printed the same as strings. Because
+ // Stringers return a string, we can print them using a string-specific
+ // verb such as %q.
+ now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.
+ fmt.Printf("%v %q\n", now, now)
+ // Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
+
+ // Output:
+ // 23
+ // 23
+ // 23
+ // int *int
+ // true true
+ // 42 42 2a 52 101010
+ // 3.141592653589793 3.141592653589793 3.14 ( 3.14) 3.141593e+00
+ // (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
+ // 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
+ // foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
+ // map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
+ // {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
+ // &{Kim 22} 0x0
+ // [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
+ // [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
+ // [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
+ // 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/export_test.go b/platform/dbops/binaries/go/go/src/fmt/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..14163a29afeb4e1615643220e8d554e1479c3064
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/export_test.go
@@ -0,0 +1,8 @@
+// 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 fmt
+
+var IsSpace = isSpace
+var Parsenum = parsenum
diff --git a/platform/dbops/binaries/go/go/src/fmt/fmt_test.go b/platform/dbops/binaries/go/go/src/fmt/fmt_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6a79862f285f331545becb8fe015bbbd06ae80c9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/fmt_test.go
@@ -0,0 +1,1948 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fmt_test
+
+import (
+ "bytes"
+ . "fmt"
+ "internal/race"
+ "io"
+ "math"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+ "unicode"
+)
+
+type (
+ renamedBool bool
+ renamedInt int
+ renamedInt8 int8
+ renamedInt16 int16
+ renamedInt32 int32
+ renamedInt64 int64
+ renamedUint uint
+ renamedUint8 uint8
+ renamedUint16 uint16
+ renamedUint32 uint32
+ renamedUint64 uint64
+ renamedUintptr uintptr
+ renamedString string
+ renamedBytes []byte
+ renamedFloat32 float32
+ renamedFloat64 float64
+ renamedComplex64 complex64
+ renamedComplex128 complex128
+)
+
+func TestFmtInterface(t *testing.T) {
+ var i1 any
+ i1 = "abc"
+ s := Sprintf("%s", i1)
+ if s != "abc" {
+ t.Errorf(`Sprintf("%%s", empty("abc")) = %q want %q`, s, "abc")
+ }
+}
+
+var (
+ NaN = math.NaN()
+ posInf = math.Inf(1)
+ negInf = math.Inf(-1)
+
+ intVar = 0
+
+ array = [5]int{1, 2, 3, 4, 5}
+ iarray = [4]any{1, "hello", 2.5, nil}
+ slice = array[:]
+ islice = iarray[:]
+)
+
+type A struct {
+ i int
+ j uint
+ s string
+ x []int
+}
+
+type I int
+
+func (i I) String() string { return Sprintf("<%d>", int(i)) }
+
+type B struct {
+ I I
+ j int
+}
+
+type C struct {
+ i int
+ B
+}
+
+type F int
+
+func (f F) Format(s State, c rune) {
+ Fprintf(s, "<%c=F(%d)>", c, int(f))
+}
+
+type G int
+
+func (g G) GoString() string {
+ return Sprintf("GoString(%d)", int(g))
+}
+
+type S struct {
+ F F // a struct field that Formats
+ G G // a struct field that GoStrings
+}
+
+type SI struct {
+ I any
+}
+
+// P is a type with a String method with pointer receiver for testing %p.
+type P int
+
+var pValue P
+
+func (p *P) String() string {
+ return "String(p)"
+}
+
+var barray = [5]renamedUint8{1, 2, 3, 4, 5}
+var bslice = barray[:]
+
+type byteStringer byte
+
+func (byteStringer) String() string {
+ return "X"
+}
+
+var byteStringerSlice = []byteStringer{'h', 'e', 'l', 'l', 'o'}
+
+type byteFormatter byte
+
+func (byteFormatter) Format(f State, _ rune) {
+ Fprint(f, "X")
+}
+
+var byteFormatterSlice = []byteFormatter{'h', 'e', 'l', 'l', 'o'}
+
+type writeStringFormatter string
+
+func (sf writeStringFormatter) Format(f State, c rune) {
+ if sw, ok := f.(io.StringWriter); ok {
+ sw.WriteString("***" + string(sf) + "***")
+ }
+}
+
+var fmtTests = []struct {
+ fmt string
+ val any
+ out string
+}{
+ {"%d", 12345, "12345"},
+ {"%v", 12345, "12345"},
+ {"%t", true, "true"},
+
+ // basic string
+ {"%s", "abc", "abc"},
+ {"%q", "abc", `"abc"`},
+ {"%x", "abc", "616263"},
+ {"%x", "\xff\xf0\x0f\xff", "fff00fff"},
+ {"%X", "\xff\xf0\x0f\xff", "FFF00FFF"},
+ {"%x", "", ""},
+ {"% x", "", ""},
+ {"%#x", "", ""},
+ {"%# x", "", ""},
+ {"%x", "xyz", "78797a"},
+ {"%X", "xyz", "78797A"},
+ {"% x", "xyz", "78 79 7a"},
+ {"% X", "xyz", "78 79 7A"},
+ {"%#x", "xyz", "0x78797a"},
+ {"%#X", "xyz", "0X78797A"},
+ {"%# x", "xyz", "0x78 0x79 0x7a"},
+ {"%# X", "xyz", "0X78 0X79 0X7A"},
+
+ // basic bytes
+ {"%s", []byte("abc"), "abc"},
+ {"%s", [3]byte{'a', 'b', 'c'}, "abc"},
+ {"%s", &[3]byte{'a', 'b', 'c'}, "&abc"},
+ {"%q", []byte("abc"), `"abc"`},
+ {"%x", []byte("abc"), "616263"},
+ {"%x", []byte("\xff\xf0\x0f\xff"), "fff00fff"},
+ {"%X", []byte("\xff\xf0\x0f\xff"), "FFF00FFF"},
+ {"%x", []byte(""), ""},
+ {"% x", []byte(""), ""},
+ {"%#x", []byte(""), ""},
+ {"%# x", []byte(""), ""},
+ {"%x", []byte("xyz"), "78797a"},
+ {"%X", []byte("xyz"), "78797A"},
+ {"% x", []byte("xyz"), "78 79 7a"},
+ {"% X", []byte("xyz"), "78 79 7A"},
+ {"%#x", []byte("xyz"), "0x78797a"},
+ {"%#X", []byte("xyz"), "0X78797A"},
+ {"%# x", []byte("xyz"), "0x78 0x79 0x7a"},
+ {"%# X", []byte("xyz"), "0X78 0X79 0X7A"},
+
+ // escaped strings
+ {"%q", "", `""`},
+ {"%#q", "", "``"},
+ {"%q", "\"", `"\""`},
+ {"%#q", "\"", "`\"`"},
+ {"%q", "`", `"` + "`" + `"`},
+ {"%#q", "`", `"` + "`" + `"`},
+ {"%q", "\n", `"\n"`},
+ {"%#q", "\n", `"\n"`},
+ {"%q", `\n`, `"\\n"`},
+ {"%#q", `\n`, "`\\n`"},
+ {"%q", "abc", `"abc"`},
+ {"%#q", "abc", "`abc`"},
+ {"%q", "日本語", `"日本語"`},
+ {"%+q", "日本語", `"\u65e5\u672c\u8a9e"`},
+ {"%#q", "日本語", "`日本語`"},
+ {"%#+q", "日本語", "`日本語`"},
+ {"%q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
+ {"%+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
+ {"%#q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
+ {"%#+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
+ {"%q", "☺", `"☺"`},
+ {"% q", "☺", `"☺"`}, // The space modifier should have no effect.
+ {"%+q", "☺", `"\u263a"`},
+ {"%#q", "☺", "`☺`"},
+ {"%#+q", "☺", "`☺`"},
+ {"%10q", "⌘", ` "⌘"`},
+ {"%+10q", "⌘", ` "\u2318"`},
+ {"%-10q", "⌘", `"⌘" `},
+ {"%+-10q", "⌘", `"\u2318" `},
+ {"%010q", "⌘", `0000000"⌘"`},
+ {"%+010q", "⌘", `00"\u2318"`},
+ {"%-010q", "⌘", `"⌘" `}, // 0 has no effect when - is present.
+ {"%+-010q", "⌘", `"\u2318" `},
+ {"%#8q", "\n", ` "\n"`},
+ {"%#+8q", "\r", ` "\r"`},
+ {"%#-8q", "\t", "` ` "},
+ {"%#+-8q", "\b", `"\b" `},
+ {"%q", "abc\xffdef", `"abc\xffdef"`},
+ {"%+q", "abc\xffdef", `"abc\xffdef"`},
+ {"%#q", "abc\xffdef", `"abc\xffdef"`},
+ {"%#+q", "abc\xffdef", `"abc\xffdef"`},
+ // Runes that are not printable.
+ {"%q", "\U0010ffff", `"\U0010ffff"`},
+ {"%+q", "\U0010ffff", `"\U0010ffff"`},
+ {"%#q", "\U0010ffff", "``"},
+ {"%#+q", "\U0010ffff", "``"},
+ // Runes that are not valid.
+ {"%q", string(rune(0x110000)), `"�"`},
+ {"%+q", string(rune(0x110000)), `"\ufffd"`},
+ {"%#q", string(rune(0x110000)), "`�`"},
+ {"%#+q", string(rune(0x110000)), "`�`"},
+
+ // characters
+ {"%c", uint('x'), "x"},
+ {"%c", 0xe4, "ä"},
+ {"%c", 0x672c, "本"},
+ {"%c", '日', "日"},
+ {"%.0c", '⌘', "⌘"}, // Specifying precision should have no effect.
+ {"%3c", '⌘', " ⌘"},
+ {"%-3c", '⌘', "⌘ "},
+ {"%c", uint64(0x100000000), "\ufffd"},
+ // Runes that are not printable.
+ {"%c", '\U00000e00', "\u0e00"},
+ {"%c", '\U0010ffff', "\U0010ffff"},
+ // Runes that are not valid.
+ {"%c", -1, "�"},
+ {"%c", 0xDC80, "�"},
+ {"%c", rune(0x110000), "�"},
+ {"%c", int64(0xFFFFFFFFF), "�"},
+ {"%c", uint64(0xFFFFFFFFF), "�"},
+
+ // escaped characters
+ {"%q", uint(0), `'\x00'`},
+ {"%+q", uint(0), `'\x00'`},
+ {"%q", '"', `'"'`},
+ {"%+q", '"', `'"'`},
+ {"%q", '\'', `'\''`},
+ {"%+q", '\'', `'\''`},
+ {"%q", '`', "'`'"},
+ {"%+q", '`', "'`'"},
+ {"%q", 'x', `'x'`},
+ {"%+q", 'x', `'x'`},
+ {"%q", 'ÿ', `'ÿ'`},
+ {"%+q", 'ÿ', `'\u00ff'`},
+ {"%q", '\n', `'\n'`},
+ {"%+q", '\n', `'\n'`},
+ {"%q", '☺', `'☺'`},
+ {"%+q", '☺', `'\u263a'`},
+ {"% q", '☺', `'☺'`}, // The space modifier should have no effect.
+ {"%.0q", '☺', `'☺'`}, // Specifying precision should have no effect.
+ {"%10q", '⌘', ` '⌘'`},
+ {"%+10q", '⌘', ` '\u2318'`},
+ {"%-10q", '⌘', `'⌘' `},
+ {"%+-10q", '⌘', `'\u2318' `},
+ {"%010q", '⌘', `0000000'⌘'`},
+ {"%+010q", '⌘', `00'\u2318'`},
+ {"%-010q", '⌘', `'⌘' `}, // 0 has no effect when - is present.
+ {"%+-010q", '⌘', `'\u2318' `},
+ // Runes that are not printable.
+ {"%q", '\U00000e00', `'\u0e00'`},
+ {"%q", '\U0010ffff', `'\U0010ffff'`},
+ // Runes that are not valid.
+ {"%q", int32(-1), `'�'`},
+ {"%q", 0xDC80, `'�'`},
+ {"%q", rune(0x110000), `'�'`},
+ {"%q", int64(0xFFFFFFFFF), `'�'`},
+ {"%q", uint64(0xFFFFFFFFF), `'�'`},
+
+ // width
+ {"%5s", "abc", " abc"},
+ {"%5s", []byte("abc"), " abc"},
+ {"%2s", "\u263a", " ☺"},
+ {"%2s", []byte("\u263a"), " ☺"},
+ {"%-5s", "abc", "abc "},
+ {"%-5s", []byte("abc"), "abc "},
+ {"%05s", "abc", "00abc"},
+ {"%05s", []byte("abc"), "00abc"},
+ {"%5s", "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"},
+ {"%5s", []byte("abcdefghijklmnopqrstuvwxyz"), "abcdefghijklmnopqrstuvwxyz"},
+ {"%.5s", "abcdefghijklmnopqrstuvwxyz", "abcde"},
+ {"%.5s", []byte("abcdefghijklmnopqrstuvwxyz"), "abcde"},
+ {"%.0s", "日本語日本語", ""},
+ {"%.0s", []byte("日本語日本語"), ""},
+ {"%.5s", "日本語日本語", "日本語日本"},
+ {"%.5s", []byte("日本語日本語"), "日本語日本"},
+ {"%.10s", "日本語日本語", "日本語日本語"},
+ {"%.10s", []byte("日本語日本語"), "日本語日本語"},
+ {"%08q", "abc", `000"abc"`},
+ {"%08q", []byte("abc"), `000"abc"`},
+ {"%-8q", "abc", `"abc" `},
+ {"%-8q", []byte("abc"), `"abc" `},
+ {"%.5q", "abcdefghijklmnopqrstuvwxyz", `"abcde"`},
+ {"%.5q", []byte("abcdefghijklmnopqrstuvwxyz"), `"abcde"`},
+ {"%.5x", "abcdefghijklmnopqrstuvwxyz", "6162636465"},
+ {"%.5x", []byte("abcdefghijklmnopqrstuvwxyz"), "6162636465"},
+ {"%.3q", "日本語日本語", `"日本語"`},
+ {"%.3q", []byte("日本語日本語"), `"日本語"`},
+ {"%.1q", "日本語", `"日"`},
+ {"%.1q", []byte("日本語"), `"日"`},
+ {"%.1x", "日本語", "e6"},
+ {"%.1X", []byte("日本語"), "E6"},
+ {"%10.1q", "日本語日本語", ` "日"`},
+ {"%10.1q", []byte("日本語日本語"), ` "日"`},
+ {"%10v", nil, " "},
+ {"%-10v", nil, " "},
+
+ // integers
+ {"%d", uint(12345), "12345"},
+ {"%d", int(-12345), "-12345"},
+ {"%d", ^uint8(0), "255"},
+ {"%d", ^uint16(0), "65535"},
+ {"%d", ^uint32(0), "4294967295"},
+ {"%d", ^uint64(0), "18446744073709551615"},
+ {"%d", int8(-1 << 7), "-128"},
+ {"%d", int16(-1 << 15), "-32768"},
+ {"%d", int32(-1 << 31), "-2147483648"},
+ {"%d", int64(-1 << 63), "-9223372036854775808"},
+ {"%.d", 0, ""},
+ {"%.0d", 0, ""},
+ {"%6.0d", 0, " "},
+ {"%06.0d", 0, " "},
+ {"% d", 12345, " 12345"},
+ {"%+d", 12345, "+12345"},
+ {"%+d", -12345, "-12345"},
+ {"%b", 7, "111"},
+ {"%b", -6, "-110"},
+ {"%#b", 7, "0b111"},
+ {"%#b", -6, "-0b110"},
+ {"%b", ^uint32(0), "11111111111111111111111111111111"},
+ {"%b", ^uint64(0), "1111111111111111111111111111111111111111111111111111111111111111"},
+ {"%b", int64(-1 << 63), zeroFill("-1", 63, "")},
+ {"%o", 01234, "1234"},
+ {"%o", -01234, "-1234"},
+ {"%#o", 01234, "01234"},
+ {"%#o", -01234, "-01234"},
+ {"%O", 01234, "0o1234"},
+ {"%O", -01234, "-0o1234"},
+ {"%o", ^uint32(0), "37777777777"},
+ {"%o", ^uint64(0), "1777777777777777777777"},
+ {"%#X", 0, "0X0"},
+ {"%x", 0x12abcdef, "12abcdef"},
+ {"%X", 0x12abcdef, "12ABCDEF"},
+ {"%x", ^uint32(0), "ffffffff"},
+ {"%X", ^uint64(0), "FFFFFFFFFFFFFFFF"},
+ {"%.20b", 7, "00000000000000000111"},
+ {"%10d", 12345, " 12345"},
+ {"%10d", -12345, " -12345"},
+ {"%+10d", 12345, " +12345"},
+ {"%010d", 12345, "0000012345"},
+ {"%010d", -12345, "-000012345"},
+ {"%20.8d", 1234, " 00001234"},
+ {"%20.8d", -1234, " -00001234"},
+ {"%020.8d", 1234, " 00001234"},
+ {"%020.8d", -1234, " -00001234"},
+ {"%-20.8d", 1234, "00001234 "},
+ {"%-20.8d", -1234, "-00001234 "},
+ {"%-#20.8x", 0x1234abc, "0x01234abc "},
+ {"%-#20.8X", 0x1234abc, "0X01234ABC "},
+ {"%-#20.8o", 01234, "00001234 "},
+
+ // Test correct f.intbuf overflow checks.
+ {"%068d", 1, zeroFill("", 68, "1")},
+ {"%068d", -1, zeroFill("-", 67, "1")},
+ {"%#.68x", 42, zeroFill("0x", 68, "2a")},
+ {"%.68d", -42, zeroFill("-", 68, "42")},
+ {"%+.68d", 42, zeroFill("+", 68, "42")},
+ {"% .68d", 42, zeroFill(" ", 68, "42")},
+ {"% +.68d", 42, zeroFill("+", 68, "42")},
+
+ // unicode format
+ {"%U", 0, "U+0000"},
+ {"%U", -1, "U+FFFFFFFFFFFFFFFF"},
+ {"%U", '\n', `U+000A`},
+ {"%#U", '\n', `U+000A`},
+ {"%+U", 'x', `U+0078`}, // Plus flag should have no effect.
+ {"%# U", 'x', `U+0078 'x'`}, // Space flag should have no effect.
+ {"%#.2U", 'x', `U+0078 'x'`}, // Precisions below 4 should print 4 digits.
+ {"%U", '\u263a', `U+263A`},
+ {"%#U", '\u263a', `U+263A '☺'`},
+ {"%U", '\U0001D6C2', `U+1D6C2`},
+ {"%#U", '\U0001D6C2', `U+1D6C2 '𝛂'`},
+ {"%#14.6U", '⌘', " U+002318 '⌘'"},
+ {"%#-14.6U", '⌘', "U+002318 '⌘' "},
+ {"%#014.6U", '⌘', " U+002318 '⌘'"},
+ {"%#-014.6U", '⌘', "U+002318 '⌘' "},
+ {"%.68U", uint(42), zeroFill("U+", 68, "2A")},
+ {"%#.68U", '日', zeroFill("U+", 68, "65E5") + " '日'"},
+
+ // floats
+ {"%+.3e", 0.0, "+0.000e+00"},
+ {"%+.3e", 1.0, "+1.000e+00"},
+ {"%+.3x", 0.0, "+0x0.000p+00"},
+ {"%+.3x", 1.0, "+0x1.000p+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"},
+ {"%-07.2f", 1.0, "1.00 "},
+ {"%-07.2f", -1.0, "-1.00 "},
+ {"%+-07.2f", 1.0, "+1.00 "},
+ {"%+-07.2f", -1.0, "-1.00 "},
+ {"%-+07.2f", 1.0, "+1.00 "},
+ {"%-+07.2f", -1.0, "-1.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"},
+ {"% .3X", -1.0, "-0X1.000P+00"},
+ {"% .3x", 1.0, " 0x1.000p+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"},
+ // Test sharp flag used with floats.
+ {"%#g", 1e-323, "1.00000e-323"},
+ {"%#g", -1.0, "-1.00000"},
+ {"%#g", 1.1, "1.10000"},
+ {"%#g", 123456.0, "123456."},
+ {"%#g", 1234567.0, "1.234567e+06"},
+ {"%#g", 1230000.0, "1.23000e+06"},
+ {"%#g", 1000000.0, "1.00000e+06"},
+ {"%#.0f", 1.0, "1."},
+ {"%#.0e", 1.0, "1.e+00"},
+ {"%#.0x", 1.0, "0x1.p+00"},
+ {"%#.0g", 1.0, "1."},
+ {"%#.0g", 1100000.0, "1.e+06"},
+ {"%#.4f", 1.0, "1.0000"},
+ {"%#.4e", 1.0, "1.0000e+00"},
+ {"%#.4x", 1.0, "0x1.0000p+00"},
+ {"%#.4g", 1.0, "1.000"},
+ {"%#.4g", 100000.0, "1.000e+05"},
+ {"%#.4g", 1.234, "1.234"},
+ {"%#.4g", 0.1234, "0.1234"},
+ {"%#.4g", 1.23, "1.230"},
+ {"%#.4g", 0.123, "0.1230"},
+ {"%#.4g", 1.2, "1.200"},
+ {"%#.4g", 0.12, "0.1200"},
+ {"%#.4g", 10.2, "10.20"},
+ {"%#.4g", 0.0, "0.000"},
+ {"%#.4g", 0.012, "0.01200"},
+ {"%#.0f", 123.0, "123."},
+ {"%#.0e", 123.0, "1.e+02"},
+ {"%#.0x", 123.0, "0x1.p+07"},
+ {"%#.0g", 123.0, "1.e+02"},
+ {"%#.4f", 123.0, "123.0000"},
+ {"%#.4e", 123.0, "1.2300e+02"},
+ {"%#.4x", 123.0, "0x1.ec00p+06"},
+ {"%#.4g", 123.0, "123.0"},
+ {"%#.4g", 123000.0, "1.230e+05"},
+ {"%#9.4g", 1.0, " 1.000"},
+ // The sharp flag has no effect for binary float format.
+ {"%#b", 1.0, "4503599627370496p-52"},
+ // Precision has no effect for binary float format.
+ {"%.4b", float32(1.0), "8388608p-23"},
+ {"%.4b", -1.0, "-4503599627370496p-52"},
+ // Test correct f.intbuf boundary checks.
+ {"%.68f", 1.0, zeroFill("1.", 68, "")},
+ {"%.68f", -1.0, zeroFill("-1.", 68, "")},
+ // float infinites and NaNs
+ {"%f", posInf, "+Inf"},
+ {"%.1f", negInf, "-Inf"},
+ {"% f", NaN, " NaN"},
+ {"%20f", posInf, " +Inf"},
+ {"% 20F", posInf, " Inf"},
+ {"% 20e", negInf, " -Inf"},
+ {"% 20x", negInf, " -Inf"},
+ {"%+20E", negInf, " -Inf"},
+ {"%+20X", negInf, " -Inf"},
+ {"% +20g", negInf, " -Inf"},
+ {"%+-20G", posInf, "+Inf "},
+ {"%20e", NaN, " NaN"},
+ {"%20x", NaN, " NaN"},
+ {"% +20E", NaN, " +NaN"},
+ {"% +20X", NaN, " +NaN"},
+ {"% -20g", NaN, " NaN "},
+ {"%+-20G", NaN, "+NaN "},
+ // Zero padding does not apply to infinities and NaN.
+ {"%+020e", posInf, " +Inf"},
+ {"%+020x", posInf, " +Inf"},
+ {"%-020f", negInf, "-Inf "},
+ {"%-020E", NaN, "NaN "},
+ {"%-020X", NaN, "NaN "},
+
+ // complex values
+ {"%.f", 0i, "(0+0i)"},
+ {"% .f", 0i, "( 0+0i)"},
+ {"%+.f", 0i, "(+0+0i)"},
+ {"% +.f", 0i, "(+0+0i)"},
+ {"%+.3e", 0i, "(+0.000e+00+0.000e+00i)"},
+ {"%+.3x", 0i, "(+0x0.000p+00+0x0.000p+00i)"},
+ {"%+.3f", 0i, "(+0.000+0.000i)"},
+ {"%+.3g", 0i, "(+0+0i)"},
+ {"%+.3e", 1 + 2i, "(+1.000e+00+2.000e+00i)"},
+ {"%+.3x", 1 + 2i, "(+0x1.000p+00+0x1.000p+01i)"},
+ {"%+.3f", 1 + 2i, "(+1.000+2.000i)"},
+ {"%+.3g", 1 + 2i, "(+1+2i)"},
+ {"%.3e", 0i, "(0.000e+00+0.000e+00i)"},
+ {"%.3x", 0i, "(0x0.000p+00+0x0.000p+00i)"},
+ {"%.3f", 0i, "(0.000+0.000i)"},
+ {"%.3F", 0i, "(0.000+0.000i)"},
+ {"%.3F", complex64(0i), "(0.000+0.000i)"},
+ {"%.3g", 0i, "(0+0i)"},
+ {"%.3e", 1 + 2i, "(1.000e+00+2.000e+00i)"},
+ {"%.3x", 1 + 2i, "(0x1.000p+00+0x1.000p+01i)"},
+ {"%.3f", 1 + 2i, "(1.000+2.000i)"},
+ {"%.3g", 1 + 2i, "(1+2i)"},
+ {"%.3e", -1 - 2i, "(-1.000e+00-2.000e+00i)"},
+ {"%.3x", -1 - 2i, "(-0x1.000p+00-0x1.000p+01i)"},
+ {"%.3f", -1 - 2i, "(-1.000-2.000i)"},
+ {"%.3g", -1 - 2i, "(-1-2i)"},
+ {"% .3E", -1 - 2i, "(-1.000E+00-2.000E+00i)"},
+ {"% .3X", -1 - 2i, "(-0X1.000P+00-0X1.000P+01i)"},
+ {"%+.3g", 1 + 2i, "(+1+2i)"},
+ {"%+.3g", complex64(1 + 2i), "(+1+2i)"},
+ {"%#g", 1 + 2i, "(1.00000+2.00000i)"},
+ {"%#g", 123456 + 789012i, "(123456.+789012.i)"},
+ {"%#g", 1e-10i, "(0.00000+1.00000e-10i)"},
+ {"%#g", -1e10 - 1.11e100i, "(-1.00000e+10-1.11000e+100i)"},
+ {"%#.0f", 1.23 + 1.0i, "(1.+1.i)"},
+ {"%#.0e", 1.23 + 1.0i, "(1.e+00+1.e+00i)"},
+ {"%#.0x", 1.23 + 1.0i, "(0x1.p+00+0x1.p+00i)"},
+ {"%#.0g", 1.23 + 1.0i, "(1.+1.i)"},
+ {"%#.0g", 0 + 100000i, "(0.+1.e+05i)"},
+ {"%#.0g", 1230000 + 0i, "(1.e+06+0.i)"},
+ {"%#.4f", 1 + 1.23i, "(1.0000+1.2300i)"},
+ {"%#.4e", 123 + 1i, "(1.2300e+02+1.0000e+00i)"},
+ {"%#.4x", 123 + 1i, "(0x1.ec00p+06+0x1.0000p+00i)"},
+ {"%#.4g", 123 + 1.23i, "(123.0+1.230i)"},
+ {"%#12.5g", 0 + 100000i, "( 0.0000 +1.0000e+05i)"},
+ {"%#12.5g", 1230000 - 0i, "( 1.2300e+06 +0.0000i)"},
+ {"%b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
+ {"%b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"},
+ // The sharp flag has no effect for binary complex format.
+ {"%#b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
+ // Precision has no effect for binary complex format.
+ {"%.4b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
+ {"%.4b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"},
+ // complex infinites and NaNs
+ {"%f", complex(posInf, posInf), "(+Inf+Infi)"},
+ {"%f", complex(negInf, negInf), "(-Inf-Infi)"},
+ {"%f", complex(NaN, NaN), "(NaN+NaNi)"},
+ {"%.1f", complex(posInf, posInf), "(+Inf+Infi)"},
+ {"% f", complex(posInf, posInf), "( Inf+Infi)"},
+ {"% f", complex(negInf, negInf), "(-Inf-Infi)"},
+ {"% f", complex(NaN, NaN), "( NaN+NaNi)"},
+ {"%8e", complex(posInf, posInf), "( +Inf +Infi)"},
+ {"%8x", complex(posInf, posInf), "( +Inf +Infi)"},
+ {"% 8E", complex(posInf, posInf), "( Inf +Infi)"},
+ {"% 8X", complex(posInf, posInf), "( Inf +Infi)"},
+ {"%+8f", complex(negInf, negInf), "( -Inf -Infi)"},
+ {"% +8g", complex(negInf, negInf), "( -Inf -Infi)"},
+ {"% -8G", complex(NaN, NaN), "( NaN +NaN i)"},
+ {"%+-8b", complex(NaN, NaN), "(+NaN +NaN i)"},
+ // Zero padding does not apply to infinities and NaN.
+ {"%08f", complex(posInf, posInf), "( +Inf +Infi)"},
+ {"%-08g", complex(negInf, negInf), "(-Inf -Inf i)"},
+ {"%-08G", complex(NaN, NaN), "(NaN +NaN i)"},
+
+ // 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.5s", "qwertyuiop", " qwert"},
+ {"%.5s", "qwertyuiop", "qwert"},
+ {"%-20.5s", "qwertyuiop", "qwert "},
+ {"%20c", 'x', " x"},
+ {"%-20c", 'x', "x "},
+ {"%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"},
+
+ // arrays
+ {"%v", array, "[1 2 3 4 5]"},
+ {"%v", iarray, "[1 hello 2.5 ]"},
+ {"%v", barray, "[1 2 3 4 5]"},
+ {"%v", &array, "&[1 2 3 4 5]"},
+ {"%v", &iarray, "&[1 hello 2.5 ]"},
+ {"%v", &barray, "&[1 2 3 4 5]"},
+
+ // slices
+ {"%v", slice, "[1 2 3 4 5]"},
+ {"%v", islice, "[1 hello 2.5 ]"},
+ {"%v", bslice, "[1 2 3 4 5]"},
+ {"%v", &slice, "&[1 2 3 4 5]"},
+ {"%v", &islice, "&[1 hello 2.5 ]"},
+ {"%v", &bslice, "&[1 2 3 4 5]"},
+
+ // byte arrays and slices with %b,%c,%d,%o,%U and %v
+ {"%b", [3]byte{65, 66, 67}, "[1000001 1000010 1000011]"},
+ {"%c", [3]byte{65, 66, 67}, "[A B C]"},
+ {"%d", [3]byte{65, 66, 67}, "[65 66 67]"},
+ {"%o", [3]byte{65, 66, 67}, "[101 102 103]"},
+ {"%U", [3]byte{65, 66, 67}, "[U+0041 U+0042 U+0043]"},
+ {"%v", [3]byte{65, 66, 67}, "[65 66 67]"},
+ {"%v", [1]byte{123}, "[123]"},
+ {"%012v", []byte{}, "[]"},
+ {"%#012v", []byte{}, "[]byte{}"},
+ {"%6v", []byte{1, 11, 111}, "[ 1 11 111]"},
+ {"%06v", []byte{1, 11, 111}, "[000001 000011 000111]"},
+ {"%-6v", []byte{1, 11, 111}, "[1 11 111 ]"},
+ {"%-06v", []byte{1, 11, 111}, "[1 11 111 ]"},
+ {"%#v", []byte{1, 11, 111}, "[]byte{0x1, 0xb, 0x6f}"},
+ {"%#6v", []byte{1, 11, 111}, "[]byte{ 0x1, 0xb, 0x6f}"},
+ {"%#06v", []byte{1, 11, 111}, "[]byte{0x000001, 0x00000b, 0x00006f}"},
+ {"%#-6v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"},
+ {"%#-06v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"},
+ // f.space should and f.plus should not have an effect with %v.
+ {"% v", []byte{1, 11, 111}, "[ 1 11 111]"},
+ {"%+v", [3]byte{1, 11, 111}, "[1 11 111]"},
+ {"%# -6v", []byte{1, 11, 111}, "[]byte{ 0x1 , 0xb , 0x6f }"},
+ {"%#+-6v", [3]byte{1, 11, 111}, "[3]uint8{0x1 , 0xb , 0x6f }"},
+ // f.space and f.plus should have an effect with %d.
+ {"% d", []byte{1, 11, 111}, "[ 1 11 111]"},
+ {"%+d", [3]byte{1, 11, 111}, "[+1 +11 +111]"},
+ {"%# -6d", []byte{1, 11, 111}, "[ 1 11 111 ]"},
+ {"%#+-6d", [3]byte{1, 11, 111}, "[+1 +11 +111 ]"},
+
+ // floates with %v
+ {"%v", 1.2345678, "1.2345678"},
+ {"%v", float32(1.2345678), "1.2345678"},
+
+ // complexes with %v
+ {"%v", 1 + 2i, "(1+2i)"},
+ {"%v", complex64(1 + 2i), "(1+2i)"},
+
+ // structs
+ {"%v", A{1, 2, "a", []int{1, 2}}, `{1 2 a [1 2]}`},
+ {"%+v", A{1, 2, "a", []int{1, 2}}, `{i:1 j:2 s:a x:[1 2]}`},
+
+ // +v on structs with Stringable items
+ {"%+v", B{1, 2}, `{I:<1> j:2}`},
+ {"%+v", C{1, B{2, 3}}, `{i:1 B:{I:<2> j:3}}`},
+
+ // other formats on Stringable items
+ {"%s", I(23), `<23>`},
+ {"%q", I(23), `"<23>"`},
+ {"%x", I(23), `3c32333e`},
+ {"%#x", I(23), `0x3c32333e`},
+ {"%# x", I(23), `0x3c 0x32 0x33 0x3e`},
+ // Stringer applies only to string formats.
+ {"%d", I(23), `23`},
+ // Stringer applies to the extracted value.
+ {"%s", reflect.ValueOf(I(23)), `<23>`},
+
+ // go syntax
+ {"%#v", A{1, 2, "a", []int{1, 2}}, `fmt_test.A{i:1, j:0x2, s:"a", x:[]int{1, 2}}`},
+ {"%#v", new(byte), "(*uint8)(0xPTR)"},
+ {"%#v", TestFmtInterface, "(func(*testing.T))(0xPTR)"},
+ {"%#v", make(chan int), "(chan int)(0xPTR)"},
+ {"%#v", uint64(1<<64 - 1), "0xffffffffffffffff"},
+ {"%#v", 1000000000, "1000000000"},
+ {"%#v", map[string]int{"a": 1}, `map[string]int{"a":1}`},
+ {"%#v", map[string]B{"a": {1, 2}}, `map[string]fmt_test.B{"a":fmt_test.B{I:1, j:2}}`},
+ {"%#v", []string{"a", "b"}, `[]string{"a", "b"}`},
+ {"%#v", SI{}, `fmt_test.SI{I:interface {}(nil)}`},
+ {"%#v", []int(nil), `[]int(nil)`},
+ {"%#v", []int{}, `[]int{}`},
+ {"%#v", array, `[5]int{1, 2, 3, 4, 5}`},
+ {"%#v", &array, `&[5]int{1, 2, 3, 4, 5}`},
+ {"%#v", iarray, `[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
+ {"%#v", &iarray, `&[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
+ {"%#v", map[int]byte(nil), `map[int]uint8(nil)`},
+ {"%#v", map[int]byte{}, `map[int]uint8{}`},
+ {"%#v", "foo", `"foo"`},
+ {"%#v", barray, `[5]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
+ {"%#v", bslice, `[]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
+ {"%#v", []int32(nil), "[]int32(nil)"},
+ {"%#v", 1.2345678, "1.2345678"},
+ {"%#v", float32(1.2345678), "1.2345678"},
+
+ // Whole number floats are printed without decimals. See Issue 27634.
+ {"%#v", 1.0, "1"},
+ {"%#v", 1000000.0, "1e+06"},
+ {"%#v", float32(1.0), "1"},
+ {"%#v", float32(1000000.0), "1e+06"},
+
+ // Only print []byte and []uint8 as type []byte if they appear at the top level.
+ {"%#v", []byte(nil), "[]byte(nil)"},
+ {"%#v", []uint8(nil), "[]byte(nil)"},
+ {"%#v", []byte{}, "[]byte{}"},
+ {"%#v", []uint8{}, "[]byte{}"},
+ {"%#v", reflect.ValueOf([]byte{}), "[]uint8{}"},
+ {"%#v", reflect.ValueOf([]uint8{}), "[]uint8{}"},
+ {"%#v", &[]byte{}, "&[]uint8{}"},
+ {"%#v", &[]byte{}, "&[]uint8{}"},
+ {"%#v", [3]byte{}, "[3]uint8{0x0, 0x0, 0x0}"},
+ {"%#v", [3]uint8{}, "[3]uint8{0x0, 0x0, 0x0}"},
+
+ // slices with other formats
+ {"%#x", []int{1, 2, 15}, `[0x1 0x2 0xf]`},
+ {"%x", []int{1, 2, 15}, `[1 2 f]`},
+ {"%d", []int{1, 2, 15}, `[1 2 15]`},
+ {"%d", []byte{1, 2, 15}, `[1 2 15]`},
+ {"%q", []string{"a", "b"}, `["a" "b"]`},
+ {"% 02x", []byte{1}, "01"},
+ {"% 02x", []byte{1, 2, 3}, "01 02 03"},
+
+ // Padding with byte slices.
+ {"%2x", []byte{}, " "},
+ {"%#2x", []byte{}, " "},
+ {"% 02x", []byte{}, "00"},
+ {"%# 02x", []byte{}, "00"},
+ {"%-2x", []byte{}, " "},
+ {"%-02x", []byte{}, " "},
+ {"%8x", []byte{0xab}, " ab"},
+ {"% 8x", []byte{0xab}, " ab"},
+ {"%#8x", []byte{0xab}, " 0xab"},
+ {"%# 8x", []byte{0xab}, " 0xab"},
+ {"%08x", []byte{0xab}, "000000ab"},
+ {"% 08x", []byte{0xab}, "000000ab"},
+ {"%#08x", []byte{0xab}, "00000xab"},
+ {"%# 08x", []byte{0xab}, "00000xab"},
+ {"%10x", []byte{0xab, 0xcd}, " abcd"},
+ {"% 10x", []byte{0xab, 0xcd}, " ab cd"},
+ {"%#10x", []byte{0xab, 0xcd}, " 0xabcd"},
+ {"%# 10x", []byte{0xab, 0xcd}, " 0xab 0xcd"},
+ {"%010x", []byte{0xab, 0xcd}, "000000abcd"},
+ {"% 010x", []byte{0xab, 0xcd}, "00000ab cd"},
+ {"%#010x", []byte{0xab, 0xcd}, "00000xabcd"},
+ {"%# 010x", []byte{0xab, 0xcd}, "00xab 0xcd"},
+ {"%-10X", []byte{0xab}, "AB "},
+ {"% -010X", []byte{0xab}, "AB "},
+ {"%#-10X", []byte{0xab, 0xcd}, "0XABCD "},
+ {"%# -010X", []byte{0xab, 0xcd}, "0XAB 0XCD "},
+ // Same for strings
+ {"%2x", "", " "},
+ {"%#2x", "", " "},
+ {"% 02x", "", "00"},
+ {"%# 02x", "", "00"},
+ {"%-2x", "", " "},
+ {"%-02x", "", " "},
+ {"%8x", "\xab", " ab"},
+ {"% 8x", "\xab", " ab"},
+ {"%#8x", "\xab", " 0xab"},
+ {"%# 8x", "\xab", " 0xab"},
+ {"%08x", "\xab", "000000ab"},
+ {"% 08x", "\xab", "000000ab"},
+ {"%#08x", "\xab", "00000xab"},
+ {"%# 08x", "\xab", "00000xab"},
+ {"%10x", "\xab\xcd", " abcd"},
+ {"% 10x", "\xab\xcd", " ab cd"},
+ {"%#10x", "\xab\xcd", " 0xabcd"},
+ {"%# 10x", "\xab\xcd", " 0xab 0xcd"},
+ {"%010x", "\xab\xcd", "000000abcd"},
+ {"% 010x", "\xab\xcd", "00000ab cd"},
+ {"%#010x", "\xab\xcd", "00000xabcd"},
+ {"%# 010x", "\xab\xcd", "00xab 0xcd"},
+ {"%-10X", "\xab", "AB "},
+ {"% -010X", "\xab", "AB "},
+ {"%#-10X", "\xab\xcd", "0XABCD "},
+ {"%# -010X", "\xab\xcd", "0XAB 0XCD "},
+
+ // renamings
+ {"%v", renamedBool(true), "true"},
+ {"%d", renamedBool(true), "%!d(fmt_test.renamedBool=true)"},
+ {"%o", renamedInt(8), "10"},
+ {"%d", renamedInt8(-9), "-9"},
+ {"%v", renamedInt16(10), "10"},
+ {"%v", renamedInt32(-11), "-11"},
+ {"%X", renamedInt64(255), "FF"},
+ {"%v", renamedUint(13), "13"},
+ {"%o", renamedUint8(14), "16"},
+ {"%X", renamedUint16(15), "F"},
+ {"%d", renamedUint32(16), "16"},
+ {"%X", renamedUint64(17), "11"},
+ {"%o", renamedUintptr(18), "22"},
+ {"%x", renamedString("thing"), "7468696e67"},
+ {"%d", renamedBytes([]byte{1, 2, 15}), `[1 2 15]`},
+ {"%q", renamedBytes([]byte("hello")), `"hello"`},
+ {"%x", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656c6c6f"},
+ {"%X", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656C6C6F"},
+ {"%s", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "hello"},
+ {"%q", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, `"hello"`},
+ {"%v", renamedFloat32(22), "22"},
+ {"%v", renamedFloat64(33), "33"},
+ {"%v", renamedComplex64(3 + 4i), "(3+4i)"},
+ {"%v", renamedComplex128(4 - 3i), "(4-3i)"},
+
+ // Formatter
+ {"%x", F(1), ""},
+ {"%x", G(2), "2"},
+ {"%+v", S{F(4), G(5)}, "{F: G:5}"},
+
+ // GoStringer
+ {"%#v", G(6), "GoString(6)"},
+ {"%#v", S{F(7), G(8)}, "fmt_test.S{F:, G:GoString(8)}"},
+
+ // %T
+ {"%T", byte(0), "uint8"},
+ {"%T", reflect.ValueOf(nil), "reflect.Value"},
+ {"%T", (4 - 3i), "complex128"},
+ {"%T", renamedComplex128(4 - 3i), "fmt_test.renamedComplex128"},
+ {"%T", intVar, "int"},
+ {"%6T", &intVar, " *int"},
+ {"%10T", nil, " "},
+ {"%-10T", nil, " "},
+
+ // %p with pointers
+ {"%p", (*int)(nil), "0x0"},
+ {"%#p", (*int)(nil), "0"},
+ {"%p", &intVar, "0xPTR"},
+ {"%#p", &intVar, "PTR"},
+ {"%p", &array, "0xPTR"},
+ {"%p", &slice, "0xPTR"},
+ {"%8.2p", (*int)(nil), " 0x00"},
+ {"%-20.16p", &intVar, "0xPTR "},
+ // %p on non-pointers
+ {"%p", make(chan int), "0xPTR"},
+ {"%p", make(map[int]int), "0xPTR"},
+ {"%p", func() {}, "0xPTR"},
+ {"%p", 27, "%!p(int=27)"}, // not a pointer at all
+ {"%p", nil, "%!p()"}, // nil on its own has no type ...
+ {"%#p", nil, "%!p()"}, // ... and hence is not a pointer type.
+ // pointers with specified base
+ {"%b", &intVar, "PTR_b"},
+ {"%d", &intVar, "PTR_d"},
+ {"%o", &intVar, "PTR_o"},
+ {"%x", &intVar, "PTR_x"},
+ {"%X", &intVar, "PTR_X"},
+ // %v on pointers
+ {"%v", nil, ""},
+ {"%#v", nil, ""},
+ {"%v", (*int)(nil), ""},
+ {"%#v", (*int)(nil), "(*int)(nil)"},
+ {"%v", &intVar, "0xPTR"},
+ {"%#v", &intVar, "(*int)(0xPTR)"},
+ {"%8.2v", (*int)(nil), " "},
+ {"%-20.16v", &intVar, "0xPTR "},
+ // string method on pointer
+ {"%s", &pValue, "String(p)"}, // String method...
+ {"%p", &pValue, "0xPTR"}, // ... is not called with %p.
+
+ // %d on Stringer should give integer if possible
+ {"%s", time.Time{}.Month(), "January"},
+ {"%d", time.Time{}.Month(), "1"},
+
+ // erroneous things
+ {"", nil, "%!(EXTRA )"},
+ {"", 2, "%!(EXTRA int=2)"},
+ {"no args", "hello", "no args%!(EXTRA string=hello)"},
+ {"%s %", "hello", "hello %!(NOVERB)"},
+ {"%s %.2", "hello", "hello %!(NOVERB)"},
+ {"%017091901790959340919092959340919017929593813360", 0, "%!(NOVERB)%!(EXTRA int=0)"},
+ {"%184467440737095516170v", 0, "%!(NOVERB)%!(EXTRA int=0)"},
+ // Extra argument errors should format without flags set.
+ {"%010.2", "12345", "%!(NOVERB)%!(EXTRA string=12345)"},
+
+ // Test that maps with non-reflexive keys print all keys and values.
+ {"%v", map[float64]int{NaN: 1, NaN: 1}, "map[NaN:1 NaN:1]"},
+
+ // Comparison of padding rules with C printf.
+ /*
+ C program:
+ #include
+
+ char *format[] = {
+ "[%.2f]",
+ "[% .2f]",
+ "[%+.2f]",
+ "[%7.2f]",
+ "[% 7.2f]",
+ "[%+7.2f]",
+ "[% +7.2f]",
+ "[%07.2f]",
+ "[% 07.2f]",
+ "[%+07.2f]",
+ "[% +07.2f]"
+ };
+
+ int main(void) {
+ int i;
+ for(i = 0; i < 11; i++) {
+ printf("%s: ", format[i]);
+ printf(format[i], 1.0);
+ printf(" ");
+ printf(format[i], -1.0);
+ printf("\n");
+ }
+ }
+
+ Output:
+ [%.2f]: [1.00] [-1.00]
+ [% .2f]: [ 1.00] [-1.00]
+ [%+.2f]: [+1.00] [-1.00]
+ [%7.2f]: [ 1.00] [ -1.00]
+ [% 7.2f]: [ 1.00] [ -1.00]
+ [%+7.2f]: [ +1.00] [ -1.00]
+ [% +7.2f]: [ +1.00] [ -1.00]
+ [%07.2f]: [0001.00] [-001.00]
+ [% 07.2f]: [ 001.00] [-001.00]
+ [%+07.2f]: [+001.00] [-001.00]
+ [% +07.2f]: [+001.00] [-001.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"},
+ {"%+.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"},
+ {"% +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"},
+ {"% +07.2f", 1.0, "+001.00"},
+ {"% +07.2f", -1.0, "-001.00"},
+
+ // Complex numbers: exhaustively tested in TestComplexFormatting.
+ {"%7.2f", 1 + 2i, "( 1.00 +2.00i)"},
+ {"%+07.2f", -1 - 2i, "(-001.00-002.00i)"},
+
+ // Use spaces instead of zero if padding to the right.
+ {"%0-5s", "abc", "abc "},
+ {"%-05.1f", 1.0, "1.0 "},
+
+ // float and complex formatting should not change the padding width
+ // for other elements. See issue 14642.
+ {"%06v", []any{+10.0, 10}, "[000010 000010]"},
+ {"%06v", []any{-10.0, 10}, "[-00010 000010]"},
+ {"%06v", []any{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"},
+ {"%06v", []any{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"},
+
+ // integer formatting should not alter padding for other elements.
+ {"%03.6v", []any{1, 2.0, "x"}, "[000001 002 00x]"},
+ {"%03.0v", []any{0, 2.0, "x"}, "[ 002 000]"},
+
+ // Complex fmt used to leave the plus flag set for future entries in the array
+ // causing +2+0i and +3+0i instead of 2+0i and 3+0i.
+ {"%v", []complex64{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
+ {"%v", []complex128{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
+
+ // Incomplete format specification caused crash.
+ {"%.", 3, "%!.(int=3)"},
+
+ // Padding for complex numbers. Has been bad, then fixed, then bad again.
+ {"%+10.2f", +104.66 + 440.51i, "( +104.66 +440.51i)"},
+ {"%+10.2f", -104.66 + 440.51i, "( -104.66 +440.51i)"},
+ {"%+10.2f", +104.66 - 440.51i, "( +104.66 -440.51i)"},
+ {"%+10.2f", -104.66 - 440.51i, "( -104.66 -440.51i)"},
+ {"%+010.2f", +104.66 + 440.51i, "(+000104.66+000440.51i)"},
+ {"%+010.2f", -104.66 + 440.51i, "(-000104.66+000440.51i)"},
+ {"%+010.2f", +104.66 - 440.51i, "(+000104.66-000440.51i)"},
+ {"%+010.2f", -104.66 - 440.51i, "(-000104.66-000440.51i)"},
+
+ // []T where type T is a byte with a Stringer method.
+ {"%v", byteStringerSlice, "[X X X X X]"},
+ {"%s", byteStringerSlice, "hello"},
+ {"%q", byteStringerSlice, "\"hello\""},
+ {"%x", byteStringerSlice, "68656c6c6f"},
+ {"%X", byteStringerSlice, "68656C6C6F"},
+ {"%#v", byteStringerSlice, "[]fmt_test.byteStringer{0x68, 0x65, 0x6c, 0x6c, 0x6f}"},
+
+ // And the same for Formatter.
+ {"%v", byteFormatterSlice, "[X X X X X]"},
+ {"%s", byteFormatterSlice, "hello"},
+ {"%q", byteFormatterSlice, "\"hello\""},
+ {"%x", byteFormatterSlice, "68656c6c6f"},
+ {"%X", byteFormatterSlice, "68656C6C6F"},
+ // This next case seems wrong, but the docs say the Formatter wins here.
+ {"%#v", byteFormatterSlice, "[]fmt_test.byteFormatter{X, X, X, X, X}"},
+
+ // pp.WriteString
+ {"%s", writeStringFormatter(""), "******"},
+ {"%s", writeStringFormatter("xyz"), "***xyz***"},
+ {"%s", writeStringFormatter("⌘/⌘"), "***⌘/⌘***"},
+
+ // reflect.Value handled specially in Go 1.5, making it possible to
+ // see inside non-exported fields (which cannot be accessed with Interface()).
+ // Issue 8965.
+ {"%v", reflect.ValueOf(A{}).Field(0).String(), ""}, // Equivalent to the old way.
+ {"%v", reflect.ValueOf(A{}).Field(0), "0"}, // Sees inside the field.
+
+ // verbs apply to the extracted value too.
+ {"%s", reflect.ValueOf("hello"), "hello"},
+ {"%q", reflect.ValueOf("hello"), `"hello"`},
+ {"%#04x", reflect.ValueOf(256), "0x0100"},
+
+ // invalid reflect.Value doesn't crash.
+ {"%v", reflect.Value{}, ""},
+ {"%v", &reflect.Value{}, ""},
+ {"%v", SI{reflect.Value{}}, "{}"},
+
+ // Tests to check that not supported verbs generate an error string.
+ {"%☠", nil, "%!☠()"},
+ {"%☠", any(nil), "%!☠()"},
+ {"%☠", int(0), "%!☠(int=0)"},
+ {"%☠", uint(0), "%!☠(uint=0)"},
+ {"%☠", []byte{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"},
+ {"%☠", []uint8{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"},
+ {"%☠", [1]byte{0}, "[%!☠(uint8=0)]"},
+ {"%☠", [1]uint8{0}, "[%!☠(uint8=0)]"},
+ {"%☠", "hello", "%!☠(string=hello)"},
+ {"%☠", 1.2345678, "%!☠(float64=1.2345678)"},
+ {"%☠", float32(1.2345678), "%!☠(float32=1.2345678)"},
+ {"%☠", 1.2345678 + 1.2345678i, "%!☠(complex128=(1.2345678+1.2345678i))"},
+ {"%☠", complex64(1.2345678 + 1.2345678i), "%!☠(complex64=(1.2345678+1.2345678i))"},
+ {"%☠", &intVar, "%!☠(*int=0xPTR)"},
+ {"%☠", make(chan int), "%!☠(chan int=0xPTR)"},
+ {"%☠", func() {}, "%!☠(func()=0xPTR)"},
+ {"%☠", reflect.ValueOf(renamedInt(0)), "%!☠(fmt_test.renamedInt=0)"},
+ {"%☠", SI{renamedInt(0)}, "{%!☠(fmt_test.renamedInt=0)}"},
+ {"%☠", &[]any{I(1), G(2)}, "&[%!☠(fmt_test.I=1) %!☠(fmt_test.G=2)]"},
+ {"%☠", SI{&[]any{I(1), G(2)}}, "{%!☠(*[]interface {}=&[1 2])}"},
+ {"%☠", reflect.Value{}, ""},
+ {"%☠", map[float64]int{NaN: 1}, "map[%!☠(float64=NaN):%!☠(int=1)]"},
+}
+
+// zeroFill generates zero-filled strings of the specified width. The length
+// of the suffix (but not the prefix) is compensated for in the width calculation.
+func zeroFill(prefix string, width int, suffix string) string {
+ return prefix + strings.Repeat("0", width-len(suffix)) + suffix
+}
+
+func TestSprintf(t *testing.T) {
+ for _, tt := range fmtTests {
+ s := Sprintf(tt.fmt, tt.val)
+ i := strings.Index(tt.out, "PTR")
+ if i >= 0 && i < len(s) {
+ var pattern, chars string
+ switch {
+ case strings.HasPrefix(tt.out[i:], "PTR_b"):
+ pattern = "PTR_b"
+ chars = "01"
+ case strings.HasPrefix(tt.out[i:], "PTR_o"):
+ pattern = "PTR_o"
+ chars = "01234567"
+ case strings.HasPrefix(tt.out[i:], "PTR_d"):
+ pattern = "PTR_d"
+ chars = "0123456789"
+ case strings.HasPrefix(tt.out[i:], "PTR_x"):
+ pattern = "PTR_x"
+ chars = "0123456789abcdef"
+ case strings.HasPrefix(tt.out[i:], "PTR_X"):
+ pattern = "PTR_X"
+ chars = "0123456789ABCDEF"
+ default:
+ pattern = "PTR"
+ chars = "0123456789abcdefABCDEF"
+ }
+ p := s[:i] + pattern
+ for j := i; j < len(s); j++ {
+ if !strings.ContainsRune(chars, rune(s[j])) {
+ p += s[j:]
+ break
+ }
+ }
+ s = p
+ }
+ if s != tt.out {
+ if _, ok := tt.val.(string); ok {
+ // Don't requote the already-quoted strings.
+ // It's too confusing to read the errors.
+ t.Errorf("Sprintf(%q, %q) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
+ } else {
+ t.Errorf("Sprintf(%q, %v) = %q want %q", tt.fmt, tt.val, s, tt.out)
+ }
+ }
+ }
+}
+
+// TestComplexFormatting checks that a complex always formats to the same
+// thing as if done by hand with two singleton prints.
+func TestComplexFormatting(t *testing.T) {
+ var yesNo = []bool{true, false}
+ var values = []float64{1, 0, -1, posInf, negInf, NaN}
+ for _, plus := range yesNo {
+ for _, zero := range yesNo {
+ for _, space := range yesNo {
+ for _, char := range "fFeEgG" {
+ realFmt := "%"
+ if zero {
+ realFmt += "0"
+ }
+ if space {
+ realFmt += " "
+ }
+ if plus {
+ realFmt += "+"
+ }
+ realFmt += "10.2"
+ realFmt += string(char)
+ // Imaginary part always has a sign, so force + and ignore space.
+ imagFmt := "%"
+ if zero {
+ imagFmt += "0"
+ }
+ imagFmt += "+"
+ imagFmt += "10.2"
+ imagFmt += string(char)
+ for _, realValue := range values {
+ for _, imagValue := range values {
+ one := Sprintf(realFmt, complex(realValue, imagValue))
+ two := Sprintf("("+realFmt+imagFmt+"i)", realValue, imagValue)
+ if one != two {
+ t.Error(f, one, two)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+type SE []any // slice of empty; notational compactness.
+
+var reorderTests = []struct {
+ fmt string
+ val SE
+ out string
+}{
+ {"%[1]d", SE{1}, "1"},
+ {"%[2]d", SE{2, 1}, "1"},
+ {"%[2]d %[1]d", SE{1, 2}, "2 1"},
+ {"%[2]*[1]d", SE{2, 5}, " 2"},
+ {"%6.2f", SE{12.0}, " 12.00"}, // Explicit version of next line.
+ {"%[3]*.[2]*[1]f", SE{12.0, 2, 6}, " 12.00"},
+ {"%[1]*.[2]*[3]f", SE{6, 2, 12.0}, " 12.00"},
+ {"%10f", SE{12.0}, " 12.000000"},
+ {"%[1]*[3]f", SE{10, 99, 12.0}, " 12.000000"},
+ {"%.6f", SE{12.0}, "12.000000"}, // Explicit version of next line.
+ {"%.[1]*[3]f", SE{6, 99, 12.0}, "12.000000"},
+ {"%6.f", SE{12.0}, " 12"}, // // Explicit version of next line; empty precision means zero.
+ {"%[1]*.[3]f", SE{6, 3, 12.0}, " 12"},
+ // An actual use! Print the same arguments twice.
+ {"%d %d %d %#[1]o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015"},
+
+ // Erroneous cases.
+ {"%[d", SE{2, 1}, "%!d(BADINDEX)"},
+ {"%]d", SE{2, 1}, "%!](int=2)d%!(EXTRA int=1)"},
+ {"%[]d", SE{2, 1}, "%!d(BADINDEX)"},
+ {"%[-3]d", SE{2, 1}, "%!d(BADINDEX)"},
+ {"%[99]d", SE{2, 1}, "%!d(BADINDEX)"},
+ {"%[3]", SE{2, 1}, "%!(NOVERB)"},
+ {"%[1].2d", SE{5, 6}, "%!d(BADINDEX)"},
+ {"%[1]2d", SE{2, 1}, "%!d(BADINDEX)"},
+ {"%3.[2]d", SE{7}, "%!d(BADINDEX)"},
+ {"%.[2]d", SE{7}, "%!d(BADINDEX)"},
+ {"%d %d %d %#[1]o %#o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015 %!o(MISSING)"},
+ {"%[5]d %[2]d %d", SE{1, 2, 3}, "%!d(BADINDEX) 2 3"},
+ {"%d %[3]d %d", SE{1, 2}, "1 %!d(BADINDEX) 2"}, // Erroneous index does not affect sequence.
+ {"%.[]", SE{}, "%!](BADINDEX)"}, // Issue 10675
+ {"%.-3d", SE{42}, "%!-(int=42)3d"}, // TODO: Should this set return better error messages?
+ {"%2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
+ {"%-2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
+ {"%.2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
+}
+
+func TestReorder(t *testing.T) {
+ for _, tt := range reorderTests {
+ s := Sprintf(tt.fmt, tt.val...)
+ if s != tt.out {
+ t.Errorf("Sprintf(%q, %v) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
+ } else {
+ }
+ }
+}
+
+func BenchmarkSprintfPadding(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%16f", 1.0)
+ }
+ })
+}
+
+func BenchmarkSprintfEmpty(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("")
+ }
+ })
+}
+
+func BenchmarkSprintfString(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%s", "hello")
+ }
+ })
+}
+
+func BenchmarkSprintfTruncateString(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%.3s", "日本語日本語日本語日本語")
+ }
+ })
+}
+
+func BenchmarkSprintfTruncateBytes(b *testing.B) {
+ var bytes any = []byte("日本語日本語日本語日本語")
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%.3s", bytes)
+ }
+ })
+}
+
+func BenchmarkSprintfSlowParsingPath(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%.v", nil)
+ }
+ })
+}
+
+func BenchmarkSprintfQuoteString(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%q", "日本語日本語日本語")
+ }
+ })
+}
+
+func BenchmarkSprintfInt(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%d", 5)
+ }
+ })
+}
+
+func BenchmarkSprintfIntInt(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%d %d", 5, 6)
+ }
+ })
+}
+
+func BenchmarkSprintfPrefixedInt(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("This is some meaningless prefix text that needs to be scanned %d", 6)
+ }
+ })
+}
+
+func BenchmarkSprintfFloat(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%g", 5.23184)
+ }
+ })
+}
+
+func BenchmarkSprintfComplex(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%f", 5.23184+5.23184i)
+ }
+ })
+}
+
+func BenchmarkSprintfBoolean(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%t", true)
+ }
+ })
+}
+
+func BenchmarkSprintfHexString(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("% #x", "0123456789abcdef")
+ }
+ })
+}
+
+func BenchmarkSprintfHexBytes(b *testing.B) {
+ data := []byte("0123456789abcdef")
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("% #x", data)
+ }
+ })
+}
+
+func BenchmarkSprintfBytes(b *testing.B) {
+ data := []byte("0123456789abcdef")
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%v", data)
+ }
+ })
+}
+
+func BenchmarkSprintfStringer(b *testing.B) {
+ stringer := I(12345)
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%v", stringer)
+ }
+ })
+}
+
+func BenchmarkSprintfStructure(b *testing.B) {
+ s := &[]any{SI{12345}, map[int]string{0: "hello"}}
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ _ = Sprintf("%#v", s)
+ }
+ })
+}
+
+func BenchmarkManyArgs(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ var buf bytes.Buffer
+ for pb.Next() {
+ buf.Reset()
+ Fprintf(&buf, "%2d/%2d/%2d %d:%d:%d %s %s\n", 3, 4, 5, 11, 12, 13, "hello", "world")
+ }
+ })
+}
+
+func BenchmarkFprintInt(b *testing.B) {
+ var buf bytes.Buffer
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ Fprint(&buf, 123456)
+ }
+}
+
+func BenchmarkFprintfBytes(b *testing.B) {
+ data := []byte(string("0123456789"))
+ var buf bytes.Buffer
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ Fprintf(&buf, "%s", data)
+ }
+}
+
+func BenchmarkFprintIntNoAlloc(b *testing.B) {
+ var x any = 123456
+ var buf bytes.Buffer
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ Fprint(&buf, x)
+ }
+}
+
+var mallocBuf bytes.Buffer
+var mallocPointer *int // A pointer so we know the interface value won't allocate.
+
+var mallocTest = []struct {
+ count int
+ desc string
+ fn func()
+}{
+ {0, `Sprintf("")`, func() { _ = Sprintf("") }},
+ {1, `Sprintf("xxx")`, func() { _ = Sprintf("xxx") }},
+ {0, `Sprintf("%x")`, func() { _ = Sprintf("%x", 7) }},
+ {1, `Sprintf("%x")`, func() { _ = Sprintf("%x", 1<<16) }},
+ {3, `Sprintf("%80000s")`, func() { _ = Sprintf("%80000s", "hello") }}, // large buffer (>64KB)
+ {1, `Sprintf("%s")`, func() { _ = Sprintf("%s", "hello") }},
+ {1, `Sprintf("%x %x")`, func() { _ = Sprintf("%x %x", 7, 112) }},
+ {1, `Sprintf("%g")`, func() { _ = Sprintf("%g", float32(3.14159)) }},
+ {0, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%s", "hello") }},
+ {0, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%x", 7) }},
+ {0, `Fprintf(buf, "%x")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%x", 1<<16) }},
+ {2, `Fprintf(buf, "%80000s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%80000s", "hello") }}, // large buffer (>64KB)
+ // If the interface value doesn't need to allocate, amortized allocation overhead should be zero.
+ {0, `Fprintf(buf, "%x %x %x")`, func() {
+ mallocBuf.Reset()
+ Fprintf(&mallocBuf, "%x %x %x", mallocPointer, mallocPointer, mallocPointer)
+ }},
+}
+
+var _ bytes.Buffer
+
+func TestCountMallocs(t *testing.T) {
+ switch {
+ case testing.Short():
+ t.Skip("skipping malloc count in short mode")
+ case runtime.GOMAXPROCS(0) > 1:
+ t.Skip("skipping; GOMAXPROCS>1")
+ case race.Enabled:
+ t.Skip("skipping malloc count under race detector")
+ }
+ for _, mt := range mallocTest {
+ mallocs := testing.AllocsPerRun(100, mt.fn)
+ if got, max := mallocs, float64(mt.count); got > max {
+ t.Errorf("%s: got %v allocs, want <=%v", mt.desc, got, max)
+ }
+ }
+}
+
+type flagPrinter struct{}
+
+func (flagPrinter) Format(f State, c rune) {
+ s := "%"
+ for i := 0; i < 128; i++ {
+ if f.Flag(i) {
+ s += string(rune(i))
+ }
+ }
+ if w, ok := f.Width(); ok {
+ s += Sprintf("%d", w)
+ }
+ if p, ok := f.Precision(); ok {
+ s += Sprintf(".%d", p)
+ }
+ s += string(c)
+ io.WriteString(f, "["+s+"]")
+}
+
+var flagtests = []struct {
+ in string
+ out string
+}{
+ {"%a", "[%a]"},
+ {"%-a", "[%-a]"},
+ {"%+a", "[%+a]"},
+ {"%#a", "[%#a]"},
+ {"% a", "[% a]"},
+ {"%0a", "[%0a]"},
+ {"%1.2a", "[%1.2a]"},
+ {"%-1.2a", "[%-1.2a]"},
+ {"%+1.2a", "[%+1.2a]"},
+ {"%-+1.2a", "[%+-1.2a]"},
+ {"%-+1.2abc", "[%+-1.2a]bc"},
+ {"%-1.2abc", "[%-1.2a]bc"},
+}
+
+func TestFlagParser(t *testing.T) {
+ var flagprinter flagPrinter
+ for _, tt := range flagtests {
+ s := Sprintf(tt.in, &flagprinter)
+ if s != tt.out {
+ t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out)
+ }
+ }
+}
+
+func TestStructPrinter(t *testing.T) {
+ type T struct {
+ a string
+ b string
+ c int
+ }
+ var s T
+ s.a = "abc"
+ s.b = "def"
+ s.c = 123
+ var tests = []struct {
+ fmt string
+ out string
+ }{
+ {"%v", "{abc def 123}"},
+ {"%+v", "{a:abc b:def c:123}"},
+ {"%#v", `fmt_test.T{a:"abc", b:"def", c:123}`},
+ }
+ for _, tt := range tests {
+ out := Sprintf(tt.fmt, s)
+ if out != tt.out {
+ t.Errorf("Sprintf(%q, s) = %#q, want %#q", tt.fmt, out, tt.out)
+ }
+ // The same but with a pointer.
+ out = Sprintf(tt.fmt, &s)
+ if out != "&"+tt.out {
+ t.Errorf("Sprintf(%q, &s) = %#q, want %#q", tt.fmt, out, "&"+tt.out)
+ }
+ }
+}
+
+func TestSlicePrinter(t *testing.T) {
+ slice := []int{}
+ s := Sprint(slice)
+ if s != "[]" {
+ t.Errorf("empty slice printed as %q not %q", s, "[]")
+ }
+ slice = []int{1, 2, 3}
+ s = Sprint(slice)
+ if s != "[1 2 3]" {
+ t.Errorf("slice: got %q expected %q", s, "[1 2 3]")
+ }
+ s = Sprint(&slice)
+ if s != "&[1 2 3]" {
+ t.Errorf("&slice: got %q expected %q", s, "&[1 2 3]")
+ }
+}
+
+// presentInMap checks map printing using substrings so we don't depend on the
+// print order.
+func presentInMap(s string, a []string, t *testing.T) {
+ for i := 0; i < len(a); i++ {
+ loc := strings.Index(s, a[i])
+ if loc < 0 {
+ t.Errorf("map print: expected to find %q in %q", a[i], s)
+ }
+ // make sure the match ends here
+ loc += len(a[i])
+ if loc >= len(s) || (s[loc] != ' ' && s[loc] != ']') {
+ t.Errorf("map print: %q not properly terminated in %q", a[i], s)
+ }
+ }
+}
+
+func TestMapPrinter(t *testing.T) {
+ m0 := make(map[int]string)
+ s := Sprint(m0)
+ if s != "map[]" {
+ t.Errorf("empty map printed as %q not %q", s, "map[]")
+ }
+ m1 := map[int]string{1: "one", 2: "two", 3: "three"}
+ a := []string{"1:one", "2:two", "3:three"}
+ presentInMap(Sprintf("%v", m1), a, t)
+ presentInMap(Sprint(m1), a, t)
+ // Pointer to map prints the same but with initial &.
+ if !strings.HasPrefix(Sprint(&m1), "&") {
+ t.Errorf("no initial & for address of map")
+ }
+ presentInMap(Sprintf("%v", &m1), a, t)
+ presentInMap(Sprint(&m1), a, t)
+}
+
+func TestEmptyMap(t *testing.T) {
+ const emptyMapStr = "map[]"
+ var m map[string]int
+ s := Sprint(m)
+ if s != emptyMapStr {
+ t.Errorf("nil map printed as %q not %q", s, emptyMapStr)
+ }
+ m = make(map[string]int)
+ s = Sprint(m)
+ if s != emptyMapStr {
+ t.Errorf("empty map printed as %q not %q", s, emptyMapStr)
+ }
+}
+
+// TestBlank checks that Sprint (and hence Print, Fprint) puts spaces in the
+// right places, that is, between arg pairs in which neither is a string.
+func TestBlank(t *testing.T) {
+ got := Sprint("<", 1, ">:", 1, 2, 3, "!")
+ expect := "<1>:1 2 3!"
+ if got != expect {
+ t.Errorf("got %q expected %q", got, expect)
+ }
+}
+
+// TestBlankln checks that Sprintln (and hence Println, Fprintln) puts spaces in
+// the right places, that is, between all arg pairs.
+func TestBlankln(t *testing.T) {
+ got := Sprintln("<", 1, ">:", 1, 2, 3, "!")
+ expect := "< 1 >: 1 2 3 !\n"
+ if got != expect {
+ t.Errorf("got %q expected %q", got, expect)
+ }
+}
+
+// TestFormatterPrintln checks Formatter with Sprint, Sprintln, Sprintf.
+func TestFormatterPrintln(t *testing.T) {
+ f := F(1)
+ expect := "\n"
+ s := Sprint(f, "\n")
+ if s != expect {
+ t.Errorf("Sprint wrong with Formatter: expected %q got %q", expect, s)
+ }
+ s = Sprintln(f)
+ if s != expect {
+ t.Errorf("Sprintln wrong with Formatter: expected %q got %q", expect, s)
+ }
+ s = Sprintf("%v\n", f)
+ if s != expect {
+ t.Errorf("Sprintf wrong with Formatter: expected %q got %q", expect, s)
+ }
+}
+
+func args(a ...any) []any { return a }
+
+var startests = []struct {
+ fmt string
+ in []any
+ out string
+}{
+ {"%*d", args(4, 42), " 42"},
+ {"%-*d", args(4, 42), "42 "},
+ {"%*d", args(-4, 42), "42 "},
+ {"%-*d", args(-4, 42), "42 "},
+ {"%.*d", args(4, 42), "0042"},
+ {"%*.*d", args(8, 4, 42), " 0042"},
+ {"%0*d", args(4, 42), "0042"},
+ // Some non-int types for width. (Issue 10732).
+ {"%0*d", args(uint(4), 42), "0042"},
+ {"%0*d", args(uint64(4), 42), "0042"},
+ {"%0*d", args('\x04', 42), "0042"},
+ {"%0*d", args(uintptr(4), 42), "0042"},
+
+ // erroneous
+ {"%*d", args(nil, 42), "%!(BADWIDTH)42"},
+ {"%*d", args(int(1e7), 42), "%!(BADWIDTH)42"},
+ {"%*d", args(int(-1e7), 42), "%!(BADWIDTH)42"},
+ {"%.*d", args(nil, 42), "%!(BADPREC)42"},
+ {"%.*d", args(-1, 42), "%!(BADPREC)42"},
+ {"%.*d", args(int(1e7), 42), "%!(BADPREC)42"},
+ {"%.*d", args(uint(1e7), 42), "%!(BADPREC)42"},
+ {"%.*d", args(uint64(1<<63), 42), "%!(BADPREC)42"}, // Huge negative (-inf).
+ {"%.*d", args(uint64(1<<64-1), 42), "%!(BADPREC)42"}, // Small negative (-1).
+ {"%*d", args(5, "foo"), "%!d(string= foo)"},
+ {"%*% %d", args(20, 5), "% 5"},
+ {"%*", args(4), "%!(NOVERB)"},
+}
+
+func TestWidthAndPrecision(t *testing.T) {
+ for i, tt := range startests {
+ s := Sprintf(tt.fmt, tt.in...)
+ if s != tt.out {
+ t.Errorf("#%d: %q: got %q expected %q", i, tt.fmt, s, tt.out)
+ }
+ }
+}
+
+// PanicS is a type that panics in String.
+type PanicS struct {
+ message any
+}
+
+// Value receiver.
+func (p PanicS) String() string {
+ panic(p.message)
+}
+
+// PanicGo is a type that panics in GoString.
+type PanicGo struct {
+ message any
+}
+
+// Value receiver.
+func (p PanicGo) GoString() string {
+ panic(p.message)
+}
+
+// PanicF is a type that panics in Format.
+type PanicF struct {
+ message any
+}
+
+// Value receiver.
+func (p PanicF) Format(f State, c rune) {
+ panic(p.message)
+}
+
+var panictests = []struct {
+ fmt string
+ in any
+ out string
+}{
+ // String
+ {"%s", (*PanicS)(nil), ""}, // nil pointer special case
+ {"%s", PanicS{io.ErrUnexpectedEOF}, "%!s(PANIC=String method: unexpected EOF)"},
+ {"%s", PanicS{3}, "%!s(PANIC=String method: 3)"},
+ // GoString
+ {"%#v", (*PanicGo)(nil), ""}, // nil pointer special case
+ {"%#v", PanicGo{io.ErrUnexpectedEOF}, "%!v(PANIC=GoString method: unexpected EOF)"},
+ {"%#v", PanicGo{3}, "%!v(PANIC=GoString method: 3)"},
+ // Issue 18282. catchPanic should not clear fmtFlags permanently.
+ {"%#v", []any{PanicGo{3}, PanicGo{3}}, "[]interface {}{%!v(PANIC=GoString method: 3), %!v(PANIC=GoString method: 3)}"},
+ // Format
+ {"%s", (*PanicF)(nil), ""}, // nil pointer special case
+ {"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=Format method: unexpected EOF)"},
+ {"%s", PanicF{3}, "%!s(PANIC=Format method: 3)"},
+}
+
+func TestPanics(t *testing.T) {
+ for i, tt := range panictests {
+ s := Sprintf(tt.fmt, tt.in)
+ if s != tt.out {
+ t.Errorf("%d: %q: got %q expected %q", i, tt.fmt, s, tt.out)
+ }
+ }
+}
+
+// recurCount tests that erroneous String routine doesn't cause fatal recursion.
+var recurCount = 0
+
+type Recur struct {
+ i int
+ failed *bool
+}
+
+func (r *Recur) String() string {
+ if recurCount++; recurCount > 10 {
+ *r.failed = true
+ return "FAIL"
+ }
+ // This will call badVerb. Before the fix, that would cause us to recur into
+ // this routine to print %!p(value). Now we don't call the user's method
+ // during an error.
+ return Sprintf("recur@%p value: %d", r, r.i)
+}
+
+func TestBadVerbRecursion(t *testing.T) {
+ failed := false
+ r := &Recur{3, &failed}
+ _ = Sprintf("recur@%p value: %d\n", &r, r.i)
+ if failed {
+ t.Error("fail with pointer")
+ }
+ failed = false
+ r = &Recur{4, &failed}
+ _ = Sprintf("recur@%p, value: %d\n", r, r.i)
+ if failed {
+ t.Error("fail with value")
+ }
+}
+
+func TestIsSpace(t *testing.T) {
+ // This tests the internal isSpace function.
+ // IsSpace = isSpace is defined in export_test.go.
+ for i := rune(0); i <= unicode.MaxRune; i++ {
+ if IsSpace(i) != unicode.IsSpace(i) {
+ t.Errorf("isSpace(%U) = %v, want %v", i, IsSpace(i), unicode.IsSpace(i))
+ }
+ }
+}
+
+func hideFromVet(s string) string { return s }
+
+func TestNilDoesNotBecomeTyped(t *testing.T) {
+ type A struct{}
+ type B struct{}
+ var a *A = nil
+ var b B = B{}
+ got := Sprintf(hideFromVet("%s %s %s %s %s"), nil, a, nil, b, nil)
+ const expect = "%!s() %!s(*fmt_test.A=) %!s() {} %!s()"
+ if got != expect {
+ t.Errorf("expected:\n\t%q\ngot:\n\t%q", expect, got)
+ }
+}
+
+var formatterFlagTests = []struct {
+ in string
+ val any
+ out string
+}{
+ // scalar values with the (unused by fmt) 'a' verb.
+ {"%a", flagPrinter{}, "[%a]"},
+ {"%-a", flagPrinter{}, "[%-a]"},
+ {"%+a", flagPrinter{}, "[%+a]"},
+ {"%#a", flagPrinter{}, "[%#a]"},
+ {"% a", flagPrinter{}, "[% a]"},
+ {"%0a", flagPrinter{}, "[%0a]"},
+ {"%1.2a", flagPrinter{}, "[%1.2a]"},
+ {"%-1.2a", flagPrinter{}, "[%-1.2a]"},
+ {"%+1.2a", flagPrinter{}, "[%+1.2a]"},
+ {"%-+1.2a", flagPrinter{}, "[%+-1.2a]"},
+ {"%-+1.2abc", flagPrinter{}, "[%+-1.2a]bc"},
+ {"%-1.2abc", flagPrinter{}, "[%-1.2a]bc"},
+
+ // composite values with the 'a' verb
+ {"%a", [1]flagPrinter{}, "[[%a]]"},
+ {"%-a", [1]flagPrinter{}, "[[%-a]]"},
+ {"%+a", [1]flagPrinter{}, "[[%+a]]"},
+ {"%#a", [1]flagPrinter{}, "[[%#a]]"},
+ {"% a", [1]flagPrinter{}, "[[% a]]"},
+ {"%0a", [1]flagPrinter{}, "[[%0a]]"},
+ {"%1.2a", [1]flagPrinter{}, "[[%1.2a]]"},
+ {"%-1.2a", [1]flagPrinter{}, "[[%-1.2a]]"},
+ {"%+1.2a", [1]flagPrinter{}, "[[%+1.2a]]"},
+ {"%-+1.2a", [1]flagPrinter{}, "[[%+-1.2a]]"},
+ {"%-+1.2abc", [1]flagPrinter{}, "[[%+-1.2a]]bc"},
+ {"%-1.2abc", [1]flagPrinter{}, "[[%-1.2a]]bc"},
+
+ // simple values with the 'v' verb
+ {"%v", flagPrinter{}, "[%v]"},
+ {"%-v", flagPrinter{}, "[%-v]"},
+ {"%+v", flagPrinter{}, "[%+v]"},
+ {"%#v", flagPrinter{}, "[%#v]"},
+ {"% v", flagPrinter{}, "[% v]"},
+ {"%0v", flagPrinter{}, "[%0v]"},
+ {"%1.2v", flagPrinter{}, "[%1.2v]"},
+ {"%-1.2v", flagPrinter{}, "[%-1.2v]"},
+ {"%+1.2v", flagPrinter{}, "[%+1.2v]"},
+ {"%-+1.2v", flagPrinter{}, "[%+-1.2v]"},
+ {"%-+1.2vbc", flagPrinter{}, "[%+-1.2v]bc"},
+ {"%-1.2vbc", flagPrinter{}, "[%-1.2v]bc"},
+
+ // composite values with the 'v' verb.
+ {"%v", [1]flagPrinter{}, "[[%v]]"},
+ {"%-v", [1]flagPrinter{}, "[[%-v]]"},
+ {"%+v", [1]flagPrinter{}, "[[%+v]]"},
+ {"%#v", [1]flagPrinter{}, "[1]fmt_test.flagPrinter{[%#v]}"},
+ {"% v", [1]flagPrinter{}, "[[% v]]"},
+ {"%0v", [1]flagPrinter{}, "[[%0v]]"},
+ {"%1.2v", [1]flagPrinter{}, "[[%1.2v]]"},
+ {"%-1.2v", [1]flagPrinter{}, "[[%-1.2v]]"},
+ {"%+1.2v", [1]flagPrinter{}, "[[%+1.2v]]"},
+ {"%-+1.2v", [1]flagPrinter{}, "[[%+-1.2v]]"},
+ {"%-+1.2vbc", [1]flagPrinter{}, "[[%+-1.2v]]bc"},
+ {"%-1.2vbc", [1]flagPrinter{}, "[[%-1.2v]]bc"},
+}
+
+func TestFormatterFlags(t *testing.T) {
+ for _, tt := range formatterFlagTests {
+ s := Sprintf(tt.in, tt.val)
+ if s != tt.out {
+ t.Errorf("Sprintf(%q, %T) = %q, want %q", tt.in, tt.val, s, tt.out)
+ }
+ }
+}
+
+func TestParsenum(t *testing.T) {
+ testCases := []struct {
+ s string
+ start, end int
+ num int
+ isnum bool
+ newi int
+ }{
+ {"a123", 0, 4, 0, false, 0},
+ {"1234", 1, 1, 0, false, 1},
+ {"123a", 0, 4, 123, true, 3},
+ {"12a3", 0, 4, 12, true, 2},
+ {"1234", 0, 4, 1234, true, 4},
+ {"1a234", 1, 3, 0, false, 1},
+ }
+ for _, tt := range testCases {
+ num, isnum, newi := Parsenum(tt.s, tt.start, tt.end)
+ if num != tt.num || isnum != tt.isnum || newi != tt.newi {
+ t.Errorf("parsenum(%q, %d, %d) = %d, %v, %d, want %d, %v, %d", tt.s, tt.start, tt.end, num, isnum, newi, tt.num, tt.isnum, tt.newi)
+ }
+ }
+}
+
+// Test the various Append printers. The details are well tested above;
+// here we just make sure the byte slice is updated.
+
+const (
+ appendResult = "hello world, 23"
+ hello = "hello "
+)
+
+func TestAppendf(t *testing.T) {
+ b := make([]byte, 100)
+ b = b[:copy(b, hello)]
+ got := Appendf(b, "world, %d", 23)
+ if string(got) != appendResult {
+ t.Fatalf("Appendf returns %q not %q", got, appendResult)
+ }
+ if &b[0] != &got[0] {
+ t.Fatalf("Appendf allocated a new slice")
+ }
+}
+
+func TestAppend(t *testing.T) {
+ b := make([]byte, 100)
+ b = b[:copy(b, hello)]
+ got := Append(b, "world", ", ", 23)
+ if string(got) != appendResult {
+ t.Fatalf("Append returns %q not %q", got, appendResult)
+ }
+ if &b[0] != &got[0] {
+ t.Fatalf("Append allocated a new slice")
+ }
+}
+
+func TestAppendln(t *testing.T) {
+ b := make([]byte, 100)
+ b = b[:copy(b, hello)]
+ got := Appendln(b, "world,", 23)
+ if string(got) != appendResult+"\n" {
+ t.Fatalf("Appendln returns %q not %q", got, appendResult+"\n")
+ }
+ if &b[0] != &got[0] {
+ t.Fatalf("Appendln allocated a new slice")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/format.go b/platform/dbops/binaries/go/go/src/fmt/format.go
new file mode 100644
index 0000000000000000000000000000000000000000..617f78f15ea2b0b71a80f39bbb4cad066c6b9289
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/format.go
@@ -0,0 +1,594 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fmt
+
+import (
+ "strconv"
+ "unicode/utf8"
+)
+
+const (
+ ldigits = "0123456789abcdefx"
+ udigits = "0123456789ABCDEFX"
+)
+
+const (
+ signed = true
+ unsigned = false
+)
+
+// flags placed in a separate struct for easy clearing.
+type fmtFlags struct {
+ widPresent bool
+ precPresent bool
+ minus bool
+ plus bool
+ sharp bool
+ space bool
+ zero bool
+
+ // For the formats %+v %#v, we set the plusV/sharpV flags
+ // and clear the plus/sharp flags since %+v and %#v are in effect
+ // different, flagless formats set at the top level.
+ plusV bool
+ sharpV bool
+}
+
+// A fmt is the raw formatter used by Printf etc.
+// It prints into a buffer that must be set up separately.
+type fmt struct {
+ buf *buffer
+
+ fmtFlags
+
+ wid int // width
+ prec int // precision
+
+ // intbuf is large enough to store %b of an int64 with a sign and
+ // avoids padding at the end of the struct on 32 bit architectures.
+ intbuf [68]byte
+}
+
+func (f *fmt) clearflags() {
+ f.fmtFlags = fmtFlags{}
+}
+
+func (f *fmt) init(buf *buffer) {
+ f.buf = buf
+ f.clearflags()
+}
+
+// writePadding generates n bytes of padding.
+func (f *fmt) writePadding(n int) {
+ if n <= 0 { // No padding bytes needed.
+ return
+ }
+ buf := *f.buf
+ oldLen := len(buf)
+ newLen := oldLen + n
+ // Make enough room for padding.
+ if newLen > cap(buf) {
+ buf = make(buffer, cap(buf)*2+n)
+ copy(buf, *f.buf)
+ }
+ // Decide which byte the padding should be filled with.
+ padByte := byte(' ')
+ if f.zero {
+ padByte = byte('0')
+ }
+ // Fill padding with padByte.
+ padding := buf[oldLen:newLen]
+ for i := range padding {
+ padding[i] = padByte
+ }
+ *f.buf = buf[:newLen]
+}
+
+// pad appends b to f.buf, padded on left (!f.minus) or right (f.minus).
+func (f *fmt) pad(b []byte) {
+ if !f.widPresent || f.wid == 0 {
+ f.buf.write(b)
+ return
+ }
+ width := f.wid - utf8.RuneCount(b)
+ if !f.minus {
+ // left padding
+ f.writePadding(width)
+ f.buf.write(b)
+ } else {
+ // right padding
+ f.buf.write(b)
+ f.writePadding(width)
+ }
+}
+
+// padString appends s to f.buf, padded on left (!f.minus) or right (f.minus).
+func (f *fmt) padString(s string) {
+ if !f.widPresent || f.wid == 0 {
+ f.buf.writeString(s)
+ return
+ }
+ width := f.wid - utf8.RuneCountInString(s)
+ if !f.minus {
+ // left padding
+ f.writePadding(width)
+ f.buf.writeString(s)
+ } else {
+ // right padding
+ f.buf.writeString(s)
+ f.writePadding(width)
+ }
+}
+
+// fmtBoolean formats a boolean.
+func (f *fmt) fmtBoolean(v bool) {
+ if v {
+ f.padString("true")
+ } else {
+ f.padString("false")
+ }
+}
+
+// fmtUnicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'".
+func (f *fmt) fmtUnicode(u uint64) {
+ buf := f.intbuf[0:]
+
+ // With default precision set the maximum needed buf length is 18
+ // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits
+ // into the already allocated intbuf with a capacity of 68 bytes.
+ prec := 4
+ if f.precPresent && f.prec > 4 {
+ prec = f.prec
+ // Compute space needed for "U+" , number, " '", character, "'".
+ width := 2 + prec + 2 + utf8.UTFMax + 1
+ if width > len(buf) {
+ buf = make([]byte, width)
+ }
+ }
+
+ // Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left.
+ i := len(buf)
+
+ // For %#U we want to add a space and a quoted character at the end of the buffer.
+ if f.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) {
+ i--
+ buf[i] = '\''
+ i -= utf8.RuneLen(rune(u))
+ utf8.EncodeRune(buf[i:], rune(u))
+ i--
+ buf[i] = '\''
+ i--
+ buf[i] = ' '
+ }
+ // Format the Unicode code point u as a hexadecimal number.
+ for u >= 16 {
+ i--
+ buf[i] = udigits[u&0xF]
+ prec--
+ u >>= 4
+ }
+ i--
+ buf[i] = udigits[u]
+ prec--
+ // Add zeros in front of the number until requested precision is reached.
+ for prec > 0 {
+ i--
+ buf[i] = '0'
+ prec--
+ }
+ // Add a leading "U+".
+ i--
+ buf[i] = '+'
+ i--
+ buf[i] = 'U'
+
+ oldZero := f.zero
+ f.zero = false
+ f.pad(buf[i:])
+ f.zero = oldZero
+}
+
+// fmtInteger formats signed and unsigned integers.
+func (f *fmt) fmtInteger(u uint64, base int, isSigned bool, verb rune, digits string) {
+ negative := isSigned && int64(u) < 0
+ if negative {
+ u = -u
+ }
+
+ buf := f.intbuf[0:]
+ // The already allocated f.intbuf with a capacity of 68 bytes
+ // is large enough for integer formatting when no precision or width is set.
+ if f.widPresent || f.precPresent {
+ // Account 3 extra bytes for possible addition of a sign and "0x".
+ width := 3 + f.wid + f.prec // wid and prec are always positive.
+ if width > len(buf) {
+ // We're going to need a bigger boat.
+ buf = make([]byte, width)
+ }
+ }
+
+ // Two ways to ask for extra leading zero digits: %.3d or %03d.
+ // If both are specified the f.zero flag is ignored and
+ // padding with spaces is used instead.
+ prec := 0
+ if f.precPresent {
+ prec = f.prec
+ // Precision of 0 and value of 0 means "print nothing" but padding.
+ if prec == 0 && u == 0 {
+ oldZero := f.zero
+ f.zero = false
+ f.writePadding(f.wid)
+ f.zero = oldZero
+ return
+ }
+ } else if f.zero && f.widPresent {
+ prec = f.wid
+ if negative || f.plus || f.space {
+ prec-- // leave room for sign
+ }
+ }
+
+ // Because printing is easier right-to-left: format u into buf, ending at buf[i].
+ // We could make things marginally faster by splitting the 32-bit case out
+ // into a separate block but it's not worth the duplication, so u has 64 bits.
+ i := len(buf)
+ // Use constants for the division and modulo for more efficient code.
+ // Switch cases ordered by popularity.
+ switch base {
+ case 10:
+ for u >= 10 {
+ i--
+ next := u / 10
+ buf[i] = byte('0' + u - next*10)
+ u = next
+ }
+ case 16:
+ for u >= 16 {
+ i--
+ buf[i] = digits[u&0xF]
+ u >>= 4
+ }
+ case 8:
+ for u >= 8 {
+ i--
+ buf[i] = byte('0' + u&7)
+ u >>= 3
+ }
+ case 2:
+ for u >= 2 {
+ i--
+ buf[i] = byte('0' + u&1)
+ u >>= 1
+ }
+ default:
+ panic("fmt: unknown base; can't happen")
+ }
+ i--
+ buf[i] = digits[u]
+ for i > 0 && prec > len(buf)-i {
+ i--
+ buf[i] = '0'
+ }
+
+ // Various prefixes: 0x, -, etc.
+ if f.sharp {
+ switch base {
+ case 2:
+ // Add a leading 0b.
+ i--
+ buf[i] = 'b'
+ i--
+ buf[i] = '0'
+ case 8:
+ if buf[i] != '0' {
+ i--
+ buf[i] = '0'
+ }
+ case 16:
+ // Add a leading 0x or 0X.
+ i--
+ buf[i] = digits[16]
+ i--
+ buf[i] = '0'
+ }
+ }
+ if verb == 'O' {
+ i--
+ buf[i] = 'o'
+ i--
+ buf[i] = '0'
+ }
+
+ if negative {
+ i--
+ buf[i] = '-'
+ } else if f.plus {
+ i--
+ buf[i] = '+'
+ } else if f.space {
+ i--
+ buf[i] = ' '
+ }
+
+ // Left padding with zeros has already been handled like precision earlier
+ // or the f.zero flag is ignored due to an explicitly set precision.
+ oldZero := f.zero
+ f.zero = false
+ f.pad(buf[i:])
+ f.zero = oldZero
+}
+
+// truncateString truncates the string s to the specified precision, if present.
+func (f *fmt) truncateString(s string) string {
+ if f.precPresent {
+ n := f.prec
+ for i := range s {
+ n--
+ if n < 0 {
+ return s[:i]
+ }
+ }
+ }
+ return s
+}
+
+// truncate truncates the byte slice b as a string of the specified precision, if present.
+func (f *fmt) truncate(b []byte) []byte {
+ if f.precPresent {
+ n := f.prec
+ for i := 0; i < len(b); {
+ n--
+ if n < 0 {
+ return b[:i]
+ }
+ wid := 1
+ if b[i] >= utf8.RuneSelf {
+ _, wid = utf8.DecodeRune(b[i:])
+ }
+ i += wid
+ }
+ }
+ return b
+}
+
+// fmtS formats a string.
+func (f *fmt) fmtS(s string) {
+ s = f.truncateString(s)
+ f.padString(s)
+}
+
+// fmtBs formats the byte slice b as if it was formatted as string with fmtS.
+func (f *fmt) fmtBs(b []byte) {
+ b = f.truncate(b)
+ f.pad(b)
+}
+
+// fmtSbx formats a string or byte slice as a hexadecimal encoding of its bytes.
+func (f *fmt) fmtSbx(s string, b []byte, digits string) {
+ length := len(b)
+ if b == nil {
+ // No byte slice present. Assume string s should be encoded.
+ length = len(s)
+ }
+ // Set length to not process more bytes than the precision demands.
+ if f.precPresent && f.prec < length {
+ length = f.prec
+ }
+ // Compute width of the encoding taking into account the f.sharp and f.space flag.
+ width := 2 * length
+ if width > 0 {
+ if f.space {
+ // Each element encoded by two hexadecimals will get a leading 0x or 0X.
+ if f.sharp {
+ width *= 2
+ }
+ // Elements will be separated by a space.
+ width += length - 1
+ } else if f.sharp {
+ // Only a leading 0x or 0X will be added for the whole string.
+ width += 2
+ }
+ } else { // The byte slice or string that should be encoded is empty.
+ if f.widPresent {
+ f.writePadding(f.wid)
+ }
+ return
+ }
+ // Handle padding to the left.
+ if f.widPresent && f.wid > width && !f.minus {
+ f.writePadding(f.wid - width)
+ }
+ // Write the encoding directly into the output buffer.
+ buf := *f.buf
+ if f.sharp {
+ // Add leading 0x or 0X.
+ buf = append(buf, '0', digits[16])
+ }
+ var c byte
+ for i := 0; i < length; i++ {
+ if f.space && i > 0 {
+ // Separate elements with a space.
+ buf = append(buf, ' ')
+ if f.sharp {
+ // Add leading 0x or 0X for each element.
+ buf = append(buf, '0', digits[16])
+ }
+ }
+ if b != nil {
+ c = b[i] // Take a byte from the input byte slice.
+ } else {
+ c = s[i] // Take a byte from the input string.
+ }
+ // Encode each byte as two hexadecimal digits.
+ buf = append(buf, digits[c>>4], digits[c&0xF])
+ }
+ *f.buf = buf
+ // Handle padding to the right.
+ if f.widPresent && f.wid > width && f.minus {
+ f.writePadding(f.wid - width)
+ }
+}
+
+// fmtSx formats a string as a hexadecimal encoding of its bytes.
+func (f *fmt) fmtSx(s, digits string) {
+ f.fmtSbx(s, nil, digits)
+}
+
+// fmtBx formats a byte slice as a hexadecimal encoding of its bytes.
+func (f *fmt) fmtBx(b []byte, digits string) {
+ f.fmtSbx("", b, digits)
+}
+
+// fmtQ formats a string as a double-quoted, escaped Go string constant.
+// If f.sharp is set a raw (backquoted) string may be returned instead
+// if the string does not contain any control characters other than tab.
+func (f *fmt) fmtQ(s string) {
+ s = f.truncateString(s)
+ if f.sharp && strconv.CanBackquote(s) {
+ f.padString("`" + s + "`")
+ return
+ }
+ buf := f.intbuf[:0]
+ if f.plus {
+ f.pad(strconv.AppendQuoteToASCII(buf, s))
+ } else {
+ f.pad(strconv.AppendQuote(buf, s))
+ }
+}
+
+// fmtC formats an integer as a Unicode character.
+// If the character is not valid Unicode, it will print '\ufffd'.
+func (f *fmt) fmtC(c uint64) {
+ // Explicitly check whether c exceeds utf8.MaxRune since the conversion
+ // of a uint64 to a rune may lose precision that indicates an overflow.
+ r := rune(c)
+ if c > utf8.MaxRune {
+ r = utf8.RuneError
+ }
+ buf := f.intbuf[:0]
+ f.pad(utf8.AppendRune(buf, r))
+}
+
+// fmtQc formats an integer as a single-quoted, escaped Go character constant.
+// If the character is not valid Unicode, it will print '\ufffd'.
+func (f *fmt) fmtQc(c uint64) {
+ r := rune(c)
+ if c > utf8.MaxRune {
+ r = utf8.RuneError
+ }
+ buf := f.intbuf[:0]
+ if f.plus {
+ f.pad(strconv.AppendQuoteRuneToASCII(buf, r))
+ } else {
+ f.pad(strconv.AppendQuoteRune(buf, r))
+ }
+}
+
+// fmtFloat formats a float64. It assumes that verb is a valid format specifier
+// for strconv.AppendFloat and therefore fits into a byte.
+func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) {
+ // Explicit precision in format specifier overrules default precision.
+ if f.precPresent {
+ prec = f.prec
+ }
+ // Format number, reserving space for leading + sign if needed.
+ num := strconv.AppendFloat(f.intbuf[:1], v, byte(verb), prec, size)
+ if num[1] == '-' || num[1] == '+' {
+ num = num[1:]
+ } else {
+ num[0] = '+'
+ }
+ // f.space means to add a leading space instead of a "+" sign unless
+ // the sign is explicitly asked for by f.plus.
+ if f.space && num[0] == '+' && !f.plus {
+ num[0] = ' '
+ }
+ // Special handling for infinities and NaN,
+ // which don't look like a number so shouldn't be padded with zeros.
+ if num[1] == 'I' || num[1] == 'N' {
+ oldZero := f.zero
+ f.zero = false
+ // Remove sign before NaN if not asked for.
+ if num[1] == 'N' && !f.space && !f.plus {
+ num = num[1:]
+ }
+ f.pad(num)
+ f.zero = oldZero
+ return
+ }
+ // The sharp flag forces printing a decimal point for non-binary formats
+ // and retains trailing zeros, which we may need to restore.
+ if f.sharp && verb != 'b' {
+ digits := 0
+ switch verb {
+ case 'v', 'g', 'G', 'x':
+ digits = prec
+ // If no precision is set explicitly use a precision of 6.
+ if digits == -1 {
+ digits = 6
+ }
+ }
+
+ // Buffer pre-allocated with enough room for
+ // exponent notations of the form "e+123" or "p-1023".
+ var tailBuf [6]byte
+ tail := tailBuf[:0]
+
+ hasDecimalPoint := false
+ sawNonzeroDigit := false
+ // Starting from i = 1 to skip sign at num[0].
+ for i := 1; i < len(num); i++ {
+ switch num[i] {
+ case '.':
+ hasDecimalPoint = true
+ case 'p', 'P':
+ tail = append(tail, num[i:]...)
+ num = num[:i]
+ case 'e', 'E':
+ if verb != 'x' && verb != 'X' {
+ tail = append(tail, num[i:]...)
+ num = num[:i]
+ break
+ }
+ fallthrough
+ default:
+ if num[i] != '0' {
+ sawNonzeroDigit = true
+ }
+ // Count significant digits after the first non-zero digit.
+ if sawNonzeroDigit {
+ digits--
+ }
+ }
+ }
+ if !hasDecimalPoint {
+ // Leading digit 0 should contribute once to digits.
+ if len(num) == 2 && num[1] == '0' {
+ digits--
+ }
+ num = append(num, '.')
+ }
+ for digits > 0 {
+ num = append(num, '0')
+ digits--
+ }
+ num = append(num, tail...)
+ }
+ // We want a sign if asked for and if the sign is not positive.
+ if f.plus || num[0] != '+' {
+ // If we're zero padding to the left we want the sign before the leading zeros.
+ // Achieve this by writing the sign out and then padding the unsigned number.
+ if f.zero && f.widPresent && f.wid > len(num) {
+ f.buf.writeByte(num[0])
+ f.writePadding(f.wid - len(num))
+ f.buf.write(num[1:])
+ return
+ }
+ f.pad(num)
+ return
+ }
+ // No sign to show and the number is positive; just print the unsigned number.
+ f.pad(num[1:])
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/gostringer_example_test.go b/platform/dbops/binaries/go/go/src/fmt/gostringer_example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ab19ee3b94d2e310c8962e85aed95cabd0203bd2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/gostringer_example_test.go
@@ -0,0 +1,59 @@
+// 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 fmt_test
+
+import (
+ "fmt"
+)
+
+// Address has a City, State and a Country.
+type Address struct {
+ City string
+ State string
+ Country string
+}
+
+// Person has a Name, Age and Address.
+type Person struct {
+ Name string
+ Age uint
+ Addr *Address
+}
+
+// GoString makes Person satisfy the GoStringer interface.
+// The return value is valid Go code that can be used to reproduce the Person struct.
+func (p Person) GoString() string {
+ if p.Addr != nil {
+ return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country)
+ }
+ return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))
+}
+
+func ExampleGoStringer() {
+ p1 := Person{
+ Name: "Warren",
+ Age: 31,
+ Addr: &Address{
+ City: "Denver",
+ State: "CO",
+ Country: "U.S.A.",
+ },
+ }
+ // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to
+ // Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
+ fmt.Printf("%#v\n", p1)
+
+ p2 := Person{
+ Name: "Theia",
+ Age: 4,
+ }
+ // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to
+ // Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
+ fmt.Printf("%#v\n", p2)
+
+ // Output:
+ // Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}}
+ // Person{Name: "Theia", Age: 4}
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/print.go b/platform/dbops/binaries/go/go/src/fmt/print.go
new file mode 100644
index 0000000000000000000000000000000000000000..cb393bd76370daa72b9af3bb8cdd2394787451bc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/print.go
@@ -0,0 +1,1224 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fmt
+
+import (
+ "internal/fmtsort"
+ "io"
+ "os"
+ "reflect"
+ "strconv"
+ "sync"
+ "unicode/utf8"
+)
+
+// Strings for use with buffer.WriteString.
+// This is less overhead than using buffer.Write with byte arrays.
+const (
+ commaSpaceString = ", "
+ nilAngleString = ""
+ nilParenString = "(nil)"
+ nilString = "nil"
+ mapString = "map["
+ percentBangString = "%!"
+ missingString = "(MISSING)"
+ badIndexString = "(BADINDEX)"
+ panicString = "(PANIC="
+ extraString = "%!(EXTRA "
+ badWidthString = "%!(BADWIDTH)"
+ badPrecString = "%!(BADPREC)"
+ noVerbString = "%!(NOVERB)"
+ invReflectString = ""
+)
+
+// State represents the printer state passed to custom formatters.
+// It provides access to the io.Writer interface plus information about
+// the flags and options for the operand's format specifier.
+type State interface {
+ // Write is the function to call to emit formatted output to be printed.
+ Write(b []byte) (n int, err error)
+ // Width returns the value of the width option and whether it has been set.
+ Width() (wid int, ok bool)
+ // Precision returns the value of the precision option and whether it has been set.
+ Precision() (prec int, ok bool)
+
+ // Flag reports whether the flag c, a character, has been set.
+ Flag(c int) bool
+}
+
+// Formatter is implemented by any value that has a Format method.
+// The implementation controls how State and rune are interpreted,
+// and may call Sprint() or Fprint(f) etc. to generate its output.
+type Formatter interface {
+ Format(f State, verb rune)
+}
+
+// Stringer is implemented by any value that has a String method,
+// which defines the “native” format for that value.
+// The String method is used to print values passed as an operand
+// to any format that accepts a string or to an unformatted printer
+// such as Print.
+type Stringer interface {
+ String() string
+}
+
+// GoStringer is implemented by any value that has a GoString method,
+// which defines the Go syntax for that value.
+// The GoString method is used to print values passed as an operand
+// to a %#v format.
+type GoStringer interface {
+ GoString() string
+}
+
+// FormatString returns a string representing the fully qualified formatting
+// directive captured by the State, followed by the argument verb. (State does not
+// itself contain the verb.) The result has a leading percent sign followed by any
+// flags, the width, and the precision. Missing flags, width, and precision are
+// omitted. This function allows a Formatter to reconstruct the original
+// directive triggering the call to Format.
+func FormatString(state State, verb rune) string {
+ var tmp [16]byte // Use a local buffer.
+ b := append(tmp[:0], '%')
+ for _, c := range " +-#0" { // All known flags
+ if state.Flag(int(c)) { // The argument is an int for historical reasons.
+ b = append(b, byte(c))
+ }
+ }
+ if w, ok := state.Width(); ok {
+ b = strconv.AppendInt(b, int64(w), 10)
+ }
+ if p, ok := state.Precision(); ok {
+ b = append(b, '.')
+ b = strconv.AppendInt(b, int64(p), 10)
+ }
+ b = utf8.AppendRune(b, verb)
+ return string(b)
+}
+
+// Use simple []byte instead of bytes.Buffer to avoid large dependency.
+type buffer []byte
+
+func (b *buffer) write(p []byte) {
+ *b = append(*b, p...)
+}
+
+func (b *buffer) writeString(s string) {
+ *b = append(*b, s...)
+}
+
+func (b *buffer) writeByte(c byte) {
+ *b = append(*b, c)
+}
+
+func (b *buffer) writeRune(r rune) {
+ *b = utf8.AppendRune(*b, r)
+}
+
+// pp is used to store a printer's state and is reused with sync.Pool to avoid allocations.
+type pp struct {
+ buf buffer
+
+ // arg holds the current item, as an interface{}.
+ arg any
+
+ // value is used instead of arg for reflect values.
+ value reflect.Value
+
+ // fmt is used to format basic items such as integers or strings.
+ fmt fmt
+
+ // reordered records whether the format string used argument reordering.
+ reordered bool
+ // goodArgNum records whether the most recent reordering directive was valid.
+ goodArgNum bool
+ // panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
+ panicking bool
+ // erroring is set when printing an error string to guard against calling handleMethods.
+ erroring bool
+ // wrapErrs is set when the format string may contain a %w verb.
+ wrapErrs bool
+ // wrappedErrs records the targets of the %w verb.
+ wrappedErrs []int
+}
+
+var ppFree = sync.Pool{
+ New: func() any { return new(pp) },
+}
+
+// newPrinter allocates a new pp struct or grabs a cached one.
+func newPrinter() *pp {
+ p := ppFree.Get().(*pp)
+ p.panicking = false
+ p.erroring = false
+ p.wrapErrs = false
+ p.fmt.init(&p.buf)
+ return p
+}
+
+// free saves used pp structs in ppFree; avoids an allocation per invocation.
+func (p *pp) free() {
+ // Proper usage of a sync.Pool requires each entry to have approximately
+ // the same memory cost. To obtain this property when the stored type
+ // contains a variably-sized buffer, we add a hard limit on the maximum
+ // buffer to place back in the pool. If the buffer is larger than the
+ // limit, we drop the buffer and recycle just the printer.
+ //
+ // See https://golang.org/issue/23199.
+ if cap(p.buf) > 64*1024 {
+ p.buf = nil
+ } else {
+ p.buf = p.buf[:0]
+ }
+ if cap(p.wrappedErrs) > 8 {
+ p.wrappedErrs = nil
+ }
+
+ p.arg = nil
+ p.value = reflect.Value{}
+ p.wrappedErrs = p.wrappedErrs[:0]
+ ppFree.Put(p)
+}
+
+func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
+
+func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
+
+func (p *pp) Flag(b int) bool {
+ switch b {
+ case '-':
+ return p.fmt.minus
+ case '+':
+ return p.fmt.plus || p.fmt.plusV
+ case '#':
+ return p.fmt.sharp || p.fmt.sharpV
+ case ' ':
+ return p.fmt.space
+ case '0':
+ return p.fmt.zero
+ }
+ return false
+}
+
+// Implement Write so we can call Fprintf on a pp (through State), for
+// recursive use in custom verbs.
+func (p *pp) Write(b []byte) (ret int, err error) {
+ p.buf.write(b)
+ return len(b), nil
+}
+
+// Implement WriteString so that we can call io.WriteString
+// on a pp (through state), for efficiency.
+func (p *pp) WriteString(s string) (ret int, err error) {
+ p.buf.writeString(s)
+ return len(s), nil
+}
+
+// These routines end in 'f' and take a format string.
+
+// Fprintf formats according to a format specifier and writes to w.
+// It returns the number of bytes written and any write error encountered.
+func Fprintf(w io.Writer, format string, a ...any) (n int, err error) {
+ p := newPrinter()
+ p.doPrintf(format, a)
+ n, err = w.Write(p.buf)
+ p.free()
+ return
+}
+
+// Printf formats according to a format specifier and writes to standard output.
+// It returns the number of bytes written and any write error encountered.
+func Printf(format string, a ...any) (n int, err error) {
+ return Fprintf(os.Stdout, format, a...)
+}
+
+// Sprintf formats according to a format specifier and returns the resulting string.
+func Sprintf(format string, a ...any) string {
+ p := newPrinter()
+ p.doPrintf(format, a)
+ s := string(p.buf)
+ p.free()
+ return s
+}
+
+// Appendf formats according to a format specifier, appends the result to the byte
+// slice, and returns the updated slice.
+func Appendf(b []byte, format string, a ...any) []byte {
+ p := newPrinter()
+ p.doPrintf(format, a)
+ b = append(b, p.buf...)
+ p.free()
+ return b
+}
+
+// These routines do not take a format string
+
+// Fprint formats using the default formats for its operands and writes to w.
+// Spaces are added between operands when neither is a string.
+// It returns the number of bytes written and any write error encountered.
+func Fprint(w io.Writer, a ...any) (n int, err error) {
+ p := newPrinter()
+ p.doPrint(a)
+ n, err = w.Write(p.buf)
+ p.free()
+ return
+}
+
+// Print formats using the default formats for its operands and writes to standard output.
+// Spaces are added between operands when neither is a string.
+// It returns the number of bytes written and any write error encountered.
+func Print(a ...any) (n int, err error) {
+ return Fprint(os.Stdout, a...)
+}
+
+// Sprint formats using the default formats for its operands and returns the resulting string.
+// Spaces are added between operands when neither is a string.
+func Sprint(a ...any) string {
+ p := newPrinter()
+ p.doPrint(a)
+ s := string(p.buf)
+ p.free()
+ return s
+}
+
+// Append formats using the default formats for its operands, appends the result to
+// the byte slice, and returns the updated slice.
+func Append(b []byte, a ...any) []byte {
+ p := newPrinter()
+ p.doPrint(a)
+ b = append(b, p.buf...)
+ p.free()
+ return b
+}
+
+// These routines end in 'ln', do not take a format string,
+// always add spaces between operands, and add a newline
+// after the last operand.
+
+// Fprintln formats using the default formats for its operands and writes to w.
+// Spaces are always added between operands and a newline is appended.
+// It returns the number of bytes written and any write error encountered.
+func Fprintln(w io.Writer, a ...any) (n int, err error) {
+ p := newPrinter()
+ p.doPrintln(a)
+ n, err = w.Write(p.buf)
+ p.free()
+ return
+}
+
+// Println formats using the default formats for its operands and writes to standard output.
+// Spaces are always added between operands and a newline is appended.
+// It returns the number of bytes written and any write error encountered.
+func Println(a ...any) (n int, err error) {
+ return Fprintln(os.Stdout, a...)
+}
+
+// Sprintln formats using the default formats for its operands and returns the resulting string.
+// Spaces are always added between operands and a newline is appended.
+func Sprintln(a ...any) string {
+ p := newPrinter()
+ p.doPrintln(a)
+ s := string(p.buf)
+ p.free()
+ return s
+}
+
+// Appendln formats using the default formats for its operands, appends the result
+// to the byte slice, and returns the updated slice. Spaces are always added
+// between operands and a newline is appended.
+func Appendln(b []byte, a ...any) []byte {
+ p := newPrinter()
+ p.doPrintln(a)
+ b = append(b, p.buf...)
+ p.free()
+ return b
+}
+
+// getField gets the i'th field of the struct value.
+// If the field itself is a non-nil interface, return a value for
+// the thing inside the interface, not the interface itself.
+func getField(v reflect.Value, i int) reflect.Value {
+ val := v.Field(i)
+ if val.Kind() == reflect.Interface && !val.IsNil() {
+ val = val.Elem()
+ }
+ return val
+}
+
+// tooLarge reports whether the magnitude of the integer is
+// too large to be used as a formatting width or precision.
+func tooLarge(x int) bool {
+ const max int = 1e6
+ return x > max || x < -max
+}
+
+// parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present.
+func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
+ if start >= end {
+ return 0, false, end
+ }
+ for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
+ if tooLarge(num) {
+ return 0, false, end // Overflow; crazy long number most likely.
+ }
+ num = num*10 + int(s[newi]-'0')
+ isnum = true
+ }
+ return
+}
+
+func (p *pp) unknownType(v reflect.Value) {
+ if !v.IsValid() {
+ p.buf.writeString(nilAngleString)
+ return
+ }
+ p.buf.writeByte('?')
+ p.buf.writeString(v.Type().String())
+ p.buf.writeByte('?')
+}
+
+func (p *pp) badVerb(verb rune) {
+ p.erroring = true
+ p.buf.writeString(percentBangString)
+ p.buf.writeRune(verb)
+ p.buf.writeByte('(')
+ switch {
+ case p.arg != nil:
+ p.buf.writeString(reflect.TypeOf(p.arg).String())
+ p.buf.writeByte('=')
+ p.printArg(p.arg, 'v')
+ case p.value.IsValid():
+ p.buf.writeString(p.value.Type().String())
+ p.buf.writeByte('=')
+ p.printValue(p.value, 'v', 0)
+ default:
+ p.buf.writeString(nilAngleString)
+ }
+ p.buf.writeByte(')')
+ p.erroring = false
+}
+
+func (p *pp) fmtBool(v bool, verb rune) {
+ switch verb {
+ case 't', 'v':
+ p.fmt.fmtBoolean(v)
+ default:
+ p.badVerb(verb)
+ }
+}
+
+// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
+// not, as requested, by temporarily setting the sharp flag.
+func (p *pp) fmt0x64(v uint64, leading0x bool) {
+ sharp := p.fmt.sharp
+ p.fmt.sharp = leading0x
+ p.fmt.fmtInteger(v, 16, unsigned, 'v', ldigits)
+ p.fmt.sharp = sharp
+}
+
+// fmtInteger formats a signed or unsigned integer.
+func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) {
+ switch verb {
+ case 'v':
+ if p.fmt.sharpV && !isSigned {
+ p.fmt0x64(v, true)
+ } else {
+ p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits)
+ }
+ case 'd':
+ p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits)
+ case 'b':
+ p.fmt.fmtInteger(v, 2, isSigned, verb, ldigits)
+ case 'o', 'O':
+ p.fmt.fmtInteger(v, 8, isSigned, verb, ldigits)
+ case 'x':
+ p.fmt.fmtInteger(v, 16, isSigned, verb, ldigits)
+ case 'X':
+ p.fmt.fmtInteger(v, 16, isSigned, verb, udigits)
+ case 'c':
+ p.fmt.fmtC(v)
+ case 'q':
+ p.fmt.fmtQc(v)
+ case 'U':
+ p.fmt.fmtUnicode(v)
+ default:
+ p.badVerb(verb)
+ }
+}
+
+// fmtFloat formats a float. The default precision for each verb
+// is specified as last argument in the call to fmt_float.
+func (p *pp) fmtFloat(v float64, size int, verb rune) {
+ switch verb {
+ case 'v':
+ p.fmt.fmtFloat(v, size, 'g', -1)
+ case 'b', 'g', 'G', 'x', 'X':
+ p.fmt.fmtFloat(v, size, verb, -1)
+ case 'f', 'e', 'E':
+ p.fmt.fmtFloat(v, size, verb, 6)
+ case 'F':
+ p.fmt.fmtFloat(v, size, 'f', 6)
+ default:
+ p.badVerb(verb)
+ }
+}
+
+// fmtComplex formats a complex number v with
+// r = real(v) and j = imag(v) as (r+ji) using
+// fmtFloat for r and j formatting.
+func (p *pp) fmtComplex(v complex128, size int, verb rune) {
+ // Make sure any unsupported verbs are found before the
+ // calls to fmtFloat to not generate an incorrect error string.
+ switch verb {
+ case 'v', 'b', 'g', 'G', 'x', 'X', 'f', 'F', 'e', 'E':
+ oldPlus := p.fmt.plus
+ p.buf.writeByte('(')
+ p.fmtFloat(real(v), size/2, verb)
+ // Imaginary part always has a sign.
+ p.fmt.plus = true
+ p.fmtFloat(imag(v), size/2, verb)
+ p.buf.writeString("i)")
+ p.fmt.plus = oldPlus
+ default:
+ p.badVerb(verb)
+ }
+}
+
+func (p *pp) fmtString(v string, verb rune) {
+ switch verb {
+ case 'v':
+ if p.fmt.sharpV {
+ p.fmt.fmtQ(v)
+ } else {
+ p.fmt.fmtS(v)
+ }
+ case 's':
+ p.fmt.fmtS(v)
+ case 'x':
+ p.fmt.fmtSx(v, ldigits)
+ case 'X':
+ p.fmt.fmtSx(v, udigits)
+ case 'q':
+ p.fmt.fmtQ(v)
+ default:
+ p.badVerb(verb)
+ }
+}
+
+func (p *pp) fmtBytes(v []byte, verb rune, typeString string) {
+ switch verb {
+ case 'v', 'd':
+ if p.fmt.sharpV {
+ p.buf.writeString(typeString)
+ if v == nil {
+ p.buf.writeString(nilParenString)
+ return
+ }
+ p.buf.writeByte('{')
+ for i, c := range v {
+ if i > 0 {
+ p.buf.writeString(commaSpaceString)
+ }
+ p.fmt0x64(uint64(c), true)
+ }
+ p.buf.writeByte('}')
+ } else {
+ p.buf.writeByte('[')
+ for i, c := range v {
+ if i > 0 {
+ p.buf.writeByte(' ')
+ }
+ p.fmt.fmtInteger(uint64(c), 10, unsigned, verb, ldigits)
+ }
+ p.buf.writeByte(']')
+ }
+ case 's':
+ p.fmt.fmtBs(v)
+ case 'x':
+ p.fmt.fmtBx(v, ldigits)
+ case 'X':
+ p.fmt.fmtBx(v, udigits)
+ case 'q':
+ p.fmt.fmtQ(string(v))
+ default:
+ p.printValue(reflect.ValueOf(v), verb, 0)
+ }
+}
+
+func (p *pp) fmtPointer(value reflect.Value, verb rune) {
+ var u uintptr
+ switch value.Kind() {
+ case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer:
+ u = uintptr(value.UnsafePointer())
+ default:
+ p.badVerb(verb)
+ return
+ }
+
+ switch verb {
+ case 'v':
+ if p.fmt.sharpV {
+ p.buf.writeByte('(')
+ p.buf.writeString(value.Type().String())
+ p.buf.writeString(")(")
+ if u == 0 {
+ p.buf.writeString(nilString)
+ } else {
+ p.fmt0x64(uint64(u), true)
+ }
+ p.buf.writeByte(')')
+ } else {
+ if u == 0 {
+ p.fmt.padString(nilAngleString)
+ } else {
+ p.fmt0x64(uint64(u), !p.fmt.sharp)
+ }
+ }
+ case 'p':
+ p.fmt0x64(uint64(u), !p.fmt.sharp)
+ case 'b', 'o', 'd', 'x', 'X':
+ p.fmtInteger(uint64(u), unsigned, verb)
+ default:
+ p.badVerb(verb)
+ }
+}
+
+func (p *pp) catchPanic(arg any, verb rune, method string) {
+ if err := recover(); err != nil {
+ // If it's a nil pointer, just say "". The likeliest causes are a
+ // Stringer that fails to guard against nil or a nil pointer for a
+ // value receiver, and in either case, "" is a nice result.
+ if v := reflect.ValueOf(arg); v.Kind() == reflect.Pointer && v.IsNil() {
+ p.buf.writeString(nilAngleString)
+ return
+ }
+ // Otherwise print a concise panic message. Most of the time the panic
+ // value will print itself nicely.
+ if p.panicking {
+ // Nested panics; the recursion in printArg cannot succeed.
+ panic(err)
+ }
+
+ oldFlags := p.fmt.fmtFlags
+ // For this output we want default behavior.
+ p.fmt.clearflags()
+
+ p.buf.writeString(percentBangString)
+ p.buf.writeRune(verb)
+ p.buf.writeString(panicString)
+ p.buf.writeString(method)
+ p.buf.writeString(" method: ")
+ p.panicking = true
+ p.printArg(err, 'v')
+ p.panicking = false
+ p.buf.writeByte(')')
+
+ p.fmt.fmtFlags = oldFlags
+ }
+}
+
+func (p *pp) handleMethods(verb rune) (handled bool) {
+ if p.erroring {
+ return
+ }
+ if verb == 'w' {
+ // It is invalid to use %w other than with Errorf or with a non-error arg.
+ _, ok := p.arg.(error)
+ if !ok || !p.wrapErrs {
+ p.badVerb(verb)
+ return true
+ }
+ // If the arg is a Formatter, pass 'v' as the verb to it.
+ verb = 'v'
+ }
+
+ // Is it a Formatter?
+ if formatter, ok := p.arg.(Formatter); ok {
+ handled = true
+ defer p.catchPanic(p.arg, verb, "Format")
+ formatter.Format(p, verb)
+ return
+ }
+
+ // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
+ if p.fmt.sharpV {
+ if stringer, ok := p.arg.(GoStringer); ok {
+ handled = true
+ defer p.catchPanic(p.arg, verb, "GoString")
+ // Print the result of GoString unadorned.
+ p.fmt.fmtS(stringer.GoString())
+ return
+ }
+ } else {
+ // If a string is acceptable according to the format, see if
+ // the value satisfies one of the string-valued interfaces.
+ // Println etc. set verb to %v, which is "stringable".
+ switch verb {
+ case 'v', 's', 'x', 'X', 'q':
+ // Is it an error or Stringer?
+ // The duplication in the bodies is necessary:
+ // setting handled and deferring catchPanic
+ // must happen before calling the method.
+ switch v := p.arg.(type) {
+ case error:
+ handled = true
+ defer p.catchPanic(p.arg, verb, "Error")
+ p.fmtString(v.Error(), verb)
+ return
+
+ case Stringer:
+ handled = true
+ defer p.catchPanic(p.arg, verb, "String")
+ p.fmtString(v.String(), verb)
+ return
+ }
+ }
+ }
+ return false
+}
+
+func (p *pp) printArg(arg any, verb rune) {
+ p.arg = arg
+ p.value = reflect.Value{}
+
+ if arg == nil {
+ switch verb {
+ case 'T', 'v':
+ p.fmt.padString(nilAngleString)
+ default:
+ p.badVerb(verb)
+ }
+ return
+ }
+
+ // Special processing considerations.
+ // %T (the value's type) and %p (its address) are special; we always do them first.
+ switch verb {
+ case 'T':
+ p.fmt.fmtS(reflect.TypeOf(arg).String())
+ return
+ case 'p':
+ p.fmtPointer(reflect.ValueOf(arg), 'p')
+ return
+ }
+
+ // Some types can be done without reflection.
+ switch f := arg.(type) {
+ case bool:
+ p.fmtBool(f, verb)
+ case float32:
+ p.fmtFloat(float64(f), 32, verb)
+ case float64:
+ p.fmtFloat(f, 64, verb)
+ case complex64:
+ p.fmtComplex(complex128(f), 64, verb)
+ case complex128:
+ p.fmtComplex(f, 128, verb)
+ case int:
+ p.fmtInteger(uint64(f), signed, verb)
+ case int8:
+ p.fmtInteger(uint64(f), signed, verb)
+ case int16:
+ p.fmtInteger(uint64(f), signed, verb)
+ case int32:
+ p.fmtInteger(uint64(f), signed, verb)
+ case int64:
+ p.fmtInteger(uint64(f), signed, verb)
+ case uint:
+ p.fmtInteger(uint64(f), unsigned, verb)
+ case uint8:
+ p.fmtInteger(uint64(f), unsigned, verb)
+ case uint16:
+ p.fmtInteger(uint64(f), unsigned, verb)
+ case uint32:
+ p.fmtInteger(uint64(f), unsigned, verb)
+ case uint64:
+ p.fmtInteger(f, unsigned, verb)
+ case uintptr:
+ p.fmtInteger(uint64(f), unsigned, verb)
+ case string:
+ p.fmtString(f, verb)
+ case []byte:
+ p.fmtBytes(f, verb, "[]byte")
+ case reflect.Value:
+ // Handle extractable values with special methods
+ // since printValue does not handle them at depth 0.
+ if f.IsValid() && f.CanInterface() {
+ p.arg = f.Interface()
+ if p.handleMethods(verb) {
+ return
+ }
+ }
+ p.printValue(f, verb, 0)
+ default:
+ // If the type is not simple, it might have methods.
+ if !p.handleMethods(verb) {
+ // Need to use reflection, since the type had no
+ // interface methods that could be used for formatting.
+ p.printValue(reflect.ValueOf(f), verb, 0)
+ }
+ }
+}
+
+// printValue is similar to printArg but starts with a reflect value, not an interface{} value.
+// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg.
+func (p *pp) printValue(value reflect.Value, verb rune, depth int) {
+ // Handle values with special methods if not already handled by printArg (depth == 0).
+ if depth > 0 && value.IsValid() && value.CanInterface() {
+ p.arg = value.Interface()
+ if p.handleMethods(verb) {
+ return
+ }
+ }
+ p.arg = nil
+ p.value = value
+
+ switch f := value; value.Kind() {
+ case reflect.Invalid:
+ if depth == 0 {
+ p.buf.writeString(invReflectString)
+ } else {
+ switch verb {
+ case 'v':
+ p.buf.writeString(nilAngleString)
+ default:
+ p.badVerb(verb)
+ }
+ }
+ case reflect.Bool:
+ p.fmtBool(f.Bool(), verb)
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ p.fmtInteger(uint64(f.Int()), signed, verb)
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ p.fmtInteger(f.Uint(), unsigned, verb)
+ case reflect.Float32:
+ p.fmtFloat(f.Float(), 32, verb)
+ case reflect.Float64:
+ p.fmtFloat(f.Float(), 64, verb)
+ case reflect.Complex64:
+ p.fmtComplex(f.Complex(), 64, verb)
+ case reflect.Complex128:
+ p.fmtComplex(f.Complex(), 128, verb)
+ case reflect.String:
+ p.fmtString(f.String(), verb)
+ case reflect.Map:
+ if p.fmt.sharpV {
+ p.buf.writeString(f.Type().String())
+ if f.IsNil() {
+ p.buf.writeString(nilParenString)
+ return
+ }
+ p.buf.writeByte('{')
+ } else {
+ p.buf.writeString(mapString)
+ }
+ sorted := fmtsort.Sort(f)
+ for i, key := range sorted.Key {
+ if i > 0 {
+ if p.fmt.sharpV {
+ p.buf.writeString(commaSpaceString)
+ } else {
+ p.buf.writeByte(' ')
+ }
+ }
+ p.printValue(key, verb, depth+1)
+ p.buf.writeByte(':')
+ p.printValue(sorted.Value[i], verb, depth+1)
+ }
+ if p.fmt.sharpV {
+ p.buf.writeByte('}')
+ } else {
+ p.buf.writeByte(']')
+ }
+ case reflect.Struct:
+ if p.fmt.sharpV {
+ p.buf.writeString(f.Type().String())
+ }
+ p.buf.writeByte('{')
+ for i := 0; i < f.NumField(); i++ {
+ if i > 0 {
+ if p.fmt.sharpV {
+ p.buf.writeString(commaSpaceString)
+ } else {
+ p.buf.writeByte(' ')
+ }
+ }
+ if p.fmt.plusV || p.fmt.sharpV {
+ if name := f.Type().Field(i).Name; name != "" {
+ p.buf.writeString(name)
+ p.buf.writeByte(':')
+ }
+ }
+ p.printValue(getField(f, i), verb, depth+1)
+ }
+ p.buf.writeByte('}')
+ case reflect.Interface:
+ value := f.Elem()
+ if !value.IsValid() {
+ if p.fmt.sharpV {
+ p.buf.writeString(f.Type().String())
+ p.buf.writeString(nilParenString)
+ } else {
+ p.buf.writeString(nilAngleString)
+ }
+ } else {
+ p.printValue(value, verb, depth+1)
+ }
+ case reflect.Array, reflect.Slice:
+ switch verb {
+ case 's', 'q', 'x', 'X':
+ // Handle byte and uint8 slices and arrays special for the above verbs.
+ t := f.Type()
+ if t.Elem().Kind() == reflect.Uint8 {
+ var bytes []byte
+ if f.Kind() == reflect.Slice || f.CanAddr() {
+ bytes = f.Bytes()
+ } else {
+ // We have an array, but we cannot Bytes() a non-addressable array,
+ // so we build a slice by hand. This is a rare case but it would be nice
+ // if reflection could help a little more.
+ bytes = make([]byte, f.Len())
+ for i := range bytes {
+ bytes[i] = byte(f.Index(i).Uint())
+ }
+ }
+ p.fmtBytes(bytes, verb, t.String())
+ return
+ }
+ }
+ if p.fmt.sharpV {
+ p.buf.writeString(f.Type().String())
+ if f.Kind() == reflect.Slice && f.IsNil() {
+ p.buf.writeString(nilParenString)
+ return
+ }
+ p.buf.writeByte('{')
+ for i := 0; i < f.Len(); i++ {
+ if i > 0 {
+ p.buf.writeString(commaSpaceString)
+ }
+ p.printValue(f.Index(i), verb, depth+1)
+ }
+ p.buf.writeByte('}')
+ } else {
+ p.buf.writeByte('[')
+ for i := 0; i < f.Len(); i++ {
+ if i > 0 {
+ p.buf.writeByte(' ')
+ }
+ p.printValue(f.Index(i), verb, depth+1)
+ }
+ p.buf.writeByte(']')
+ }
+ case reflect.Pointer:
+ // pointer to array or slice or struct? ok at top level
+ // but not embedded (avoid loops)
+ if depth == 0 && f.UnsafePointer() != nil {
+ switch a := f.Elem(); a.Kind() {
+ case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:
+ p.buf.writeByte('&')
+ p.printValue(a, verb, depth+1)
+ return
+ }
+ }
+ fallthrough
+ case reflect.Chan, reflect.Func, reflect.UnsafePointer:
+ p.fmtPointer(f, verb)
+ default:
+ p.unknownType(f)
+ }
+}
+
+// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type.
+func intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) {
+ newArgNum = argNum
+ if argNum < len(a) {
+ num, isInt = a[argNum].(int) // Almost always OK.
+ if !isInt {
+ // Work harder.
+ switch v := reflect.ValueOf(a[argNum]); v.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ n := v.Int()
+ if int64(int(n)) == n {
+ num = int(n)
+ isInt = true
+ }
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ n := v.Uint()
+ if int64(n) >= 0 && uint64(int(n)) == n {
+ num = int(n)
+ isInt = true
+ }
+ default:
+ // Already 0, false.
+ }
+ }
+ newArgNum = argNum + 1
+ if tooLarge(num) {
+ num = 0
+ isInt = false
+ }
+ }
+ return
+}
+
+// parseArgNumber returns the value of the bracketed number, minus 1
+// (explicit argument numbers are one-indexed but we want zero-indexed).
+// The opening bracket is known to be present at format[0].
+// The returned values are the index, the number of bytes to consume
+// up to the closing paren, if present, and whether the number parsed
+// ok. The bytes to consume will be 1 if no closing paren is present.
+func parseArgNumber(format string) (index int, wid int, ok bool) {
+ // There must be at least 3 bytes: [n].
+ if len(format) < 3 {
+ return 0, 1, false
+ }
+
+ // Find closing bracket.
+ for i := 1; i < len(format); i++ {
+ if format[i] == ']' {
+ width, ok, newi := parsenum(format, 1, i)
+ if !ok || newi != i {
+ return 0, i + 1, false
+ }
+ return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
+ }
+ }
+ return 0, 1, false
+}
+
+// argNumber returns the next argument to evaluate, which is either the value of the passed-in
+// argNum or the value of the bracketed integer that begins format[i:]. It also returns
+// the new value of i, that is, the index of the next byte of the format to process.
+func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
+ if len(format) <= i || format[i] != '[' {
+ return argNum, i, false
+ }
+ p.reordered = true
+ index, wid, ok := parseArgNumber(format[i:])
+ if ok && 0 <= index && index < numArgs {
+ return index, i + wid, true
+ }
+ p.goodArgNum = false
+ return argNum, i + wid, ok
+}
+
+func (p *pp) badArgNum(verb rune) {
+ p.buf.writeString(percentBangString)
+ p.buf.writeRune(verb)
+ p.buf.writeString(badIndexString)
+}
+
+func (p *pp) missingArg(verb rune) {
+ p.buf.writeString(percentBangString)
+ p.buf.writeRune(verb)
+ p.buf.writeString(missingString)
+}
+
+func (p *pp) doPrintf(format string, a []any) {
+ end := len(format)
+ argNum := 0 // we process one argument per non-trivial format
+ afterIndex := false // previous item in format was an index like [3].
+ p.reordered = false
+formatLoop:
+ for i := 0; i < end; {
+ p.goodArgNum = true
+ lasti := i
+ for i < end && format[i] != '%' {
+ i++
+ }
+ if i > lasti {
+ p.buf.writeString(format[lasti:i])
+ }
+ if i >= end {
+ // done processing format string
+ break
+ }
+
+ // Process one verb
+ i++
+
+ // Do we have flags?
+ p.fmt.clearflags()
+ simpleFormat:
+ for ; i < end; i++ {
+ c := format[i]
+ switch c {
+ case '#':
+ p.fmt.sharp = true
+ case '0':
+ p.fmt.zero = !p.fmt.minus // Only allow zero padding to the left.
+ case '+':
+ p.fmt.plus = true
+ case '-':
+ p.fmt.minus = true
+ p.fmt.zero = false // Do not pad with zeros to the right.
+ case ' ':
+ p.fmt.space = true
+ default:
+ // Fast path for common case of ascii lower case simple verbs
+ // without precision or width or argument indices.
+ if 'a' <= c && c <= 'z' && argNum < len(a) {
+ switch c {
+ case 'w':
+ p.wrappedErrs = append(p.wrappedErrs, argNum)
+ fallthrough
+ case 'v':
+ // Go syntax
+ p.fmt.sharpV = p.fmt.sharp
+ p.fmt.sharp = false
+ // Struct-field syntax
+ p.fmt.plusV = p.fmt.plus
+ p.fmt.plus = false
+ }
+ p.printArg(a[argNum], rune(c))
+ argNum++
+ i++
+ continue formatLoop
+ }
+ // Format is more complex than simple flags and a verb or is malformed.
+ break simpleFormat
+ }
+ }
+
+ // Do we have an explicit argument index?
+ argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
+
+ // Do we have width?
+ if i < end && format[i] == '*' {
+ i++
+ p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)
+
+ if !p.fmt.widPresent {
+ p.buf.writeString(badWidthString)
+ }
+
+ // We have a negative width, so take its value and ensure
+ // that the minus flag is set
+ if p.fmt.wid < 0 {
+ p.fmt.wid = -p.fmt.wid
+ p.fmt.minus = true
+ p.fmt.zero = false // Do not pad with zeros to the right.
+ }
+ afterIndex = false
+ } else {
+ p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
+ if afterIndex && p.fmt.widPresent { // "%[3]2d"
+ p.goodArgNum = false
+ }
+ }
+
+ // Do we have precision?
+ if i+1 < end && format[i] == '.' {
+ i++
+ if afterIndex { // "%[3].2d"
+ p.goodArgNum = false
+ }
+ argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
+ if i < end && format[i] == '*' {
+ i++
+ p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
+ // Negative precision arguments don't make sense
+ if p.fmt.prec < 0 {
+ p.fmt.prec = 0
+ p.fmt.precPresent = false
+ }
+ if !p.fmt.precPresent {
+ p.buf.writeString(badPrecString)
+ }
+ afterIndex = false
+ } else {
+ p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
+ if !p.fmt.precPresent {
+ p.fmt.prec = 0
+ p.fmt.precPresent = true
+ }
+ }
+ }
+
+ if !afterIndex {
+ argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
+ }
+
+ if i >= end {
+ p.buf.writeString(noVerbString)
+ break
+ }
+
+ verb, size := rune(format[i]), 1
+ if verb >= utf8.RuneSelf {
+ verb, size = utf8.DecodeRuneInString(format[i:])
+ }
+ i += size
+
+ switch {
+ case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec.
+ p.buf.writeByte('%')
+ case !p.goodArgNum:
+ p.badArgNum(verb)
+ case argNum >= len(a): // No argument left over to print for the current verb.
+ p.missingArg(verb)
+ case verb == 'w':
+ p.wrappedErrs = append(p.wrappedErrs, argNum)
+ fallthrough
+ case verb == 'v':
+ // Go syntax
+ p.fmt.sharpV = p.fmt.sharp
+ p.fmt.sharp = false
+ // Struct-field syntax
+ p.fmt.plusV = p.fmt.plus
+ p.fmt.plus = false
+ fallthrough
+ default:
+ p.printArg(a[argNum], verb)
+ argNum++
+ }
+ }
+
+ // Check for extra arguments unless the call accessed the arguments
+ // out of order, in which case it's too expensive to detect if they've all
+ // been used and arguably OK if they're not.
+ if !p.reordered && argNum < len(a) {
+ p.fmt.clearflags()
+ p.buf.writeString(extraString)
+ for i, arg := range a[argNum:] {
+ if i > 0 {
+ p.buf.writeString(commaSpaceString)
+ }
+ if arg == nil {
+ p.buf.writeString(nilAngleString)
+ } else {
+ p.buf.writeString(reflect.TypeOf(arg).String())
+ p.buf.writeByte('=')
+ p.printArg(arg, 'v')
+ }
+ }
+ p.buf.writeByte(')')
+ }
+}
+
+func (p *pp) doPrint(a []any) {
+ prevString := false
+ for argNum, arg := range a {
+ isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
+ // Add a space between two non-string arguments.
+ if argNum > 0 && !isString && !prevString {
+ p.buf.writeByte(' ')
+ }
+ p.printArg(arg, 'v')
+ prevString = isString
+ }
+}
+
+// doPrintln is like doPrint but always adds a space between arguments
+// and a newline after the last argument.
+func (p *pp) doPrintln(a []any) {
+ for argNum, arg := range a {
+ if argNum > 0 {
+ p.buf.writeByte(' ')
+ }
+ p.printArg(arg, 'v')
+ }
+ p.buf.writeByte('\n')
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/scan.go b/platform/dbops/binaries/go/go/src/fmt/scan.go
new file mode 100644
index 0000000000000000000000000000000000000000..5dd0971642d111f65f01c7b91e7ce2c46a52fa01
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/scan.go
@@ -0,0 +1,1238 @@
+// 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 fmt
+
+import (
+ "errors"
+ "io"
+ "math"
+ "os"
+ "reflect"
+ "strconv"
+ "sync"
+ "unicode/utf8"
+)
+
+// ScanState represents the scanner state passed to custom scanners.
+// Scanners may do rune-at-a-time scanning or ask the ScanState
+// to discover the next space-delimited token.
+type ScanState interface {
+ // ReadRune reads the next rune (Unicode code point) from the input.
+ // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
+ // return EOF after returning the first '\n' or when reading beyond
+ // the specified width.
+ ReadRune() (r rune, size int, err error)
+ // UnreadRune causes the next call to ReadRune to return the same rune.
+ UnreadRune() error
+ // SkipSpace skips space in the input. Newlines are treated appropriately
+ // for the operation being performed; see the package documentation
+ // for more information.
+ SkipSpace()
+ // Token skips space in the input if skipSpace is true, then returns the
+ // run of Unicode code points c satisfying f(c). If f is nil,
+ // !unicode.IsSpace(c) is used; that is, the token will hold non-space
+ // characters. Newlines are treated appropriately for the operation being
+ // performed; see the package documentation for more information.
+ // The returned slice points to shared data that may be overwritten
+ // by the next call to Token, a call to a Scan function using the ScanState
+ // as input, or when the calling Scan method returns.
+ Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
+ // Width returns the value of the width option and whether it has been set.
+ // The unit is Unicode code points.
+ Width() (wid int, ok bool)
+ // Because ReadRune is implemented by the interface, Read should never be
+ // called by the scanning routines and a valid implementation of
+ // ScanState may choose always to return an error from Read.
+ Read(buf []byte) (n int, err error)
+}
+
+// Scanner is implemented by any value that has a Scan method, which scans
+// the input for the representation of a value and stores the result in the
+// receiver, which must be a pointer to be useful. The Scan method is called
+// for any argument to Scan, Scanf, or Scanln that implements it.
+type Scanner interface {
+ Scan(state ScanState, verb rune) error
+}
+
+// Scan scans text read from standard input, storing successive
+// space-separated values into successive arguments. Newlines count
+// as space. It returns the number of items successfully scanned.
+// If that is less than the number of arguments, err will report why.
+func Scan(a ...any) (n int, err error) {
+ return Fscan(os.Stdin, a...)
+}
+
+// Scanln is similar to Scan, but stops scanning at a newline and
+// after the final item there must be a newline or EOF.
+func Scanln(a ...any) (n int, err error) {
+ return Fscanln(os.Stdin, a...)
+}
+
+// Scanf scans text read from standard input, storing successive
+// space-separated values into successive arguments as determined by
+// the format. It returns the number of items successfully scanned.
+// If that is less than the number of arguments, err will report why.
+// Newlines in the input must match newlines in the format.
+// The one exception: the verb %c always scans the next rune in the
+// input, even if it is a space (or tab etc.) or newline.
+func Scanf(format string, a ...any) (n int, err error) {
+ return Fscanf(os.Stdin, format, a...)
+}
+
+type stringReader string
+
+func (r *stringReader) Read(b []byte) (n int, err error) {
+ n = copy(b, *r)
+ *r = (*r)[n:]
+ if n == 0 {
+ err = io.EOF
+ }
+ return
+}
+
+// Sscan scans the argument string, storing successive space-separated
+// values into successive arguments. Newlines count as space. It
+// returns the number of items successfully scanned. If that is less
+// than the number of arguments, err will report why.
+func Sscan(str string, a ...any) (n int, err error) {
+ return Fscan((*stringReader)(&str), a...)
+}
+
+// Sscanln is similar to Sscan, but stops scanning at a newline and
+// after the final item there must be a newline or EOF.
+func Sscanln(str string, a ...any) (n int, err error) {
+ return Fscanln((*stringReader)(&str), a...)
+}
+
+// Sscanf scans the argument string, storing successive space-separated
+// values into successive arguments as determined by the format. It
+// returns the number of items successfully parsed.
+// Newlines in the input must match newlines in the format.
+func Sscanf(str string, format string, a ...any) (n int, err error) {
+ return Fscanf((*stringReader)(&str), format, a...)
+}
+
+// Fscan scans text read from r, storing successive space-separated
+// values into successive arguments. Newlines count as space. It
+// returns the number of items successfully scanned. If that is less
+// than the number of arguments, err will report why.
+func Fscan(r io.Reader, a ...any) (n int, err error) {
+ s, old := newScanState(r, true, false)
+ n, err = s.doScan(a)
+ s.free(old)
+ return
+}
+
+// Fscanln is similar to Fscan, but stops scanning at a newline and
+// after the final item there must be a newline or EOF.
+func Fscanln(r io.Reader, a ...any) (n int, err error) {
+ s, old := newScanState(r, false, true)
+ n, err = s.doScan(a)
+ s.free(old)
+ return
+}
+
+// Fscanf scans text read from r, storing successive space-separated
+// values into successive arguments as determined by the format. It
+// returns the number of items successfully parsed.
+// Newlines in the input must match newlines in the format.
+func Fscanf(r io.Reader, format string, a ...any) (n int, err error) {
+ s, old := newScanState(r, false, false)
+ n, err = s.doScanf(format, a)
+ s.free(old)
+ return
+}
+
+// scanError represents an error generated by the scanning software.
+// It's used as a unique signature to identify such errors when recovering.
+type scanError struct {
+ err error
+}
+
+const eof = -1
+
+// ss is the internal implementation of ScanState.
+type ss struct {
+ rs io.RuneScanner // where to read input
+ buf buffer // token accumulator
+ count int // runes consumed so far.
+ atEOF bool // already read EOF
+ ssave
+}
+
+// ssave holds the parts of ss that need to be
+// saved and restored on recursive scans.
+type ssave struct {
+ validSave bool // is or was a part of an actual ss.
+ nlIsEnd bool // whether newline terminates scan
+ nlIsSpace bool // whether newline counts as white space
+ argLimit int // max value of ss.count for this arg; argLimit <= limit
+ limit int // max value of ss.count.
+ maxWid int // width of this arg.
+}
+
+// The Read method is only in ScanState so that ScanState
+// satisfies io.Reader. It will never be called when used as
+// intended, so there is no need to make it actually work.
+func (s *ss) Read(buf []byte) (n int, err error) {
+ return 0, errors.New("ScanState's Read should not be called. Use ReadRune")
+}
+
+func (s *ss) ReadRune() (r rune, size int, err error) {
+ if s.atEOF || s.count >= s.argLimit {
+ err = io.EOF
+ return
+ }
+
+ r, size, err = s.rs.ReadRune()
+ if err == nil {
+ s.count++
+ if s.nlIsEnd && r == '\n' {
+ s.atEOF = true
+ }
+ } else if err == io.EOF {
+ s.atEOF = true
+ }
+ return
+}
+
+func (s *ss) Width() (wid int, ok bool) {
+ if s.maxWid == hugeWid {
+ return 0, false
+ }
+ return s.maxWid, true
+}
+
+// The public method returns an error; this private one panics.
+// If getRune reaches EOF, the return value is EOF (-1).
+func (s *ss) getRune() (r rune) {
+ r, _, err := s.ReadRune()
+ if err != nil {
+ if err == io.EOF {
+ return eof
+ }
+ s.error(err)
+ }
+ return
+}
+
+// mustReadRune turns io.EOF into a panic(io.ErrUnexpectedEOF).
+// It is called in cases such as string scanning where an EOF is a
+// syntax error.
+func (s *ss) mustReadRune() (r rune) {
+ r = s.getRune()
+ if r == eof {
+ s.error(io.ErrUnexpectedEOF)
+ }
+ return
+}
+
+func (s *ss) UnreadRune() error {
+ s.rs.UnreadRune()
+ s.atEOF = false
+ s.count--
+ return nil
+}
+
+func (s *ss) error(err error) {
+ panic(scanError{err})
+}
+
+func (s *ss) errorString(err string) {
+ panic(scanError{errors.New(err)})
+}
+
+func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) {
+ defer func() {
+ if e := recover(); e != nil {
+ if se, ok := e.(scanError); ok {
+ err = se.err
+ } else {
+ panic(e)
+ }
+ }
+ }()
+ if f == nil {
+ f = notSpace
+ }
+ s.buf = s.buf[:0]
+ tok = s.token(skipSpace, f)
+ return
+}
+
+// space is a copy of the unicode.White_Space ranges,
+// to avoid depending on package unicode.
+var space = [][2]uint16{
+ {0x0009, 0x000d},
+ {0x0020, 0x0020},
+ {0x0085, 0x0085},
+ {0x00a0, 0x00a0},
+ {0x1680, 0x1680},
+ {0x2000, 0x200a},
+ {0x2028, 0x2029},
+ {0x202f, 0x202f},
+ {0x205f, 0x205f},
+ {0x3000, 0x3000},
+}
+
+func isSpace(r rune) bool {
+ if r >= 1<<16 {
+ return false
+ }
+ rx := uint16(r)
+ for _, rng := range space {
+ if rx < rng[0] {
+ return false
+ }
+ if rx <= rng[1] {
+ return true
+ }
+ }
+ return false
+}
+
+// notSpace is the default scanning function used in Token.
+func notSpace(r rune) bool {
+ return !isSpace(r)
+}
+
+// readRune is a structure to enable reading UTF-8 encoded code points
+// from an io.Reader. It is used if the Reader given to the scanner does
+// not already implement io.RuneScanner.
+type readRune struct {
+ reader io.Reader
+ buf [utf8.UTFMax]byte // used only inside ReadRune
+ pending int // number of bytes in pendBuf; only >0 for bad UTF-8
+ pendBuf [utf8.UTFMax]byte // bytes left over
+ peekRune rune // if >=0 next rune; when <0 is ^(previous Rune)
+}
+
+// readByte returns the next byte from the input, which may be
+// left over from a previous read if the UTF-8 was ill-formed.
+func (r *readRune) readByte() (b byte, err error) {
+ if r.pending > 0 {
+ b = r.pendBuf[0]
+ copy(r.pendBuf[0:], r.pendBuf[1:])
+ r.pending--
+ return
+ }
+ n, err := io.ReadFull(r.reader, r.pendBuf[:1])
+ if n != 1 {
+ return 0, err
+ }
+ return r.pendBuf[0], err
+}
+
+// ReadRune returns the next UTF-8 encoded code point from the
+// io.Reader inside r.
+func (r *readRune) ReadRune() (rr rune, size int, err error) {
+ if r.peekRune >= 0 {
+ rr = r.peekRune
+ r.peekRune = ^r.peekRune
+ size = utf8.RuneLen(rr)
+ return
+ }
+ r.buf[0], err = r.readByte()
+ if err != nil {
+ return
+ }
+ if r.buf[0] < utf8.RuneSelf { // fast check for common ASCII case
+ rr = rune(r.buf[0])
+ size = 1 // Known to be 1.
+ // Flip the bits of the rune so it's available to UnreadRune.
+ r.peekRune = ^rr
+ return
+ }
+ var n int
+ for n = 1; !utf8.FullRune(r.buf[:n]); n++ {
+ r.buf[n], err = r.readByte()
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ break
+ }
+ return
+ }
+ }
+ rr, size = utf8.DecodeRune(r.buf[:n])
+ if size < n { // an error, save the bytes for the next read
+ copy(r.pendBuf[r.pending:], r.buf[size:n])
+ r.pending += n - size
+ }
+ // Flip the bits of the rune so it's available to UnreadRune.
+ r.peekRune = ^rr
+ return
+}
+
+func (r *readRune) UnreadRune() error {
+ if r.peekRune >= 0 {
+ return errors.New("fmt: scanning called UnreadRune with no rune available")
+ }
+ // Reverse bit flip of previously read rune to obtain valid >=0 state.
+ r.peekRune = ^r.peekRune
+ return nil
+}
+
+var ssFree = sync.Pool{
+ New: func() any { return new(ss) },
+}
+
+// newScanState allocates a new ss struct or grab a cached one.
+func newScanState(r io.Reader, nlIsSpace, nlIsEnd bool) (s *ss, old ssave) {
+ s = ssFree.Get().(*ss)
+ if rs, ok := r.(io.RuneScanner); ok {
+ s.rs = rs
+ } else {
+ s.rs = &readRune{reader: r, peekRune: -1}
+ }
+ s.nlIsSpace = nlIsSpace
+ s.nlIsEnd = nlIsEnd
+ s.atEOF = false
+ s.limit = hugeWid
+ s.argLimit = hugeWid
+ s.maxWid = hugeWid
+ s.validSave = true
+ s.count = 0
+ return
+}
+
+// free saves used ss structs in ssFree; avoid an allocation per invocation.
+func (s *ss) free(old ssave) {
+ // If it was used recursively, just restore the old state.
+ if old.validSave {
+ s.ssave = old
+ return
+ }
+ // Don't hold on to ss structs with large buffers.
+ if cap(s.buf) > 1024 {
+ return
+ }
+ s.buf = s.buf[:0]
+ s.rs = nil
+ ssFree.Put(s)
+}
+
+// SkipSpace provides Scan methods the ability to skip space and newline
+// characters in keeping with the current scanning mode set by format strings
+// and Scan/Scanln.
+func (s *ss) SkipSpace() {
+ for {
+ r := s.getRune()
+ if r == eof {
+ return
+ }
+ if r == '\r' && s.peek("\n") {
+ continue
+ }
+ if r == '\n' {
+ if s.nlIsSpace {
+ continue
+ }
+ s.errorString("unexpected newline")
+ return
+ }
+ if !isSpace(r) {
+ s.UnreadRune()
+ break
+ }
+ }
+}
+
+// token returns the next space-delimited string from the input. It
+// skips white space. For Scanln, it stops at newlines. For Scan,
+// newlines are treated as spaces.
+func (s *ss) token(skipSpace bool, f func(rune) bool) []byte {
+ if skipSpace {
+ s.SkipSpace()
+ }
+ // read until white space or newline
+ for {
+ r := s.getRune()
+ if r == eof {
+ break
+ }
+ if !f(r) {
+ s.UnreadRune()
+ break
+ }
+ s.buf.writeRune(r)
+ }
+ return s.buf
+}
+
+var errComplex = errors.New("syntax error scanning complex number")
+var errBool = errors.New("syntax error scanning boolean")
+
+func indexRune(s string, r rune) int {
+ for i, c := range s {
+ if c == r {
+ return i
+ }
+ }
+ return -1
+}
+
+// consume reads the next rune in the input and reports whether it is in the ok string.
+// If accept is true, it puts the character into the input token.
+func (s *ss) consume(ok string, accept bool) bool {
+ r := s.getRune()
+ if r == eof {
+ return false
+ }
+ if indexRune(ok, r) >= 0 {
+ if accept {
+ s.buf.writeRune(r)
+ }
+ return true
+ }
+ if r != eof && accept {
+ s.UnreadRune()
+ }
+ return false
+}
+
+// peek reports whether the next character is in the ok string, without consuming it.
+func (s *ss) peek(ok string) bool {
+ r := s.getRune()
+ if r != eof {
+ s.UnreadRune()
+ }
+ return indexRune(ok, r) >= 0
+}
+
+func (s *ss) notEOF() {
+ // Guarantee there is data to be read.
+ if r := s.getRune(); r == eof {
+ panic(io.EOF)
+ }
+ s.UnreadRune()
+}
+
+// accept checks the next rune in the input. If it's a byte (sic) in the string, it puts it in the
+// buffer and returns true. Otherwise it return false.
+func (s *ss) accept(ok string) bool {
+ return s.consume(ok, true)
+}
+
+// okVerb verifies that the verb is present in the list, setting s.err appropriately if not.
+func (s *ss) okVerb(verb rune, okVerbs, typ string) bool {
+ for _, v := range okVerbs {
+ if v == verb {
+ return true
+ }
+ }
+ s.errorString("bad verb '%" + string(verb) + "' for " + typ)
+ return false
+}
+
+// scanBool returns the value of the boolean represented by the next token.
+func (s *ss) scanBool(verb rune) bool {
+ s.SkipSpace()
+ s.notEOF()
+ if !s.okVerb(verb, "tv", "boolean") {
+ return false
+ }
+ // Syntax-checking a boolean is annoying. We're not fastidious about case.
+ switch s.getRune() {
+ case '0':
+ return false
+ case '1':
+ return true
+ case 't', 'T':
+ if s.accept("rR") && (!s.accept("uU") || !s.accept("eE")) {
+ s.error(errBool)
+ }
+ return true
+ case 'f', 'F':
+ if s.accept("aA") && (!s.accept("lL") || !s.accept("sS") || !s.accept("eE")) {
+ s.error(errBool)
+ }
+ return false
+ }
+ return false
+}
+
+// Numerical elements
+const (
+ binaryDigits = "01"
+ octalDigits = "01234567"
+ decimalDigits = "0123456789"
+ hexadecimalDigits = "0123456789aAbBcCdDeEfF"
+ sign = "+-"
+ period = "."
+ exponent = "eEpP"
+)
+
+// getBase returns the numeric base represented by the verb and its digit string.
+func (s *ss) getBase(verb rune) (base int, digits string) {
+ s.okVerb(verb, "bdoUxXv", "integer") // sets s.err
+ base = 10
+ digits = decimalDigits
+ switch verb {
+ case 'b':
+ base = 2
+ digits = binaryDigits
+ case 'o':
+ base = 8
+ digits = octalDigits
+ case 'x', 'X', 'U':
+ base = 16
+ digits = hexadecimalDigits
+ }
+ return
+}
+
+// scanNumber returns the numerical string with specified digits starting here.
+func (s *ss) scanNumber(digits string, haveDigits bool) string {
+ if !haveDigits {
+ s.notEOF()
+ if !s.accept(digits) {
+ s.errorString("expected integer")
+ }
+ }
+ for s.accept(digits) {
+ }
+ return string(s.buf)
+}
+
+// scanRune returns the next rune value in the input.
+func (s *ss) scanRune(bitSize int) int64 {
+ s.notEOF()
+ r := s.getRune()
+ n := uint(bitSize)
+ x := (int64(r) << (64 - n)) >> (64 - n)
+ if x != int64(r) {
+ s.errorString("overflow on character value " + string(r))
+ }
+ return int64(r)
+}
+
+// scanBasePrefix reports whether the integer begins with a base prefix
+// and returns the base, digit string, and whether a zero was found.
+// It is called only if the verb is %v.
+func (s *ss) scanBasePrefix() (base int, digits string, zeroFound bool) {
+ if !s.peek("0") {
+ return 0, decimalDigits + "_", false
+ }
+ s.accept("0")
+ // Special cases for 0, 0b, 0o, 0x.
+ switch {
+ case s.peek("bB"):
+ s.consume("bB", true)
+ return 0, binaryDigits + "_", true
+ case s.peek("oO"):
+ s.consume("oO", true)
+ return 0, octalDigits + "_", true
+ case s.peek("xX"):
+ s.consume("xX", true)
+ return 0, hexadecimalDigits + "_", true
+ default:
+ return 0, octalDigits + "_", true
+ }
+}
+
+// scanInt returns the value of the integer represented by the next
+// token, checking for overflow. Any error is stored in s.err.
+func (s *ss) scanInt(verb rune, bitSize int) int64 {
+ if verb == 'c' {
+ return s.scanRune(bitSize)
+ }
+ s.SkipSpace()
+ s.notEOF()
+ base, digits := s.getBase(verb)
+ haveDigits := false
+ if verb == 'U' {
+ if !s.consume("U", false) || !s.consume("+", false) {
+ s.errorString("bad unicode format ")
+ }
+ } else {
+ s.accept(sign) // If there's a sign, it will be left in the token buffer.
+ if verb == 'v' {
+ base, digits, haveDigits = s.scanBasePrefix()
+ }
+ }
+ tok := s.scanNumber(digits, haveDigits)
+ i, err := strconv.ParseInt(tok, base, 64)
+ if err != nil {
+ s.error(err)
+ }
+ n := uint(bitSize)
+ x := (i << (64 - n)) >> (64 - n)
+ if x != i {
+ s.errorString("integer overflow on token " + tok)
+ }
+ return i
+}
+
+// scanUint returns the value of the unsigned integer represented
+// by the next token, checking for overflow. Any error is stored in s.err.
+func (s *ss) scanUint(verb rune, bitSize int) uint64 {
+ if verb == 'c' {
+ return uint64(s.scanRune(bitSize))
+ }
+ s.SkipSpace()
+ s.notEOF()
+ base, digits := s.getBase(verb)
+ haveDigits := false
+ if verb == 'U' {
+ if !s.consume("U", false) || !s.consume("+", false) {
+ s.errorString("bad unicode format ")
+ }
+ } else if verb == 'v' {
+ base, digits, haveDigits = s.scanBasePrefix()
+ }
+ tok := s.scanNumber(digits, haveDigits)
+ i, err := strconv.ParseUint(tok, base, 64)
+ if err != nil {
+ s.error(err)
+ }
+ n := uint(bitSize)
+ x := (i << (64 - n)) >> (64 - n)
+ if x != i {
+ s.errorString("unsigned integer overflow on token " + tok)
+ }
+ return i
+}
+
+// floatToken returns the floating-point number starting here, no longer than swid
+// if the width is specified. It's not rigorous about syntax because it doesn't check that
+// we have at least some digits, but Atof will do that.
+func (s *ss) floatToken() string {
+ s.buf = s.buf[:0]
+ // NaN?
+ if s.accept("nN") && s.accept("aA") && s.accept("nN") {
+ return string(s.buf)
+ }
+ // leading sign?
+ s.accept(sign)
+ // Inf?
+ if s.accept("iI") && s.accept("nN") && s.accept("fF") {
+ return string(s.buf)
+ }
+ digits := decimalDigits + "_"
+ exp := exponent
+ if s.accept("0") && s.accept("xX") {
+ digits = hexadecimalDigits + "_"
+ exp = "pP"
+ }
+ // digits?
+ for s.accept(digits) {
+ }
+ // decimal point?
+ if s.accept(period) {
+ // fraction?
+ for s.accept(digits) {
+ }
+ }
+ // exponent?
+ if s.accept(exp) {
+ // leading sign?
+ s.accept(sign)
+ // digits?
+ for s.accept(decimalDigits + "_") {
+ }
+ }
+ return string(s.buf)
+}
+
+// complexTokens returns the real and imaginary parts of the complex number starting here.
+// The number might be parenthesized and has the format (N+Ni) where N is a floating-point
+// number and there are no spaces within.
+func (s *ss) complexTokens() (real, imag string) {
+ // TODO: accept N and Ni independently?
+ parens := s.accept("(")
+ real = s.floatToken()
+ s.buf = s.buf[:0]
+ // Must now have a sign.
+ if !s.accept("+-") {
+ s.error(errComplex)
+ }
+ // Sign is now in buffer
+ imagSign := string(s.buf)
+ imag = s.floatToken()
+ if !s.accept("i") {
+ s.error(errComplex)
+ }
+ if parens && !s.accept(")") {
+ s.error(errComplex)
+ }
+ return real, imagSign + imag
+}
+
+func hasX(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 'x' || s[i] == 'X' {
+ return true
+ }
+ }
+ return false
+}
+
+// convertFloat converts the string to a float64value.
+func (s *ss) convertFloat(str string, n int) float64 {
+ // strconv.ParseFloat will handle "+0x1.fp+2",
+ // but we have to implement our non-standard
+ // decimal+binary exponent mix (1.2p4) ourselves.
+ if p := indexRune(str, 'p'); p >= 0 && !hasX(str) {
+ // Atof doesn't handle power-of-2 exponents,
+ // but they're easy to evaluate.
+ f, err := strconv.ParseFloat(str[:p], n)
+ if err != nil {
+ // Put full string into error.
+ if e, ok := err.(*strconv.NumError); ok {
+ e.Num = str
+ }
+ s.error(err)
+ }
+ m, err := strconv.Atoi(str[p+1:])
+ if err != nil {
+ // Put full string into error.
+ if e, ok := err.(*strconv.NumError); ok {
+ e.Num = str
+ }
+ s.error(err)
+ }
+ return math.Ldexp(f, m)
+ }
+ f, err := strconv.ParseFloat(str, n)
+ if err != nil {
+ s.error(err)
+ }
+ return f
+}
+
+// scanComplex converts the next token to a complex128 value.
+// The atof argument is a type-specific reader for the underlying type.
+// If we're reading complex64, atof will parse float32s and convert them
+// to float64's to avoid reproducing this code for each complex type.
+func (s *ss) scanComplex(verb rune, n int) complex128 {
+ if !s.okVerb(verb, floatVerbs, "complex") {
+ return 0
+ }
+ s.SkipSpace()
+ s.notEOF()
+ sreal, simag := s.complexTokens()
+ real := s.convertFloat(sreal, n/2)
+ imag := s.convertFloat(simag, n/2)
+ return complex(real, imag)
+}
+
+// convertString returns the string represented by the next input characters.
+// The format of the input is determined by the verb.
+func (s *ss) convertString(verb rune) (str string) {
+ if !s.okVerb(verb, "svqxX", "string") {
+ return ""
+ }
+ s.SkipSpace()
+ s.notEOF()
+ switch verb {
+ case 'q':
+ str = s.quotedString()
+ case 'x', 'X':
+ str = s.hexString()
+ default:
+ str = string(s.token(true, notSpace)) // %s and %v just return the next word
+ }
+ return
+}
+
+// quotedString returns the double- or back-quoted string represented by the next input characters.
+func (s *ss) quotedString() string {
+ s.notEOF()
+ quote := s.getRune()
+ switch quote {
+ case '`':
+ // Back-quoted: Anything goes until EOF or back quote.
+ for {
+ r := s.mustReadRune()
+ if r == quote {
+ break
+ }
+ s.buf.writeRune(r)
+ }
+ return string(s.buf)
+ case '"':
+ // Double-quoted: Include the quotes and let strconv.Unquote do the backslash escapes.
+ s.buf.writeByte('"')
+ for {
+ r := s.mustReadRune()
+ s.buf.writeRune(r)
+ if r == '\\' {
+ // In a legal backslash escape, no matter how long, only the character
+ // immediately after the escape can itself be a backslash or quote.
+ // Thus we only need to protect the first character after the backslash.
+ s.buf.writeRune(s.mustReadRune())
+ } else if r == '"' {
+ break
+ }
+ }
+ result, err := strconv.Unquote(string(s.buf))
+ if err != nil {
+ s.error(err)
+ }
+ return result
+ default:
+ s.errorString("expected quoted string")
+ }
+ return ""
+}
+
+// hexDigit returns the value of the hexadecimal digit.
+func hexDigit(d rune) (int, bool) {
+ digit := int(d)
+ switch digit {
+ case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
+ return digit - '0', true
+ case 'a', 'b', 'c', 'd', 'e', 'f':
+ return 10 + digit - 'a', true
+ case 'A', 'B', 'C', 'D', 'E', 'F':
+ return 10 + digit - 'A', true
+ }
+ return -1, false
+}
+
+// hexByte returns the next hex-encoded (two-character) byte from the input.
+// It returns ok==false if the next bytes in the input do not encode a hex byte.
+// If the first byte is hex and the second is not, processing stops.
+func (s *ss) hexByte() (b byte, ok bool) {
+ rune1 := s.getRune()
+ if rune1 == eof {
+ return
+ }
+ value1, ok := hexDigit(rune1)
+ if !ok {
+ s.UnreadRune()
+ return
+ }
+ value2, ok := hexDigit(s.mustReadRune())
+ if !ok {
+ s.errorString("illegal hex digit")
+ return
+ }
+ return byte(value1<<4 | value2), true
+}
+
+// hexString returns the space-delimited hexpair-encoded string.
+func (s *ss) hexString() string {
+ s.notEOF()
+ for {
+ b, ok := s.hexByte()
+ if !ok {
+ break
+ }
+ s.buf.writeByte(b)
+ }
+ if len(s.buf) == 0 {
+ s.errorString("no hex data for %x string")
+ return ""
+ }
+ return string(s.buf)
+}
+
+const (
+ floatVerbs = "beEfFgGv"
+
+ hugeWid = 1 << 30
+
+ intBits = 32 << (^uint(0) >> 63)
+ uintptrBits = 32 << (^uintptr(0) >> 63)
+)
+
+// scanPercent scans a literal percent character.
+func (s *ss) scanPercent() {
+ s.SkipSpace()
+ s.notEOF()
+ if !s.accept("%") {
+ s.errorString("missing literal %")
+ }
+}
+
+// scanOne scans a single value, deriving the scanner from the type of the argument.
+func (s *ss) scanOne(verb rune, arg any) {
+ s.buf = s.buf[:0]
+ var err error
+ // If the parameter has its own Scan method, use that.
+ if v, ok := arg.(Scanner); ok {
+ err = v.Scan(s, verb)
+ if err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ s.error(err)
+ }
+ return
+ }
+
+ switch v := arg.(type) {
+ case *bool:
+ *v = s.scanBool(verb)
+ case *complex64:
+ *v = complex64(s.scanComplex(verb, 64))
+ case *complex128:
+ *v = s.scanComplex(verb, 128)
+ case *int:
+ *v = int(s.scanInt(verb, intBits))
+ case *int8:
+ *v = int8(s.scanInt(verb, 8))
+ case *int16:
+ *v = int16(s.scanInt(verb, 16))
+ case *int32:
+ *v = int32(s.scanInt(verb, 32))
+ case *int64:
+ *v = s.scanInt(verb, 64)
+ case *uint:
+ *v = uint(s.scanUint(verb, intBits))
+ case *uint8:
+ *v = uint8(s.scanUint(verb, 8))
+ case *uint16:
+ *v = uint16(s.scanUint(verb, 16))
+ case *uint32:
+ *v = uint32(s.scanUint(verb, 32))
+ case *uint64:
+ *v = s.scanUint(verb, 64)
+ case *uintptr:
+ *v = uintptr(s.scanUint(verb, uintptrBits))
+ // Floats are tricky because you want to scan in the precision of the result, not
+ // scan in high precision and convert, in order to preserve the correct error condition.
+ case *float32:
+ if s.okVerb(verb, floatVerbs, "float32") {
+ s.SkipSpace()
+ s.notEOF()
+ *v = float32(s.convertFloat(s.floatToken(), 32))
+ }
+ case *float64:
+ if s.okVerb(verb, floatVerbs, "float64") {
+ s.SkipSpace()
+ s.notEOF()
+ *v = s.convertFloat(s.floatToken(), 64)
+ }
+ case *string:
+ *v = s.convertString(verb)
+ case *[]byte:
+ // We scan to string and convert so we get a copy of the data.
+ // If we scanned to bytes, the slice would point at the buffer.
+ *v = []byte(s.convertString(verb))
+ default:
+ val := reflect.ValueOf(v)
+ ptr := val
+ if ptr.Kind() != reflect.Pointer {
+ s.errorString("type not a pointer: " + val.Type().String())
+ return
+ }
+ switch v := ptr.Elem(); v.Kind() {
+ case reflect.Bool:
+ v.SetBool(s.scanBool(verb))
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ v.SetInt(s.scanInt(verb, v.Type().Bits()))
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ v.SetUint(s.scanUint(verb, v.Type().Bits()))
+ case reflect.String:
+ v.SetString(s.convertString(verb))
+ case reflect.Slice:
+ // For now, can only handle (renamed) []byte.
+ typ := v.Type()
+ if typ.Elem().Kind() != reflect.Uint8 {
+ s.errorString("can't scan type: " + val.Type().String())
+ }
+ str := s.convertString(verb)
+ v.Set(reflect.MakeSlice(typ, len(str), len(str)))
+ for i := 0; i < len(str); i++ {
+ v.Index(i).SetUint(uint64(str[i]))
+ }
+ case reflect.Float32, reflect.Float64:
+ s.SkipSpace()
+ s.notEOF()
+ v.SetFloat(s.convertFloat(s.floatToken(), v.Type().Bits()))
+ case reflect.Complex64, reflect.Complex128:
+ v.SetComplex(s.scanComplex(verb, v.Type().Bits()))
+ default:
+ s.errorString("can't scan type: " + val.Type().String())
+ }
+ }
+}
+
+// errorHandler turns local panics into error returns.
+func errorHandler(errp *error) {
+ if e := recover(); e != nil {
+ if se, ok := e.(scanError); ok { // catch local error
+ *errp = se.err
+ } else if eof, ok := e.(error); ok && eof == io.EOF { // out of input
+ *errp = eof
+ } else {
+ panic(e)
+ }
+ }
+}
+
+// doScan does the real work for scanning without a format string.
+func (s *ss) doScan(a []any) (numProcessed int, err error) {
+ defer errorHandler(&err)
+ for _, arg := range a {
+ s.scanOne('v', arg)
+ numProcessed++
+ }
+ // Check for newline (or EOF) if required (Scanln etc.).
+ if s.nlIsEnd {
+ for {
+ r := s.getRune()
+ if r == '\n' || r == eof {
+ break
+ }
+ if !isSpace(r) {
+ s.errorString("expected newline")
+ break
+ }
+ }
+ }
+ return
+}
+
+// advance determines whether the next characters in the input match
+// those of the format. It returns the number of bytes (sic) consumed
+// in the format. All runs of space characters in either input or
+// format behave as a single space. Newlines are special, though:
+// newlines in the format must match those in the input and vice versa.
+// This routine also handles the %% case. If the return value is zero,
+// either format starts with a % (with no following %) or the input
+// is empty. If it is negative, the input did not match the string.
+func (s *ss) advance(format string) (i int) {
+ for i < len(format) {
+ fmtc, w := utf8.DecodeRuneInString(format[i:])
+
+ // Space processing.
+ // In the rest of this comment "space" means spaces other than newline.
+ // Newline in the format matches input of zero or more spaces and then newline or end-of-input.
+ // Spaces in the format before the newline are collapsed into the newline.
+ // Spaces in the format after the newline match zero or more spaces after the corresponding input newline.
+ // Other spaces in the format match input of one or more spaces or end-of-input.
+ if isSpace(fmtc) {
+ newlines := 0
+ trailingSpace := false
+ for isSpace(fmtc) && i < len(format) {
+ if fmtc == '\n' {
+ newlines++
+ trailingSpace = false
+ } else {
+ trailingSpace = true
+ }
+ i += w
+ fmtc, w = utf8.DecodeRuneInString(format[i:])
+ }
+ for j := 0; j < newlines; j++ {
+ inputc := s.getRune()
+ for isSpace(inputc) && inputc != '\n' {
+ inputc = s.getRune()
+ }
+ if inputc != '\n' && inputc != eof {
+ s.errorString("newline in format does not match input")
+ }
+ }
+ if trailingSpace {
+ inputc := s.getRune()
+ if newlines == 0 {
+ // If the trailing space stood alone (did not follow a newline),
+ // it must find at least one space to consume.
+ if !isSpace(inputc) && inputc != eof {
+ s.errorString("expected space in input to match format")
+ }
+ if inputc == '\n' {
+ s.errorString("newline in input does not match format")
+ }
+ }
+ for isSpace(inputc) && inputc != '\n' {
+ inputc = s.getRune()
+ }
+ if inputc != eof {
+ s.UnreadRune()
+ }
+ }
+ continue
+ }
+
+ // Verbs.
+ if fmtc == '%' {
+ // % at end of string is an error.
+ if i+w == len(format) {
+ s.errorString("missing verb: % at end of format string")
+ }
+ // %% acts like a real percent
+ nextc, _ := utf8.DecodeRuneInString(format[i+w:]) // will not match % if string is empty
+ if nextc != '%' {
+ return
+ }
+ i += w // skip the first %
+ }
+
+ // Literals.
+ inputc := s.mustReadRune()
+ if fmtc != inputc {
+ s.UnreadRune()
+ return -1
+ }
+ i += w
+ }
+ return
+}
+
+// doScanf does the real work when scanning with a format string.
+// At the moment, it handles only pointers to basic types.
+func (s *ss) doScanf(format string, a []any) (numProcessed int, err error) {
+ defer errorHandler(&err)
+ end := len(format) - 1
+ // We process one item per non-trivial format
+ for i := 0; i <= end; {
+ w := s.advance(format[i:])
+ if w > 0 {
+ i += w
+ continue
+ }
+ // Either we failed to advance, we have a percent character, or we ran out of input.
+ if format[i] != '%' {
+ // Can't advance format. Why not?
+ if w < 0 {
+ s.errorString("input does not match format")
+ }
+ // Otherwise at EOF; "too many operands" error handled below
+ break
+ }
+ i++ // % is one byte
+
+ // do we have 20 (width)?
+ var widPresent bool
+ s.maxWid, widPresent, i = parsenum(format, i, end)
+ if !widPresent {
+ s.maxWid = hugeWid
+ }
+
+ c, w := utf8.DecodeRuneInString(format[i:])
+ i += w
+
+ if c != 'c' {
+ s.SkipSpace()
+ }
+ if c == '%' {
+ s.scanPercent()
+ continue // Do not consume an argument.
+ }
+ s.argLimit = s.limit
+ if f := s.count + s.maxWid; f < s.argLimit {
+ s.argLimit = f
+ }
+
+ if numProcessed >= len(a) { // out of operands
+ s.errorString("too few operands for format '%" + format[i-w:] + "'")
+ break
+ }
+ arg := a[numProcessed]
+
+ s.scanOne(c, arg)
+ numProcessed++
+ s.argLimit = s.limit
+ }
+ if numProcessed < len(a) {
+ s.errorString("too many operands")
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/scan_test.go b/platform/dbops/binaries/go/go/src/fmt/scan_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a4f80c23c2410063f25c212e6227f01c9a9553f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/scan_test.go
@@ -0,0 +1,1334 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fmt_test
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ . "fmt"
+ "io"
+ "math"
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+ "testing/iotest"
+ "unicode/utf8"
+)
+
+type ScanTest struct {
+ text string
+ in any
+ out any
+}
+
+type ScanfTest struct {
+ format string
+ text string
+ in any
+ out any
+}
+
+type ScanfMultiTest struct {
+ format string
+ text string
+ in []any
+ out []any
+ err string
+}
+
+var (
+ boolVal bool
+ intVal int
+ int8Val int8
+ int16Val int16
+ int32Val int32
+ int64Val int64
+ uintVal uint
+ uint8Val uint8
+ uint16Val uint16
+ uint32Val uint32
+ uint64Val uint64
+ uintptrVal uintptr
+ float32Val float32
+ float64Val float64
+ stringVal string
+ bytesVal []byte
+ runeVal rune
+ complex64Val complex64
+ complex128Val complex128
+ renamedBoolVal renamedBool
+ renamedIntVal renamedInt
+ renamedInt8Val renamedInt8
+ renamedInt16Val renamedInt16
+ renamedInt32Val renamedInt32
+ renamedInt64Val renamedInt64
+ renamedUintVal renamedUint
+ renamedUint8Val renamedUint8
+ renamedUint16Val renamedUint16
+ renamedUint32Val renamedUint32
+ renamedUint64Val renamedUint64
+ renamedUintptrVal renamedUintptr
+ renamedStringVal renamedString
+ renamedBytesVal renamedBytes
+ renamedFloat32Val renamedFloat32
+ renamedFloat64Val renamedFloat64
+ renamedComplex64Val renamedComplex64
+ renamedComplex128Val renamedComplex128
+)
+
+// Xs accepts any non-empty run of the verb character
+type Xs string
+
+func (x *Xs) Scan(state ScanState, verb rune) error {
+ tok, err := state.Token(true, func(r rune) bool { return r == verb })
+ if err != nil {
+ return err
+ }
+ s := string(tok)
+ if !regexp.MustCompile("^" + string(verb) + "+$").MatchString(s) {
+ return errors.New("syntax error for xs")
+ }
+ *x = Xs(s)
+ return nil
+}
+
+var xVal Xs
+
+// IntString accepts an integer followed immediately by a string.
+// It tests the embedding of a scan within a scan.
+type IntString struct {
+ i int
+ s string
+}
+
+func (s *IntString) Scan(state ScanState, verb rune) error {
+ if _, err := Fscan(state, &s.i); err != nil {
+ return err
+ }
+
+ tok, err := state.Token(true, nil)
+ if err != nil {
+ return err
+ }
+ s.s = string(tok)
+ return nil
+}
+
+var intStringVal IntString
+
+var scanTests = []ScanTest{
+ // Basic types
+ {"T\n", &boolVal, true}, // boolean test vals toggle to be sure they are written
+ {"F\n", &boolVal, false}, // restored to zero value
+ {"21\n", &intVal, 21},
+ {"2_1\n", &intVal, 21},
+ {"0\n", &intVal, 0},
+ {"000\n", &intVal, 0},
+ {"0x10\n", &intVal, 0x10},
+ {"0x_1_0\n", &intVal, 0x10},
+ {"-0x10\n", &intVal, -0x10},
+ {"0377\n", &intVal, 0377},
+ {"0_3_7_7\n", &intVal, 0377},
+ {"0o377\n", &intVal, 0377},
+ {"0o_3_7_7\n", &intVal, 0377},
+ {"-0377\n", &intVal, -0377},
+ {"-0o377\n", &intVal, -0377},
+ {"0\n", &uintVal, uint(0)},
+ {"000\n", &uintVal, uint(0)},
+ {"0x10\n", &uintVal, uint(0x10)},
+ {"0377\n", &uintVal, uint(0377)},
+ {"22\n", &int8Val, int8(22)},
+ {"23\n", &int16Val, int16(23)},
+ {"24\n", &int32Val, int32(24)},
+ {"25\n", &int64Val, int64(25)},
+ {"127\n", &int8Val, int8(127)},
+ {"-21\n", &intVal, -21},
+ {"-22\n", &int8Val, int8(-22)},
+ {"-23\n", &int16Val, int16(-23)},
+ {"-24\n", &int32Val, int32(-24)},
+ {"-25\n", &int64Val, int64(-25)},
+ {"-128\n", &int8Val, int8(-128)},
+ {"+21\n", &intVal, +21},
+ {"+22\n", &int8Val, int8(+22)},
+ {"+23\n", &int16Val, int16(+23)},
+ {"+24\n", &int32Val, int32(+24)},
+ {"+25\n", &int64Val, int64(+25)},
+ {"+127\n", &int8Val, int8(+127)},
+ {"26\n", &uintVal, uint(26)},
+ {"27\n", &uint8Val, uint8(27)},
+ {"28\n", &uint16Val, uint16(28)},
+ {"29\n", &uint32Val, uint32(29)},
+ {"30\n", &uint64Val, uint64(30)},
+ {"31\n", &uintptrVal, uintptr(31)},
+ {"255\n", &uint8Val, uint8(255)},
+ {"32767\n", &int16Val, int16(32767)},
+ {"2.3\n", &float64Val, 2.3},
+ {"2.3e1\n", &float32Val, float32(2.3e1)},
+ {"2.3e2\n", &float64Val, 2.3e2},
+ {"2.3p2\n", &float64Val, 2.3 * 4},
+ {"2.3p+2\n", &float64Val, 2.3 * 4},
+ {"2.3p+66\n", &float64Val, 2.3 * (1 << 66)},
+ {"2.3p-66\n", &float64Val, 2.3 / (1 << 66)},
+ {"0x2.3p-66\n", &float64Val, float64(0x23) / (1 << 70)},
+ {"2_3.4_5\n", &float64Val, 23.45},
+ {"2.35\n", &stringVal, "2.35"},
+ {"2345678\n", &bytesVal, []byte("2345678")},
+ {"(3.4e1-2i)\n", &complex128Val, 3.4e1 - 2i},
+ {"-3.45e1-3i\n", &complex64Val, complex64(-3.45e1 - 3i)},
+ {"-.45e1-1e2i\n", &complex128Val, complex128(-.45e1 - 100i)},
+ {"-.4_5e1-1E2i\n", &complex128Val, complex128(-.45e1 - 100i)},
+ {"0x1.0p1+0x1.0P2i\n", &complex128Val, complex128(2 + 4i)},
+ {"-0x1p1-0x1p2i\n", &complex128Val, complex128(-2 - 4i)},
+ {"-0x1ep-1-0x1p2i\n", &complex128Val, complex128(-15 - 4i)},
+ {"-0x1_Ep-1-0x1p0_2i\n", &complex128Val, complex128(-15 - 4i)},
+ {"hello\n", &stringVal, "hello"},
+
+ // Carriage-return followed by newline. (We treat \r\n as \n always.)
+ {"hello\r\n", &stringVal, "hello"},
+ {"27\r\n", &uint8Val, uint8(27)},
+
+ // Renamed types
+ {"true\n", &renamedBoolVal, renamedBool(true)},
+ {"F\n", &renamedBoolVal, renamedBool(false)},
+ {"101\n", &renamedIntVal, renamedInt(101)},
+ {"102\n", &renamedIntVal, renamedInt(102)},
+ {"103\n", &renamedUintVal, renamedUint(103)},
+ {"104\n", &renamedUintVal, renamedUint(104)},
+ {"105\n", &renamedInt8Val, renamedInt8(105)},
+ {"106\n", &renamedInt16Val, renamedInt16(106)},
+ {"107\n", &renamedInt32Val, renamedInt32(107)},
+ {"108\n", &renamedInt64Val, renamedInt64(108)},
+ {"109\n", &renamedUint8Val, renamedUint8(109)},
+ {"110\n", &renamedUint16Val, renamedUint16(110)},
+ {"111\n", &renamedUint32Val, renamedUint32(111)},
+ {"112\n", &renamedUint64Val, renamedUint64(112)},
+ {"113\n", &renamedUintptrVal, renamedUintptr(113)},
+ {"114\n", &renamedStringVal, renamedString("114")},
+ {"115\n", &renamedBytesVal, renamedBytes([]byte("115"))},
+
+ // Custom scanners.
+ {" vvv ", &xVal, Xs("vvv")},
+ {" 1234hello", &intStringVal, IntString{1234, "hello"}},
+
+ // Fixed bugs
+ {"2147483648\n", &int64Val, int64(2147483648)}, // was: integer overflow
+}
+
+var scanfTests = []ScanfTest{
+ {"%v", "TRUE\n", &boolVal, true},
+ {"%t", "false\n", &boolVal, false},
+ {"%v", "-71\n", &intVal, -71},
+ {"%v", "-7_1\n", &intVal, -71},
+ {"%v", "0b111\n", &intVal, 7},
+ {"%v", "0b_1_1_1\n", &intVal, 7},
+ {"%v", "0377\n", &intVal, 0377},
+ {"%v", "0_3_7_7\n", &intVal, 0377},
+ {"%v", "0o377\n", &intVal, 0377},
+ {"%v", "0o_3_7_7\n", &intVal, 0377},
+ {"%v", "0x44\n", &intVal, 0x44},
+ {"%v", "0x_4_4\n", &intVal, 0x44},
+ {"%d", "72\n", &intVal, 72},
+ {"%c", "a\n", &runeVal, 'a'},
+ {"%c", "\u5072\n", &runeVal, '\u5072'},
+ {"%c", "\u1234\n", &runeVal, '\u1234'},
+ {"%d", "73\n", &int8Val, int8(73)},
+ {"%d", "+74\n", &int16Val, int16(74)},
+ {"%d", "75\n", &int32Val, int32(75)},
+ {"%d", "76\n", &int64Val, int64(76)},
+ {"%b", "1001001\n", &intVal, 73},
+ {"%o", "075\n", &intVal, 075},
+ {"%x", "a75\n", &intVal, 0xa75},
+ {"%v", "71\n", &uintVal, uint(71)},
+ {"%d", "72\n", &uintVal, uint(72)},
+ {"%d", "7_2\n", &uintVal, uint(7)}, // only %v takes underscores
+ {"%d", "73\n", &uint8Val, uint8(73)},
+ {"%d", "74\n", &uint16Val, uint16(74)},
+ {"%d", "75\n", &uint32Val, uint32(75)},
+ {"%d", "76\n", &uint64Val, uint64(76)},
+ {"%d", "77\n", &uintptrVal, uintptr(77)},
+ {"%b", "1001001\n", &uintVal, uint(73)},
+ {"%b", "100_1001\n", &uintVal, uint(4)},
+ {"%o", "075\n", &uintVal, uint(075)},
+ {"%o", "07_5\n", &uintVal, uint(07)}, // only %v takes underscores
+ {"%x", "a75\n", &uintVal, uint(0xa75)},
+ {"%x", "A75\n", &uintVal, uint(0xa75)},
+ {"%x", "A7_5\n", &uintVal, uint(0xa7)}, // only %v takes underscores
+ {"%U", "U+1234\n", &intVal, int(0x1234)},
+ {"%U", "U+4567\n", &uintVal, uint(0x4567)},
+
+ {"%e", "2.3\n", &float64Val, 2.3},
+ {"%E", "2.3e1\n", &float32Val, float32(2.3e1)},
+ {"%f", "2.3e2\n", &float64Val, 2.3e2},
+ {"%g", "2.3p2\n", &float64Val, 2.3 * 4},
+ {"%G", "2.3p+2\n", &float64Val, 2.3 * 4},
+ {"%v", "2.3p+66\n", &float64Val, 2.3 * (1 << 66)},
+ {"%f", "2.3p-66\n", &float64Val, 2.3 / (1 << 66)},
+ {"%G", "0x2.3p-66\n", &float64Val, float64(0x23) / (1 << 70)},
+ {"%E", "2_3.4_5\n", &float64Val, 23.45},
+
+ // Strings
+ {"%s", "using-%s\n", &stringVal, "using-%s"},
+ {"%x", "7573696e672d2578\n", &stringVal, "using-%x"},
+ {"%X", "7573696E672D2558\n", &stringVal, "using-%X"},
+ {"%q", `"quoted\twith\\do\u0075bl\x65s"` + "\n", &stringVal, "quoted\twith\\doubles"},
+ {"%q", "`quoted with backs`\n", &stringVal, "quoted with backs"},
+
+ // Byte slices
+ {"%s", "bytes-%s\n", &bytesVal, []byte("bytes-%s")},
+ {"%x", "62797465732d2578\n", &bytesVal, []byte("bytes-%x")},
+ {"%X", "62797465732D2558\n", &bytesVal, []byte("bytes-%X")},
+ {"%q", `"bytes\rwith\vdo\u0075bl\x65s"` + "\n", &bytesVal, []byte("bytes\rwith\vdoubles")},
+ {"%q", "`bytes with backs`\n", &bytesVal, []byte("bytes with backs")},
+
+ // Renamed types
+ {"%v\n", "true\n", &renamedBoolVal, renamedBool(true)},
+ {"%t\n", "F\n", &renamedBoolVal, renamedBool(false)},
+ {"%v", "101\n", &renamedIntVal, renamedInt(101)},
+ {"%c", "\u0101\n", &renamedIntVal, renamedInt('\u0101')},
+ {"%o", "0146\n", &renamedIntVal, renamedInt(102)},
+ {"%v", "103\n", &renamedUintVal, renamedUint(103)},
+ {"%d", "104\n", &renamedUintVal, renamedUint(104)},
+ {"%d", "105\n", &renamedInt8Val, renamedInt8(105)},
+ {"%d", "106\n", &renamedInt16Val, renamedInt16(106)},
+ {"%d", "107\n", &renamedInt32Val, renamedInt32(107)},
+ {"%d", "108\n", &renamedInt64Val, renamedInt64(108)},
+ {"%x", "6D\n", &renamedUint8Val, renamedUint8(109)},
+ {"%o", "0156\n", &renamedUint16Val, renamedUint16(110)},
+ {"%d", "111\n", &renamedUint32Val, renamedUint32(111)},
+ {"%d", "112\n", &renamedUint64Val, renamedUint64(112)},
+ {"%d", "113\n", &renamedUintptrVal, renamedUintptr(113)},
+ {"%s", "114\n", &renamedStringVal, renamedString("114")},
+ {"%q", "\"1155\"\n", &renamedBytesVal, renamedBytes([]byte("1155"))},
+ {"%g", "116e1\n", &renamedFloat32Val, renamedFloat32(116e1)},
+ {"%g", "-11.7e+1", &renamedFloat64Val, renamedFloat64(-11.7e+1)},
+ {"%g", "11+6e1i\n", &renamedComplex64Val, renamedComplex64(11 + 6e1i)},
+ {"%g", "-11.+7e+1i", &renamedComplex128Val, renamedComplex128(-11. + 7e+1i)},
+
+ // Interesting formats
+ {"here is\tthe value:%d", "here is the\tvalue:118\n", &intVal, 118},
+ {"%% %%:%d", "% %:119\n", &intVal, 119},
+ {"%d%%", "42%", &intVal, 42}, // %% at end of string.
+
+ // Corner cases
+ {"%x", "FFFFFFFF\n", &uint32Val, uint32(0xFFFFFFFF)},
+
+ // Custom scanner.
+ {"%s", " sss ", &xVal, Xs("sss")},
+ {"%2s", "sssss", &xVal, Xs("ss")},
+
+ // Fixed bugs
+ {"%d\n", "27\n", &intVal, 27}, // ok
+ {"%d\n", "28 \n", &intVal, 28}, // was: "unexpected newline"
+ {"%v", "0", &intVal, 0}, // was: "EOF"; 0 was taken as base prefix and not counted.
+ {"%v", "0", &uintVal, uint(0)}, // was: "EOF"; 0 was taken as base prefix and not counted.
+ {"%c", " ", &uintVal, uint(' ')}, // %c must accept a blank.
+ {"%c", "\t", &uintVal, uint('\t')}, // %c must accept any space.
+ {"%c", "\n", &uintVal, uint('\n')}, // %c must accept any space.
+ {"%d%%", "23%\n", &uintVal, uint(23)}, // %% matches literal %.
+ {"%%%d", "%23\n", &uintVal, uint(23)}, // %% matches literal %.
+
+ // space handling
+ {"%d", "27", &intVal, 27},
+ {"%d", "27 ", &intVal, 27},
+ {"%d", " 27", &intVal, 27},
+ {"%d", " 27 ", &intVal, 27},
+
+ {"X%d", "X27", &intVal, 27},
+ {"X%d", "X27 ", &intVal, 27},
+ {"X%d", "X 27", &intVal, 27},
+ {"X%d", "X 27 ", &intVal, 27},
+
+ {"X %d", "X27", &intVal, nil}, // expected space in input to match format
+ {"X %d", "X27 ", &intVal, nil}, // expected space in input to match format
+ {"X %d", "X 27", &intVal, 27},
+ {"X %d", "X 27 ", &intVal, 27},
+
+ {"%dX", "27X", &intVal, 27},
+ {"%dX", "27 X", &intVal, nil}, // input does not match format
+ {"%dX", " 27X", &intVal, 27},
+ {"%dX", " 27 X", &intVal, nil}, // input does not match format
+
+ {"%d X", "27X", &intVal, nil}, // expected space in input to match format
+ {"%d X", "27 X", &intVal, 27},
+ {"%d X", " 27X", &intVal, nil}, // expected space in input to match format
+ {"%d X", " 27 X", &intVal, 27},
+
+ {"X %d X", "X27X", &intVal, nil}, // expected space in input to match format
+ {"X %d X", "X27 X", &intVal, nil}, // expected space in input to match format
+ {"X %d X", "X 27X", &intVal, nil}, // expected space in input to match format
+ {"X %d X", "X 27 X", &intVal, 27},
+
+ {"X %s X", "X27X", &stringVal, nil}, // expected space in input to match format
+ {"X %s X", "X27 X", &stringVal, nil}, // expected space in input to match format
+ {"X %s X", "X 27X", &stringVal, nil}, // unexpected EOF
+ {"X %s X", "X 27 X", &stringVal, "27"},
+
+ {"X%sX", "X27X", &stringVal, nil}, // unexpected EOF
+ {"X%sX", "X27 X", &stringVal, nil}, // input does not match format
+ {"X%sX", "X 27X", &stringVal, nil}, // unexpected EOF
+ {"X%sX", "X 27 X", &stringVal, nil}, // input does not match format
+
+ {"X%s", "X27", &stringVal, "27"},
+ {"X%s", "X27 ", &stringVal, "27"},
+ {"X%s", "X 27", &stringVal, "27"},
+ {"X%s", "X 27 ", &stringVal, "27"},
+
+ {"X%dX", "X27X", &intVal, 27},
+ {"X%dX", "X27 X", &intVal, nil}, // input does not match format
+ {"X%dX", "X 27X", &intVal, 27},
+ {"X%dX", "X 27 X", &intVal, nil}, // input does not match format
+
+ {"X%dX", "X27X", &intVal, 27},
+ {"X%dX", "X27X ", &intVal, 27},
+ {"X%dX", " X27X", &intVal, nil}, // input does not match format
+ {"X%dX", " X27X ", &intVal, nil}, // input does not match format
+
+ {"X%dX\n", "X27X", &intVal, 27},
+ {"X%dX \n", "X27X ", &intVal, 27},
+ {"X%dX\n", "X27X\n", &intVal, 27},
+ {"X%dX\n", "X27X \n", &intVal, 27},
+
+ {"X%dX \n", "X27X", &intVal, 27},
+ {"X%dX \n", "X27X ", &intVal, 27},
+ {"X%dX \n", "X27X\n", &intVal, 27},
+ {"X%dX \n", "X27X \n", &intVal, 27},
+
+ {"X%c", "X\n", &runeVal, '\n'},
+ {"X%c", "X \n", &runeVal, ' '},
+ {"X %c", "X!", &runeVal, nil}, // expected space in input to match format
+ {"X %c", "X\n", &runeVal, nil}, // newline in input does not match format
+ {"X %c", "X !", &runeVal, '!'},
+ {"X %c", "X \n", &runeVal, '\n'},
+
+ {" X%dX", "X27X", &intVal, nil}, // expected space in input to match format
+ {" X%dX", "X27X ", &intVal, nil}, // expected space in input to match format
+ {" X%dX", " X27X", &intVal, 27},
+ {" X%dX", " X27X ", &intVal, 27},
+
+ {"X%dX ", "X27X", &intVal, 27},
+ {"X%dX ", "X27X ", &intVal, 27},
+ {"X%dX ", " X27X", &intVal, nil}, // input does not match format
+ {"X%dX ", " X27X ", &intVal, nil}, // input does not match format
+
+ {" X%dX ", "X27X", &intVal, nil}, // expected space in input to match format
+ {" X%dX ", "X27X ", &intVal, nil}, // expected space in input to match format
+ {" X%dX ", " X27X", &intVal, 27},
+ {" X%dX ", " X27X ", &intVal, 27},
+
+ {"%d\nX", "27\nX", &intVal, 27},
+ {"%dX\n X", "27X\n X", &intVal, 27},
+}
+
+var overflowTests = []ScanTest{
+ {"128", &int8Val, 0},
+ {"32768", &int16Val, 0},
+ {"-129", &int8Val, 0},
+ {"-32769", &int16Val, 0},
+ {"256", &uint8Val, 0},
+ {"65536", &uint16Val, 0},
+ {"1e100", &float32Val, 0},
+ {"1e500", &float64Val, 0},
+ {"(1e100+0i)", &complex64Val, 0},
+ {"(1+1e100i)", &complex64Val, 0},
+ {"(1-1e500i)", &complex128Val, 0},
+}
+
+var truth bool
+var i, j, k int
+var f float64
+var s, t string
+var c complex128
+var x, y Xs
+var z IntString
+var r1, r2, r3 rune
+
+var multiTests = []ScanfMultiTest{
+ {"", "", []any{}, []any{}, ""},
+ {"%d", "23", args(&i), args(23), ""},
+ {"%2s%3s", "22333", args(&s, &t), args("22", "333"), ""},
+ {"%2d%3d", "44555", args(&i, &j), args(44, 555), ""},
+ {"%2d.%3d", "66.777", args(&i, &j), args(66, 777), ""},
+ {"%d, %d", "23, 18", args(&i, &j), args(23, 18), ""},
+ {"%3d22%3d", "33322333", args(&i, &j), args(333, 333), ""},
+ {"%6vX=%3fY", "3+2iX=2.5Y", args(&c, &f), args((3 + 2i), 2.5), ""},
+ {"%d%s", "123abc", args(&i, &s), args(123, "abc"), ""},
+ {"%c%c%c", "2\u50c2X", args(&r1, &r2, &r3), args('2', '\u50c2', 'X'), ""},
+ {"%5s%d", " 1234567 ", args(&s, &i), args("12345", 67), ""},
+ {"%5s%d", " 12 34 567 ", args(&s, &i), args("12", 34), ""},
+
+ // Custom scanners.
+ {"%e%f", "eefffff", args(&x, &y), args(Xs("ee"), Xs("fffff")), ""},
+ {"%4v%s", "12abcd", args(&z, &s), args(IntString{12, "ab"}, "cd"), ""},
+
+ // Errors
+ {"%t", "23 18", args(&i), nil, "bad verb"},
+ {"%d %d %d", "23 18", args(&i, &j), args(23, 18), "too few operands"},
+ {"%d %d", "23 18 27", args(&i, &j, &k), args(23, 18), "too many operands"},
+ {"%c", "\u0100", args(&int8Val), nil, "overflow"},
+ {"X%d", "10X", args(&intVal), nil, "input does not match format"},
+ {"%d%", "42%", args(&intVal), args(42), "missing verb: % at end of format string"},
+ {"%d% ", "42%", args(&intVal), args(42), "too few operands for format '% '"}, // Slightly odd error, but correct.
+ {"%%%d", "xxx 42", args(&intVal), args(42), "missing literal %"},
+ {"%%%d", "x42", args(&intVal), args(42), "missing literal %"},
+ {"%%%d", "42", args(&intVal), args(42), "missing literal %"},
+
+ // Bad UTF-8: should see every byte.
+ {"%c%c%c", "\xc2X\xc2", args(&r1, &r2, &r3), args(utf8.RuneError, 'X', utf8.RuneError), ""},
+
+ // Fixed bugs
+ {"%v%v", "FALSE23", args(&truth, &i), args(false, 23), ""},
+}
+
+var readers = []struct {
+ name string
+ f func(string) io.Reader
+}{
+ {"StringReader", func(s string) io.Reader {
+ return strings.NewReader(s)
+ }},
+ {"ReaderOnly", func(s string) io.Reader {
+ return struct{ io.Reader }{strings.NewReader(s)}
+ }},
+ {"OneByteReader", func(s string) io.Reader {
+ return iotest.OneByteReader(strings.NewReader(s))
+ }},
+ {"DataErrReader", func(s string) io.Reader {
+ return iotest.DataErrReader(strings.NewReader(s))
+ }},
+}
+
+func testScan(t *testing.T, f func(string) io.Reader, scan func(r io.Reader, a ...any) (int, error)) {
+ for _, test := range scanTests {
+ r := f(test.text)
+ n, err := scan(r, test.in)
+ if err != nil {
+ m := ""
+ if n > 0 {
+ m = Sprintf(" (%d fields ok)", n)
+ }
+ t.Errorf("got error scanning %q: %s%s", test.text, err, m)
+ continue
+ }
+ if n != 1 {
+ t.Errorf("count error on entry %q: got %d", test.text, n)
+ continue
+ }
+ // The incoming value may be a pointer
+ v := reflect.ValueOf(test.in)
+ if p := v; p.Kind() == reflect.Pointer {
+ v = p.Elem()
+ }
+ val := v.Interface()
+ if !reflect.DeepEqual(val, test.out) {
+ t.Errorf("scanning %q: expected %#v got %#v, type %T", test.text, test.out, val, val)
+ }
+ }
+}
+
+func TestScan(t *testing.T) {
+ for _, r := range readers {
+ t.Run(r.name, func(t *testing.T) {
+ testScan(t, r.f, Fscan)
+ })
+ }
+}
+
+func TestScanln(t *testing.T) {
+ for _, r := range readers {
+ t.Run(r.name, func(t *testing.T) {
+ testScan(t, r.f, Fscanln)
+ })
+ }
+}
+
+func TestScanf(t *testing.T) {
+ for _, test := range scanfTests {
+ n, err := Sscanf(test.text, test.format, test.in)
+ if err != nil {
+ if test.out != nil {
+ t.Errorf("Sscanf(%q, %q): unexpected error: %v", test.text, test.format, err)
+ }
+ continue
+ }
+ if test.out == nil {
+ t.Errorf("Sscanf(%q, %q): unexpected success", test.text, test.format)
+ continue
+ }
+ if n != 1 {
+ t.Errorf("Sscanf(%q, %q): parsed %d field, want 1", test.text, test.format, n)
+ continue
+ }
+ // The incoming value may be a pointer
+ v := reflect.ValueOf(test.in)
+ if p := v; p.Kind() == reflect.Pointer {
+ v = p.Elem()
+ }
+ val := v.Interface()
+ if !reflect.DeepEqual(val, test.out) {
+ t.Errorf("Sscanf(%q, %q): parsed value %T(%#v), want %T(%#v)", test.text, test.format, val, val, test.out, test.out)
+ }
+ }
+}
+
+func TestScanOverflow(t *testing.T) {
+ // different machines and different types report errors with different strings.
+ re := regexp.MustCompile("overflow|too large|out of range|not representable")
+ for _, test := range overflowTests {
+ _, err := Sscan(test.text, test.in)
+ if err == nil {
+ t.Errorf("expected overflow scanning %q", test.text)
+ continue
+ }
+ if !re.MatchString(err.Error()) {
+ t.Errorf("expected overflow error scanning %q: %s", test.text, err)
+ }
+ }
+}
+
+func verifyNaN(str string, t *testing.T) {
+ var f float64
+ var f32 float32
+ var f64 float64
+ text := str + " " + str + " " + str
+ n, err := Fscan(strings.NewReader(text), &f, &f32, &f64)
+ if err != nil {
+ t.Errorf("got error scanning %q: %s", text, err)
+ }
+ if n != 3 {
+ t.Errorf("count error scanning %q: got %d", text, n)
+ }
+ if !math.IsNaN(float64(f)) || !math.IsNaN(float64(f32)) || !math.IsNaN(f64) {
+ t.Errorf("didn't get NaNs scanning %q: got %g %g %g", text, f, f32, f64)
+ }
+}
+
+func TestNaN(t *testing.T) {
+ for _, s := range []string{"nan", "NAN", "NaN"} {
+ verifyNaN(s, t)
+ }
+}
+
+func verifyInf(str string, t *testing.T) {
+ var f float64
+ var f32 float32
+ var f64 float64
+ text := str + " " + str + " " + str
+ n, err := Fscan(strings.NewReader(text), &f, &f32, &f64)
+ if err != nil {
+ t.Errorf("got error scanning %q: %s", text, err)
+ }
+ if n != 3 {
+ t.Errorf("count error scanning %q: got %d", text, n)
+ }
+ sign := 1
+ if str[0] == '-' {
+ sign = -1
+ }
+ if !math.IsInf(float64(f), sign) || !math.IsInf(float64(f32), sign) || !math.IsInf(f64, sign) {
+ t.Errorf("didn't get right Infs scanning %q: got %g %g %g", text, f, f32, f64)
+ }
+}
+
+func TestInf(t *testing.T) {
+ for _, s := range []string{"inf", "+inf", "-inf", "INF", "-INF", "+INF", "Inf", "-Inf", "+Inf"} {
+ verifyInf(s, t)
+ }
+}
+
+func testScanfMulti(t *testing.T, f func(string) io.Reader) {
+ sliceType := reflect.TypeOf(make([]any, 1))
+ for _, test := range multiTests {
+ r := f(test.text)
+ n, err := Fscanf(r, test.format, test.in...)
+ if err != nil {
+ if test.err == "" {
+ t.Errorf("got error scanning (%q, %q): %q", test.format, test.text, err)
+ } else if !strings.Contains(err.Error(), test.err) {
+ t.Errorf("got wrong error scanning (%q, %q): %q; expected %q", test.format, test.text, err, test.err)
+ }
+ continue
+ }
+ if test.err != "" {
+ t.Errorf("expected error %q error scanning (%q, %q)", test.err, test.format, test.text)
+ }
+ if n != len(test.out) {
+ t.Errorf("count error on entry (%q, %q): expected %d got %d", test.format, test.text, len(test.out), n)
+ continue
+ }
+ // Convert the slice of pointers into a slice of values
+ resultVal := reflect.MakeSlice(sliceType, n, n)
+ for i := 0; i < n; i++ {
+ v := reflect.ValueOf(test.in[i]).Elem()
+ resultVal.Index(i).Set(v)
+ }
+ result := resultVal.Interface()
+ if !reflect.DeepEqual(result, test.out) {
+ t.Errorf("scanning (%q, %q): expected %#v got %#v", test.format, test.text, test.out, result)
+ }
+ }
+}
+
+func TestScanfMulti(t *testing.T) {
+ for _, r := range readers {
+ t.Run(r.name, func(t *testing.T) {
+ testScanfMulti(t, r.f)
+ })
+ }
+}
+
+func TestScanMultiple(t *testing.T) {
+ var a int
+ var s string
+ n, err := Sscan("123abc", &a, &s)
+ if n != 2 {
+ t.Errorf("Sscan count error: expected 2: got %d", n)
+ }
+ if err != nil {
+ t.Errorf("Sscan expected no error; got %s", err)
+ }
+ if a != 123 || s != "abc" {
+ t.Errorf("Sscan wrong values: got (%d %q) expected (123 \"abc\")", a, s)
+ }
+ n, err = Sscan("asdf", &s, &a)
+ if n != 1 {
+ t.Errorf("Sscan count error: expected 1: got %d", n)
+ }
+ if err == nil {
+ t.Errorf("Sscan expected error; got none: %s", err)
+ }
+ if s != "asdf" {
+ t.Errorf("Sscan wrong values: got %q expected \"asdf\"", s)
+ }
+}
+
+// Empty strings are not valid input when scanning a string.
+func TestScanEmpty(t *testing.T) {
+ var s1, s2 string
+ n, err := Sscan("abc", &s1, &s2)
+ if n != 1 {
+ t.Errorf("Sscan count error: expected 1: got %d", n)
+ }
+ if err == nil {
+ t.Error("Sscan expected error; got none")
+ }
+ if s1 != "abc" {
+ t.Errorf("Sscan wrong values: got %q expected \"abc\"", s1)
+ }
+ n, err = Sscan("", &s1, &s2)
+ if n != 0 {
+ t.Errorf("Sscan count error: expected 0: got %d", n)
+ }
+ if err == nil {
+ t.Error("Sscan expected error; got none")
+ }
+ // Quoted empty string is OK.
+ n, err = Sscanf(`""`, "%q", &s1)
+ if n != 1 {
+ t.Errorf("Sscanf count error: expected 1: got %d", n)
+ }
+ if err != nil {
+ t.Errorf("Sscanf expected no error with quoted string; got %s", err)
+ }
+}
+
+func TestScanNotPointer(t *testing.T) {
+ r := strings.NewReader("1")
+ var a int
+ _, err := Fscan(r, a)
+ if err == nil {
+ t.Error("expected error scanning non-pointer")
+ } else if !strings.Contains(err.Error(), "pointer") {
+ t.Errorf("expected pointer error scanning non-pointer, got: %s", err)
+ }
+}
+
+func TestScanlnNoNewline(t *testing.T) {
+ var a int
+ _, err := Sscanln("1 x\n", &a)
+ if err == nil {
+ t.Error("expected error scanning string missing newline")
+ } else if !strings.Contains(err.Error(), "newline") {
+ t.Errorf("expected newline error scanning string missing newline, got: %s", err)
+ }
+}
+
+func TestScanlnWithMiddleNewline(t *testing.T) {
+ r := strings.NewReader("123\n456\n")
+ var a, b int
+ _, err := Fscanln(r, &a, &b)
+ if err == nil {
+ t.Error("expected error scanning string with extra newline")
+ } else if !strings.Contains(err.Error(), "newline") {
+ t.Errorf("expected newline error scanning string with extra newline, got: %s", err)
+ }
+}
+
+// eofCounter is a special Reader that counts reads at end of file.
+type eofCounter struct {
+ reader *strings.Reader
+ eofCount int
+}
+
+func (ec *eofCounter) Read(b []byte) (n int, err error) {
+ n, err = ec.reader.Read(b)
+ if n == 0 {
+ ec.eofCount++
+ }
+ return
+}
+
+// TestEOF verifies that when we scan, we see at most EOF once per call to a
+// Scan function, and then only when it's really an EOF.
+func TestEOF(t *testing.T) {
+ ec := &eofCounter{strings.NewReader("123\n"), 0}
+ var a int
+ n, err := Fscanln(ec, &a)
+ if err != nil {
+ t.Error("unexpected error", err)
+ }
+ if n != 1 {
+ t.Error("expected to scan one item, got", n)
+ }
+ if ec.eofCount != 0 {
+ t.Error("expected zero EOFs", ec.eofCount)
+ ec.eofCount = 0 // reset for next test
+ }
+ n, err = Fscanln(ec, &a)
+ if err == nil {
+ t.Error("expected error scanning empty string")
+ }
+ if n != 0 {
+ t.Error("expected to scan zero items, got", n)
+ }
+ if ec.eofCount != 1 {
+ t.Error("expected one EOF, got", ec.eofCount)
+ }
+}
+
+// TestEOFAtEndOfInput verifies that we see an EOF error if we run out of input.
+// This was a buglet: we used to get "expected integer".
+func TestEOFAtEndOfInput(t *testing.T) {
+ var i, j int
+ n, err := Sscanf("23", "%d %d", &i, &j)
+ if n != 1 || i != 23 {
+ t.Errorf("Sscanf expected one value of 23; got %d %d", n, i)
+ }
+ if err != io.EOF {
+ t.Errorf("Sscanf expected EOF; got %q", err)
+ }
+ n, err = Sscan("234", &i, &j)
+ if n != 1 || i != 234 {
+ t.Errorf("Sscan expected one value of 234; got %d %d", n, i)
+ }
+ if err != io.EOF {
+ t.Errorf("Sscan expected EOF; got %q", err)
+ }
+ // Trailing space is tougher.
+ n, err = Sscan("234 ", &i, &j)
+ if n != 1 || i != 234 {
+ t.Errorf("Sscan expected one value of 234; got %d %d", n, i)
+ }
+ if err != io.EOF {
+ t.Errorf("Sscan expected EOF; got %q", err)
+ }
+}
+
+var eofTests = []struct {
+ format string
+ v any
+}{
+ {"%s", &stringVal},
+ {"%q", &stringVal},
+ {"%x", &stringVal},
+ {"%v", &stringVal},
+ {"%v", &bytesVal},
+ {"%v", &intVal},
+ {"%v", &uintVal},
+ {"%v", &boolVal},
+ {"%v", &float32Val},
+ {"%v", &complex64Val},
+ {"%v", &renamedStringVal},
+ {"%v", &renamedBytesVal},
+ {"%v", &renamedIntVal},
+ {"%v", &renamedUintVal},
+ {"%v", &renamedBoolVal},
+ {"%v", &renamedFloat32Val},
+ {"%v", &renamedComplex64Val},
+}
+
+func TestEOFAllTypes(t *testing.T) {
+ for i, test := range eofTests {
+ if _, err := Sscanf("", test.format, test.v); err != io.EOF {
+ t.Errorf("#%d: %s %T not eof on empty string: %s", i, test.format, test.v, err)
+ }
+ if _, err := Sscanf(" ", test.format, test.v); err != io.EOF {
+ t.Errorf("#%d: %s %T not eof on trailing blanks: %s", i, test.format, test.v, err)
+ }
+ }
+}
+
+// TestUnreadRuneWithBufio verifies that, at least when using bufio, successive
+// calls to Fscan do not lose runes.
+func TestUnreadRuneWithBufio(t *testing.T) {
+ r := bufio.NewReader(strings.NewReader("123αb"))
+ var i int
+ var a string
+ n, err := Fscanf(r, "%d", &i)
+ if n != 1 || err != nil {
+ t.Errorf("reading int expected one item, no errors; got %d %q", n, err)
+ }
+ if i != 123 {
+ t.Errorf("expected 123; got %d", i)
+ }
+ n, err = Fscanf(r, "%s", &a)
+ if n != 1 || err != nil {
+ t.Errorf("reading string expected one item, no errors; got %d %q", n, err)
+ }
+ if a != "αb" {
+ t.Errorf("expected αb; got %q", a)
+ }
+}
+
+type TwoLines string
+
+// Scan attempts to read two lines into the object. Scanln should prevent this
+// because it stops at newline; Scan and Scanf should be fine.
+func (t *TwoLines) Scan(state ScanState, verb rune) error {
+ chars := make([]rune, 0, 100)
+ for nlCount := 0; nlCount < 2; {
+ c, _, err := state.ReadRune()
+ if err != nil {
+ return err
+ }
+ chars = append(chars, c)
+ if c == '\n' {
+ nlCount++
+ }
+ }
+ *t = TwoLines(string(chars))
+ return nil
+}
+
+func TestMultiLine(t *testing.T) {
+ input := "abc\ndef\n"
+ // Sscan should work
+ var tscan TwoLines
+ n, err := Sscan(input, &tscan)
+ if n != 1 {
+ t.Errorf("Sscan: expected 1 item; got %d", n)
+ }
+ if err != nil {
+ t.Errorf("Sscan: expected no error; got %s", err)
+ }
+ if string(tscan) != input {
+ t.Errorf("Sscan: expected %q; got %q", input, tscan)
+ }
+ // Sscanf should work
+ var tscanf TwoLines
+ n, err = Sscanf(input, "%s", &tscanf)
+ if n != 1 {
+ t.Errorf("Sscanf: expected 1 item; got %d", n)
+ }
+ if err != nil {
+ t.Errorf("Sscanf: expected no error; got %s", err)
+ }
+ if string(tscanf) != input {
+ t.Errorf("Sscanf: expected %q; got %q", input, tscanf)
+ }
+ // Sscanln should not work
+ var tscanln TwoLines
+ n, err = Sscanln(input, &tscanln)
+ if n != 0 {
+ t.Errorf("Sscanln: expected 0 items; got %d: %q", n, tscanln)
+ }
+ if err == nil {
+ t.Error("Sscanln: expected error; got none")
+ } else if err != io.ErrUnexpectedEOF {
+ t.Errorf("Sscanln: expected io.ErrUnexpectedEOF (ha!); got %s", err)
+ }
+}
+
+// TestLineByLineFscanf tests that Fscanf does not read past newline. Issue
+// 3481.
+func TestLineByLineFscanf(t *testing.T) {
+ r := struct{ io.Reader }{strings.NewReader("1\n2\n")}
+ var i, j int
+ n, err := Fscanf(r, "%v\n", &i)
+ if n != 1 || err != nil {
+ t.Fatalf("first read: %d %q", n, err)
+ }
+ n, err = Fscanf(r, "%v\n", &j)
+ if n != 1 || err != nil {
+ t.Fatalf("second read: %d %q", n, err)
+ }
+ if i != 1 || j != 2 {
+ t.Errorf("wrong values; wanted 1 2 got %d %d", i, j)
+ }
+}
+
+// TestScanStateCount verifies the correct byte count is returned. Issue 8512.
+
+// runeScanner implements the Scanner interface for TestScanStateCount.
+type runeScanner struct {
+ rune rune
+ size int
+}
+
+func (rs *runeScanner) Scan(state ScanState, verb rune) error {
+ r, size, err := state.ReadRune()
+ rs.rune = r
+ rs.size = size
+ return err
+}
+
+func TestScanStateCount(t *testing.T) {
+ var a, b, c runeScanner
+ n, err := Sscanf("12➂", "%c%c%c", &a, &b, &c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != 3 {
+ t.Fatalf("expected 3 items consumed, got %d", n)
+ }
+ if a.rune != '1' || b.rune != '2' || c.rune != '➂' {
+ t.Errorf("bad scan rune: %q %q %q should be '1' '2' '➂'", a.rune, b.rune, c.rune)
+ }
+ if a.size != 1 || b.size != 1 || c.size != 3 {
+ t.Errorf("bad scan size: %q %q %q should be 1 1 3", a.size, b.size, c.size)
+ }
+}
+
+// RecursiveInt accepts a string matching %d.%d.%d....
+// and parses it into a linked list.
+// It allows us to benchmark recursive descent style scanners.
+type RecursiveInt struct {
+ i int
+ next *RecursiveInt
+}
+
+func (r *RecursiveInt) Scan(state ScanState, verb rune) (err error) {
+ _, err = Fscan(state, &r.i)
+ if err != nil {
+ return
+ }
+ next := new(RecursiveInt)
+ _, err = Fscanf(state, ".%v", next)
+ if err != nil {
+ if err == io.ErrUnexpectedEOF {
+ err = nil
+ }
+ return
+ }
+ r.next = next
+ return
+}
+
+// scanInts performs the same scanning task as RecursiveInt.Scan
+// but without recurring through scanner, so we can compare
+// performance more directly.
+func scanInts(r *RecursiveInt, b *bytes.Buffer) (err error) {
+ r.next = nil
+ _, err = Fscan(b, &r.i)
+ if err != nil {
+ return
+ }
+ c, _, err := b.ReadRune()
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ }
+ return
+ }
+ if c != '.' {
+ return
+ }
+ next := new(RecursiveInt)
+ err = scanInts(next, b)
+ if err == nil {
+ r.next = next
+ }
+ return
+}
+
+func makeInts(n int) []byte {
+ var buf bytes.Buffer
+ Fprintf(&buf, "1")
+ for i := 1; i < n; i++ {
+ Fprintf(&buf, ".%d", i+1)
+ }
+ return buf.Bytes()
+}
+
+func TestScanInts(t *testing.T) {
+ testScanInts(t, scanInts)
+ testScanInts(t, func(r *RecursiveInt, b *bytes.Buffer) (err error) {
+ _, err = Fscan(b, r)
+ return
+ })
+}
+
+// 800 is small enough to not overflow the stack when using gccgo on a
+// platform that does not support split stack.
+const intCount = 800
+
+func testScanInts(t *testing.T, scan func(*RecursiveInt, *bytes.Buffer) error) {
+ r := new(RecursiveInt)
+ ints := makeInts(intCount)
+ buf := bytes.NewBuffer(ints)
+ err := scan(r, buf)
+ if err != nil {
+ t.Error("unexpected error", err)
+ }
+ i := 1
+ for ; r != nil; r = r.next {
+ if r.i != i {
+ t.Fatalf("bad scan: expected %d got %d", i, r.i)
+ }
+ i++
+ }
+ if i-1 != intCount {
+ t.Fatalf("bad scan count: expected %d got %d", intCount, i-1)
+ }
+}
+
+func BenchmarkScanInts(b *testing.B) {
+ b.StopTimer()
+ ints := makeInts(intCount)
+ var r RecursiveInt
+ for i := 0; i < b.N; i++ {
+ buf := bytes.NewBuffer(ints)
+ b.StartTimer()
+ scanInts(&r, buf)
+ b.StopTimer()
+ }
+}
+
+func BenchmarkScanRecursiveInt(b *testing.B) {
+ b.StopTimer()
+ ints := makeInts(intCount)
+ var r RecursiveInt
+ for i := 0; i < b.N; i++ {
+ buf := bytes.NewBuffer(ints)
+ b.StartTimer()
+ Fscan(buf, &r)
+ b.StopTimer()
+ }
+}
+
+func BenchmarkScanRecursiveIntReaderWrapper(b *testing.B) {
+ b.StopTimer()
+ ints := makeInts(intCount)
+ var r RecursiveInt
+ for i := 0; i < b.N; i++ {
+ buf := struct{ io.Reader }{strings.NewReader(string(ints))}
+ b.StartTimer()
+ Fscan(buf, &r)
+ b.StopTimer()
+ }
+}
+
+// Issue 9124.
+// %x on bytes couldn't handle non-space bytes terminating the scan.
+func TestHexBytes(t *testing.T) {
+ var a, b []byte
+ n, err := Sscanf("00010203", "%x", &a)
+ if n != 1 || err != nil {
+ t.Errorf("simple: got count, err = %d, %v; expected 1, nil", n, err)
+ }
+ check := func(msg string, x []byte) {
+ if len(x) != 4 {
+ t.Errorf("%s: bad length %d", msg, len(x))
+ }
+ for i, b := range x {
+ if int(b) != i {
+ t.Errorf("%s: bad x[%d] = %x", msg, i, x[i])
+ }
+ }
+ }
+ check("simple", a)
+ a = nil
+
+ n, err = Sscanf("00010203 00010203", "%x %x", &a, &b)
+ if n != 2 || err != nil {
+ t.Errorf("simple pair: got count, err = %d, %v; expected 2, nil", n, err)
+ }
+ check("simple pair a", a)
+ check("simple pair b", b)
+ a = nil
+ b = nil
+
+ n, err = Sscanf("00010203:", "%x", &a)
+ if n != 1 || err != nil {
+ t.Errorf("colon: got count, err = %d, %v; expected 1, nil", n, err)
+ }
+ check("colon", a)
+ a = nil
+
+ n, err = Sscanf("00010203:00010203", "%x:%x", &a, &b)
+ if n != 2 || err != nil {
+ t.Errorf("colon pair: got count, err = %d, %v; expected 2, nil", n, err)
+ }
+ check("colon pair a", a)
+ check("colon pair b", b)
+ a = nil
+ b = nil
+
+ // This one fails because there is a hex byte after the data,
+ // that is, an odd number of hex input bytes.
+ n, err = Sscanf("000102034:", "%x", &a)
+ if n != 0 || err == nil {
+ t.Errorf("odd count: got count, err = %d, %v; expected 0, error", n, err)
+ }
+}
+
+func TestScanNewlinesAreSpaces(t *testing.T) {
+ var a, b int
+ var tests = []struct {
+ name string
+ text string
+ count int
+ }{
+ {"newlines", "1\n2\n", 2},
+ {"no final newline", "1\n2", 2},
+ {"newlines with spaces ", "1 \n 2 \n", 2},
+ {"no final newline with spaces", "1 \n 2", 2},
+ }
+ for _, test := range tests {
+ n, err := Sscan(test.text, &a, &b)
+ if n != test.count {
+ t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n)
+ }
+ if err != nil {
+ t.Errorf("%s: unexpected error: %s", test.name, err)
+ }
+ }
+}
+
+func TestScanlnNewlinesTerminate(t *testing.T) {
+ var a, b int
+ var tests = []struct {
+ name string
+ text string
+ count int
+ ok bool
+ }{
+ {"one line one item", "1\n", 1, false},
+ {"one line two items with spaces ", " 1 2 \n", 2, true},
+ {"one line two items no newline", " 1 2", 2, true},
+ {"two lines two items", "1\n2\n", 1, false},
+ }
+ for _, test := range tests {
+ n, err := Sscanln(test.text, &a, &b)
+ if n != test.count {
+ t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n)
+ }
+ if test.ok && err != nil {
+ t.Errorf("%s: unexpected error: %s", test.name, err)
+ }
+ if !test.ok && err == nil {
+ t.Errorf("%s: expected error; got none", test.name)
+ }
+ }
+}
+
+func TestScanfNewlineMatchFormat(t *testing.T) {
+ var a, b int
+ var tests = []struct {
+ name string
+ text string
+ format string
+ count int
+ ok bool
+ }{
+ {"newline in both", "1\n2", "%d\n%d\n", 2, true},
+ {"newline in input", "1\n2", "%d %d", 1, false},
+ {"space-newline in input", "1 \n2", "%d %d", 1, false},
+ {"newline in format", "1 2", "%d\n%d", 1, false},
+ {"space-newline in format", "1 2", "%d \n%d", 1, false},
+ {"space-newline in both", "1 \n2", "%d \n%d", 2, true},
+ {"extra space in format", "1\n2", "%d\n %d", 2, true},
+ {"two extra spaces in format", "1\n2", "%d \n %d", 2, true},
+ {"space vs newline 0000", "1\n2", "%d\n%d", 2, true},
+ {"space vs newline 0001", "1\n2", "%d\n %d", 2, true},
+ {"space vs newline 0010", "1\n2", "%d \n%d", 2, true},
+ {"space vs newline 0011", "1\n2", "%d \n %d", 2, true},
+ {"space vs newline 0100", "1\n 2", "%d\n%d", 2, true},
+ {"space vs newline 0101", "1\n 2", "%d\n%d ", 2, true},
+ {"space vs newline 0110", "1\n 2", "%d \n%d", 2, true},
+ {"space vs newline 0111", "1\n 2", "%d \n %d", 2, true},
+ {"space vs newline 1000", "1 \n2", "%d\n%d", 2, true},
+ {"space vs newline 1001", "1 \n2", "%d\n %d", 2, true},
+ {"space vs newline 1010", "1 \n2", "%d \n%d", 2, true},
+ {"space vs newline 1011", "1 \n2", "%d \n %d", 2, true},
+ {"space vs newline 1100", "1 \n 2", "%d\n%d", 2, true},
+ {"space vs newline 1101", "1 \n 2", "%d\n %d", 2, true},
+ {"space vs newline 1110", "1 \n 2", "%d \n%d", 2, true},
+ {"space vs newline 1111", "1 \n 2", "%d \n %d", 2, true},
+ {"space vs newline no-percent 0000", "1\n2", "1\n2", 0, true},
+ {"space vs newline no-percent 0001", "1\n2", "1\n 2", 0, true},
+ {"space vs newline no-percent 0010", "1\n2", "1 \n2", 0, true},
+ {"space vs newline no-percent 0011", "1\n2", "1 \n 2", 0, true},
+ {"space vs newline no-percent 0100", "1\n 2", "1\n2", 0, false}, // fails: space after nl in input but not pattern
+ {"space vs newline no-percent 0101", "1\n 2", "1\n2 ", 0, false}, // fails: space after nl in input but not pattern
+ {"space vs newline no-percent 0110", "1\n 2", "1 \n2", 0, false}, // fails: space after nl in input but not pattern
+ {"space vs newline no-percent 0111", "1\n 2", "1 \n 2", 0, true},
+ {"space vs newline no-percent 1000", "1 \n2", "1\n2", 0, true},
+ {"space vs newline no-percent 1001", "1 \n2", "1\n 2", 0, true},
+ {"space vs newline no-percent 1010", "1 \n2", "1 \n2", 0, true},
+ {"space vs newline no-percent 1011", "1 \n2", "1 \n 2", 0, true},
+ {"space vs newline no-percent 1100", "1 \n 2", "1\n2", 0, false}, // fails: space after nl in input but not pattern
+ {"space vs newline no-percent 1101", "1 \n 2", "1\n 2", 0, true},
+ {"space vs newline no-percent 1110", "1 \n 2", "1 \n2", 0, false}, // fails: space after nl in input but not pattern
+ {"space vs newline no-percent 1111", "1 \n 2", "1 \n 2", 0, true},
+ }
+ for _, test := range tests {
+ var n int
+ var err error
+ if strings.Contains(test.format, "%") {
+ n, err = Sscanf(test.text, test.format, &a, &b)
+ } else {
+ n, err = Sscanf(test.text, test.format)
+ }
+ if n != test.count {
+ t.Errorf("%s: expected to scan %d item(s), scanned %d", test.name, test.count, n)
+ }
+ if test.ok && err != nil {
+ t.Errorf("%s: unexpected error: %s", test.name, err)
+ }
+ if !test.ok && err == nil {
+ t.Errorf("%s: expected error; got none", test.name)
+ }
+ }
+}
+
+// Test for issue 12090: Was unreading at EOF, double-scanning a byte.
+
+type hexBytes [2]byte
+
+func (h *hexBytes) Scan(ss ScanState, verb rune) error {
+ var b []byte
+ _, err := Fscanf(ss, "%4x", &b)
+ if err != nil {
+ panic(err) // Really shouldn't happen.
+ }
+ copy((*h)[:], b)
+ return err
+}
+
+func TestHexByte(t *testing.T) {
+ var h hexBytes
+ n, err := Sscanln("0123\n", &h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != 1 {
+ t.Fatalf("expected 1 item; scanned %d", n)
+ }
+ if h[0] != 0x01 || h[1] != 0x23 {
+ t.Fatalf("expected 0123 got %x", h)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/state_test.go b/platform/dbops/binaries/go/go/src/fmt/state_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..fda660aa3241bbdec6bc81f39913fdd8e8d6b1b9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/state_test.go
@@ -0,0 +1,80 @@
+// 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 fmt_test
+
+import (
+ "fmt"
+ "testing"
+)
+
+type testState struct {
+ width int
+ widthOK bool
+ prec int
+ precOK bool
+ flag map[int]bool
+}
+
+var _ fmt.State = testState{}
+
+func (s testState) Write(b []byte) (n int, err error) {
+ panic("unimplemented")
+}
+
+func (s testState) Width() (wid int, ok bool) {
+ return s.width, s.widthOK
+}
+
+func (s testState) Precision() (prec int, ok bool) {
+ return s.prec, s.precOK
+}
+
+func (s testState) Flag(c int) bool {
+ return s.flag[c]
+}
+
+const NO = -1000
+
+func mkState(w, p int, flags string) testState {
+ s := testState{}
+ if w != NO {
+ s.width = w
+ s.widthOK = true
+ }
+ if p != NO {
+ s.prec = p
+ s.precOK = true
+ }
+ s.flag = make(map[int]bool)
+ for _, c := range flags {
+ s.flag[int(c)] = true
+ }
+ return s
+}
+
+func TestFormatString(t *testing.T) {
+ var tests = []struct {
+ width, prec int
+ flags string
+ result string
+ }{
+ {NO, NO, "", "%x"},
+ {NO, 3, "", "%.3x"},
+ {3, NO, "", "%3x"},
+ {7, 3, "", "%7.3x"},
+ {NO, NO, " +-#0", "% +-#0x"},
+ {7, 3, "+", "%+7.3x"},
+ {7, -3, "-", "%-7.-3x"},
+ {7, 3, " ", "% 7.3x"},
+ {7, 3, "#", "%#7.3x"},
+ {7, 3, "0", "%07.3x"},
+ }
+ for _, test := range tests {
+ got := fmt.FormatString(mkState(test.width, test.prec, test.flags), 'x')
+ if got != test.result {
+ t.Errorf("%v: got %s", test, got)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/stringer_example_test.go b/platform/dbops/binaries/go/go/src/fmt/stringer_example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c77e78809cc56ccdfa0f13aaddeed1a7a58e3abc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/stringer_example_test.go
@@ -0,0 +1,29 @@
+// 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 fmt_test
+
+import (
+ "fmt"
+)
+
+// Animal has a Name and an Age to represent an animal.
+type Animal struct {
+ Name string
+ Age uint
+}
+
+// String makes Animal satisfy the Stringer interface.
+func (a Animal) String() string {
+ return fmt.Sprintf("%v (%d)", a.Name, a.Age)
+}
+
+func ExampleStringer() {
+ a := Animal{
+ Name: "Gopher",
+ Age: 2,
+ }
+ fmt.Println(a)
+ // Output: Gopher (2)
+}
diff --git a/platform/dbops/binaries/go/go/src/fmt/stringer_test.go b/platform/dbops/binaries/go/go/src/fmt/stringer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0ca3f522d622aa7d6b2af6a97f253fa3eca869b5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/fmt/stringer_test.go
@@ -0,0 +1,61 @@
+// 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 fmt_test
+
+import (
+ . "fmt"
+ "testing"
+)
+
+type TI int
+type TI8 int8
+type TI16 int16
+type TI32 int32
+type TI64 int64
+type TU uint
+type TU8 uint8
+type TU16 uint16
+type TU32 uint32
+type TU64 uint64
+type TUI uintptr
+type TF float64
+type TF32 float32
+type TF64 float64
+type TB bool
+type TS string
+
+func (v TI) String() string { return Sprintf("I: %d", int(v)) }
+func (v TI8) String() string { return Sprintf("I8: %d", int8(v)) }
+func (v TI16) String() string { return Sprintf("I16: %d", int16(v)) }
+func (v TI32) String() string { return Sprintf("I32: %d", int32(v)) }
+func (v TI64) String() string { return Sprintf("I64: %d", int64(v)) }
+func (v TU) String() string { return Sprintf("U: %d", uint(v)) }
+func (v TU8) String() string { return Sprintf("U8: %d", uint8(v)) }
+func (v TU16) String() string { return Sprintf("U16: %d", uint16(v)) }
+func (v TU32) String() string { return Sprintf("U32: %d", uint32(v)) }
+func (v TU64) String() string { return Sprintf("U64: %d", uint64(v)) }
+func (v TUI) String() string { return Sprintf("UI: %d", uintptr(v)) }
+func (v TF) String() string { return Sprintf("F: %f", float64(v)) }
+func (v TF32) String() string { return Sprintf("F32: %f", float32(v)) }
+func (v TF64) String() string { return Sprintf("F64: %f", float64(v)) }
+func (v TB) String() string { return Sprintf("B: %t", bool(v)) }
+func (v TS) String() string { return Sprintf("S: %q", string(v)) }
+
+func check(t *testing.T, got, want string) {
+ if got != want {
+ t.Error(got, "!=", want)
+ }
+}
+
+func TestStringer(t *testing.T) {
+ s := Sprintf("%v %v %v %v %v", TI(0), TI8(1), TI16(2), TI32(3), TI64(4))
+ check(t, s, "I: 0 I8: 1 I16: 2 I32: 3 I64: 4")
+ s = Sprintf("%v %v %v %v %v %v", TU(5), TU8(6), TU16(7), TU32(8), TU64(9), TUI(10))
+ check(t, s, "U: 5 U8: 6 U16: 7 U32: 8 U64: 9 UI: 10")
+ s = Sprintf("%v %v %v", TF(1.0), TF32(2.0), TF64(3.0))
+ check(t, s, "F: 1.000000 F32: 2.000000 F64: 3.000000")
+ s = Sprintf("%v %v", TB(true), TS("x"))
+ check(t, s, "B: true S: \"x\"")
+}
diff --git a/platform/dbops/binaries/go/go/src/hash/example_test.go b/platform/dbops/binaries/go/go/src/hash/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f07b9aaa2c4898b5765ba66da0faf6cf48fa4e42
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/hash/example_test.go
@@ -0,0 +1,51 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package hash_test
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding"
+ "fmt"
+ "log"
+)
+
+func Example_binaryMarshaler() {
+ const (
+ input1 = "The tunneling gopher digs downwards, "
+ input2 = "unaware of what he will find."
+ )
+
+ first := sha256.New()
+ first.Write([]byte(input1))
+
+ marshaler, ok := first.(encoding.BinaryMarshaler)
+ if !ok {
+ log.Fatal("first does not implement encoding.BinaryMarshaler")
+ }
+ state, err := marshaler.MarshalBinary()
+ if err != nil {
+ log.Fatal("unable to marshal hash:", err)
+ }
+
+ second := sha256.New()
+
+ unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
+ if !ok {
+ log.Fatal("second does not implement encoding.BinaryUnmarshaler")
+ }
+ if err := unmarshaler.UnmarshalBinary(state); err != nil {
+ log.Fatal("unable to unmarshal hash:", err)
+ }
+
+ first.Write([]byte(input2))
+ second.Write([]byte(input2))
+
+ fmt.Printf("%x\n", first.Sum(nil))
+ fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
+ // Output:
+ // 57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
+ // true
+}
diff --git a/platform/dbops/binaries/go/go/src/hash/hash.go b/platform/dbops/binaries/go/go/src/hash/hash.go
new file mode 100644
index 0000000000000000000000000000000000000000..82c81034ffcb515885edb83f910d72427a45d4d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/hash/hash.go
@@ -0,0 +1,58 @@
+// 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 hash provides interfaces for hash functions.
+package hash
+
+import "io"
+
+// Hash is the common interface implemented by all hash functions.
+//
+// Hash implementations in the standard library (e.g. [hash/crc32] and
+// [crypto/sha256]) implement the [encoding.BinaryMarshaler] and
+// [encoding.BinaryUnmarshaler] interfaces. Marshaling a hash implementation
+// allows its internal state to be saved and used for additional processing
+// later, without having to re-write the data previously written to the hash.
+// The hash state may contain portions of the input in its original form,
+// which users are expected to handle for any possible security implications.
+//
+// Compatibility: Any future changes to hash or crypto packages will endeavor
+// to maintain compatibility with state encoded using previous versions.
+// That is, any released versions of the packages should be able to
+// decode data written with any previously released version,
+// subject to issues such as security fixes.
+// See the Go compatibility document for background: https://golang.org/doc/go1compat
+type Hash interface {
+ // Write (via the embedded io.Writer interface) adds more data to the running hash.
+ // It never returns an error.
+ io.Writer
+
+ // Sum appends the current hash to b and returns the resulting slice.
+ // It does not change the underlying hash state.
+ Sum(b []byte) []byte
+
+ // Reset resets the Hash to its initial state.
+ Reset()
+
+ // Size returns the number of bytes Sum will return.
+ Size() int
+
+ // BlockSize returns the hash's underlying block size.
+ // The Write method must be able to accept any amount
+ // of data, but it may operate more efficiently if all writes
+ // are a multiple of the block size.
+ BlockSize() int
+}
+
+// Hash32 is the common interface implemented by all 32-bit hash functions.
+type Hash32 interface {
+ Hash
+ Sum32() uint32
+}
+
+// Hash64 is the common interface implemented by all 64-bit hash functions.
+type Hash64 interface {
+ Hash
+ Sum64() uint64
+}
diff --git a/platform/dbops/binaries/go/go/src/hash/marshal_test.go b/platform/dbops/binaries/go/go/src/hash/marshal_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3091f7a67acedeaf72fd3851cf295c1e7bd88e8f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/hash/marshal_test.go
@@ -0,0 +1,107 @@
+// 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.
+
+// Test that the hashes in the standard library implement
+// BinaryMarshaler, BinaryUnmarshaler,
+// and lock in the current representations.
+
+package hash_test
+
+import (
+ "bytes"
+ "crypto/md5"
+ "crypto/sha1"
+ "crypto/sha256"
+ "crypto/sha512"
+ "encoding"
+ "encoding/hex"
+ "hash"
+ "hash/adler32"
+ "hash/crc32"
+ "hash/crc64"
+ "hash/fnv"
+ "testing"
+)
+
+func fromHex(s string) []byte {
+ b, err := hex.DecodeString(s)
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
+
+var marshalTests = []struct {
+ name string
+ new func() hash.Hash
+ golden []byte
+}{
+ {"adler32", func() hash.Hash { return adler32.New() }, fromHex("61646c01460a789d")},
+ {"crc32", func() hash.Hash { return crc32.NewIEEE() }, fromHex("63726301ca87914dc956d3e8")},
+ {"crc64", func() hash.Hash { return crc64.New(crc64.MakeTable(crc64.ISO)) }, fromHex("6372630273ba8484bbcd5def5d51c83c581695be")},
+ {"fnv32", func() hash.Hash { return fnv.New32() }, fromHex("666e760171ba3d77")},
+ {"fnv32a", func() hash.Hash { return fnv.New32a() }, fromHex("666e76027439f86f")},
+ {"fnv64", func() hash.Hash { return fnv.New64() }, fromHex("666e7603cc64e0e97692c637")},
+ {"fnv64a", func() hash.Hash { return fnv.New64a() }, fromHex("666e7604c522af9b0dede66f")},
+ {"fnv128", func() hash.Hash { return fnv.New128() }, fromHex("666e760561587a70a0f66d7981dc980e2cabbaf7")},
+ {"fnv128a", func() hash.Hash { return fnv.New128a() }, fromHex("666e7606a955802b0136cb67622b461d9f91e6ff")},
+ {"md5", md5.New, fromHex("6d643501a91b0023007aa14740a3979210b5f024c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha1", sha1.New, fromHex("736861016dad5acb4dc003952f7a0b352ee5537ec381a228c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha224", sha256.New224, fromHex("73686102f8b92fc047c9b4d82f01a6370841277b7a0d92108440178c83db855a8e66c2d9c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha256", sha256.New, fromHex("736861032bed68b99987cae48183b2b049d393d0050868e4e8ba3730e9112b08765929b7c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha384", sha512.New384, fromHex("736861046f1664d213dd802f7c47bc50637cf93592570a2b8695839148bf38341c6eacd05326452ef1cbe64d90f1ef73bb5ac7d2803565467d0ddb10c5ee3fc050f9f0c1808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha512_224", sha512.New512_224, fromHex("736861056f1a450ec15af20572d0d1ee6518104d7cbbbe79a038557af5450ed7dbd420b53b7335209e951b4d9aff401f90549b9604fa3d823fbb8581c73582a88aa84022808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha512_256", sha512.New512_256, fromHex("736861067c541f1d1a72536b1f5dad64026bcc7c508f8a2126b51f46f8b9bff63a26fee70980718031e96832e95547f4fe76160ff84076db53b4549b86354af8e17b5116808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+ {"sha512", sha512.New, fromHex("736861078e03953cd57cd6879321270afa70c5827bb5b69be59a8f0130147e94f2aedf7bdc01c56c92343ca8bd837bb7f0208f5a23e155694516b6f147099d491a30b151808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f80000000000000000000000000000f9")},
+}
+
+func TestMarshalHash(t *testing.T) {
+ for _, tt := range marshalTests {
+ t.Run(tt.name, func(t *testing.T) {
+ buf := make([]byte, 256)
+ for i := range buf {
+ buf[i] = byte(i)
+ }
+
+ h := tt.new()
+ h.Write(buf[:256])
+ sum := h.Sum(nil)
+
+ h2 := tt.new()
+ h3 := tt.new()
+ const split = 249
+ for i := 0; i < split; i++ {
+ h2.Write(buf[i : i+1])
+ }
+ h2m, ok := h2.(encoding.BinaryMarshaler)
+ if !ok {
+ t.Fatalf("Hash does not implement MarshalBinary")
+ }
+ enc, err := h2m.MarshalBinary()
+ if err != nil {
+ t.Fatalf("MarshalBinary: %v", err)
+ }
+ if !bytes.Equal(enc, tt.golden) {
+ t.Errorf("MarshalBinary = %x, want %x", enc, tt.golden)
+ }
+ h3u, ok := h3.(encoding.BinaryUnmarshaler)
+ if !ok {
+ t.Fatalf("Hash does not implement UnmarshalBinary")
+ }
+ if err := h3u.UnmarshalBinary(enc); err != nil {
+ t.Fatalf("UnmarshalBinary: %v", err)
+ }
+ h2.Write(buf[split:])
+ h3.Write(buf[split:])
+ sum2 := h2.Sum(nil)
+ sum3 := h3.Sum(nil)
+ if !bytes.Equal(sum2, sum) {
+ t.Fatalf("Sum after MarshalBinary = %x, want %x", sum2, sum)
+ }
+ if !bytes.Equal(sum3, sum) {
+ t.Fatalf("Sum after UnmarshalBinary = %x, want %x", sum3, sum)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/hash/test_cases.txt b/platform/dbops/binaries/go/go/src/hash/test_cases.txt
new file mode 100644
index 0000000000000000000000000000000000000000..26d3ccc052495c1517ce4e5a30af947c3fb176c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/hash/test_cases.txt
@@ -0,0 +1,31 @@
+
+a
+ab
+abc
+abcd
+abcde
+abcdef
+abcdefg
+abcdefgh
+abcdefghi
+abcdefghij
+Discard medicine more than two years old.
+He who has a shady past knows that nice guys finish last.
+I wouldn't marry him with a ten foot pole.
+Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave
+The days of the digital watch are numbered. -Tom Stoppard
+Nepal premier won't resign.
+For every action there is an equal and opposite government program.
+His money is twice tainted: 'taint yours and 'taint mine.
+There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977
+It's a tiny change to the code and not completely disgusting. - Bob Manchek
+size: a.out: bad magic
+The major problem is with sendmail. -Mark Horton
+Give me a rock, paper and scissors and I will move the world. CCFestoon
+If the enemy is within range, then so are you.
+It's well we cannot hear the screams/That we create in others' dreams.
+You remind me of a TV show, but that's all right: I watch it anyway.
+C is as portable as Stonehedge!!
+Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley
+The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule
+How can you write a big system without C++? -Paul Glick
diff --git a/platform/dbops/binaries/go/go/src/hash/test_gen.awk b/platform/dbops/binaries/go/go/src/hash/test_gen.awk
new file mode 100644
index 0000000000000000000000000000000000000000..804f786795fa84cae233259bde18c1d7997ffa74
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/hash/test_gen.awk
@@ -0,0 +1,14 @@
+# 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.
+
+# awk -f test_gen.awk test_cases.txt
+# generates test case table.
+# edit next line to set particular reference implementation and name.
+BEGIN { cmd = "echo -n `9 sha1sum`"; name = "Sha1Test" }
+{
+ printf("\t%s{ \"", name);
+ printf("%s", $0) |cmd;
+ close(cmd);
+ printf("\", \"%s\" },\n", $0);
+}
diff --git a/platform/dbops/binaries/go/go/src/html/entity.go b/platform/dbops/binaries/go/go/src/html/entity.go
new file mode 100644
index 0000000000000000000000000000000000000000..f0f9a6a973c649b6a3cdad24248ff6ec24dab9a0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/entity.go
@@ -0,0 +1,2265 @@
+// 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 html
+
+import "sync"
+
+// All entities that do not end with ';' are 6 or fewer bytes long.
+const longestEntityWithoutSemicolon = 6
+
+// entity is a map from HTML entity names to their values. The semicolon matters:
+// https://html.spec.whatwg.org/multipage/named-characters.html
+// lists both "amp" and "amp;" as two separate entries.
+//
+// Note that the HTML5 list is larger than the HTML4 list at
+// http://www.w3.org/TR/html4/sgml/entities.html
+var entity map[string]rune
+
+// HTML entities that are two unicode codepoints.
+var entity2 map[string][2]rune
+
+// populateMapsOnce guards calling populateMaps.
+var populateMapsOnce sync.Once
+
+// populateMaps populates entity and entity2.
+func populateMaps() {
+ entity = map[string]rune{
+ "AElig;": '\U000000C6',
+ "AMP;": '\U00000026',
+ "Aacute;": '\U000000C1',
+ "Abreve;": '\U00000102',
+ "Acirc;": '\U000000C2',
+ "Acy;": '\U00000410',
+ "Afr;": '\U0001D504',
+ "Agrave;": '\U000000C0',
+ "Alpha;": '\U00000391',
+ "Amacr;": '\U00000100',
+ "And;": '\U00002A53',
+ "Aogon;": '\U00000104',
+ "Aopf;": '\U0001D538',
+ "ApplyFunction;": '\U00002061',
+ "Aring;": '\U000000C5',
+ "Ascr;": '\U0001D49C',
+ "Assign;": '\U00002254',
+ "Atilde;": '\U000000C3',
+ "Auml;": '\U000000C4',
+ "Backslash;": '\U00002216',
+ "Barv;": '\U00002AE7',
+ "Barwed;": '\U00002306',
+ "Bcy;": '\U00000411',
+ "Because;": '\U00002235',
+ "Bernoullis;": '\U0000212C',
+ "Beta;": '\U00000392',
+ "Bfr;": '\U0001D505',
+ "Bopf;": '\U0001D539',
+ "Breve;": '\U000002D8',
+ "Bscr;": '\U0000212C',
+ "Bumpeq;": '\U0000224E',
+ "CHcy;": '\U00000427',
+ "COPY;": '\U000000A9',
+ "Cacute;": '\U00000106',
+ "Cap;": '\U000022D2',
+ "CapitalDifferentialD;": '\U00002145',
+ "Cayleys;": '\U0000212D',
+ "Ccaron;": '\U0000010C',
+ "Ccedil;": '\U000000C7',
+ "Ccirc;": '\U00000108',
+ "Cconint;": '\U00002230',
+ "Cdot;": '\U0000010A',
+ "Cedilla;": '\U000000B8',
+ "CenterDot;": '\U000000B7',
+ "Cfr;": '\U0000212D',
+ "Chi;": '\U000003A7',
+ "CircleDot;": '\U00002299',
+ "CircleMinus;": '\U00002296',
+ "CirclePlus;": '\U00002295',
+ "CircleTimes;": '\U00002297',
+ "ClockwiseContourIntegral;": '\U00002232',
+ "CloseCurlyDoubleQuote;": '\U0000201D',
+ "CloseCurlyQuote;": '\U00002019',
+ "Colon;": '\U00002237',
+ "Colone;": '\U00002A74',
+ "Congruent;": '\U00002261',
+ "Conint;": '\U0000222F',
+ "ContourIntegral;": '\U0000222E',
+ "Copf;": '\U00002102',
+ "Coproduct;": '\U00002210',
+ "CounterClockwiseContourIntegral;": '\U00002233',
+ "Cross;": '\U00002A2F',
+ "Cscr;": '\U0001D49E',
+ "Cup;": '\U000022D3',
+ "CupCap;": '\U0000224D',
+ "DD;": '\U00002145',
+ "DDotrahd;": '\U00002911',
+ "DJcy;": '\U00000402',
+ "DScy;": '\U00000405',
+ "DZcy;": '\U0000040F',
+ "Dagger;": '\U00002021',
+ "Darr;": '\U000021A1',
+ "Dashv;": '\U00002AE4',
+ "Dcaron;": '\U0000010E',
+ "Dcy;": '\U00000414',
+ "Del;": '\U00002207',
+ "Delta;": '\U00000394',
+ "Dfr;": '\U0001D507',
+ "DiacriticalAcute;": '\U000000B4',
+ "DiacriticalDot;": '\U000002D9',
+ "DiacriticalDoubleAcute;": '\U000002DD',
+ "DiacriticalGrave;": '\U00000060',
+ "DiacriticalTilde;": '\U000002DC',
+ "Diamond;": '\U000022C4',
+ "DifferentialD;": '\U00002146',
+ "Dopf;": '\U0001D53B',
+ "Dot;": '\U000000A8',
+ "DotDot;": '\U000020DC',
+ "DotEqual;": '\U00002250',
+ "DoubleContourIntegral;": '\U0000222F',
+ "DoubleDot;": '\U000000A8',
+ "DoubleDownArrow;": '\U000021D3',
+ "DoubleLeftArrow;": '\U000021D0',
+ "DoubleLeftRightArrow;": '\U000021D4',
+ "DoubleLeftTee;": '\U00002AE4',
+ "DoubleLongLeftArrow;": '\U000027F8',
+ "DoubleLongLeftRightArrow;": '\U000027FA',
+ "DoubleLongRightArrow;": '\U000027F9',
+ "DoubleRightArrow;": '\U000021D2',
+ "DoubleRightTee;": '\U000022A8',
+ "DoubleUpArrow;": '\U000021D1',
+ "DoubleUpDownArrow;": '\U000021D5',
+ "DoubleVerticalBar;": '\U00002225',
+ "DownArrow;": '\U00002193',
+ "DownArrowBar;": '\U00002913',
+ "DownArrowUpArrow;": '\U000021F5',
+ "DownBreve;": '\U00000311',
+ "DownLeftRightVector;": '\U00002950',
+ "DownLeftTeeVector;": '\U0000295E',
+ "DownLeftVector;": '\U000021BD',
+ "DownLeftVectorBar;": '\U00002956',
+ "DownRightTeeVector;": '\U0000295F',
+ "DownRightVector;": '\U000021C1',
+ "DownRightVectorBar;": '\U00002957',
+ "DownTee;": '\U000022A4',
+ "DownTeeArrow;": '\U000021A7',
+ "Downarrow;": '\U000021D3',
+ "Dscr;": '\U0001D49F',
+ "Dstrok;": '\U00000110',
+ "ENG;": '\U0000014A',
+ "ETH;": '\U000000D0',
+ "Eacute;": '\U000000C9',
+ "Ecaron;": '\U0000011A',
+ "Ecirc;": '\U000000CA',
+ "Ecy;": '\U0000042D',
+ "Edot;": '\U00000116',
+ "Efr;": '\U0001D508',
+ "Egrave;": '\U000000C8',
+ "Element;": '\U00002208',
+ "Emacr;": '\U00000112',
+ "EmptySmallSquare;": '\U000025FB',
+ "EmptyVerySmallSquare;": '\U000025AB',
+ "Eogon;": '\U00000118',
+ "Eopf;": '\U0001D53C',
+ "Epsilon;": '\U00000395',
+ "Equal;": '\U00002A75',
+ "EqualTilde;": '\U00002242',
+ "Equilibrium;": '\U000021CC',
+ "Escr;": '\U00002130',
+ "Esim;": '\U00002A73',
+ "Eta;": '\U00000397',
+ "Euml;": '\U000000CB',
+ "Exists;": '\U00002203',
+ "ExponentialE;": '\U00002147',
+ "Fcy;": '\U00000424',
+ "Ffr;": '\U0001D509',
+ "FilledSmallSquare;": '\U000025FC',
+ "FilledVerySmallSquare;": '\U000025AA',
+ "Fopf;": '\U0001D53D',
+ "ForAll;": '\U00002200',
+ "Fouriertrf;": '\U00002131',
+ "Fscr;": '\U00002131',
+ "GJcy;": '\U00000403',
+ "GT;": '\U0000003E',
+ "Gamma;": '\U00000393',
+ "Gammad;": '\U000003DC',
+ "Gbreve;": '\U0000011E',
+ "Gcedil;": '\U00000122',
+ "Gcirc;": '\U0000011C',
+ "Gcy;": '\U00000413',
+ "Gdot;": '\U00000120',
+ "Gfr;": '\U0001D50A',
+ "Gg;": '\U000022D9',
+ "Gopf;": '\U0001D53E',
+ "GreaterEqual;": '\U00002265',
+ "GreaterEqualLess;": '\U000022DB',
+ "GreaterFullEqual;": '\U00002267',
+ "GreaterGreater;": '\U00002AA2',
+ "GreaterLess;": '\U00002277',
+ "GreaterSlantEqual;": '\U00002A7E',
+ "GreaterTilde;": '\U00002273',
+ "Gscr;": '\U0001D4A2',
+ "Gt;": '\U0000226B',
+ "HARDcy;": '\U0000042A',
+ "Hacek;": '\U000002C7',
+ "Hat;": '\U0000005E',
+ "Hcirc;": '\U00000124',
+ "Hfr;": '\U0000210C',
+ "HilbertSpace;": '\U0000210B',
+ "Hopf;": '\U0000210D',
+ "HorizontalLine;": '\U00002500',
+ "Hscr;": '\U0000210B',
+ "Hstrok;": '\U00000126',
+ "HumpDownHump;": '\U0000224E',
+ "HumpEqual;": '\U0000224F',
+ "IEcy;": '\U00000415',
+ "IJlig;": '\U00000132',
+ "IOcy;": '\U00000401',
+ "Iacute;": '\U000000CD',
+ "Icirc;": '\U000000CE',
+ "Icy;": '\U00000418',
+ "Idot;": '\U00000130',
+ "Ifr;": '\U00002111',
+ "Igrave;": '\U000000CC',
+ "Im;": '\U00002111',
+ "Imacr;": '\U0000012A',
+ "ImaginaryI;": '\U00002148',
+ "Implies;": '\U000021D2',
+ "Int;": '\U0000222C',
+ "Integral;": '\U0000222B',
+ "Intersection;": '\U000022C2',
+ "InvisibleComma;": '\U00002063',
+ "InvisibleTimes;": '\U00002062',
+ "Iogon;": '\U0000012E',
+ "Iopf;": '\U0001D540',
+ "Iota;": '\U00000399',
+ "Iscr;": '\U00002110',
+ "Itilde;": '\U00000128',
+ "Iukcy;": '\U00000406',
+ "Iuml;": '\U000000CF',
+ "Jcirc;": '\U00000134',
+ "Jcy;": '\U00000419',
+ "Jfr;": '\U0001D50D',
+ "Jopf;": '\U0001D541',
+ "Jscr;": '\U0001D4A5',
+ "Jsercy;": '\U00000408',
+ "Jukcy;": '\U00000404',
+ "KHcy;": '\U00000425',
+ "KJcy;": '\U0000040C',
+ "Kappa;": '\U0000039A',
+ "Kcedil;": '\U00000136',
+ "Kcy;": '\U0000041A',
+ "Kfr;": '\U0001D50E',
+ "Kopf;": '\U0001D542',
+ "Kscr;": '\U0001D4A6',
+ "LJcy;": '\U00000409',
+ "LT;": '\U0000003C',
+ "Lacute;": '\U00000139',
+ "Lambda;": '\U0000039B',
+ "Lang;": '\U000027EA',
+ "Laplacetrf;": '\U00002112',
+ "Larr;": '\U0000219E',
+ "Lcaron;": '\U0000013D',
+ "Lcedil;": '\U0000013B',
+ "Lcy;": '\U0000041B',
+ "LeftAngleBracket;": '\U000027E8',
+ "LeftArrow;": '\U00002190',
+ "LeftArrowBar;": '\U000021E4',
+ "LeftArrowRightArrow;": '\U000021C6',
+ "LeftCeiling;": '\U00002308',
+ "LeftDoubleBracket;": '\U000027E6',
+ "LeftDownTeeVector;": '\U00002961',
+ "LeftDownVector;": '\U000021C3',
+ "LeftDownVectorBar;": '\U00002959',
+ "LeftFloor;": '\U0000230A',
+ "LeftRightArrow;": '\U00002194',
+ "LeftRightVector;": '\U0000294E',
+ "LeftTee;": '\U000022A3',
+ "LeftTeeArrow;": '\U000021A4',
+ "LeftTeeVector;": '\U0000295A',
+ "LeftTriangle;": '\U000022B2',
+ "LeftTriangleBar;": '\U000029CF',
+ "LeftTriangleEqual;": '\U000022B4',
+ "LeftUpDownVector;": '\U00002951',
+ "LeftUpTeeVector;": '\U00002960',
+ "LeftUpVector;": '\U000021BF',
+ "LeftUpVectorBar;": '\U00002958',
+ "LeftVector;": '\U000021BC',
+ "LeftVectorBar;": '\U00002952',
+ "Leftarrow;": '\U000021D0',
+ "Leftrightarrow;": '\U000021D4',
+ "LessEqualGreater;": '\U000022DA',
+ "LessFullEqual;": '\U00002266',
+ "LessGreater;": '\U00002276',
+ "LessLess;": '\U00002AA1',
+ "LessSlantEqual;": '\U00002A7D',
+ "LessTilde;": '\U00002272',
+ "Lfr;": '\U0001D50F',
+ "Ll;": '\U000022D8',
+ "Lleftarrow;": '\U000021DA',
+ "Lmidot;": '\U0000013F',
+ "LongLeftArrow;": '\U000027F5',
+ "LongLeftRightArrow;": '\U000027F7',
+ "LongRightArrow;": '\U000027F6',
+ "Longleftarrow;": '\U000027F8',
+ "Longleftrightarrow;": '\U000027FA',
+ "Longrightarrow;": '\U000027F9',
+ "Lopf;": '\U0001D543',
+ "LowerLeftArrow;": '\U00002199',
+ "LowerRightArrow;": '\U00002198',
+ "Lscr;": '\U00002112',
+ "Lsh;": '\U000021B0',
+ "Lstrok;": '\U00000141',
+ "Lt;": '\U0000226A',
+ "Map;": '\U00002905',
+ "Mcy;": '\U0000041C',
+ "MediumSpace;": '\U0000205F',
+ "Mellintrf;": '\U00002133',
+ "Mfr;": '\U0001D510',
+ "MinusPlus;": '\U00002213',
+ "Mopf;": '\U0001D544',
+ "Mscr;": '\U00002133',
+ "Mu;": '\U0000039C',
+ "NJcy;": '\U0000040A',
+ "Nacute;": '\U00000143',
+ "Ncaron;": '\U00000147',
+ "Ncedil;": '\U00000145',
+ "Ncy;": '\U0000041D',
+ "NegativeMediumSpace;": '\U0000200B',
+ "NegativeThickSpace;": '\U0000200B',
+ "NegativeThinSpace;": '\U0000200B',
+ "NegativeVeryThinSpace;": '\U0000200B',
+ "NestedGreaterGreater;": '\U0000226B',
+ "NestedLessLess;": '\U0000226A',
+ "NewLine;": '\U0000000A',
+ "Nfr;": '\U0001D511',
+ "NoBreak;": '\U00002060',
+ "NonBreakingSpace;": '\U000000A0',
+ "Nopf;": '\U00002115',
+ "Not;": '\U00002AEC',
+ "NotCongruent;": '\U00002262',
+ "NotCupCap;": '\U0000226D',
+ "NotDoubleVerticalBar;": '\U00002226',
+ "NotElement;": '\U00002209',
+ "NotEqual;": '\U00002260',
+ "NotExists;": '\U00002204',
+ "NotGreater;": '\U0000226F',
+ "NotGreaterEqual;": '\U00002271',
+ "NotGreaterLess;": '\U00002279',
+ "NotGreaterTilde;": '\U00002275',
+ "NotLeftTriangle;": '\U000022EA',
+ "NotLeftTriangleEqual;": '\U000022EC',
+ "NotLess;": '\U0000226E',
+ "NotLessEqual;": '\U00002270',
+ "NotLessGreater;": '\U00002278',
+ "NotLessTilde;": '\U00002274',
+ "NotPrecedes;": '\U00002280',
+ "NotPrecedesSlantEqual;": '\U000022E0',
+ "NotReverseElement;": '\U0000220C',
+ "NotRightTriangle;": '\U000022EB',
+ "NotRightTriangleEqual;": '\U000022ED',
+ "NotSquareSubsetEqual;": '\U000022E2',
+ "NotSquareSupersetEqual;": '\U000022E3',
+ "NotSubsetEqual;": '\U00002288',
+ "NotSucceeds;": '\U00002281',
+ "NotSucceedsSlantEqual;": '\U000022E1',
+ "NotSupersetEqual;": '\U00002289',
+ "NotTilde;": '\U00002241',
+ "NotTildeEqual;": '\U00002244',
+ "NotTildeFullEqual;": '\U00002247',
+ "NotTildeTilde;": '\U00002249',
+ "NotVerticalBar;": '\U00002224',
+ "Nscr;": '\U0001D4A9',
+ "Ntilde;": '\U000000D1',
+ "Nu;": '\U0000039D',
+ "OElig;": '\U00000152',
+ "Oacute;": '\U000000D3',
+ "Ocirc;": '\U000000D4',
+ "Ocy;": '\U0000041E',
+ "Odblac;": '\U00000150',
+ "Ofr;": '\U0001D512',
+ "Ograve;": '\U000000D2',
+ "Omacr;": '\U0000014C',
+ "Omega;": '\U000003A9',
+ "Omicron;": '\U0000039F',
+ "Oopf;": '\U0001D546',
+ "OpenCurlyDoubleQuote;": '\U0000201C',
+ "OpenCurlyQuote;": '\U00002018',
+ "Or;": '\U00002A54',
+ "Oscr;": '\U0001D4AA',
+ "Oslash;": '\U000000D8',
+ "Otilde;": '\U000000D5',
+ "Otimes;": '\U00002A37',
+ "Ouml;": '\U000000D6',
+ "OverBar;": '\U0000203E',
+ "OverBrace;": '\U000023DE',
+ "OverBracket;": '\U000023B4',
+ "OverParenthesis;": '\U000023DC',
+ "PartialD;": '\U00002202',
+ "Pcy;": '\U0000041F',
+ "Pfr;": '\U0001D513',
+ "Phi;": '\U000003A6',
+ "Pi;": '\U000003A0',
+ "PlusMinus;": '\U000000B1',
+ "Poincareplane;": '\U0000210C',
+ "Popf;": '\U00002119',
+ "Pr;": '\U00002ABB',
+ "Precedes;": '\U0000227A',
+ "PrecedesEqual;": '\U00002AAF',
+ "PrecedesSlantEqual;": '\U0000227C',
+ "PrecedesTilde;": '\U0000227E',
+ "Prime;": '\U00002033',
+ "Product;": '\U0000220F',
+ "Proportion;": '\U00002237',
+ "Proportional;": '\U0000221D',
+ "Pscr;": '\U0001D4AB',
+ "Psi;": '\U000003A8',
+ "QUOT;": '\U00000022',
+ "Qfr;": '\U0001D514',
+ "Qopf;": '\U0000211A',
+ "Qscr;": '\U0001D4AC',
+ "RBarr;": '\U00002910',
+ "REG;": '\U000000AE',
+ "Racute;": '\U00000154',
+ "Rang;": '\U000027EB',
+ "Rarr;": '\U000021A0',
+ "Rarrtl;": '\U00002916',
+ "Rcaron;": '\U00000158',
+ "Rcedil;": '\U00000156',
+ "Rcy;": '\U00000420',
+ "Re;": '\U0000211C',
+ "ReverseElement;": '\U0000220B',
+ "ReverseEquilibrium;": '\U000021CB',
+ "ReverseUpEquilibrium;": '\U0000296F',
+ "Rfr;": '\U0000211C',
+ "Rho;": '\U000003A1',
+ "RightAngleBracket;": '\U000027E9',
+ "RightArrow;": '\U00002192',
+ "RightArrowBar;": '\U000021E5',
+ "RightArrowLeftArrow;": '\U000021C4',
+ "RightCeiling;": '\U00002309',
+ "RightDoubleBracket;": '\U000027E7',
+ "RightDownTeeVector;": '\U0000295D',
+ "RightDownVector;": '\U000021C2',
+ "RightDownVectorBar;": '\U00002955',
+ "RightFloor;": '\U0000230B',
+ "RightTee;": '\U000022A2',
+ "RightTeeArrow;": '\U000021A6',
+ "RightTeeVector;": '\U0000295B',
+ "RightTriangle;": '\U000022B3',
+ "RightTriangleBar;": '\U000029D0',
+ "RightTriangleEqual;": '\U000022B5',
+ "RightUpDownVector;": '\U0000294F',
+ "RightUpTeeVector;": '\U0000295C',
+ "RightUpVector;": '\U000021BE',
+ "RightUpVectorBar;": '\U00002954',
+ "RightVector;": '\U000021C0',
+ "RightVectorBar;": '\U00002953',
+ "Rightarrow;": '\U000021D2',
+ "Ropf;": '\U0000211D',
+ "RoundImplies;": '\U00002970',
+ "Rrightarrow;": '\U000021DB',
+ "Rscr;": '\U0000211B',
+ "Rsh;": '\U000021B1',
+ "RuleDelayed;": '\U000029F4',
+ "SHCHcy;": '\U00000429',
+ "SHcy;": '\U00000428',
+ "SOFTcy;": '\U0000042C',
+ "Sacute;": '\U0000015A',
+ "Sc;": '\U00002ABC',
+ "Scaron;": '\U00000160',
+ "Scedil;": '\U0000015E',
+ "Scirc;": '\U0000015C',
+ "Scy;": '\U00000421',
+ "Sfr;": '\U0001D516',
+ "ShortDownArrow;": '\U00002193',
+ "ShortLeftArrow;": '\U00002190',
+ "ShortRightArrow;": '\U00002192',
+ "ShortUpArrow;": '\U00002191',
+ "Sigma;": '\U000003A3',
+ "SmallCircle;": '\U00002218',
+ "Sopf;": '\U0001D54A',
+ "Sqrt;": '\U0000221A',
+ "Square;": '\U000025A1',
+ "SquareIntersection;": '\U00002293',
+ "SquareSubset;": '\U0000228F',
+ "SquareSubsetEqual;": '\U00002291',
+ "SquareSuperset;": '\U00002290',
+ "SquareSupersetEqual;": '\U00002292',
+ "SquareUnion;": '\U00002294',
+ "Sscr;": '\U0001D4AE',
+ "Star;": '\U000022C6',
+ "Sub;": '\U000022D0',
+ "Subset;": '\U000022D0',
+ "SubsetEqual;": '\U00002286',
+ "Succeeds;": '\U0000227B',
+ "SucceedsEqual;": '\U00002AB0',
+ "SucceedsSlantEqual;": '\U0000227D',
+ "SucceedsTilde;": '\U0000227F',
+ "SuchThat;": '\U0000220B',
+ "Sum;": '\U00002211',
+ "Sup;": '\U000022D1',
+ "Superset;": '\U00002283',
+ "SupersetEqual;": '\U00002287',
+ "Supset;": '\U000022D1',
+ "THORN;": '\U000000DE',
+ "TRADE;": '\U00002122',
+ "TSHcy;": '\U0000040B',
+ "TScy;": '\U00000426',
+ "Tab;": '\U00000009',
+ "Tau;": '\U000003A4',
+ "Tcaron;": '\U00000164',
+ "Tcedil;": '\U00000162',
+ "Tcy;": '\U00000422',
+ "Tfr;": '\U0001D517',
+ "Therefore;": '\U00002234',
+ "Theta;": '\U00000398',
+ "ThinSpace;": '\U00002009',
+ "Tilde;": '\U0000223C',
+ "TildeEqual;": '\U00002243',
+ "TildeFullEqual;": '\U00002245',
+ "TildeTilde;": '\U00002248',
+ "Topf;": '\U0001D54B',
+ "TripleDot;": '\U000020DB',
+ "Tscr;": '\U0001D4AF',
+ "Tstrok;": '\U00000166',
+ "Uacute;": '\U000000DA',
+ "Uarr;": '\U0000219F',
+ "Uarrocir;": '\U00002949',
+ "Ubrcy;": '\U0000040E',
+ "Ubreve;": '\U0000016C',
+ "Ucirc;": '\U000000DB',
+ "Ucy;": '\U00000423',
+ "Udblac;": '\U00000170',
+ "Ufr;": '\U0001D518',
+ "Ugrave;": '\U000000D9',
+ "Umacr;": '\U0000016A',
+ "UnderBar;": '\U0000005F',
+ "UnderBrace;": '\U000023DF',
+ "UnderBracket;": '\U000023B5',
+ "UnderParenthesis;": '\U000023DD',
+ "Union;": '\U000022C3',
+ "UnionPlus;": '\U0000228E',
+ "Uogon;": '\U00000172',
+ "Uopf;": '\U0001D54C',
+ "UpArrow;": '\U00002191',
+ "UpArrowBar;": '\U00002912',
+ "UpArrowDownArrow;": '\U000021C5',
+ "UpDownArrow;": '\U00002195',
+ "UpEquilibrium;": '\U0000296E',
+ "UpTee;": '\U000022A5',
+ "UpTeeArrow;": '\U000021A5',
+ "Uparrow;": '\U000021D1',
+ "Updownarrow;": '\U000021D5',
+ "UpperLeftArrow;": '\U00002196',
+ "UpperRightArrow;": '\U00002197',
+ "Upsi;": '\U000003D2',
+ "Upsilon;": '\U000003A5',
+ "Uring;": '\U0000016E',
+ "Uscr;": '\U0001D4B0',
+ "Utilde;": '\U00000168',
+ "Uuml;": '\U000000DC',
+ "VDash;": '\U000022AB',
+ "Vbar;": '\U00002AEB',
+ "Vcy;": '\U00000412',
+ "Vdash;": '\U000022A9',
+ "Vdashl;": '\U00002AE6',
+ "Vee;": '\U000022C1',
+ "Verbar;": '\U00002016',
+ "Vert;": '\U00002016',
+ "VerticalBar;": '\U00002223',
+ "VerticalLine;": '\U0000007C',
+ "VerticalSeparator;": '\U00002758',
+ "VerticalTilde;": '\U00002240',
+ "VeryThinSpace;": '\U0000200A',
+ "Vfr;": '\U0001D519',
+ "Vopf;": '\U0001D54D',
+ "Vscr;": '\U0001D4B1',
+ "Vvdash;": '\U000022AA',
+ "Wcirc;": '\U00000174',
+ "Wedge;": '\U000022C0',
+ "Wfr;": '\U0001D51A',
+ "Wopf;": '\U0001D54E',
+ "Wscr;": '\U0001D4B2',
+ "Xfr;": '\U0001D51B',
+ "Xi;": '\U0000039E',
+ "Xopf;": '\U0001D54F',
+ "Xscr;": '\U0001D4B3',
+ "YAcy;": '\U0000042F',
+ "YIcy;": '\U00000407',
+ "YUcy;": '\U0000042E',
+ "Yacute;": '\U000000DD',
+ "Ycirc;": '\U00000176',
+ "Ycy;": '\U0000042B',
+ "Yfr;": '\U0001D51C',
+ "Yopf;": '\U0001D550',
+ "Yscr;": '\U0001D4B4',
+ "Yuml;": '\U00000178',
+ "ZHcy;": '\U00000416',
+ "Zacute;": '\U00000179',
+ "Zcaron;": '\U0000017D',
+ "Zcy;": '\U00000417',
+ "Zdot;": '\U0000017B',
+ "ZeroWidthSpace;": '\U0000200B',
+ "Zeta;": '\U00000396',
+ "Zfr;": '\U00002128',
+ "Zopf;": '\U00002124',
+ "Zscr;": '\U0001D4B5',
+ "aacute;": '\U000000E1',
+ "abreve;": '\U00000103',
+ "ac;": '\U0000223E',
+ "acd;": '\U0000223F',
+ "acirc;": '\U000000E2',
+ "acute;": '\U000000B4',
+ "acy;": '\U00000430',
+ "aelig;": '\U000000E6',
+ "af;": '\U00002061',
+ "afr;": '\U0001D51E',
+ "agrave;": '\U000000E0',
+ "alefsym;": '\U00002135',
+ "aleph;": '\U00002135',
+ "alpha;": '\U000003B1',
+ "amacr;": '\U00000101',
+ "amalg;": '\U00002A3F',
+ "amp;": '\U00000026',
+ "and;": '\U00002227',
+ "andand;": '\U00002A55',
+ "andd;": '\U00002A5C',
+ "andslope;": '\U00002A58',
+ "andv;": '\U00002A5A',
+ "ang;": '\U00002220',
+ "ange;": '\U000029A4',
+ "angle;": '\U00002220',
+ "angmsd;": '\U00002221',
+ "angmsdaa;": '\U000029A8',
+ "angmsdab;": '\U000029A9',
+ "angmsdac;": '\U000029AA',
+ "angmsdad;": '\U000029AB',
+ "angmsdae;": '\U000029AC',
+ "angmsdaf;": '\U000029AD',
+ "angmsdag;": '\U000029AE',
+ "angmsdah;": '\U000029AF',
+ "angrt;": '\U0000221F',
+ "angrtvb;": '\U000022BE',
+ "angrtvbd;": '\U0000299D',
+ "angsph;": '\U00002222',
+ "angst;": '\U000000C5',
+ "angzarr;": '\U0000237C',
+ "aogon;": '\U00000105',
+ "aopf;": '\U0001D552',
+ "ap;": '\U00002248',
+ "apE;": '\U00002A70',
+ "apacir;": '\U00002A6F',
+ "ape;": '\U0000224A',
+ "apid;": '\U0000224B',
+ "apos;": '\U00000027',
+ "approx;": '\U00002248',
+ "approxeq;": '\U0000224A',
+ "aring;": '\U000000E5',
+ "ascr;": '\U0001D4B6',
+ "ast;": '\U0000002A',
+ "asymp;": '\U00002248',
+ "asympeq;": '\U0000224D',
+ "atilde;": '\U000000E3',
+ "auml;": '\U000000E4',
+ "awconint;": '\U00002233',
+ "awint;": '\U00002A11',
+ "bNot;": '\U00002AED',
+ "backcong;": '\U0000224C',
+ "backepsilon;": '\U000003F6',
+ "backprime;": '\U00002035',
+ "backsim;": '\U0000223D',
+ "backsimeq;": '\U000022CD',
+ "barvee;": '\U000022BD',
+ "barwed;": '\U00002305',
+ "barwedge;": '\U00002305',
+ "bbrk;": '\U000023B5',
+ "bbrktbrk;": '\U000023B6',
+ "bcong;": '\U0000224C',
+ "bcy;": '\U00000431',
+ "bdquo;": '\U0000201E',
+ "becaus;": '\U00002235',
+ "because;": '\U00002235',
+ "bemptyv;": '\U000029B0',
+ "bepsi;": '\U000003F6',
+ "bernou;": '\U0000212C',
+ "beta;": '\U000003B2',
+ "beth;": '\U00002136',
+ "between;": '\U0000226C',
+ "bfr;": '\U0001D51F',
+ "bigcap;": '\U000022C2',
+ "bigcirc;": '\U000025EF',
+ "bigcup;": '\U000022C3',
+ "bigodot;": '\U00002A00',
+ "bigoplus;": '\U00002A01',
+ "bigotimes;": '\U00002A02',
+ "bigsqcup;": '\U00002A06',
+ "bigstar;": '\U00002605',
+ "bigtriangledown;": '\U000025BD',
+ "bigtriangleup;": '\U000025B3',
+ "biguplus;": '\U00002A04',
+ "bigvee;": '\U000022C1',
+ "bigwedge;": '\U000022C0',
+ "bkarow;": '\U0000290D',
+ "blacklozenge;": '\U000029EB',
+ "blacksquare;": '\U000025AA',
+ "blacktriangle;": '\U000025B4',
+ "blacktriangledown;": '\U000025BE',
+ "blacktriangleleft;": '\U000025C2',
+ "blacktriangleright;": '\U000025B8',
+ "blank;": '\U00002423',
+ "blk12;": '\U00002592',
+ "blk14;": '\U00002591',
+ "blk34;": '\U00002593',
+ "block;": '\U00002588',
+ "bnot;": '\U00002310',
+ "bopf;": '\U0001D553',
+ "bot;": '\U000022A5',
+ "bottom;": '\U000022A5',
+ "bowtie;": '\U000022C8',
+ "boxDL;": '\U00002557',
+ "boxDR;": '\U00002554',
+ "boxDl;": '\U00002556',
+ "boxDr;": '\U00002553',
+ "boxH;": '\U00002550',
+ "boxHD;": '\U00002566',
+ "boxHU;": '\U00002569',
+ "boxHd;": '\U00002564',
+ "boxHu;": '\U00002567',
+ "boxUL;": '\U0000255D',
+ "boxUR;": '\U0000255A',
+ "boxUl;": '\U0000255C',
+ "boxUr;": '\U00002559',
+ "boxV;": '\U00002551',
+ "boxVH;": '\U0000256C',
+ "boxVL;": '\U00002563',
+ "boxVR;": '\U00002560',
+ "boxVh;": '\U0000256B',
+ "boxVl;": '\U00002562',
+ "boxVr;": '\U0000255F',
+ "boxbox;": '\U000029C9',
+ "boxdL;": '\U00002555',
+ "boxdR;": '\U00002552',
+ "boxdl;": '\U00002510',
+ "boxdr;": '\U0000250C',
+ "boxh;": '\U00002500',
+ "boxhD;": '\U00002565',
+ "boxhU;": '\U00002568',
+ "boxhd;": '\U0000252C',
+ "boxhu;": '\U00002534',
+ "boxminus;": '\U0000229F',
+ "boxplus;": '\U0000229E',
+ "boxtimes;": '\U000022A0',
+ "boxuL;": '\U0000255B',
+ "boxuR;": '\U00002558',
+ "boxul;": '\U00002518',
+ "boxur;": '\U00002514',
+ "boxv;": '\U00002502',
+ "boxvH;": '\U0000256A',
+ "boxvL;": '\U00002561',
+ "boxvR;": '\U0000255E',
+ "boxvh;": '\U0000253C',
+ "boxvl;": '\U00002524',
+ "boxvr;": '\U0000251C',
+ "bprime;": '\U00002035',
+ "breve;": '\U000002D8',
+ "brvbar;": '\U000000A6',
+ "bscr;": '\U0001D4B7',
+ "bsemi;": '\U0000204F',
+ "bsim;": '\U0000223D',
+ "bsime;": '\U000022CD',
+ "bsol;": '\U0000005C',
+ "bsolb;": '\U000029C5',
+ "bsolhsub;": '\U000027C8',
+ "bull;": '\U00002022',
+ "bullet;": '\U00002022',
+ "bump;": '\U0000224E',
+ "bumpE;": '\U00002AAE',
+ "bumpe;": '\U0000224F',
+ "bumpeq;": '\U0000224F',
+ "cacute;": '\U00000107',
+ "cap;": '\U00002229',
+ "capand;": '\U00002A44',
+ "capbrcup;": '\U00002A49',
+ "capcap;": '\U00002A4B',
+ "capcup;": '\U00002A47',
+ "capdot;": '\U00002A40',
+ "caret;": '\U00002041',
+ "caron;": '\U000002C7',
+ "ccaps;": '\U00002A4D',
+ "ccaron;": '\U0000010D',
+ "ccedil;": '\U000000E7',
+ "ccirc;": '\U00000109',
+ "ccups;": '\U00002A4C',
+ "ccupssm;": '\U00002A50',
+ "cdot;": '\U0000010B',
+ "cedil;": '\U000000B8',
+ "cemptyv;": '\U000029B2',
+ "cent;": '\U000000A2',
+ "centerdot;": '\U000000B7',
+ "cfr;": '\U0001D520',
+ "chcy;": '\U00000447',
+ "check;": '\U00002713',
+ "checkmark;": '\U00002713',
+ "chi;": '\U000003C7',
+ "cir;": '\U000025CB',
+ "cirE;": '\U000029C3',
+ "circ;": '\U000002C6',
+ "circeq;": '\U00002257',
+ "circlearrowleft;": '\U000021BA',
+ "circlearrowright;": '\U000021BB',
+ "circledR;": '\U000000AE',
+ "circledS;": '\U000024C8',
+ "circledast;": '\U0000229B',
+ "circledcirc;": '\U0000229A',
+ "circleddash;": '\U0000229D',
+ "cire;": '\U00002257',
+ "cirfnint;": '\U00002A10',
+ "cirmid;": '\U00002AEF',
+ "cirscir;": '\U000029C2',
+ "clubs;": '\U00002663',
+ "clubsuit;": '\U00002663',
+ "colon;": '\U0000003A',
+ "colone;": '\U00002254',
+ "coloneq;": '\U00002254',
+ "comma;": '\U0000002C',
+ "commat;": '\U00000040',
+ "comp;": '\U00002201',
+ "compfn;": '\U00002218',
+ "complement;": '\U00002201',
+ "complexes;": '\U00002102',
+ "cong;": '\U00002245',
+ "congdot;": '\U00002A6D',
+ "conint;": '\U0000222E',
+ "copf;": '\U0001D554',
+ "coprod;": '\U00002210',
+ "copy;": '\U000000A9',
+ "copysr;": '\U00002117',
+ "crarr;": '\U000021B5',
+ "cross;": '\U00002717',
+ "cscr;": '\U0001D4B8',
+ "csub;": '\U00002ACF',
+ "csube;": '\U00002AD1',
+ "csup;": '\U00002AD0',
+ "csupe;": '\U00002AD2',
+ "ctdot;": '\U000022EF',
+ "cudarrl;": '\U00002938',
+ "cudarrr;": '\U00002935',
+ "cuepr;": '\U000022DE',
+ "cuesc;": '\U000022DF',
+ "cularr;": '\U000021B6',
+ "cularrp;": '\U0000293D',
+ "cup;": '\U0000222A',
+ "cupbrcap;": '\U00002A48',
+ "cupcap;": '\U00002A46',
+ "cupcup;": '\U00002A4A',
+ "cupdot;": '\U0000228D',
+ "cupor;": '\U00002A45',
+ "curarr;": '\U000021B7',
+ "curarrm;": '\U0000293C',
+ "curlyeqprec;": '\U000022DE',
+ "curlyeqsucc;": '\U000022DF',
+ "curlyvee;": '\U000022CE',
+ "curlywedge;": '\U000022CF',
+ "curren;": '\U000000A4',
+ "curvearrowleft;": '\U000021B6',
+ "curvearrowright;": '\U000021B7',
+ "cuvee;": '\U000022CE',
+ "cuwed;": '\U000022CF',
+ "cwconint;": '\U00002232',
+ "cwint;": '\U00002231',
+ "cylcty;": '\U0000232D',
+ "dArr;": '\U000021D3',
+ "dHar;": '\U00002965',
+ "dagger;": '\U00002020',
+ "daleth;": '\U00002138',
+ "darr;": '\U00002193',
+ "dash;": '\U00002010',
+ "dashv;": '\U000022A3',
+ "dbkarow;": '\U0000290F',
+ "dblac;": '\U000002DD',
+ "dcaron;": '\U0000010F',
+ "dcy;": '\U00000434',
+ "dd;": '\U00002146',
+ "ddagger;": '\U00002021',
+ "ddarr;": '\U000021CA',
+ "ddotseq;": '\U00002A77',
+ "deg;": '\U000000B0',
+ "delta;": '\U000003B4',
+ "demptyv;": '\U000029B1',
+ "dfisht;": '\U0000297F',
+ "dfr;": '\U0001D521',
+ "dharl;": '\U000021C3',
+ "dharr;": '\U000021C2',
+ "diam;": '\U000022C4',
+ "diamond;": '\U000022C4',
+ "diamondsuit;": '\U00002666',
+ "diams;": '\U00002666',
+ "die;": '\U000000A8',
+ "digamma;": '\U000003DD',
+ "disin;": '\U000022F2',
+ "div;": '\U000000F7',
+ "divide;": '\U000000F7',
+ "divideontimes;": '\U000022C7',
+ "divonx;": '\U000022C7',
+ "djcy;": '\U00000452',
+ "dlcorn;": '\U0000231E',
+ "dlcrop;": '\U0000230D',
+ "dollar;": '\U00000024',
+ "dopf;": '\U0001D555',
+ "dot;": '\U000002D9',
+ "doteq;": '\U00002250',
+ "doteqdot;": '\U00002251',
+ "dotminus;": '\U00002238',
+ "dotplus;": '\U00002214',
+ "dotsquare;": '\U000022A1',
+ "doublebarwedge;": '\U00002306',
+ "downarrow;": '\U00002193',
+ "downdownarrows;": '\U000021CA',
+ "downharpoonleft;": '\U000021C3',
+ "downharpoonright;": '\U000021C2',
+ "drbkarow;": '\U00002910',
+ "drcorn;": '\U0000231F',
+ "drcrop;": '\U0000230C',
+ "dscr;": '\U0001D4B9',
+ "dscy;": '\U00000455',
+ "dsol;": '\U000029F6',
+ "dstrok;": '\U00000111',
+ "dtdot;": '\U000022F1',
+ "dtri;": '\U000025BF',
+ "dtrif;": '\U000025BE',
+ "duarr;": '\U000021F5',
+ "duhar;": '\U0000296F',
+ "dwangle;": '\U000029A6',
+ "dzcy;": '\U0000045F',
+ "dzigrarr;": '\U000027FF',
+ "eDDot;": '\U00002A77',
+ "eDot;": '\U00002251',
+ "eacute;": '\U000000E9',
+ "easter;": '\U00002A6E',
+ "ecaron;": '\U0000011B',
+ "ecir;": '\U00002256',
+ "ecirc;": '\U000000EA',
+ "ecolon;": '\U00002255',
+ "ecy;": '\U0000044D',
+ "edot;": '\U00000117',
+ "ee;": '\U00002147',
+ "efDot;": '\U00002252',
+ "efr;": '\U0001D522',
+ "eg;": '\U00002A9A',
+ "egrave;": '\U000000E8',
+ "egs;": '\U00002A96',
+ "egsdot;": '\U00002A98',
+ "el;": '\U00002A99',
+ "elinters;": '\U000023E7',
+ "ell;": '\U00002113',
+ "els;": '\U00002A95',
+ "elsdot;": '\U00002A97',
+ "emacr;": '\U00000113',
+ "empty;": '\U00002205',
+ "emptyset;": '\U00002205',
+ "emptyv;": '\U00002205',
+ "emsp;": '\U00002003',
+ "emsp13;": '\U00002004',
+ "emsp14;": '\U00002005',
+ "eng;": '\U0000014B',
+ "ensp;": '\U00002002',
+ "eogon;": '\U00000119',
+ "eopf;": '\U0001D556',
+ "epar;": '\U000022D5',
+ "eparsl;": '\U000029E3',
+ "eplus;": '\U00002A71',
+ "epsi;": '\U000003B5',
+ "epsilon;": '\U000003B5',
+ "epsiv;": '\U000003F5',
+ "eqcirc;": '\U00002256',
+ "eqcolon;": '\U00002255',
+ "eqsim;": '\U00002242',
+ "eqslantgtr;": '\U00002A96',
+ "eqslantless;": '\U00002A95',
+ "equals;": '\U0000003D',
+ "equest;": '\U0000225F',
+ "equiv;": '\U00002261',
+ "equivDD;": '\U00002A78',
+ "eqvparsl;": '\U000029E5',
+ "erDot;": '\U00002253',
+ "erarr;": '\U00002971',
+ "escr;": '\U0000212F',
+ "esdot;": '\U00002250',
+ "esim;": '\U00002242',
+ "eta;": '\U000003B7',
+ "eth;": '\U000000F0',
+ "euml;": '\U000000EB',
+ "euro;": '\U000020AC',
+ "excl;": '\U00000021',
+ "exist;": '\U00002203',
+ "expectation;": '\U00002130',
+ "exponentiale;": '\U00002147',
+ "fallingdotseq;": '\U00002252',
+ "fcy;": '\U00000444',
+ "female;": '\U00002640',
+ "ffilig;": '\U0000FB03',
+ "fflig;": '\U0000FB00',
+ "ffllig;": '\U0000FB04',
+ "ffr;": '\U0001D523',
+ "filig;": '\U0000FB01',
+ "flat;": '\U0000266D',
+ "fllig;": '\U0000FB02',
+ "fltns;": '\U000025B1',
+ "fnof;": '\U00000192',
+ "fopf;": '\U0001D557',
+ "forall;": '\U00002200',
+ "fork;": '\U000022D4',
+ "forkv;": '\U00002AD9',
+ "fpartint;": '\U00002A0D',
+ "frac12;": '\U000000BD',
+ "frac13;": '\U00002153',
+ "frac14;": '\U000000BC',
+ "frac15;": '\U00002155',
+ "frac16;": '\U00002159',
+ "frac18;": '\U0000215B',
+ "frac23;": '\U00002154',
+ "frac25;": '\U00002156',
+ "frac34;": '\U000000BE',
+ "frac35;": '\U00002157',
+ "frac38;": '\U0000215C',
+ "frac45;": '\U00002158',
+ "frac56;": '\U0000215A',
+ "frac58;": '\U0000215D',
+ "frac78;": '\U0000215E',
+ "frasl;": '\U00002044',
+ "frown;": '\U00002322',
+ "fscr;": '\U0001D4BB',
+ "gE;": '\U00002267',
+ "gEl;": '\U00002A8C',
+ "gacute;": '\U000001F5',
+ "gamma;": '\U000003B3',
+ "gammad;": '\U000003DD',
+ "gap;": '\U00002A86',
+ "gbreve;": '\U0000011F',
+ "gcirc;": '\U0000011D',
+ "gcy;": '\U00000433',
+ "gdot;": '\U00000121',
+ "ge;": '\U00002265',
+ "gel;": '\U000022DB',
+ "geq;": '\U00002265',
+ "geqq;": '\U00002267',
+ "geqslant;": '\U00002A7E',
+ "ges;": '\U00002A7E',
+ "gescc;": '\U00002AA9',
+ "gesdot;": '\U00002A80',
+ "gesdoto;": '\U00002A82',
+ "gesdotol;": '\U00002A84',
+ "gesles;": '\U00002A94',
+ "gfr;": '\U0001D524',
+ "gg;": '\U0000226B',
+ "ggg;": '\U000022D9',
+ "gimel;": '\U00002137',
+ "gjcy;": '\U00000453',
+ "gl;": '\U00002277',
+ "glE;": '\U00002A92',
+ "gla;": '\U00002AA5',
+ "glj;": '\U00002AA4',
+ "gnE;": '\U00002269',
+ "gnap;": '\U00002A8A',
+ "gnapprox;": '\U00002A8A',
+ "gne;": '\U00002A88',
+ "gneq;": '\U00002A88',
+ "gneqq;": '\U00002269',
+ "gnsim;": '\U000022E7',
+ "gopf;": '\U0001D558',
+ "grave;": '\U00000060',
+ "gscr;": '\U0000210A',
+ "gsim;": '\U00002273',
+ "gsime;": '\U00002A8E',
+ "gsiml;": '\U00002A90',
+ "gt;": '\U0000003E',
+ "gtcc;": '\U00002AA7',
+ "gtcir;": '\U00002A7A',
+ "gtdot;": '\U000022D7',
+ "gtlPar;": '\U00002995',
+ "gtquest;": '\U00002A7C',
+ "gtrapprox;": '\U00002A86',
+ "gtrarr;": '\U00002978',
+ "gtrdot;": '\U000022D7',
+ "gtreqless;": '\U000022DB',
+ "gtreqqless;": '\U00002A8C',
+ "gtrless;": '\U00002277',
+ "gtrsim;": '\U00002273',
+ "hArr;": '\U000021D4',
+ "hairsp;": '\U0000200A',
+ "half;": '\U000000BD',
+ "hamilt;": '\U0000210B',
+ "hardcy;": '\U0000044A',
+ "harr;": '\U00002194',
+ "harrcir;": '\U00002948',
+ "harrw;": '\U000021AD',
+ "hbar;": '\U0000210F',
+ "hcirc;": '\U00000125',
+ "hearts;": '\U00002665',
+ "heartsuit;": '\U00002665',
+ "hellip;": '\U00002026',
+ "hercon;": '\U000022B9',
+ "hfr;": '\U0001D525',
+ "hksearow;": '\U00002925',
+ "hkswarow;": '\U00002926',
+ "hoarr;": '\U000021FF',
+ "homtht;": '\U0000223B',
+ "hookleftarrow;": '\U000021A9',
+ "hookrightarrow;": '\U000021AA',
+ "hopf;": '\U0001D559',
+ "horbar;": '\U00002015',
+ "hscr;": '\U0001D4BD',
+ "hslash;": '\U0000210F',
+ "hstrok;": '\U00000127',
+ "hybull;": '\U00002043',
+ "hyphen;": '\U00002010',
+ "iacute;": '\U000000ED',
+ "ic;": '\U00002063',
+ "icirc;": '\U000000EE',
+ "icy;": '\U00000438',
+ "iecy;": '\U00000435',
+ "iexcl;": '\U000000A1',
+ "iff;": '\U000021D4',
+ "ifr;": '\U0001D526',
+ "igrave;": '\U000000EC',
+ "ii;": '\U00002148',
+ "iiiint;": '\U00002A0C',
+ "iiint;": '\U0000222D',
+ "iinfin;": '\U000029DC',
+ "iiota;": '\U00002129',
+ "ijlig;": '\U00000133',
+ "imacr;": '\U0000012B',
+ "image;": '\U00002111',
+ "imagline;": '\U00002110',
+ "imagpart;": '\U00002111',
+ "imath;": '\U00000131',
+ "imof;": '\U000022B7',
+ "imped;": '\U000001B5',
+ "in;": '\U00002208',
+ "incare;": '\U00002105',
+ "infin;": '\U0000221E',
+ "infintie;": '\U000029DD',
+ "inodot;": '\U00000131',
+ "int;": '\U0000222B',
+ "intcal;": '\U000022BA',
+ "integers;": '\U00002124',
+ "intercal;": '\U000022BA',
+ "intlarhk;": '\U00002A17',
+ "intprod;": '\U00002A3C',
+ "iocy;": '\U00000451',
+ "iogon;": '\U0000012F',
+ "iopf;": '\U0001D55A',
+ "iota;": '\U000003B9',
+ "iprod;": '\U00002A3C',
+ "iquest;": '\U000000BF',
+ "iscr;": '\U0001D4BE',
+ "isin;": '\U00002208',
+ "isinE;": '\U000022F9',
+ "isindot;": '\U000022F5',
+ "isins;": '\U000022F4',
+ "isinsv;": '\U000022F3',
+ "isinv;": '\U00002208',
+ "it;": '\U00002062',
+ "itilde;": '\U00000129',
+ "iukcy;": '\U00000456',
+ "iuml;": '\U000000EF',
+ "jcirc;": '\U00000135',
+ "jcy;": '\U00000439',
+ "jfr;": '\U0001D527',
+ "jmath;": '\U00000237',
+ "jopf;": '\U0001D55B',
+ "jscr;": '\U0001D4BF',
+ "jsercy;": '\U00000458',
+ "jukcy;": '\U00000454',
+ "kappa;": '\U000003BA',
+ "kappav;": '\U000003F0',
+ "kcedil;": '\U00000137',
+ "kcy;": '\U0000043A',
+ "kfr;": '\U0001D528',
+ "kgreen;": '\U00000138',
+ "khcy;": '\U00000445',
+ "kjcy;": '\U0000045C',
+ "kopf;": '\U0001D55C',
+ "kscr;": '\U0001D4C0',
+ "lAarr;": '\U000021DA',
+ "lArr;": '\U000021D0',
+ "lAtail;": '\U0000291B',
+ "lBarr;": '\U0000290E',
+ "lE;": '\U00002266',
+ "lEg;": '\U00002A8B',
+ "lHar;": '\U00002962',
+ "lacute;": '\U0000013A',
+ "laemptyv;": '\U000029B4',
+ "lagran;": '\U00002112',
+ "lambda;": '\U000003BB',
+ "lang;": '\U000027E8',
+ "langd;": '\U00002991',
+ "langle;": '\U000027E8',
+ "lap;": '\U00002A85',
+ "laquo;": '\U000000AB',
+ "larr;": '\U00002190',
+ "larrb;": '\U000021E4',
+ "larrbfs;": '\U0000291F',
+ "larrfs;": '\U0000291D',
+ "larrhk;": '\U000021A9',
+ "larrlp;": '\U000021AB',
+ "larrpl;": '\U00002939',
+ "larrsim;": '\U00002973',
+ "larrtl;": '\U000021A2',
+ "lat;": '\U00002AAB',
+ "latail;": '\U00002919',
+ "late;": '\U00002AAD',
+ "lbarr;": '\U0000290C',
+ "lbbrk;": '\U00002772',
+ "lbrace;": '\U0000007B',
+ "lbrack;": '\U0000005B',
+ "lbrke;": '\U0000298B',
+ "lbrksld;": '\U0000298F',
+ "lbrkslu;": '\U0000298D',
+ "lcaron;": '\U0000013E',
+ "lcedil;": '\U0000013C',
+ "lceil;": '\U00002308',
+ "lcub;": '\U0000007B',
+ "lcy;": '\U0000043B',
+ "ldca;": '\U00002936',
+ "ldquo;": '\U0000201C',
+ "ldquor;": '\U0000201E',
+ "ldrdhar;": '\U00002967',
+ "ldrushar;": '\U0000294B',
+ "ldsh;": '\U000021B2',
+ "le;": '\U00002264',
+ "leftarrow;": '\U00002190',
+ "leftarrowtail;": '\U000021A2',
+ "leftharpoondown;": '\U000021BD',
+ "leftharpoonup;": '\U000021BC',
+ "leftleftarrows;": '\U000021C7',
+ "leftrightarrow;": '\U00002194',
+ "leftrightarrows;": '\U000021C6',
+ "leftrightharpoons;": '\U000021CB',
+ "leftrightsquigarrow;": '\U000021AD',
+ "leftthreetimes;": '\U000022CB',
+ "leg;": '\U000022DA',
+ "leq;": '\U00002264',
+ "leqq;": '\U00002266',
+ "leqslant;": '\U00002A7D',
+ "les;": '\U00002A7D',
+ "lescc;": '\U00002AA8',
+ "lesdot;": '\U00002A7F',
+ "lesdoto;": '\U00002A81',
+ "lesdotor;": '\U00002A83',
+ "lesges;": '\U00002A93',
+ "lessapprox;": '\U00002A85',
+ "lessdot;": '\U000022D6',
+ "lesseqgtr;": '\U000022DA',
+ "lesseqqgtr;": '\U00002A8B',
+ "lessgtr;": '\U00002276',
+ "lesssim;": '\U00002272',
+ "lfisht;": '\U0000297C',
+ "lfloor;": '\U0000230A',
+ "lfr;": '\U0001D529',
+ "lg;": '\U00002276',
+ "lgE;": '\U00002A91',
+ "lhard;": '\U000021BD',
+ "lharu;": '\U000021BC',
+ "lharul;": '\U0000296A',
+ "lhblk;": '\U00002584',
+ "ljcy;": '\U00000459',
+ "ll;": '\U0000226A',
+ "llarr;": '\U000021C7',
+ "llcorner;": '\U0000231E',
+ "llhard;": '\U0000296B',
+ "lltri;": '\U000025FA',
+ "lmidot;": '\U00000140',
+ "lmoust;": '\U000023B0',
+ "lmoustache;": '\U000023B0',
+ "lnE;": '\U00002268',
+ "lnap;": '\U00002A89',
+ "lnapprox;": '\U00002A89',
+ "lne;": '\U00002A87',
+ "lneq;": '\U00002A87',
+ "lneqq;": '\U00002268',
+ "lnsim;": '\U000022E6',
+ "loang;": '\U000027EC',
+ "loarr;": '\U000021FD',
+ "lobrk;": '\U000027E6',
+ "longleftarrow;": '\U000027F5',
+ "longleftrightarrow;": '\U000027F7',
+ "longmapsto;": '\U000027FC',
+ "longrightarrow;": '\U000027F6',
+ "looparrowleft;": '\U000021AB',
+ "looparrowright;": '\U000021AC',
+ "lopar;": '\U00002985',
+ "lopf;": '\U0001D55D',
+ "loplus;": '\U00002A2D',
+ "lotimes;": '\U00002A34',
+ "lowast;": '\U00002217',
+ "lowbar;": '\U0000005F',
+ "loz;": '\U000025CA',
+ "lozenge;": '\U000025CA',
+ "lozf;": '\U000029EB',
+ "lpar;": '\U00000028',
+ "lparlt;": '\U00002993',
+ "lrarr;": '\U000021C6',
+ "lrcorner;": '\U0000231F',
+ "lrhar;": '\U000021CB',
+ "lrhard;": '\U0000296D',
+ "lrm;": '\U0000200E',
+ "lrtri;": '\U000022BF',
+ "lsaquo;": '\U00002039',
+ "lscr;": '\U0001D4C1',
+ "lsh;": '\U000021B0',
+ "lsim;": '\U00002272',
+ "lsime;": '\U00002A8D',
+ "lsimg;": '\U00002A8F',
+ "lsqb;": '\U0000005B',
+ "lsquo;": '\U00002018',
+ "lsquor;": '\U0000201A',
+ "lstrok;": '\U00000142',
+ "lt;": '\U0000003C',
+ "ltcc;": '\U00002AA6',
+ "ltcir;": '\U00002A79',
+ "ltdot;": '\U000022D6',
+ "lthree;": '\U000022CB',
+ "ltimes;": '\U000022C9',
+ "ltlarr;": '\U00002976',
+ "ltquest;": '\U00002A7B',
+ "ltrPar;": '\U00002996',
+ "ltri;": '\U000025C3',
+ "ltrie;": '\U000022B4',
+ "ltrif;": '\U000025C2',
+ "lurdshar;": '\U0000294A',
+ "luruhar;": '\U00002966',
+ "mDDot;": '\U0000223A',
+ "macr;": '\U000000AF',
+ "male;": '\U00002642',
+ "malt;": '\U00002720',
+ "maltese;": '\U00002720',
+ "map;": '\U000021A6',
+ "mapsto;": '\U000021A6',
+ "mapstodown;": '\U000021A7',
+ "mapstoleft;": '\U000021A4',
+ "mapstoup;": '\U000021A5',
+ "marker;": '\U000025AE',
+ "mcomma;": '\U00002A29',
+ "mcy;": '\U0000043C',
+ "mdash;": '\U00002014',
+ "measuredangle;": '\U00002221',
+ "mfr;": '\U0001D52A',
+ "mho;": '\U00002127',
+ "micro;": '\U000000B5',
+ "mid;": '\U00002223',
+ "midast;": '\U0000002A',
+ "midcir;": '\U00002AF0',
+ "middot;": '\U000000B7',
+ "minus;": '\U00002212',
+ "minusb;": '\U0000229F',
+ "minusd;": '\U00002238',
+ "minusdu;": '\U00002A2A',
+ "mlcp;": '\U00002ADB',
+ "mldr;": '\U00002026',
+ "mnplus;": '\U00002213',
+ "models;": '\U000022A7',
+ "mopf;": '\U0001D55E',
+ "mp;": '\U00002213',
+ "mscr;": '\U0001D4C2',
+ "mstpos;": '\U0000223E',
+ "mu;": '\U000003BC',
+ "multimap;": '\U000022B8',
+ "mumap;": '\U000022B8',
+ "nLeftarrow;": '\U000021CD',
+ "nLeftrightarrow;": '\U000021CE',
+ "nRightarrow;": '\U000021CF',
+ "nVDash;": '\U000022AF',
+ "nVdash;": '\U000022AE',
+ "nabla;": '\U00002207',
+ "nacute;": '\U00000144',
+ "nap;": '\U00002249',
+ "napos;": '\U00000149',
+ "napprox;": '\U00002249',
+ "natur;": '\U0000266E',
+ "natural;": '\U0000266E',
+ "naturals;": '\U00002115',
+ "nbsp;": '\U000000A0',
+ "ncap;": '\U00002A43',
+ "ncaron;": '\U00000148',
+ "ncedil;": '\U00000146',
+ "ncong;": '\U00002247',
+ "ncup;": '\U00002A42',
+ "ncy;": '\U0000043D',
+ "ndash;": '\U00002013',
+ "ne;": '\U00002260',
+ "neArr;": '\U000021D7',
+ "nearhk;": '\U00002924',
+ "nearr;": '\U00002197',
+ "nearrow;": '\U00002197',
+ "nequiv;": '\U00002262',
+ "nesear;": '\U00002928',
+ "nexist;": '\U00002204',
+ "nexists;": '\U00002204',
+ "nfr;": '\U0001D52B',
+ "nge;": '\U00002271',
+ "ngeq;": '\U00002271',
+ "ngsim;": '\U00002275',
+ "ngt;": '\U0000226F',
+ "ngtr;": '\U0000226F',
+ "nhArr;": '\U000021CE',
+ "nharr;": '\U000021AE',
+ "nhpar;": '\U00002AF2',
+ "ni;": '\U0000220B',
+ "nis;": '\U000022FC',
+ "nisd;": '\U000022FA',
+ "niv;": '\U0000220B',
+ "njcy;": '\U0000045A',
+ "nlArr;": '\U000021CD',
+ "nlarr;": '\U0000219A',
+ "nldr;": '\U00002025',
+ "nle;": '\U00002270',
+ "nleftarrow;": '\U0000219A',
+ "nleftrightarrow;": '\U000021AE',
+ "nleq;": '\U00002270',
+ "nless;": '\U0000226E',
+ "nlsim;": '\U00002274',
+ "nlt;": '\U0000226E',
+ "nltri;": '\U000022EA',
+ "nltrie;": '\U000022EC',
+ "nmid;": '\U00002224',
+ "nopf;": '\U0001D55F',
+ "not;": '\U000000AC',
+ "notin;": '\U00002209',
+ "notinva;": '\U00002209',
+ "notinvb;": '\U000022F7',
+ "notinvc;": '\U000022F6',
+ "notni;": '\U0000220C',
+ "notniva;": '\U0000220C',
+ "notnivb;": '\U000022FE',
+ "notnivc;": '\U000022FD',
+ "npar;": '\U00002226',
+ "nparallel;": '\U00002226',
+ "npolint;": '\U00002A14',
+ "npr;": '\U00002280',
+ "nprcue;": '\U000022E0',
+ "nprec;": '\U00002280',
+ "nrArr;": '\U000021CF',
+ "nrarr;": '\U0000219B',
+ "nrightarrow;": '\U0000219B',
+ "nrtri;": '\U000022EB',
+ "nrtrie;": '\U000022ED',
+ "nsc;": '\U00002281',
+ "nsccue;": '\U000022E1',
+ "nscr;": '\U0001D4C3',
+ "nshortmid;": '\U00002224',
+ "nshortparallel;": '\U00002226',
+ "nsim;": '\U00002241',
+ "nsime;": '\U00002244',
+ "nsimeq;": '\U00002244',
+ "nsmid;": '\U00002224',
+ "nspar;": '\U00002226',
+ "nsqsube;": '\U000022E2',
+ "nsqsupe;": '\U000022E3',
+ "nsub;": '\U00002284',
+ "nsube;": '\U00002288',
+ "nsubseteq;": '\U00002288',
+ "nsucc;": '\U00002281',
+ "nsup;": '\U00002285',
+ "nsupe;": '\U00002289',
+ "nsupseteq;": '\U00002289',
+ "ntgl;": '\U00002279',
+ "ntilde;": '\U000000F1',
+ "ntlg;": '\U00002278',
+ "ntriangleleft;": '\U000022EA',
+ "ntrianglelefteq;": '\U000022EC',
+ "ntriangleright;": '\U000022EB',
+ "ntrianglerighteq;": '\U000022ED',
+ "nu;": '\U000003BD',
+ "num;": '\U00000023',
+ "numero;": '\U00002116',
+ "numsp;": '\U00002007',
+ "nvDash;": '\U000022AD',
+ "nvHarr;": '\U00002904',
+ "nvdash;": '\U000022AC',
+ "nvinfin;": '\U000029DE',
+ "nvlArr;": '\U00002902',
+ "nvrArr;": '\U00002903',
+ "nwArr;": '\U000021D6',
+ "nwarhk;": '\U00002923',
+ "nwarr;": '\U00002196',
+ "nwarrow;": '\U00002196',
+ "nwnear;": '\U00002927',
+ "oS;": '\U000024C8',
+ "oacute;": '\U000000F3',
+ "oast;": '\U0000229B',
+ "ocir;": '\U0000229A',
+ "ocirc;": '\U000000F4',
+ "ocy;": '\U0000043E',
+ "odash;": '\U0000229D',
+ "odblac;": '\U00000151',
+ "odiv;": '\U00002A38',
+ "odot;": '\U00002299',
+ "odsold;": '\U000029BC',
+ "oelig;": '\U00000153',
+ "ofcir;": '\U000029BF',
+ "ofr;": '\U0001D52C',
+ "ogon;": '\U000002DB',
+ "ograve;": '\U000000F2',
+ "ogt;": '\U000029C1',
+ "ohbar;": '\U000029B5',
+ "ohm;": '\U000003A9',
+ "oint;": '\U0000222E',
+ "olarr;": '\U000021BA',
+ "olcir;": '\U000029BE',
+ "olcross;": '\U000029BB',
+ "oline;": '\U0000203E',
+ "olt;": '\U000029C0',
+ "omacr;": '\U0000014D',
+ "omega;": '\U000003C9',
+ "omicron;": '\U000003BF',
+ "omid;": '\U000029B6',
+ "ominus;": '\U00002296',
+ "oopf;": '\U0001D560',
+ "opar;": '\U000029B7',
+ "operp;": '\U000029B9',
+ "oplus;": '\U00002295',
+ "or;": '\U00002228',
+ "orarr;": '\U000021BB',
+ "ord;": '\U00002A5D',
+ "order;": '\U00002134',
+ "orderof;": '\U00002134',
+ "ordf;": '\U000000AA',
+ "ordm;": '\U000000BA',
+ "origof;": '\U000022B6',
+ "oror;": '\U00002A56',
+ "orslope;": '\U00002A57',
+ "orv;": '\U00002A5B',
+ "oscr;": '\U00002134',
+ "oslash;": '\U000000F8',
+ "osol;": '\U00002298',
+ "otilde;": '\U000000F5',
+ "otimes;": '\U00002297',
+ "otimesas;": '\U00002A36',
+ "ouml;": '\U000000F6',
+ "ovbar;": '\U0000233D',
+ "par;": '\U00002225',
+ "para;": '\U000000B6',
+ "parallel;": '\U00002225',
+ "parsim;": '\U00002AF3',
+ "parsl;": '\U00002AFD',
+ "part;": '\U00002202',
+ "pcy;": '\U0000043F',
+ "percnt;": '\U00000025',
+ "period;": '\U0000002E',
+ "permil;": '\U00002030',
+ "perp;": '\U000022A5',
+ "pertenk;": '\U00002031',
+ "pfr;": '\U0001D52D',
+ "phi;": '\U000003C6',
+ "phiv;": '\U000003D5',
+ "phmmat;": '\U00002133',
+ "phone;": '\U0000260E',
+ "pi;": '\U000003C0',
+ "pitchfork;": '\U000022D4',
+ "piv;": '\U000003D6',
+ "planck;": '\U0000210F',
+ "planckh;": '\U0000210E',
+ "plankv;": '\U0000210F',
+ "plus;": '\U0000002B',
+ "plusacir;": '\U00002A23',
+ "plusb;": '\U0000229E',
+ "pluscir;": '\U00002A22',
+ "plusdo;": '\U00002214',
+ "plusdu;": '\U00002A25',
+ "pluse;": '\U00002A72',
+ "plusmn;": '\U000000B1',
+ "plussim;": '\U00002A26',
+ "plustwo;": '\U00002A27',
+ "pm;": '\U000000B1',
+ "pointint;": '\U00002A15',
+ "popf;": '\U0001D561',
+ "pound;": '\U000000A3',
+ "pr;": '\U0000227A',
+ "prE;": '\U00002AB3',
+ "prap;": '\U00002AB7',
+ "prcue;": '\U0000227C',
+ "pre;": '\U00002AAF',
+ "prec;": '\U0000227A',
+ "precapprox;": '\U00002AB7',
+ "preccurlyeq;": '\U0000227C',
+ "preceq;": '\U00002AAF',
+ "precnapprox;": '\U00002AB9',
+ "precneqq;": '\U00002AB5',
+ "precnsim;": '\U000022E8',
+ "precsim;": '\U0000227E',
+ "prime;": '\U00002032',
+ "primes;": '\U00002119',
+ "prnE;": '\U00002AB5',
+ "prnap;": '\U00002AB9',
+ "prnsim;": '\U000022E8',
+ "prod;": '\U0000220F',
+ "profalar;": '\U0000232E',
+ "profline;": '\U00002312',
+ "profsurf;": '\U00002313',
+ "prop;": '\U0000221D',
+ "propto;": '\U0000221D',
+ "prsim;": '\U0000227E',
+ "prurel;": '\U000022B0',
+ "pscr;": '\U0001D4C5',
+ "psi;": '\U000003C8',
+ "puncsp;": '\U00002008',
+ "qfr;": '\U0001D52E',
+ "qint;": '\U00002A0C',
+ "qopf;": '\U0001D562',
+ "qprime;": '\U00002057',
+ "qscr;": '\U0001D4C6',
+ "quaternions;": '\U0000210D',
+ "quatint;": '\U00002A16',
+ "quest;": '\U0000003F',
+ "questeq;": '\U0000225F',
+ "quot;": '\U00000022',
+ "rAarr;": '\U000021DB',
+ "rArr;": '\U000021D2',
+ "rAtail;": '\U0000291C',
+ "rBarr;": '\U0000290F',
+ "rHar;": '\U00002964',
+ "racute;": '\U00000155',
+ "radic;": '\U0000221A',
+ "raemptyv;": '\U000029B3',
+ "rang;": '\U000027E9',
+ "rangd;": '\U00002992',
+ "range;": '\U000029A5',
+ "rangle;": '\U000027E9',
+ "raquo;": '\U000000BB',
+ "rarr;": '\U00002192',
+ "rarrap;": '\U00002975',
+ "rarrb;": '\U000021E5',
+ "rarrbfs;": '\U00002920',
+ "rarrc;": '\U00002933',
+ "rarrfs;": '\U0000291E',
+ "rarrhk;": '\U000021AA',
+ "rarrlp;": '\U000021AC',
+ "rarrpl;": '\U00002945',
+ "rarrsim;": '\U00002974',
+ "rarrtl;": '\U000021A3',
+ "rarrw;": '\U0000219D',
+ "ratail;": '\U0000291A',
+ "ratio;": '\U00002236',
+ "rationals;": '\U0000211A',
+ "rbarr;": '\U0000290D',
+ "rbbrk;": '\U00002773',
+ "rbrace;": '\U0000007D',
+ "rbrack;": '\U0000005D',
+ "rbrke;": '\U0000298C',
+ "rbrksld;": '\U0000298E',
+ "rbrkslu;": '\U00002990',
+ "rcaron;": '\U00000159',
+ "rcedil;": '\U00000157',
+ "rceil;": '\U00002309',
+ "rcub;": '\U0000007D',
+ "rcy;": '\U00000440',
+ "rdca;": '\U00002937',
+ "rdldhar;": '\U00002969',
+ "rdquo;": '\U0000201D',
+ "rdquor;": '\U0000201D',
+ "rdsh;": '\U000021B3',
+ "real;": '\U0000211C',
+ "realine;": '\U0000211B',
+ "realpart;": '\U0000211C',
+ "reals;": '\U0000211D',
+ "rect;": '\U000025AD',
+ "reg;": '\U000000AE',
+ "rfisht;": '\U0000297D',
+ "rfloor;": '\U0000230B',
+ "rfr;": '\U0001D52F',
+ "rhard;": '\U000021C1',
+ "rharu;": '\U000021C0',
+ "rharul;": '\U0000296C',
+ "rho;": '\U000003C1',
+ "rhov;": '\U000003F1',
+ "rightarrow;": '\U00002192',
+ "rightarrowtail;": '\U000021A3',
+ "rightharpoondown;": '\U000021C1',
+ "rightharpoonup;": '\U000021C0',
+ "rightleftarrows;": '\U000021C4',
+ "rightleftharpoons;": '\U000021CC',
+ "rightrightarrows;": '\U000021C9',
+ "rightsquigarrow;": '\U0000219D',
+ "rightthreetimes;": '\U000022CC',
+ "ring;": '\U000002DA',
+ "risingdotseq;": '\U00002253',
+ "rlarr;": '\U000021C4',
+ "rlhar;": '\U000021CC',
+ "rlm;": '\U0000200F',
+ "rmoust;": '\U000023B1',
+ "rmoustache;": '\U000023B1',
+ "rnmid;": '\U00002AEE',
+ "roang;": '\U000027ED',
+ "roarr;": '\U000021FE',
+ "robrk;": '\U000027E7',
+ "ropar;": '\U00002986',
+ "ropf;": '\U0001D563',
+ "roplus;": '\U00002A2E',
+ "rotimes;": '\U00002A35',
+ "rpar;": '\U00000029',
+ "rpargt;": '\U00002994',
+ "rppolint;": '\U00002A12',
+ "rrarr;": '\U000021C9',
+ "rsaquo;": '\U0000203A',
+ "rscr;": '\U0001D4C7',
+ "rsh;": '\U000021B1',
+ "rsqb;": '\U0000005D',
+ "rsquo;": '\U00002019',
+ "rsquor;": '\U00002019',
+ "rthree;": '\U000022CC',
+ "rtimes;": '\U000022CA',
+ "rtri;": '\U000025B9',
+ "rtrie;": '\U000022B5',
+ "rtrif;": '\U000025B8',
+ "rtriltri;": '\U000029CE',
+ "ruluhar;": '\U00002968',
+ "rx;": '\U0000211E',
+ "sacute;": '\U0000015B',
+ "sbquo;": '\U0000201A',
+ "sc;": '\U0000227B',
+ "scE;": '\U00002AB4',
+ "scap;": '\U00002AB8',
+ "scaron;": '\U00000161',
+ "sccue;": '\U0000227D',
+ "sce;": '\U00002AB0',
+ "scedil;": '\U0000015F',
+ "scirc;": '\U0000015D',
+ "scnE;": '\U00002AB6',
+ "scnap;": '\U00002ABA',
+ "scnsim;": '\U000022E9',
+ "scpolint;": '\U00002A13',
+ "scsim;": '\U0000227F',
+ "scy;": '\U00000441',
+ "sdot;": '\U000022C5',
+ "sdotb;": '\U000022A1',
+ "sdote;": '\U00002A66',
+ "seArr;": '\U000021D8',
+ "searhk;": '\U00002925',
+ "searr;": '\U00002198',
+ "searrow;": '\U00002198',
+ "sect;": '\U000000A7',
+ "semi;": '\U0000003B',
+ "seswar;": '\U00002929',
+ "setminus;": '\U00002216',
+ "setmn;": '\U00002216',
+ "sext;": '\U00002736',
+ "sfr;": '\U0001D530',
+ "sfrown;": '\U00002322',
+ "sharp;": '\U0000266F',
+ "shchcy;": '\U00000449',
+ "shcy;": '\U00000448',
+ "shortmid;": '\U00002223',
+ "shortparallel;": '\U00002225',
+ "shy;": '\U000000AD',
+ "sigma;": '\U000003C3',
+ "sigmaf;": '\U000003C2',
+ "sigmav;": '\U000003C2',
+ "sim;": '\U0000223C',
+ "simdot;": '\U00002A6A',
+ "sime;": '\U00002243',
+ "simeq;": '\U00002243',
+ "simg;": '\U00002A9E',
+ "simgE;": '\U00002AA0',
+ "siml;": '\U00002A9D',
+ "simlE;": '\U00002A9F',
+ "simne;": '\U00002246',
+ "simplus;": '\U00002A24',
+ "simrarr;": '\U00002972',
+ "slarr;": '\U00002190',
+ "smallsetminus;": '\U00002216',
+ "smashp;": '\U00002A33',
+ "smeparsl;": '\U000029E4',
+ "smid;": '\U00002223',
+ "smile;": '\U00002323',
+ "smt;": '\U00002AAA',
+ "smte;": '\U00002AAC',
+ "softcy;": '\U0000044C',
+ "sol;": '\U0000002F',
+ "solb;": '\U000029C4',
+ "solbar;": '\U0000233F',
+ "sopf;": '\U0001D564',
+ "spades;": '\U00002660',
+ "spadesuit;": '\U00002660',
+ "spar;": '\U00002225',
+ "sqcap;": '\U00002293',
+ "sqcup;": '\U00002294',
+ "sqsub;": '\U0000228F',
+ "sqsube;": '\U00002291',
+ "sqsubset;": '\U0000228F',
+ "sqsubseteq;": '\U00002291',
+ "sqsup;": '\U00002290',
+ "sqsupe;": '\U00002292',
+ "sqsupset;": '\U00002290',
+ "sqsupseteq;": '\U00002292',
+ "squ;": '\U000025A1',
+ "square;": '\U000025A1',
+ "squarf;": '\U000025AA',
+ "squf;": '\U000025AA',
+ "srarr;": '\U00002192',
+ "sscr;": '\U0001D4C8',
+ "ssetmn;": '\U00002216',
+ "ssmile;": '\U00002323',
+ "sstarf;": '\U000022C6',
+ "star;": '\U00002606',
+ "starf;": '\U00002605',
+ "straightepsilon;": '\U000003F5',
+ "straightphi;": '\U000003D5',
+ "strns;": '\U000000AF',
+ "sub;": '\U00002282',
+ "subE;": '\U00002AC5',
+ "subdot;": '\U00002ABD',
+ "sube;": '\U00002286',
+ "subedot;": '\U00002AC3',
+ "submult;": '\U00002AC1',
+ "subnE;": '\U00002ACB',
+ "subne;": '\U0000228A',
+ "subplus;": '\U00002ABF',
+ "subrarr;": '\U00002979',
+ "subset;": '\U00002282',
+ "subseteq;": '\U00002286',
+ "subseteqq;": '\U00002AC5',
+ "subsetneq;": '\U0000228A',
+ "subsetneqq;": '\U00002ACB',
+ "subsim;": '\U00002AC7',
+ "subsub;": '\U00002AD5',
+ "subsup;": '\U00002AD3',
+ "succ;": '\U0000227B',
+ "succapprox;": '\U00002AB8',
+ "succcurlyeq;": '\U0000227D',
+ "succeq;": '\U00002AB0',
+ "succnapprox;": '\U00002ABA',
+ "succneqq;": '\U00002AB6',
+ "succnsim;": '\U000022E9',
+ "succsim;": '\U0000227F',
+ "sum;": '\U00002211',
+ "sung;": '\U0000266A',
+ "sup;": '\U00002283',
+ "sup1;": '\U000000B9',
+ "sup2;": '\U000000B2',
+ "sup3;": '\U000000B3',
+ "supE;": '\U00002AC6',
+ "supdot;": '\U00002ABE',
+ "supdsub;": '\U00002AD8',
+ "supe;": '\U00002287',
+ "supedot;": '\U00002AC4',
+ "suphsol;": '\U000027C9',
+ "suphsub;": '\U00002AD7',
+ "suplarr;": '\U0000297B',
+ "supmult;": '\U00002AC2',
+ "supnE;": '\U00002ACC',
+ "supne;": '\U0000228B',
+ "supplus;": '\U00002AC0',
+ "supset;": '\U00002283',
+ "supseteq;": '\U00002287',
+ "supseteqq;": '\U00002AC6',
+ "supsetneq;": '\U0000228B',
+ "supsetneqq;": '\U00002ACC',
+ "supsim;": '\U00002AC8',
+ "supsub;": '\U00002AD4',
+ "supsup;": '\U00002AD6',
+ "swArr;": '\U000021D9',
+ "swarhk;": '\U00002926',
+ "swarr;": '\U00002199',
+ "swarrow;": '\U00002199',
+ "swnwar;": '\U0000292A',
+ "szlig;": '\U000000DF',
+ "target;": '\U00002316',
+ "tau;": '\U000003C4',
+ "tbrk;": '\U000023B4',
+ "tcaron;": '\U00000165',
+ "tcedil;": '\U00000163',
+ "tcy;": '\U00000442',
+ "tdot;": '\U000020DB',
+ "telrec;": '\U00002315',
+ "tfr;": '\U0001D531',
+ "there4;": '\U00002234',
+ "therefore;": '\U00002234',
+ "theta;": '\U000003B8',
+ "thetasym;": '\U000003D1',
+ "thetav;": '\U000003D1',
+ "thickapprox;": '\U00002248',
+ "thicksim;": '\U0000223C',
+ "thinsp;": '\U00002009',
+ "thkap;": '\U00002248',
+ "thksim;": '\U0000223C',
+ "thorn;": '\U000000FE',
+ "tilde;": '\U000002DC',
+ "times;": '\U000000D7',
+ "timesb;": '\U000022A0',
+ "timesbar;": '\U00002A31',
+ "timesd;": '\U00002A30',
+ "tint;": '\U0000222D',
+ "toea;": '\U00002928',
+ "top;": '\U000022A4',
+ "topbot;": '\U00002336',
+ "topcir;": '\U00002AF1',
+ "topf;": '\U0001D565',
+ "topfork;": '\U00002ADA',
+ "tosa;": '\U00002929',
+ "tprime;": '\U00002034',
+ "trade;": '\U00002122',
+ "triangle;": '\U000025B5',
+ "triangledown;": '\U000025BF',
+ "triangleleft;": '\U000025C3',
+ "trianglelefteq;": '\U000022B4',
+ "triangleq;": '\U0000225C',
+ "triangleright;": '\U000025B9',
+ "trianglerighteq;": '\U000022B5',
+ "tridot;": '\U000025EC',
+ "trie;": '\U0000225C',
+ "triminus;": '\U00002A3A',
+ "triplus;": '\U00002A39',
+ "trisb;": '\U000029CD',
+ "tritime;": '\U00002A3B',
+ "trpezium;": '\U000023E2',
+ "tscr;": '\U0001D4C9',
+ "tscy;": '\U00000446',
+ "tshcy;": '\U0000045B',
+ "tstrok;": '\U00000167',
+ "twixt;": '\U0000226C',
+ "twoheadleftarrow;": '\U0000219E',
+ "twoheadrightarrow;": '\U000021A0',
+ "uArr;": '\U000021D1',
+ "uHar;": '\U00002963',
+ "uacute;": '\U000000FA',
+ "uarr;": '\U00002191',
+ "ubrcy;": '\U0000045E',
+ "ubreve;": '\U0000016D',
+ "ucirc;": '\U000000FB',
+ "ucy;": '\U00000443',
+ "udarr;": '\U000021C5',
+ "udblac;": '\U00000171',
+ "udhar;": '\U0000296E',
+ "ufisht;": '\U0000297E',
+ "ufr;": '\U0001D532',
+ "ugrave;": '\U000000F9',
+ "uharl;": '\U000021BF',
+ "uharr;": '\U000021BE',
+ "uhblk;": '\U00002580',
+ "ulcorn;": '\U0000231C',
+ "ulcorner;": '\U0000231C',
+ "ulcrop;": '\U0000230F',
+ "ultri;": '\U000025F8',
+ "umacr;": '\U0000016B',
+ "uml;": '\U000000A8',
+ "uogon;": '\U00000173',
+ "uopf;": '\U0001D566',
+ "uparrow;": '\U00002191',
+ "updownarrow;": '\U00002195',
+ "upharpoonleft;": '\U000021BF',
+ "upharpoonright;": '\U000021BE',
+ "uplus;": '\U0000228E',
+ "upsi;": '\U000003C5',
+ "upsih;": '\U000003D2',
+ "upsilon;": '\U000003C5',
+ "upuparrows;": '\U000021C8',
+ "urcorn;": '\U0000231D',
+ "urcorner;": '\U0000231D',
+ "urcrop;": '\U0000230E',
+ "uring;": '\U0000016F',
+ "urtri;": '\U000025F9',
+ "uscr;": '\U0001D4CA',
+ "utdot;": '\U000022F0',
+ "utilde;": '\U00000169',
+ "utri;": '\U000025B5',
+ "utrif;": '\U000025B4',
+ "uuarr;": '\U000021C8',
+ "uuml;": '\U000000FC',
+ "uwangle;": '\U000029A7',
+ "vArr;": '\U000021D5',
+ "vBar;": '\U00002AE8',
+ "vBarv;": '\U00002AE9',
+ "vDash;": '\U000022A8',
+ "vangrt;": '\U0000299C',
+ "varepsilon;": '\U000003F5',
+ "varkappa;": '\U000003F0',
+ "varnothing;": '\U00002205',
+ "varphi;": '\U000003D5',
+ "varpi;": '\U000003D6',
+ "varpropto;": '\U0000221D',
+ "varr;": '\U00002195',
+ "varrho;": '\U000003F1',
+ "varsigma;": '\U000003C2',
+ "vartheta;": '\U000003D1',
+ "vartriangleleft;": '\U000022B2',
+ "vartriangleright;": '\U000022B3',
+ "vcy;": '\U00000432',
+ "vdash;": '\U000022A2',
+ "vee;": '\U00002228',
+ "veebar;": '\U000022BB',
+ "veeeq;": '\U0000225A',
+ "vellip;": '\U000022EE',
+ "verbar;": '\U0000007C',
+ "vert;": '\U0000007C',
+ "vfr;": '\U0001D533',
+ "vltri;": '\U000022B2',
+ "vopf;": '\U0001D567',
+ "vprop;": '\U0000221D',
+ "vrtri;": '\U000022B3',
+ "vscr;": '\U0001D4CB',
+ "vzigzag;": '\U0000299A',
+ "wcirc;": '\U00000175',
+ "wedbar;": '\U00002A5F',
+ "wedge;": '\U00002227',
+ "wedgeq;": '\U00002259',
+ "weierp;": '\U00002118',
+ "wfr;": '\U0001D534',
+ "wopf;": '\U0001D568',
+ "wp;": '\U00002118',
+ "wr;": '\U00002240',
+ "wreath;": '\U00002240',
+ "wscr;": '\U0001D4CC',
+ "xcap;": '\U000022C2',
+ "xcirc;": '\U000025EF',
+ "xcup;": '\U000022C3',
+ "xdtri;": '\U000025BD',
+ "xfr;": '\U0001D535',
+ "xhArr;": '\U000027FA',
+ "xharr;": '\U000027F7',
+ "xi;": '\U000003BE',
+ "xlArr;": '\U000027F8',
+ "xlarr;": '\U000027F5',
+ "xmap;": '\U000027FC',
+ "xnis;": '\U000022FB',
+ "xodot;": '\U00002A00',
+ "xopf;": '\U0001D569',
+ "xoplus;": '\U00002A01',
+ "xotime;": '\U00002A02',
+ "xrArr;": '\U000027F9',
+ "xrarr;": '\U000027F6',
+ "xscr;": '\U0001D4CD',
+ "xsqcup;": '\U00002A06',
+ "xuplus;": '\U00002A04',
+ "xutri;": '\U000025B3',
+ "xvee;": '\U000022C1',
+ "xwedge;": '\U000022C0',
+ "yacute;": '\U000000FD',
+ "yacy;": '\U0000044F',
+ "ycirc;": '\U00000177',
+ "ycy;": '\U0000044B',
+ "yen;": '\U000000A5',
+ "yfr;": '\U0001D536',
+ "yicy;": '\U00000457',
+ "yopf;": '\U0001D56A',
+ "yscr;": '\U0001D4CE',
+ "yucy;": '\U0000044E',
+ "yuml;": '\U000000FF',
+ "zacute;": '\U0000017A',
+ "zcaron;": '\U0000017E',
+ "zcy;": '\U00000437',
+ "zdot;": '\U0000017C',
+ "zeetrf;": '\U00002128',
+ "zeta;": '\U000003B6',
+ "zfr;": '\U0001D537',
+ "zhcy;": '\U00000436',
+ "zigrarr;": '\U000021DD',
+ "zopf;": '\U0001D56B',
+ "zscr;": '\U0001D4CF',
+ "zwj;": '\U0000200D',
+ "zwnj;": '\U0000200C',
+ "AElig": '\U000000C6',
+ "AMP": '\U00000026',
+ "Aacute": '\U000000C1',
+ "Acirc": '\U000000C2',
+ "Agrave": '\U000000C0',
+ "Aring": '\U000000C5',
+ "Atilde": '\U000000C3',
+ "Auml": '\U000000C4',
+ "COPY": '\U000000A9',
+ "Ccedil": '\U000000C7',
+ "ETH": '\U000000D0',
+ "Eacute": '\U000000C9',
+ "Ecirc": '\U000000CA',
+ "Egrave": '\U000000C8',
+ "Euml": '\U000000CB',
+ "GT": '\U0000003E',
+ "Iacute": '\U000000CD',
+ "Icirc": '\U000000CE',
+ "Igrave": '\U000000CC',
+ "Iuml": '\U000000CF',
+ "LT": '\U0000003C',
+ "Ntilde": '\U000000D1',
+ "Oacute": '\U000000D3',
+ "Ocirc": '\U000000D4',
+ "Ograve": '\U000000D2',
+ "Oslash": '\U000000D8',
+ "Otilde": '\U000000D5',
+ "Ouml": '\U000000D6',
+ "QUOT": '\U00000022',
+ "REG": '\U000000AE',
+ "THORN": '\U000000DE',
+ "Uacute": '\U000000DA',
+ "Ucirc": '\U000000DB',
+ "Ugrave": '\U000000D9',
+ "Uuml": '\U000000DC',
+ "Yacute": '\U000000DD',
+ "aacute": '\U000000E1',
+ "acirc": '\U000000E2',
+ "acute": '\U000000B4',
+ "aelig": '\U000000E6',
+ "agrave": '\U000000E0',
+ "amp": '\U00000026',
+ "aring": '\U000000E5',
+ "atilde": '\U000000E3',
+ "auml": '\U000000E4',
+ "brvbar": '\U000000A6',
+ "ccedil": '\U000000E7',
+ "cedil": '\U000000B8',
+ "cent": '\U000000A2',
+ "copy": '\U000000A9',
+ "curren": '\U000000A4',
+ "deg": '\U000000B0',
+ "divide": '\U000000F7',
+ "eacute": '\U000000E9',
+ "ecirc": '\U000000EA',
+ "egrave": '\U000000E8',
+ "eth": '\U000000F0',
+ "euml": '\U000000EB',
+ "frac12": '\U000000BD',
+ "frac14": '\U000000BC',
+ "frac34": '\U000000BE',
+ "gt": '\U0000003E',
+ "iacute": '\U000000ED',
+ "icirc": '\U000000EE',
+ "iexcl": '\U000000A1',
+ "igrave": '\U000000EC',
+ "iquest": '\U000000BF',
+ "iuml": '\U000000EF',
+ "laquo": '\U000000AB',
+ "lt": '\U0000003C',
+ "macr": '\U000000AF',
+ "micro": '\U000000B5',
+ "middot": '\U000000B7',
+ "nbsp": '\U000000A0',
+ "not": '\U000000AC',
+ "ntilde": '\U000000F1',
+ "oacute": '\U000000F3',
+ "ocirc": '\U000000F4',
+ "ograve": '\U000000F2',
+ "ordf": '\U000000AA',
+ "ordm": '\U000000BA',
+ "oslash": '\U000000F8',
+ "otilde": '\U000000F5',
+ "ouml": '\U000000F6',
+ "para": '\U000000B6',
+ "plusmn": '\U000000B1',
+ "pound": '\U000000A3',
+ "quot": '\U00000022',
+ "raquo": '\U000000BB',
+ "reg": '\U000000AE',
+ "sect": '\U000000A7',
+ "shy": '\U000000AD',
+ "sup1": '\U000000B9',
+ "sup2": '\U000000B2',
+ "sup3": '\U000000B3',
+ "szlig": '\U000000DF',
+ "thorn": '\U000000FE',
+ "times": '\U000000D7',
+ "uacute": '\U000000FA',
+ "ucirc": '\U000000FB',
+ "ugrave": '\U000000F9',
+ "uml": '\U000000A8',
+ "uuml": '\U000000FC',
+ "yacute": '\U000000FD',
+ "yen": '\U000000A5',
+ "yuml": '\U000000FF',
+ }
+
+ entity2 = map[string][2]rune{
+ // TODO(nigeltao): Handle replacements that are wider than their names.
+ // "nLt;": {'\u226A', '\u20D2'},
+ // "nGt;": {'\u226B', '\u20D2'},
+ "NotEqualTilde;": {'\u2242', '\u0338'},
+ "NotGreaterFullEqual;": {'\u2267', '\u0338'},
+ "NotGreaterGreater;": {'\u226B', '\u0338'},
+ "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'},
+ "NotHumpDownHump;": {'\u224E', '\u0338'},
+ "NotHumpEqual;": {'\u224F', '\u0338'},
+ "NotLeftTriangleBar;": {'\u29CF', '\u0338'},
+ "NotLessLess;": {'\u226A', '\u0338'},
+ "NotLessSlantEqual;": {'\u2A7D', '\u0338'},
+ "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'},
+ "NotNestedLessLess;": {'\u2AA1', '\u0338'},
+ "NotPrecedesEqual;": {'\u2AAF', '\u0338'},
+ "NotRightTriangleBar;": {'\u29D0', '\u0338'},
+ "NotSquareSubset;": {'\u228F', '\u0338'},
+ "NotSquareSuperset;": {'\u2290', '\u0338'},
+ "NotSubset;": {'\u2282', '\u20D2'},
+ "NotSucceedsEqual;": {'\u2AB0', '\u0338'},
+ "NotSucceedsTilde;": {'\u227F', '\u0338'},
+ "NotSuperset;": {'\u2283', '\u20D2'},
+ "ThickSpace;": {'\u205F', '\u200A'},
+ "acE;": {'\u223E', '\u0333'},
+ "bne;": {'\u003D', '\u20E5'},
+ "bnequiv;": {'\u2261', '\u20E5'},
+ "caps;": {'\u2229', '\uFE00'},
+ "cups;": {'\u222A', '\uFE00'},
+ "fjlig;": {'\u0066', '\u006A'},
+ "gesl;": {'\u22DB', '\uFE00'},
+ "gvertneqq;": {'\u2269', '\uFE00'},
+ "gvnE;": {'\u2269', '\uFE00'},
+ "lates;": {'\u2AAD', '\uFE00'},
+ "lesg;": {'\u22DA', '\uFE00'},
+ "lvertneqq;": {'\u2268', '\uFE00'},
+ "lvnE;": {'\u2268', '\uFE00'},
+ "nGg;": {'\u22D9', '\u0338'},
+ "nGtv;": {'\u226B', '\u0338'},
+ "nLl;": {'\u22D8', '\u0338'},
+ "nLtv;": {'\u226A', '\u0338'},
+ "nang;": {'\u2220', '\u20D2'},
+ "napE;": {'\u2A70', '\u0338'},
+ "napid;": {'\u224B', '\u0338'},
+ "nbump;": {'\u224E', '\u0338'},
+ "nbumpe;": {'\u224F', '\u0338'},
+ "ncongdot;": {'\u2A6D', '\u0338'},
+ "nedot;": {'\u2250', '\u0338'},
+ "nesim;": {'\u2242', '\u0338'},
+ "ngE;": {'\u2267', '\u0338'},
+ "ngeqq;": {'\u2267', '\u0338'},
+ "ngeqslant;": {'\u2A7E', '\u0338'},
+ "nges;": {'\u2A7E', '\u0338'},
+ "nlE;": {'\u2266', '\u0338'},
+ "nleqq;": {'\u2266', '\u0338'},
+ "nleqslant;": {'\u2A7D', '\u0338'},
+ "nles;": {'\u2A7D', '\u0338'},
+ "notinE;": {'\u22F9', '\u0338'},
+ "notindot;": {'\u22F5', '\u0338'},
+ "nparsl;": {'\u2AFD', '\u20E5'},
+ "npart;": {'\u2202', '\u0338'},
+ "npre;": {'\u2AAF', '\u0338'},
+ "npreceq;": {'\u2AAF', '\u0338'},
+ "nrarrc;": {'\u2933', '\u0338'},
+ "nrarrw;": {'\u219D', '\u0338'},
+ "nsce;": {'\u2AB0', '\u0338'},
+ "nsubE;": {'\u2AC5', '\u0338'},
+ "nsubset;": {'\u2282', '\u20D2'},
+ "nsubseteqq;": {'\u2AC5', '\u0338'},
+ "nsucceq;": {'\u2AB0', '\u0338'},
+ "nsupE;": {'\u2AC6', '\u0338'},
+ "nsupset;": {'\u2283', '\u20D2'},
+ "nsupseteqq;": {'\u2AC6', '\u0338'},
+ "nvap;": {'\u224D', '\u20D2'},
+ "nvge;": {'\u2265', '\u20D2'},
+ "nvgt;": {'\u003E', '\u20D2'},
+ "nvle;": {'\u2264', '\u20D2'},
+ "nvlt;": {'\u003C', '\u20D2'},
+ "nvltrie;": {'\u22B4', '\u20D2'},
+ "nvrtrie;": {'\u22B5', '\u20D2'},
+ "nvsim;": {'\u223C', '\u20D2'},
+ "race;": {'\u223D', '\u0331'},
+ "smtes;": {'\u2AAC', '\uFE00'},
+ "sqcaps;": {'\u2293', '\uFE00'},
+ "sqcups;": {'\u2294', '\uFE00'},
+ "varsubsetneq;": {'\u228A', '\uFE00'},
+ "varsubsetneqq;": {'\u2ACB', '\uFE00'},
+ "varsupsetneq;": {'\u228B', '\uFE00'},
+ "varsupsetneqq;": {'\u2ACC', '\uFE00'},
+ "vnsub;": {'\u2282', '\u20D2'},
+ "vnsup;": {'\u2283', '\u20D2'},
+ "vsubnE;": {'\u2ACB', '\uFE00'},
+ "vsubne;": {'\u228A', '\uFE00'},
+ "vsupnE;": {'\u2ACC', '\uFE00'},
+ "vsupne;": {'\u228B', '\uFE00'},
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/html/entity_test.go b/platform/dbops/binaries/go/go/src/html/entity_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..6688ed2c43ab6c0fc8be66d49a111832c882a6bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/entity_test.go
@@ -0,0 +1,37 @@
+// 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 html
+
+import (
+ "testing"
+ "unicode/utf8"
+)
+
+func init() {
+ UnescapeString("") // force load of entity maps
+}
+
+func TestEntityLength(t *testing.T) {
+ if len(entity) == 0 || len(entity2) == 0 {
+ t.Fatal("maps not loaded")
+ }
+
+ // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key).
+ // The +1 comes from the leading "&". This property implies that the length of
+ // unescaped text is <= the length of escaped text.
+ for k, v := range entity {
+ if 1+len(k) < utf8.RuneLen(v) {
+ t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v))
+ }
+ if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' {
+ t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon)
+ }
+ }
+ for k, v := range entity2 {
+ if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) {
+ t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1]))
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/html/escape.go b/platform/dbops/binaries/go/go/src/html/escape.go
new file mode 100644
index 0000000000000000000000000000000000000000..1dc12873b0fa9ea5e6727a6d29256b58c23b670d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/escape.go
@@ -0,0 +1,214 @@
+// 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 html provides functions for escaping and unescaping HTML text.
+package html
+
+import (
+ "strings"
+ "unicode/utf8"
+)
+
+// These replacements permit compatibility with old numeric entities that
+// assumed Windows-1252 encoding.
+// https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
+var replacementTable = [...]rune{
+ '\u20AC', // First entry is what 0x80 should be replaced with.
+ '\u0081',
+ '\u201A',
+ '\u0192',
+ '\u201E',
+ '\u2026',
+ '\u2020',
+ '\u2021',
+ '\u02C6',
+ '\u2030',
+ '\u0160',
+ '\u2039',
+ '\u0152',
+ '\u008D',
+ '\u017D',
+ '\u008F',
+ '\u0090',
+ '\u2018',
+ '\u2019',
+ '\u201C',
+ '\u201D',
+ '\u2022',
+ '\u2013',
+ '\u2014',
+ '\u02DC',
+ '\u2122',
+ '\u0161',
+ '\u203A',
+ '\u0153',
+ '\u009D',
+ '\u017E',
+ '\u0178', // Last entry is 0x9F.
+ // 0x00->'\uFFFD' is handled programmatically.
+ // 0x0D->'\u000D' is a no-op.
+}
+
+// unescapeEntity reads an entity like "<" from b[src:] and writes the
+// corresponding "<" to b[dst:], returning the incremented dst and src cursors.
+// Precondition: b[src] == '&' && dst <= src.
+func unescapeEntity(b []byte, dst, src int) (dst1, src1 int) {
+ const attribute = false
+
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#consume-a-character-reference
+
+ // i starts at 1 because we already know that s[0] == '&'.
+ i, s := 1, b[src:]
+
+ if len(s) <= 1 {
+ b[dst] = b[src]
+ return dst + 1, src + 1
+ }
+
+ if s[i] == '#' {
+ if len(s) <= 3 { // We need to have at least ".".
+ b[dst] = b[src]
+ return dst + 1, src + 1
+ }
+ i++
+ c := s[i]
+ hex := false
+ if c == 'x' || c == 'X' {
+ hex = true
+ i++
+ }
+
+ x := '\x00'
+ for i < len(s) {
+ c = s[i]
+ i++
+ if hex {
+ if '0' <= c && c <= '9' {
+ x = 16*x + rune(c) - '0'
+ continue
+ } else if 'a' <= c && c <= 'f' {
+ x = 16*x + rune(c) - 'a' + 10
+ continue
+ } else if 'A' <= c && c <= 'F' {
+ x = 16*x + rune(c) - 'A' + 10
+ continue
+ }
+ } else if '0' <= c && c <= '9' {
+ x = 10*x + rune(c) - '0'
+ continue
+ }
+ if c != ';' {
+ i--
+ }
+ break
+ }
+
+ if i <= 3 { // No characters matched.
+ b[dst] = b[src]
+ return dst + 1, src + 1
+ }
+
+ if 0x80 <= x && x <= 0x9F {
+ // Replace characters from Windows-1252 with UTF-8 equivalents.
+ x = replacementTable[x-0x80]
+ } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF {
+ // Replace invalid characters with the replacement character.
+ x = '\uFFFD'
+ }
+
+ return dst + utf8.EncodeRune(b[dst:], x), src + i
+ }
+
+ // Consume the maximum number of characters possible, with the
+ // consumed characters matching one of the named references.
+
+ for i < len(s) {
+ c := s[i]
+ i++
+ // Lower-cased characters are more common in entities, so we check for them first.
+ if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
+ continue
+ }
+ if c != ';' {
+ i--
+ }
+ break
+ }
+
+ entityName := s[1:i]
+ if len(entityName) == 0 {
+ // No-op.
+ } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' {
+ // No-op.
+ } else if x := entity[string(entityName)]; x != 0 {
+ return dst + utf8.EncodeRune(b[dst:], x), src + i
+ } else if x := entity2[string(entityName)]; x[0] != 0 {
+ dst1 := dst + utf8.EncodeRune(b[dst:], x[0])
+ return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i
+ } else if !attribute {
+ maxLen := len(entityName) - 1
+ if maxLen > longestEntityWithoutSemicolon {
+ maxLen = longestEntityWithoutSemicolon
+ }
+ for j := maxLen; j > 1; j-- {
+ if x := entity[string(entityName[:j])]; x != 0 {
+ return dst + utf8.EncodeRune(b[dst:], x), src + j + 1
+ }
+ }
+ }
+
+ dst1, src1 = dst+i, src+i
+ copy(b[dst:dst1], b[src:src1])
+ return dst1, src1
+}
+
+var htmlEscaper = strings.NewReplacer(
+ `&`, "&",
+ `'`, "'", // "'" is shorter than "'" and apos was not in HTML until HTML5.
+ `<`, "<",
+ `>`, ">",
+ `"`, """, // """ is shorter than """.
+)
+
+// EscapeString escapes special characters like "<" to become "<". It
+// escapes only five such characters: <, >, &, ' and ".
+// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't
+// always true.
+func EscapeString(s string) string {
+ return htmlEscaper.Replace(s)
+}
+
+// UnescapeString unescapes entities like "<" to become "<". It unescapes a
+// larger range of entities than EscapeString escapes. For example, "á"
+// unescapes to "á", as does "á" and "á".
+// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't
+// always true.
+func UnescapeString(s string) string {
+ populateMapsOnce.Do(populateMaps)
+ i := strings.IndexByte(s, '&')
+
+ if i < 0 {
+ return s
+ }
+
+ b := []byte(s)
+ dst, src := unescapeEntity(b, i, i)
+ for len(s[src:]) > 0 {
+ if s[src] == '&' {
+ i = 0
+ } else {
+ i = strings.IndexByte(s[src:], '&')
+ }
+ if i < 0 {
+ dst += copy(b[dst:], s[src:])
+ break
+ }
+
+ if i > 0 {
+ copy(b[dst:], s[src:src+i])
+ }
+ dst, src = unescapeEntity(b, dst+i, src+i)
+ }
+ return string(b[:dst])
+}
diff --git a/platform/dbops/binaries/go/go/src/html/escape_test.go b/platform/dbops/binaries/go/go/src/html/escape_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8b51a55409fa55ee04149b31bafbe4657312d138
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/escape_test.go
@@ -0,0 +1,169 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package html
+
+import (
+ "strings"
+ "testing"
+)
+
+type unescapeTest struct {
+ // A short description of the test case.
+ desc string
+ // The HTML text.
+ html string
+ // The unescaped text.
+ unescaped string
+}
+
+var unescapeTests = []unescapeTest{
+ // Handle no entities.
+ {
+ "copy",
+ "A\ttext\nstring",
+ "A\ttext\nstring",
+ },
+ // Handle simple named entities.
+ {
+ "simple",
+ "& > <",
+ "& > <",
+ },
+ // Handle hitting the end of the string.
+ {
+ "stringEnd",
+ "& &",
+ "& &",
+ },
+ // Handle entities with two codepoints.
+ {
+ "multiCodepoint",
+ "text ⋛︀ blah",
+ "text \u22db\ufe00 blah",
+ },
+ // Handle decimal numeric entities.
+ {
+ "decimalEntity",
+ "Delta = Δ ",
+ "Delta = Δ ",
+ },
+ // Handle hexadecimal numeric entities.
+ {
+ "hexadecimalEntity",
+ "Lambda = λ = λ ",
+ "Lambda = λ = λ ",
+ },
+ // Handle numeric early termination.
+ {
+ "numericEnds",
+ " 43 © = ©f = ©",
+ " €43 © = ©f = ©",
+ },
+ // Handle numeric ISO-8859-1 entity replacements.
+ {
+ "numericReplacements",
+ "Footnote",
+ "Footnote‡",
+ },
+ // Handle single ampersand.
+ {
+ "copySingleAmpersand",
+ "&",
+ "&",
+ },
+ // Handle ampersand followed by non-entity.
+ {
+ "copyAmpersandNonEntity",
+ "text &test",
+ "text &test",
+ },
+ // Handle "".
+ {
+ "copyAmpersandHash",
+ "text ",
+ "text ",
+ },
+}
+
+func TestUnescape(t *testing.T) {
+ for _, tt := range unescapeTests {
+ unescaped := UnescapeString(tt.html)
+ if unescaped != tt.unescaped {
+ t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped)
+ }
+ }
+}
+
+func TestUnescapeEscape(t *testing.T) {
+ ss := []string{
+ ``,
+ `abc def`,
+ `a & b`,
+ `a&b`,
+ `a & b`,
+ `"`,
+ `"`,
+ `"<&>"`,
+ `"<&>"`,
+ `3&5==1 && 0<1, "0<1", a+acute=á`,
+ `The special characters are: <, >, &, ' and "`,
+ }
+ for _, s := range ss {
+ if got := UnescapeString(EscapeString(s)); got != s {
+ t.Errorf("got %q want %q", got, s)
+ }
+ }
+}
+
+var (
+ benchEscapeData = strings.Repeat("AAAAA < BBBBB > CCCCC & DDDDD ' EEEEE \" ", 100)
+ benchEscapeNone = strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 100)
+ benchUnescapeSparse = strings.Repeat(strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 10)+"&", 10)
+ benchUnescapeDense = strings.Repeat("&< & <", 100)
+)
+
+func BenchmarkEscape(b *testing.B) {
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(EscapeString(benchEscapeData))
+ }
+}
+
+func BenchmarkEscapeNone(b *testing.B) {
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(EscapeString(benchEscapeNone))
+ }
+}
+
+func BenchmarkUnescape(b *testing.B) {
+ s := EscapeString(benchEscapeData)
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(UnescapeString(s))
+ }
+}
+
+func BenchmarkUnescapeNone(b *testing.B) {
+ s := EscapeString(benchEscapeNone)
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(UnescapeString(s))
+ }
+}
+
+func BenchmarkUnescapeSparse(b *testing.B) {
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(UnescapeString(benchUnescapeSparse))
+ }
+}
+
+func BenchmarkUnescapeDense(b *testing.B) {
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(UnescapeString(benchUnescapeDense))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/html/example_test.go b/platform/dbops/binaries/go/go/src/html/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0e28cac1be5e4f8ead17ffb4b4cfd90803fc2e48
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/example_test.go
@@ -0,0 +1,22 @@
+// 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 html_test
+
+import (
+ "fmt"
+ "html"
+)
+
+func ExampleEscapeString() {
+ const s = `"Fran & Freddie's Diner" `
+ fmt.Println(html.EscapeString(s))
+ // Output: "Fran & Freddie's Diner" <tasty@example.com>
+}
+
+func ExampleUnescapeString() {
+ const s = `"Fran & Freddie's Diner" <tasty@example.com>`
+ fmt.Println(html.UnescapeString(s))
+ // Output: "Fran & Freddie's Diner"
+}
diff --git a/platform/dbops/binaries/go/go/src/html/fuzz_test.go b/platform/dbops/binaries/go/go/src/html/fuzz_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ed15d8f270b93e49ee852ba1b7bec901256b9076
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/html/fuzz_test.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.
+
+package html
+
+import "testing"
+
+func FuzzEscapeUnescape(f *testing.F) {
+ f.Fuzz(func(t *testing.T, v string) {
+ e := EscapeString(v)
+ u := UnescapeString(e)
+ if u != v {
+ t.Errorf("EscapeString(%q) = %q, UnescapeString(%q) = %q, want %q", v, e, e, u, v)
+ }
+
+ // As per the documentation, this isn't always equal to v, so it makes
+ // no sense to check for equality. It can still be interesting to find
+ // panics in it though.
+ EscapeString(UnescapeString(v))
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/image/decode_example_test.go b/platform/dbops/binaries/go/go/src/image/decode_example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..526c03f3c1a78b02ac77a56038ef673fe1a368ed
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/decode_example_test.go
@@ -0,0 +1,149 @@
+// 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 example demonstrates decoding a JPEG image and examining its pixels.
+package image_test
+
+import (
+ "encoding/base64"
+ "fmt"
+ "image"
+ "log"
+ "strings"
+
+ // Package image/jpeg is not used explicitly in the code below,
+ // but is imported for its initialization side-effect, which allows
+ // image.Decode to understand JPEG formatted images. Uncomment these
+ // two lines to also understand GIF and PNG images:
+ // _ "image/gif"
+ // _ "image/png"
+ _ "image/jpeg"
+)
+
+func Example_decodeConfig() {
+ reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
+ config, format, err := image.DecodeConfig(reader)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
+}
+
+func Example() {
+ // Decode the JPEG data. If reading from file, create a reader with
+ //
+ // reader, err := os.Open("testdata/video-001.q50.420.jpeg")
+ // if err != nil {
+ // log.Fatal(err)
+ // }
+ // defer reader.Close()
+ reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
+ m, _, err := image.Decode(reader)
+ if err != nil {
+ log.Fatal(err)
+ }
+ bounds := m.Bounds()
+
+ // Calculate a 16-bin histogram for m's red, green, blue and alpha components.
+ //
+ // An image's bounds do not necessarily start at (0, 0), so the two loops start
+ // at bounds.Min.Y and bounds.Min.X. Looping over Y first and X second is more
+ // likely to result in better memory access patterns than X first and Y second.
+ var histogram [16][4]int
+ for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
+ for x := bounds.Min.X; x < bounds.Max.X; x++ {
+ r, g, b, a := m.At(x, y).RGBA()
+ // A color's RGBA method returns values in the range [0, 65535].
+ // Shifting by 12 reduces this to the range [0, 15].
+ histogram[r>>12][0]++
+ histogram[g>>12][1]++
+ histogram[b>>12][2]++
+ histogram[a>>12][3]++
+ }
+ }
+
+ // Print the results.
+ fmt.Printf("%-14s %6s %6s %6s %6s\n", "bin", "red", "green", "blue", "alpha")
+ for i, x := range histogram {
+ fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3])
+ }
+ // Output:
+ // bin red green blue alpha
+ // 0x0000-0x0fff: 364 790 7242 0
+ // 0x1000-0x1fff: 645 2967 1039 0
+ // 0x2000-0x2fff: 1072 2299 979 0
+ // 0x3000-0x3fff: 820 2266 980 0
+ // 0x4000-0x4fff: 537 1305 541 0
+ // 0x5000-0x5fff: 319 962 261 0
+ // 0x6000-0x6fff: 322 375 177 0
+ // 0x7000-0x7fff: 601 279 214 0
+ // 0x8000-0x8fff: 3478 227 273 0
+ // 0x9000-0x9fff: 2260 234 329 0
+ // 0xa000-0xafff: 921 282 373 0
+ // 0xb000-0xbfff: 321 335 397 0
+ // 0xc000-0xcfff: 229 388 298 0
+ // 0xd000-0xdfff: 260 414 277 0
+ // 0xe000-0xefff: 516 428 298 0
+ // 0xf000-0xffff: 2785 1899 1772 15450
+}
+
+const data = `
+/9j/4AAQSkZJRgABAQIAHAAcAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdA
+SFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2Nj
+Y2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABnAJYDASIAAhEBAxEB/8QA
+HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh
+MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW
+V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
+x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQF
+BgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV
+YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE
+hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq
+8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDlwKMD0pwzSiuK57QzGDxS7D6in8Y5ximnAPUfSlcq4m3ilUYp
+2OKXHvRcVxnTtS7c07HNFK4DQPakC4PNOA+tOx70XAjK/So5gBGP94fzqfvUVx/qxx/EP51UXqRP4WSE
+cmgjilP3jSEZqS0IO/NGDnpUiocDg/McDjvV6HTPOdVWYgsM5KcfzzQ2JySM2jp6VYu7SWzmMUwG4cgj
+kMPUVBjjtTGtRu0Zopw+lFFxhinrGzuqqMsxAA9yaXFSRv5cqSEcIwYj6GpuZ30O30fSLKzhUpbpNMv3
+5XGTn29BV28jt7pPLuIVljPBBFVreYx+VbqAjycgt3x14zRcNOxGyVFHQkIc/wA61exyKLbuzjdZ046d
+ftEuTEw3Rk9SPT8P8Kpbea3tchbyVae4JkjbbGpGdwOM89Af6ViFTWUtGdcXoM2+woK1JtpNtTcoZt+l
+Jt7ZqTbRtouFyPFRXI/c9D94fzqzioLsfuD/ALw/nVReqIn8LJCOTSY+tSMOTmkIpXLRu+F0t5pJxPHG
+wjjUAuBjJJz1+laD6Pai+WaK9SBX6puzn6ZP+NV/Dkdtc6ZNbyAFwxLAHDYPv6VoQ21nPNEEiQGEFRtk
+Gf0NaWTOeW7Of8QwGG4MRZnEbYXPJwRnOR0zWNXW+KrqBLUWi5EjbWCgcAA9c/gRXKYqZaGlK/LqMH0F
+FLtHvRSNiYD2pSDTgpp6p0ywUHoTULXYxcktzrdCf7Xo8LP/AKyEmMNjJ46dfbFWJ5TDGNwB9lFUvDV9
+YrbfYGbyrjcWG88S57g+vtV26ZIvMlumKwwjLZ6V0WfU54yTvYwtbubea2WNWbzg4bYQeBgj8OtYeKhj
+u4y2HQxqxOD1xzxmrWAQCCGB6EGsaikndmsJxeiYzBo280/Z7UbayuaXGY5oIp+2lx9KLjIsVDeD/Rj/
+ALy/zq1t96r3y4tT/vL/ADq4P3kRP4WSleTSFKkkKoCW4GaqNcMxIjXj1pxjKT0FKrGC1Nrw3vGrKkYz
+5kTAr6455/HH510UdwPtRgWCbzF5+YYUf4Vwun39xpmoR3qASMmQUJwGU9Rnt/8AWrpbrxhb8/ZdOmaQ
+gAGZwFH5ZJrpVKVlY5ZYhN6kXiu2eO/ikZlIljAAB5yM549OawSOOlPuLqe+umuLqTfM4OSOAo7ADsKh
+hl/cRsTuJHPv7mlKi3sVTxNtGP20VJhThgSQaK52mnZnUqsWrpkyeUrr5pABOAPU1AGaXUCWJISHGPfP
+P8qL7BiKnsMg46H3qrbzupbj5mPTPTpXVSglG551SpzSsXJ4/MBUgYIxyKpySyGBYJriV1D7kRpCVH4V
+bSeNJ4xchni3DeqnBI+td7F4b0mKIRjT45VbktJlzk455+n6VtYzv2PNwFZWBHBGKVJDGVC54/nXQeMN
+NttLNkba1jgWVWDmM8bhg4/nzXLSSbXVj6fyNKUdNRp21RtIRJGrjuM0u3FQ2DbodvcEkfQmrW2vLqLl
+k0ejCXNFMj2/jQV9qkxSYNRcsZiq2oI32N2CkhWXJxwOe9XMcVt6hoPn6dFaW0wgRpNzvKDlz6+/0rai
+ryv2Jm9LHJai+ZRGCBjnr71ErdAxAY9B611t1Y2cunbbaOQ3FvKZI3UqGlZMbiWwfcfhV231iwvLSM3U
+lt5Uq52TuZG+hGMA12xXJGxxzjzybOQtNOvb5j9ktZJhnBIHyg+5PFX38JayqK/2eLJIBUTgkDA9q7ex
+itrSHFpGsUbndhRgc+g7VNIyfZJAoJZUbb3I46CtFJMylBo8sdWhmYMuCnylc9wef5VUT7+1chc5NS7h
+sUZO5RtIPUH3pkBDOxxxmqM9TQtn+WilhHfHaik43KTG3Z4IyPyrNVjGCsZ+dmwv6V3cXhSG8sYpJLud
+JJIwxChdoJGcYx/Wkg8DafA4knvLiQr/ALqj+VQpKw3FtnFFfvbiSMgZJ6/jXp2n3d9cQRBTFsKD96EP
+oOxPU/8A68VVtbbRtMVntbePKDLTSHJH/Aj/AEqHTvE66rq72VugMMcbSGTnL4wMAfjT5n0HyW3L+s6b
+baxaJBdzN+7bcrxkAhun0rz3VNCv7e7lgigknWI43xLu6jjIHTjtXqfkpPGVYsBkghTikgsYIN/lhgXb
+cxLkknp/ShczQ7xtY8vtEmhkj8yGRBuCnehUcnHcVtmwfJ/fQ8e7f/E12txZW91C0U6b42xlST2OR/Ko
+Bo1gM/uW55/1jf41nOipu7LhV5FZHIGzI6zwj/vr/Ck+yr3uYf8Ax7/CutbQdMb71tn/ALaN/jSf8I/p
+X/PoP++2/wAan6rAr6wzkWt0II+1Rc/7Lf4Vd1eeCSKBbdZDdShYoiZNoyfY10P/AAj2lf8APmP++2/x
+oPh/SjKspsozIuNrZORjp3qo0FHYPb3OZt7ae3SzjuItsiRSAgnccl/UA+3Q1yNjKLR4ZZYY5VD7tkv3
+WwO/+e1evPp9nI257aJm6bioz1z1+tY+s6Hplnot9PbWMMcqwOFcLyOO1bJWMZSTOPHi+9w3mosrlyd2
+9lCj02g9P/1e9a3hzxAbl2ikZRcdQueHHt7j864Y8Z4I4oRzG6urFWU5BHBB7HNJxTFGbR6he6Vpmtgm
+eLy5zwZI/lb8fX8azIvBUUTHdfSFP4QsYB/HNZ+k+KEnRY75hHOvAk6K/v7H9K6yyvlnQBmDZ6GsnzR0
+N0oy1RzOtaN/Y1tHNFO06u+zYy4I4Jzx9KKveJblXuordSGES5b6n/62PzorKVdp2LjQTVyWz8UWEWlq
+jSgyxfJt6EgdDzWTdeLIZGO7zHI/hVajGmWWP+PWL8qwlAIURrhpMAHHJA71pRcZrToZzcoEuo6heakA
+GHk245CZ6/X1qPTLq40q+W5t2QybSpDAkEEc55/zilk5k2r91eKhLDzWz2rpsczbbuemeD76fUNG865I
+MiysmQMZAAwa3a5j4ftu0ByP+fh/5CulkLLG7INzhSVHqe1Fh3uOoqn9qQQxyhndmHIxwOmSR2xQ13KD
+KoiBZOV9JBnt707MVy5RWdNdy7wRGf3bfMinnO1jg+vY03WXLaJO3mhQ20b0zwpYf0qlG7S7icrJs08U
+VwumgC+YiQyeVtZH567hzj8aSL949oGhE/2v5pJCDkksQwBHC4/+vXQ8LZ2uYxxCavY7us/xCcaBfn0h
+b+VP0bnSrb94ZMJgOecj1rl/GfidUE2k2gy5+SeQjgA/wj3rlas2jdao48qrjLAGkSKPk4Gc1WMj92I+
+lIJnU8OfxPWo5inBokmtQTmM4OOh71b0q6vbFmWCbaxHyqQGAP0PT8KhSTzVyo5ocSKA5VfTOTmqsmRd
+pl99XjPzThzK3zOeOSeveirNmkgg/fIpYsTkYORxRXmzlTjJqx6EVUcU7mhkKCzdAK59QI9zYxtG1fYU
+UVtgtmY4nZEa8Ak9aqFv3rfSiiu1nMeifDv/AJF+T/r4f+QrqqKKQwzQenNFFMCOKFIgNuThdoJ5OPSk
+ubeK6t3gnXdG4wwziiii/UTKMOg6dbzJLFE4dSCP3rEdeOM8805tDsGMvySgSsS6rM6gk9eAcUUVftZt
+3uyVGNthuq3Eei6DK8H7sRR7YuMgHtXkc8rzTNLM26RyWY+p70UVnLY0iEsUipG7rhZBlDkc1HgYoorM
+0HwyBXGeRjmrcUhMg2ghezd//rUUVcTKW5s2jZtY/QDaOKKKK8ip8bPRj8KP/9k=
+`
diff --git a/platform/dbops/binaries/go/go/src/image/decode_test.go b/platform/dbops/binaries/go/go/src/image/decode_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2b3ff6ba582662c11c4e19392741513e584e0b38
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/decode_test.go
@@ -0,0 +1,135 @@
+// 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 image_test
+
+import (
+ "bufio"
+ "fmt"
+ "image"
+ "image/color"
+ "os"
+ "testing"
+
+ _ "image/gif"
+ _ "image/jpeg"
+ _ "image/png"
+)
+
+type imageTest struct {
+ goldenFilename string
+ filename string
+ tolerance int
+}
+
+var imageTests = []imageTest{
+ {"testdata/video-001.png", "testdata/video-001.png", 0},
+ // GIF images are restricted to a 256-color palette and the conversion
+ // to GIF loses significant image quality.
+ {"testdata/video-001.png", "testdata/video-001.gif", 64 << 8},
+ {"testdata/video-001.png", "testdata/video-001.interlaced.gif", 64 << 8},
+ {"testdata/video-001.png", "testdata/video-001.5bpp.gif", 128 << 8},
+ // JPEG is a lossy format and hence needs a non-zero tolerance.
+ {"testdata/video-001.png", "testdata/video-001.jpeg", 8 << 8},
+ {"testdata/video-001.png", "testdata/video-001.progressive.jpeg", 8 << 8},
+ {"testdata/video-001.221212.png", "testdata/video-001.221212.jpeg", 8 << 8},
+ {"testdata/video-001.cmyk.png", "testdata/video-001.cmyk.jpeg", 8 << 8},
+ {"testdata/video-001.rgb.png", "testdata/video-001.rgb.jpeg", 8 << 8},
+ {"testdata/video-001.progressive.truncated.png", "testdata/video-001.progressive.truncated.jpeg", 8 << 8},
+ // Grayscale images.
+ {"testdata/video-005.gray.png", "testdata/video-005.gray.jpeg", 8 << 8},
+ {"testdata/video-005.gray.png", "testdata/video-005.gray.png", 0},
+}
+
+func decode(filename string) (image.Image, string, error) {
+ f, err := os.Open(filename)
+ if err != nil {
+ return nil, "", err
+ }
+ defer f.Close()
+ return image.Decode(bufio.NewReader(f))
+}
+
+func decodeConfig(filename string) (image.Config, string, error) {
+ f, err := os.Open(filename)
+ if err != nil {
+ return image.Config{}, "", err
+ }
+ defer f.Close()
+ return image.DecodeConfig(bufio.NewReader(f))
+}
+
+func delta(u0, u1 uint32) int {
+ d := int(u0) - int(u1)
+ if d < 0 {
+ return -d
+ }
+ return d
+}
+
+func withinTolerance(c0, c1 color.Color, tolerance int) bool {
+ r0, g0, b0, a0 := c0.RGBA()
+ r1, g1, b1, a1 := c1.RGBA()
+ r := delta(r0, r1)
+ g := delta(g0, g1)
+ b := delta(b0, b1)
+ a := delta(a0, a1)
+ return r <= tolerance && g <= tolerance && b <= tolerance && a <= tolerance
+}
+
+func TestDecode(t *testing.T) {
+ rgba := func(c color.Color) string {
+ r, g, b, a := c.RGBA()
+ return fmt.Sprintf("rgba = 0x%04x, 0x%04x, 0x%04x, 0x%04x for %T%v", r, g, b, a, c, c)
+ }
+
+ golden := make(map[string]image.Image)
+loop:
+ for _, it := range imageTests {
+ g := golden[it.goldenFilename]
+ if g == nil {
+ var err error
+ g, _, err = decode(it.goldenFilename)
+ if err != nil {
+ t.Errorf("%s: %v", it.goldenFilename, err)
+ continue loop
+ }
+ golden[it.goldenFilename] = g
+ }
+ m, imageFormat, err := decode(it.filename)
+ if err != nil {
+ t.Errorf("%s: %v", it.filename, err)
+ continue loop
+ }
+ b := g.Bounds()
+ if !b.Eq(m.Bounds()) {
+ t.Errorf("%s: got bounds %v want %v", it.filename, m.Bounds(), b)
+ continue loop
+ }
+ for y := b.Min.Y; y < b.Max.Y; y++ {
+ for x := b.Min.X; x < b.Max.X; x++ {
+ if !withinTolerance(g.At(x, y), m.At(x, y), it.tolerance) {
+ t.Errorf("%s: at (%d, %d):\ngot %v\nwant %v",
+ it.filename, x, y, rgba(m.At(x, y)), rgba(g.At(x, y)))
+ continue loop
+ }
+ }
+ }
+ if imageFormat == "gif" {
+ // Each frame of a GIF can have a frame-local palette override the
+ // GIF-global palette. Thus, image.Decode can yield a different ColorModel
+ // than image.DecodeConfig.
+ continue
+ }
+ c, _, err := decodeConfig(it.filename)
+ if err != nil {
+ t.Errorf("%s: %v", it.filename, err)
+ continue loop
+ }
+ if m.ColorModel() != c.ColorModel {
+ t.Errorf("%s: color models differ", it.filename)
+ continue loop
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/image/format.go b/platform/dbops/binaries/go/go/src/image/format.go
new file mode 100644
index 0000000000000000000000000000000000000000..7426afb3e69e906406ad69ed68f051366d18a0e8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/format.go
@@ -0,0 +1,109 @@
+// 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 image
+
+import (
+ "bufio"
+ "errors"
+ "io"
+ "sync"
+ "sync/atomic"
+)
+
+// ErrFormat indicates that decoding encountered an unknown format.
+var ErrFormat = errors.New("image: unknown format")
+
+// A format holds an image format's name, magic header and how to decode it.
+type format struct {
+ name, magic string
+ decode func(io.Reader) (Image, error)
+ decodeConfig func(io.Reader) (Config, error)
+}
+
+// Formats is the list of registered formats.
+var (
+ formatsMu sync.Mutex
+ atomicFormats atomic.Value
+)
+
+// RegisterFormat registers an image format for use by [Decode].
+// Name is the name of the format, like "jpeg" or "png".
+// Magic is the magic prefix that identifies the format's encoding. The magic
+// string can contain "?" wildcards that each match any one byte.
+// [Decode] is the function that decodes the encoded image.
+// [DecodeConfig] is the function that decodes just its configuration.
+func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error)) {
+ formatsMu.Lock()
+ formats, _ := atomicFormats.Load().([]format)
+ atomicFormats.Store(append(formats, format{name, magic, decode, decodeConfig}))
+ formatsMu.Unlock()
+}
+
+// A reader is an io.Reader that can also peek ahead.
+type reader interface {
+ io.Reader
+ Peek(int) ([]byte, error)
+}
+
+// asReader converts an io.Reader to a reader.
+func asReader(r io.Reader) reader {
+ if rr, ok := r.(reader); ok {
+ return rr
+ }
+ return bufio.NewReader(r)
+}
+
+// match reports whether magic matches b. Magic may contain "?" wildcards.
+func match(magic string, b []byte) bool {
+ if len(magic) != len(b) {
+ return false
+ }
+ for i, c := range b {
+ if magic[i] != c && magic[i] != '?' {
+ return false
+ }
+ }
+ return true
+}
+
+// sniff determines the format of r's data.
+func sniff(r reader) format {
+ formats, _ := atomicFormats.Load().([]format)
+ for _, f := range formats {
+ b, err := r.Peek(len(f.magic))
+ if err == nil && match(f.magic, b) {
+ return f
+ }
+ }
+ return format{}
+}
+
+// Decode decodes an image that has been encoded in a registered format.
+// The string returned is the format name used during format registration.
+// Format registration is typically done by an init function in the codec-
+// specific package.
+func Decode(r io.Reader) (Image, string, error) {
+ rr := asReader(r)
+ f := sniff(rr)
+ if f.decode == nil {
+ return nil, "", ErrFormat
+ }
+ m, err := f.decode(rr)
+ return m, f.name, err
+}
+
+// DecodeConfig decodes the color model and dimensions of an image that has
+// been encoded in a registered format. The string returned is the format name
+// used during format registration. Format registration is typically done by
+// an init function in the codec-specific package.
+func DecodeConfig(r io.Reader) (Config, string, error) {
+ rr := asReader(r)
+ f := sniff(rr)
+ if f.decodeConfig == nil {
+ return Config{}, "", ErrFormat
+ }
+ c, err := f.decodeConfig(rr)
+ return c, f.name, err
+}
diff --git a/platform/dbops/binaries/go/go/src/image/geom.go b/platform/dbops/binaries/go/go/src/image/geom.go
new file mode 100644
index 0000000000000000000000000000000000000000..7731b6bad8c43be2de176a5ee3f8929819fcc193
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/geom.go
@@ -0,0 +1,317 @@
+// 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 image
+
+import (
+ "image/color"
+ "math/bits"
+ "strconv"
+)
+
+// A Point is an X, Y coordinate pair. The axes increase right and down.
+type Point struct {
+ X, Y int
+}
+
+// String returns a string representation of p like "(3,4)".
+func (p Point) String() string {
+ return "(" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + ")"
+}
+
+// Add returns the vector p+q.
+func (p Point) Add(q Point) Point {
+ return Point{p.X + q.X, p.Y + q.Y}
+}
+
+// Sub returns the vector p-q.
+func (p Point) Sub(q Point) Point {
+ return Point{p.X - q.X, p.Y - q.Y}
+}
+
+// Mul returns the vector p*k.
+func (p Point) Mul(k int) Point {
+ return Point{p.X * k, p.Y * k}
+}
+
+// Div returns the vector p/k.
+func (p Point) Div(k int) Point {
+ return Point{p.X / k, p.Y / k}
+}
+
+// In reports whether p is in r.
+func (p Point) In(r Rectangle) bool {
+ return r.Min.X <= p.X && p.X < r.Max.X &&
+ r.Min.Y <= p.Y && p.Y < r.Max.Y
+}
+
+// Mod returns the point q in r such that p.X-q.X is a multiple of r's width
+// and p.Y-q.Y is a multiple of r's height.
+func (p Point) Mod(r Rectangle) Point {
+ w, h := r.Dx(), r.Dy()
+ p = p.Sub(r.Min)
+ p.X = p.X % w
+ if p.X < 0 {
+ p.X += w
+ }
+ p.Y = p.Y % h
+ if p.Y < 0 {
+ p.Y += h
+ }
+ return p.Add(r.Min)
+}
+
+// Eq reports whether p and q are equal.
+func (p Point) Eq(q Point) bool {
+ return p == q
+}
+
+// ZP is the zero [Point].
+//
+// Deprecated: Use a literal [image.Point] instead.
+var ZP Point
+
+// Pt is shorthand for [Point]{X, Y}.
+func Pt(X, Y int) Point {
+ return Point{X, Y}
+}
+
+// A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y.
+// It is well-formed if Min.X <= Max.X and likewise for Y. Points are always
+// well-formed. A rectangle's methods always return well-formed outputs for
+// well-formed inputs.
+//
+// A Rectangle is also an [Image] whose bounds are the rectangle itself. At
+// returns color.Opaque for points in the rectangle and color.Transparent
+// otherwise.
+type Rectangle struct {
+ Min, Max Point
+}
+
+// String returns a string representation of r like "(3,4)-(6,5)".
+func (r Rectangle) String() string {
+ return r.Min.String() + "-" + r.Max.String()
+}
+
+// Dx returns r's width.
+func (r Rectangle) Dx() int {
+ return r.Max.X - r.Min.X
+}
+
+// Dy returns r's height.
+func (r Rectangle) Dy() int {
+ return r.Max.Y - r.Min.Y
+}
+
+// Size returns r's width and height.
+func (r Rectangle) Size() Point {
+ return Point{
+ r.Max.X - r.Min.X,
+ r.Max.Y - r.Min.Y,
+ }
+}
+
+// Add returns the rectangle r translated by p.
+func (r Rectangle) Add(p Point) Rectangle {
+ return Rectangle{
+ Point{r.Min.X + p.X, r.Min.Y + p.Y},
+ Point{r.Max.X + p.X, r.Max.Y + p.Y},
+ }
+}
+
+// Sub returns the rectangle r translated by -p.
+func (r Rectangle) Sub(p Point) Rectangle {
+ return Rectangle{
+ Point{r.Min.X - p.X, r.Min.Y - p.Y},
+ Point{r.Max.X - p.X, r.Max.Y - p.Y},
+ }
+}
+
+// Inset returns the rectangle r inset by n, which may be negative. If either
+// of r's dimensions is less than 2*n then an empty rectangle near the center
+// of r will be returned.
+func (r Rectangle) Inset(n int) Rectangle {
+ if r.Dx() < 2*n {
+ r.Min.X = (r.Min.X + r.Max.X) / 2
+ r.Max.X = r.Min.X
+ } else {
+ r.Min.X += n
+ r.Max.X -= n
+ }
+ if r.Dy() < 2*n {
+ r.Min.Y = (r.Min.Y + r.Max.Y) / 2
+ r.Max.Y = r.Min.Y
+ } else {
+ r.Min.Y += n
+ r.Max.Y -= n
+ }
+ return r
+}
+
+// Intersect returns the largest rectangle contained by both r and s. If the
+// two rectangles do not overlap then the zero rectangle will be returned.
+func (r Rectangle) Intersect(s Rectangle) Rectangle {
+ if r.Min.X < s.Min.X {
+ r.Min.X = s.Min.X
+ }
+ if r.Min.Y < s.Min.Y {
+ r.Min.Y = s.Min.Y
+ }
+ if r.Max.X > s.Max.X {
+ r.Max.X = s.Max.X
+ }
+ if r.Max.Y > s.Max.Y {
+ r.Max.Y = s.Max.Y
+ }
+ // Letting r0 and s0 be the values of r and s at the time that the method
+ // is called, this next line is equivalent to:
+ //
+ // if max(r0.Min.X, s0.Min.X) >= min(r0.Max.X, s0.Max.X) || likewiseForY { etc }
+ if r.Empty() {
+ return ZR
+ }
+ return r
+}
+
+// Union returns the smallest rectangle that contains both r and s.
+func (r Rectangle) Union(s Rectangle) Rectangle {
+ if r.Empty() {
+ return s
+ }
+ if s.Empty() {
+ return r
+ }
+ if r.Min.X > s.Min.X {
+ r.Min.X = s.Min.X
+ }
+ if r.Min.Y > s.Min.Y {
+ r.Min.Y = s.Min.Y
+ }
+ if r.Max.X < s.Max.X {
+ r.Max.X = s.Max.X
+ }
+ if r.Max.Y < s.Max.Y {
+ r.Max.Y = s.Max.Y
+ }
+ return r
+}
+
+// Empty reports whether the rectangle contains no points.
+func (r Rectangle) Empty() bool {
+ return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y
+}
+
+// Eq reports whether r and s contain the same set of points. All empty
+// rectangles are considered equal.
+func (r Rectangle) Eq(s Rectangle) bool {
+ return r == s || r.Empty() && s.Empty()
+}
+
+// Overlaps reports whether r and s have a non-empty intersection.
+func (r Rectangle) Overlaps(s Rectangle) bool {
+ return !r.Empty() && !s.Empty() &&
+ r.Min.X < s.Max.X && s.Min.X < r.Max.X &&
+ r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y
+}
+
+// In reports whether every point in r is in s.
+func (r Rectangle) In(s Rectangle) bool {
+ if r.Empty() {
+ return true
+ }
+ // Note that r.Max is an exclusive bound for r, so that r.In(s)
+ // does not require that r.Max.In(s).
+ return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X &&
+ s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y
+}
+
+// Canon returns the canonical version of r. The returned rectangle has minimum
+// and maximum coordinates swapped if necessary so that it is well-formed.
+func (r Rectangle) Canon() Rectangle {
+ if r.Max.X < r.Min.X {
+ r.Min.X, r.Max.X = r.Max.X, r.Min.X
+ }
+ if r.Max.Y < r.Min.Y {
+ r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y
+ }
+ return r
+}
+
+// At implements the [Image] interface.
+func (r Rectangle) At(x, y int) color.Color {
+ if (Point{x, y}).In(r) {
+ return color.Opaque
+ }
+ return color.Transparent
+}
+
+// RGBA64At implements the [RGBA64Image] interface.
+func (r Rectangle) RGBA64At(x, y int) color.RGBA64 {
+ if (Point{x, y}).In(r) {
+ return color.RGBA64{0xffff, 0xffff, 0xffff, 0xffff}
+ }
+ return color.RGBA64{}
+}
+
+// Bounds implements the [Image] interface.
+func (r Rectangle) Bounds() Rectangle {
+ return r
+}
+
+// ColorModel implements the [Image] interface.
+func (r Rectangle) ColorModel() color.Model {
+ return color.Alpha16Model
+}
+
+// ZR is the zero [Rectangle].
+//
+// Deprecated: Use a literal [image.Rectangle] instead.
+var ZR Rectangle
+
+// Rect is shorthand for [Rectangle]{Pt(x0, y0), [Pt](x1, y1)}. The returned
+// rectangle has minimum and maximum coordinates swapped if necessary so that
+// it is well-formed.
+func Rect(x0, y0, x1, y1 int) Rectangle {
+ if x0 > x1 {
+ x0, x1 = x1, x0
+ }
+ if y0 > y1 {
+ y0, y1 = y1, y0
+ }
+ return Rectangle{Point{x0, y0}, Point{x1, y1}}
+}
+
+// mul3NonNeg returns (x * y * z), unless at least one argument is negative or
+// if the computation overflows the int type, in which case it returns -1.
+func mul3NonNeg(x int, y int, z int) int {
+ if (x < 0) || (y < 0) || (z < 0) {
+ return -1
+ }
+ hi, lo := bits.Mul64(uint64(x), uint64(y))
+ if hi != 0 {
+ return -1
+ }
+ hi, lo = bits.Mul64(lo, uint64(z))
+ if hi != 0 {
+ return -1
+ }
+ a := int(lo)
+ if (a < 0) || (uint64(a) != lo) {
+ return -1
+ }
+ return a
+}
+
+// add2NonNeg returns (x + y), unless at least one argument is negative or if
+// the computation overflows the int type, in which case it returns -1.
+func add2NonNeg(x int, y int) int {
+ if (x < 0) || (y < 0) {
+ return -1
+ }
+ a := x + y
+ if a < 0 {
+ return -1
+ }
+ return a
+}
diff --git a/platform/dbops/binaries/go/go/src/image/geom_test.go b/platform/dbops/binaries/go/go/src/image/geom_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fede027218c31e54a478cd6a40bd4e34fac577b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/geom_test.go
@@ -0,0 +1,116 @@
+// 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 image
+
+import (
+ "fmt"
+ "testing"
+)
+
+func TestRectangle(t *testing.T) {
+ // in checks that every point in f is in g.
+ in := func(f, g Rectangle) error {
+ if !f.In(g) {
+ return fmt.Errorf("f=%s, f.In(%s): got false, want true", f, g)
+ }
+ for y := f.Min.Y; y < f.Max.Y; y++ {
+ for x := f.Min.X; x < f.Max.X; x++ {
+ p := Point{x, y}
+ if !p.In(g) {
+ return fmt.Errorf("p=%s, p.In(%s): got false, want true", p, g)
+ }
+ }
+ }
+ return nil
+ }
+
+ rects := []Rectangle{
+ Rect(0, 0, 10, 10),
+ Rect(10, 0, 20, 10),
+ Rect(1, 2, 3, 4),
+ Rect(4, 6, 10, 10),
+ Rect(2, 3, 12, 5),
+ Rect(-1, -2, 0, 0),
+ Rect(-1, -2, 4, 6),
+ Rect(-10, -20, 30, 40),
+ Rect(8, 8, 8, 8),
+ Rect(88, 88, 88, 88),
+ Rect(6, 5, 4, 3),
+ }
+
+ // r.Eq(s) should be equivalent to every point in r being in s, and every
+ // point in s being in r.
+ for _, r := range rects {
+ for _, s := range rects {
+ got := r.Eq(s)
+ want := in(r, s) == nil && in(s, r) == nil
+ if got != want {
+ t.Errorf("Eq: r=%s, s=%s: got %t, want %t", r, s, got, want)
+ }
+ }
+ }
+
+ // The intersection should be the largest rectangle a such that every point
+ // in a is both in r and in s.
+ for _, r := range rects {
+ for _, s := range rects {
+ a := r.Intersect(s)
+ if err := in(a, r); err != nil {
+ t.Errorf("Intersect: r=%s, s=%s, a=%s, a not in r: %v", r, s, a, err)
+ }
+ if err := in(a, s); err != nil {
+ t.Errorf("Intersect: r=%s, s=%s, a=%s, a not in s: %v", r, s, a, err)
+ }
+ if isZero, overlaps := a == (Rectangle{}), r.Overlaps(s); isZero == overlaps {
+ t.Errorf("Intersect: r=%s, s=%s, a=%s: isZero=%t same as overlaps=%t",
+ r, s, a, isZero, overlaps)
+ }
+ largerThanA := [4]Rectangle{a, a, a, a}
+ largerThanA[0].Min.X--
+ largerThanA[1].Min.Y--
+ largerThanA[2].Max.X++
+ largerThanA[3].Max.Y++
+ for i, b := range largerThanA {
+ if b.Empty() {
+ // b isn't actually larger than a.
+ continue
+ }
+ if in(b, r) == nil && in(b, s) == nil {
+ t.Errorf("Intersect: r=%s, s=%s, a=%s, b=%s, i=%d: intersection could be larger",
+ r, s, a, b, i)
+ }
+ }
+ }
+ }
+
+ // The union should be the smallest rectangle a such that every point in r
+ // is in a and every point in s is in a.
+ for _, r := range rects {
+ for _, s := range rects {
+ a := r.Union(s)
+ if err := in(r, a); err != nil {
+ t.Errorf("Union: r=%s, s=%s, a=%s, r not in a: %v", r, s, a, err)
+ }
+ if err := in(s, a); err != nil {
+ t.Errorf("Union: r=%s, s=%s, a=%s, s not in a: %v", r, s, a, err)
+ }
+ if a.Empty() {
+ // You can't get any smaller than a.
+ continue
+ }
+ smallerThanA := [4]Rectangle{a, a, a, a}
+ smallerThanA[0].Min.X++
+ smallerThanA[1].Min.Y++
+ smallerThanA[2].Max.X--
+ smallerThanA[3].Max.Y--
+ for i, b := range smallerThanA {
+ if in(r, b) == nil && in(s, b) == nil {
+ t.Errorf("Union: r=%s, s=%s, a=%s, b=%s, i=%d: union could be smaller",
+ r, s, a, b, i)
+ }
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/image/image.go b/platform/dbops/binaries/go/go/src/image/image.go
new file mode 100644
index 0000000000000000000000000000000000000000..f08182ba06fa2c6ba487e79f319e73b5c93c623e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/image.go
@@ -0,0 +1,1287 @@
+// 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 image implements a basic 2-D image library.
+//
+// The fundamental interface is called [Image]. An [Image] contains colors, which
+// are described in the image/color package.
+//
+// Values of the [Image] interface are created either by calling functions such
+// as [NewRGBA] and [NewPaletted], or by calling [Decode] on an [io.Reader] containing
+// image data in a format such as GIF, JPEG or PNG. Decoding any particular
+// image format requires the prior registration of a decoder function.
+// Registration is typically automatic as a side effect of initializing that
+// format's package so that, to decode a PNG image, it suffices to have
+//
+// import _ "image/png"
+//
+// in a program's main package. The _ means to import a package purely for its
+// initialization side effects.
+//
+// See "The Go image package" for more details:
+// https://golang.org/doc/articles/image_package.html
+//
+// # Security Considerations
+//
+// The image package can be used to parse arbitrarily large images, which can
+// cause resource exhaustion on machines which do not have enough memory to
+// store them. When operating on arbitrary images, [DecodeConfig] should be called
+// before [Decode], so that the program can decide whether the image, as defined
+// in the returned header, can be safely decoded with the available resources. A
+// call to [Decode] which produces an extremely large image, as defined in the
+// header returned by [DecodeConfig], is not considered a security issue,
+// regardless of whether the image is itself malformed or not. A call to
+// [DecodeConfig] which returns a header which does not match the image returned
+// by [Decode] may be considered a security issue, and should be reported per the
+// [Go Security Policy](https://go.dev/security/policy).
+package image
+
+import (
+ "image/color"
+)
+
+// Config holds an image's color model and dimensions.
+type Config struct {
+ ColorModel color.Model
+ Width, Height int
+}
+
+// Image is a finite rectangular grid of [color.Color] values taken from a color
+// model.
+type Image interface {
+ // ColorModel returns the Image's color model.
+ ColorModel() color.Model
+ // Bounds returns the domain for which At can return non-zero color.
+ // The bounds do not necessarily contain the point (0, 0).
+ Bounds() Rectangle
+ // At returns the color of the pixel at (x, y).
+ // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
+ // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
+ At(x, y int) color.Color
+}
+
+// RGBA64Image is an [Image] whose pixels can be converted directly to a
+// color.RGBA64.
+type RGBA64Image interface {
+ // RGBA64At returns the RGBA64 color of the pixel at (x, y). It is
+ // equivalent to calling At(x, y).RGBA() and converting the resulting
+ // 32-bit return values to a color.RGBA64, but it can avoid allocations
+ // from converting concrete color types to the color.Color interface type.
+ RGBA64At(x, y int) color.RGBA64
+ Image
+}
+
+// PalettedImage is an image whose colors may come from a limited palette.
+// If m is a PalettedImage and m.ColorModel() returns a [color.Palette] p,
+// then m.At(x, y) should be equivalent to p[m.ColorIndexAt(x, y)]. If m's
+// color model is not a color.Palette, then ColorIndexAt's behavior is
+// undefined.
+type PalettedImage interface {
+ // ColorIndexAt returns the palette index of the pixel at (x, y).
+ ColorIndexAt(x, y int) uint8
+ Image
+}
+
+// pixelBufferLength returns the length of the []uint8 typed Pix slice field
+// for the NewXxx functions. Conceptually, this is just (bpp * width * height),
+// but this function panics if at least one of those is negative or if the
+// computation would overflow the int type.
+//
+// This panics instead of returning an error because of backwards
+// compatibility. The NewXxx functions do not return an error.
+func pixelBufferLength(bytesPerPixel int, r Rectangle, imageTypeName string) int {
+ totalLength := mul3NonNeg(bytesPerPixel, r.Dx(), r.Dy())
+ if totalLength < 0 {
+ panic("image: New" + imageTypeName + " Rectangle has huge or negative dimensions")
+ }
+ return totalLength
+}
+
+// RGBA is an in-memory image whose At method returns [color.RGBA] values.
+type RGBA struct {
+ // Pix holds the image's pixels, in R, G, B, A order. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *RGBA) ColorModel() color.Model { return color.RGBAModel }
+
+func (p *RGBA) Bounds() Rectangle { return p.Rect }
+
+func (p *RGBA) At(x, y int) color.Color {
+ return p.RGBAAt(x, y)
+}
+
+func (p *RGBA) RGBA64At(x, y int) color.RGBA64 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.RGBA64{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ r := uint16(s[0])
+ g := uint16(s[1])
+ b := uint16(s[2])
+ a := uint16(s[3])
+ return color.RGBA64{
+ (r << 8) | r,
+ (g << 8) | g,
+ (b << 8) | b,
+ (a << 8) | a,
+ }
+}
+
+func (p *RGBA) RGBAAt(x, y int) color.RGBA {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.RGBA{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ return color.RGBA{s[0], s[1], s[2], s[3]}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *RGBA) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4
+}
+
+func (p *RGBA) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.RGBAModel.Convert(c).(color.RGBA)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c1.R
+ s[1] = c1.G
+ s[2] = c1.B
+ s[3] = c1.A
+}
+
+func (p *RGBA) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(c.R >> 8)
+ s[1] = uint8(c.G >> 8)
+ s[2] = uint8(c.B >> 8)
+ s[3] = uint8(c.A >> 8)
+}
+
+func (p *RGBA) SetRGBA(x, y int, c color.RGBA) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c.R
+ s[1] = c.G
+ s[2] = c.B
+ s[3] = c.A
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *RGBA) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &RGBA{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &RGBA{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *RGBA) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 3, p.Rect.Dx()*4
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i += 4 {
+ if p.Pix[i] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewRGBA returns a new [RGBA] image with the given bounds.
+func NewRGBA(r Rectangle) *RGBA {
+ return &RGBA{
+ Pix: make([]uint8, pixelBufferLength(4, r, "RGBA")),
+ Stride: 4 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// RGBA64 is an in-memory image whose At method returns [color.RGBA64] values.
+type RGBA64 struct {
+ // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *RGBA64) ColorModel() color.Model { return color.RGBA64Model }
+
+func (p *RGBA64) Bounds() Rectangle { return p.Rect }
+
+func (p *RGBA64) At(x, y int) color.Color {
+ return p.RGBA64At(x, y)
+}
+
+func (p *RGBA64) RGBA64At(x, y int) color.RGBA64 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.RGBA64{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ return color.RGBA64{
+ uint16(s[0])<<8 | uint16(s[1]),
+ uint16(s[2])<<8 | uint16(s[3]),
+ uint16(s[4])<<8 | uint16(s[5]),
+ uint16(s[6])<<8 | uint16(s[7]),
+ }
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *RGBA64) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8
+}
+
+func (p *RGBA64) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.RGBA64Model.Convert(c).(color.RGBA64)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(c1.R >> 8)
+ s[1] = uint8(c1.R)
+ s[2] = uint8(c1.G >> 8)
+ s[3] = uint8(c1.G)
+ s[4] = uint8(c1.B >> 8)
+ s[5] = uint8(c1.B)
+ s[6] = uint8(c1.A >> 8)
+ s[7] = uint8(c1.A)
+}
+
+func (p *RGBA64) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(c.R >> 8)
+ s[1] = uint8(c.R)
+ s[2] = uint8(c.G >> 8)
+ s[3] = uint8(c.G)
+ s[4] = uint8(c.B >> 8)
+ s[5] = uint8(c.B)
+ s[6] = uint8(c.A >> 8)
+ s[7] = uint8(c.A)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *RGBA64) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &RGBA64{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &RGBA64{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *RGBA64) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 6, p.Rect.Dx()*8
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i += 8 {
+ if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewRGBA64 returns a new [RGBA64] image with the given bounds.
+func NewRGBA64(r Rectangle) *RGBA64 {
+ return &RGBA64{
+ Pix: make([]uint8, pixelBufferLength(8, r, "RGBA64")),
+ Stride: 8 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// NRGBA is an in-memory image whose At method returns [color.NRGBA] values.
+type NRGBA struct {
+ // Pix holds the image's pixels, in R, G, B, A order. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *NRGBA) ColorModel() color.Model { return color.NRGBAModel }
+
+func (p *NRGBA) Bounds() Rectangle { return p.Rect }
+
+func (p *NRGBA) At(x, y int) color.Color {
+ return p.NRGBAAt(x, y)
+}
+
+func (p *NRGBA) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := p.NRGBAAt(x, y).RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+func (p *NRGBA) NRGBAAt(x, y int) color.NRGBA {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.NRGBA{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ return color.NRGBA{s[0], s[1], s[2], s[3]}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *NRGBA) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4
+}
+
+func (p *NRGBA) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.NRGBAModel.Convert(c).(color.NRGBA)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c1.R
+ s[1] = c1.G
+ s[2] = c1.B
+ s[3] = c1.A
+}
+
+func (p *NRGBA) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ r, g, b, a := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A)
+ if (a != 0) && (a != 0xffff) {
+ r = (r * 0xffff) / a
+ g = (g * 0xffff) / a
+ b = (b * 0xffff) / a
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(r >> 8)
+ s[1] = uint8(g >> 8)
+ s[2] = uint8(b >> 8)
+ s[3] = uint8(a >> 8)
+}
+
+func (p *NRGBA) SetNRGBA(x, y int, c color.NRGBA) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c.R
+ s[1] = c.G
+ s[2] = c.B
+ s[3] = c.A
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *NRGBA) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &NRGBA{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &NRGBA{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *NRGBA) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 3, p.Rect.Dx()*4
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i += 4 {
+ if p.Pix[i] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewNRGBA returns a new [NRGBA] image with the given bounds.
+func NewNRGBA(r Rectangle) *NRGBA {
+ return &NRGBA{
+ Pix: make([]uint8, pixelBufferLength(4, r, "NRGBA")),
+ Stride: 4 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// NRGBA64 is an in-memory image whose At method returns [color.NRGBA64] values.
+type NRGBA64 struct {
+ // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *NRGBA64) ColorModel() color.Model { return color.NRGBA64Model }
+
+func (p *NRGBA64) Bounds() Rectangle { return p.Rect }
+
+func (p *NRGBA64) At(x, y int) color.Color {
+ return p.NRGBA64At(x, y)
+}
+
+func (p *NRGBA64) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := p.NRGBA64At(x, y).RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+func (p *NRGBA64) NRGBA64At(x, y int) color.NRGBA64 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.NRGBA64{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ return color.NRGBA64{
+ uint16(s[0])<<8 | uint16(s[1]),
+ uint16(s[2])<<8 | uint16(s[3]),
+ uint16(s[4])<<8 | uint16(s[5]),
+ uint16(s[6])<<8 | uint16(s[7]),
+ }
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *NRGBA64) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8
+}
+
+func (p *NRGBA64) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.NRGBA64Model.Convert(c).(color.NRGBA64)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(c1.R >> 8)
+ s[1] = uint8(c1.R)
+ s[2] = uint8(c1.G >> 8)
+ s[3] = uint8(c1.G)
+ s[4] = uint8(c1.B >> 8)
+ s[5] = uint8(c1.B)
+ s[6] = uint8(c1.A >> 8)
+ s[7] = uint8(c1.A)
+}
+
+func (p *NRGBA64) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ r, g, b, a := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A)
+ if (a != 0) && (a != 0xffff) {
+ r = (r * 0xffff) / a
+ g = (g * 0xffff) / a
+ b = (b * 0xffff) / a
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(r >> 8)
+ s[1] = uint8(r)
+ s[2] = uint8(g >> 8)
+ s[3] = uint8(g)
+ s[4] = uint8(b >> 8)
+ s[5] = uint8(b)
+ s[6] = uint8(a >> 8)
+ s[7] = uint8(a)
+}
+
+func (p *NRGBA64) SetNRGBA64(x, y int, c color.NRGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+8 : i+8] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = uint8(c.R >> 8)
+ s[1] = uint8(c.R)
+ s[2] = uint8(c.G >> 8)
+ s[3] = uint8(c.G)
+ s[4] = uint8(c.B >> 8)
+ s[5] = uint8(c.B)
+ s[6] = uint8(c.A >> 8)
+ s[7] = uint8(c.A)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *NRGBA64) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &NRGBA64{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &NRGBA64{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *NRGBA64) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 6, p.Rect.Dx()*8
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i += 8 {
+ if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewNRGBA64 returns a new [NRGBA64] image with the given bounds.
+func NewNRGBA64(r Rectangle) *NRGBA64 {
+ return &NRGBA64{
+ Pix: make([]uint8, pixelBufferLength(8, r, "NRGBA64")),
+ Stride: 8 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// Alpha is an in-memory image whose At method returns [color.Alpha] values.
+type Alpha struct {
+ // Pix holds the image's pixels, as alpha values. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *Alpha) ColorModel() color.Model { return color.AlphaModel }
+
+func (p *Alpha) Bounds() Rectangle { return p.Rect }
+
+func (p *Alpha) At(x, y int) color.Color {
+ return p.AlphaAt(x, y)
+}
+
+func (p *Alpha) RGBA64At(x, y int) color.RGBA64 {
+ a := uint16(p.AlphaAt(x, y).A)
+ a |= a << 8
+ return color.RGBA64{a, a, a, a}
+}
+
+func (p *Alpha) AlphaAt(x, y int) color.Alpha {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.Alpha{}
+ }
+ i := p.PixOffset(x, y)
+ return color.Alpha{p.Pix[i]}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *Alpha) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1
+}
+
+func (p *Alpha) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = color.AlphaModel.Convert(c).(color.Alpha).A
+}
+
+func (p *Alpha) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = uint8(c.A >> 8)
+}
+
+func (p *Alpha) SetAlpha(x, y int, c color.Alpha) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = c.A
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *Alpha) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &Alpha{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &Alpha{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *Alpha) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 0, p.Rect.Dx()
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i++ {
+ if p.Pix[i] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewAlpha returns a new [Alpha] image with the given bounds.
+func NewAlpha(r Rectangle) *Alpha {
+ return &Alpha{
+ Pix: make([]uint8, pixelBufferLength(1, r, "Alpha")),
+ Stride: 1 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// Alpha16 is an in-memory image whose At method returns [color.Alpha16] values.
+type Alpha16 struct {
+ // Pix holds the image's pixels, as alpha values in big-endian format. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *Alpha16) ColorModel() color.Model { return color.Alpha16Model }
+
+func (p *Alpha16) Bounds() Rectangle { return p.Rect }
+
+func (p *Alpha16) At(x, y int) color.Color {
+ return p.Alpha16At(x, y)
+}
+
+func (p *Alpha16) RGBA64At(x, y int) color.RGBA64 {
+ a := p.Alpha16At(x, y).A
+ return color.RGBA64{a, a, a, a}
+}
+
+func (p *Alpha16) Alpha16At(x, y int) color.Alpha16 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.Alpha16{}
+ }
+ i := p.PixOffset(x, y)
+ return color.Alpha16{uint16(p.Pix[i+0])<<8 | uint16(p.Pix[i+1])}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *Alpha16) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2
+}
+
+func (p *Alpha16) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.Alpha16Model.Convert(c).(color.Alpha16)
+ p.Pix[i+0] = uint8(c1.A >> 8)
+ p.Pix[i+1] = uint8(c1.A)
+}
+
+func (p *Alpha16) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i+0] = uint8(c.A >> 8)
+ p.Pix[i+1] = uint8(c.A)
+}
+
+func (p *Alpha16) SetAlpha16(x, y int, c color.Alpha16) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i+0] = uint8(c.A >> 8)
+ p.Pix[i+1] = uint8(c.A)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *Alpha16) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &Alpha16{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &Alpha16{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *Alpha16) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 0, p.Rect.Dx()*2
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for i := i0; i < i1; i += 2 {
+ if p.Pix[i+0] != 0xff || p.Pix[i+1] != 0xff {
+ return false
+ }
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ return true
+}
+
+// NewAlpha16 returns a new [Alpha16] image with the given bounds.
+func NewAlpha16(r Rectangle) *Alpha16 {
+ return &Alpha16{
+ Pix: make([]uint8, pixelBufferLength(2, r, "Alpha16")),
+ Stride: 2 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// Gray is an in-memory image whose At method returns [color.Gray] values.
+type Gray struct {
+ // Pix holds the image's pixels, as gray values. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *Gray) ColorModel() color.Model { return color.GrayModel }
+
+func (p *Gray) Bounds() Rectangle { return p.Rect }
+
+func (p *Gray) At(x, y int) color.Color {
+ return p.GrayAt(x, y)
+}
+
+func (p *Gray) RGBA64At(x, y int) color.RGBA64 {
+ gray := uint16(p.GrayAt(x, y).Y)
+ gray |= gray << 8
+ return color.RGBA64{gray, gray, gray, 0xffff}
+}
+
+func (p *Gray) GrayAt(x, y int) color.Gray {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.Gray{}
+ }
+ i := p.PixOffset(x, y)
+ return color.Gray{p.Pix[i]}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *Gray) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1
+}
+
+func (p *Gray) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = color.GrayModel.Convert(c).(color.Gray).Y
+}
+
+func (p *Gray) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ // This formula is the same as in color.grayModel.
+ gray := (19595*uint32(c.R) + 38470*uint32(c.G) + 7471*uint32(c.B) + 1<<15) >> 24
+ i := p.PixOffset(x, y)
+ p.Pix[i] = uint8(gray)
+}
+
+func (p *Gray) SetGray(x, y int, c color.Gray) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = c.Y
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *Gray) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &Gray{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &Gray{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *Gray) Opaque() bool {
+ return true
+}
+
+// NewGray returns a new [Gray] image with the given bounds.
+func NewGray(r Rectangle) *Gray {
+ return &Gray{
+ Pix: make([]uint8, pixelBufferLength(1, r, "Gray")),
+ Stride: 1 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// Gray16 is an in-memory image whose At method returns [color.Gray16] values.
+type Gray16 struct {
+ // Pix holds the image's pixels, as gray values in big-endian format. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *Gray16) ColorModel() color.Model { return color.Gray16Model }
+
+func (p *Gray16) Bounds() Rectangle { return p.Rect }
+
+func (p *Gray16) At(x, y int) color.Color {
+ return p.Gray16At(x, y)
+}
+
+func (p *Gray16) RGBA64At(x, y int) color.RGBA64 {
+ gray := p.Gray16At(x, y).Y
+ return color.RGBA64{gray, gray, gray, 0xffff}
+}
+
+func (p *Gray16) Gray16At(x, y int) color.Gray16 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.Gray16{}
+ }
+ i := p.PixOffset(x, y)
+ return color.Gray16{uint16(p.Pix[i+0])<<8 | uint16(p.Pix[i+1])}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *Gray16) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2
+}
+
+func (p *Gray16) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.Gray16Model.Convert(c).(color.Gray16)
+ p.Pix[i+0] = uint8(c1.Y >> 8)
+ p.Pix[i+1] = uint8(c1.Y)
+}
+
+func (p *Gray16) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ // This formula is the same as in color.gray16Model.
+ gray := (19595*uint32(c.R) + 38470*uint32(c.G) + 7471*uint32(c.B) + 1<<15) >> 16
+ i := p.PixOffset(x, y)
+ p.Pix[i+0] = uint8(gray >> 8)
+ p.Pix[i+1] = uint8(gray)
+}
+
+func (p *Gray16) SetGray16(x, y int, c color.Gray16) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i+0] = uint8(c.Y >> 8)
+ p.Pix[i+1] = uint8(c.Y)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *Gray16) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &Gray16{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &Gray16{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *Gray16) Opaque() bool {
+ return true
+}
+
+// NewGray16 returns a new [Gray16] image with the given bounds.
+func NewGray16(r Rectangle) *Gray16 {
+ return &Gray16{
+ Pix: make([]uint8, pixelBufferLength(2, r, "Gray16")),
+ Stride: 2 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// CMYK is an in-memory image whose At method returns [color.CMYK] values.
+type CMYK struct {
+ // Pix holds the image's pixels, in C, M, Y, K order. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+}
+
+func (p *CMYK) ColorModel() color.Model { return color.CMYKModel }
+
+func (p *CMYK) Bounds() Rectangle { return p.Rect }
+
+func (p *CMYK) At(x, y int) color.Color {
+ return p.CMYKAt(x, y)
+}
+
+func (p *CMYK) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := p.CMYKAt(x, y).RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+func (p *CMYK) CMYKAt(x, y int) color.CMYK {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.CMYK{}
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ return color.CMYK{s[0], s[1], s[2], s[3]}
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *CMYK) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4
+}
+
+func (p *CMYK) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ c1 := color.CMYKModel.Convert(c).(color.CMYK)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c1.C
+ s[1] = c1.M
+ s[2] = c1.Y
+ s[3] = c1.K
+}
+
+func (p *CMYK) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ cc, mm, yy, kk := color.RGBToCMYK(uint8(c.R>>8), uint8(c.G>>8), uint8(c.B>>8))
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = cc
+ s[1] = mm
+ s[2] = yy
+ s[3] = kk
+}
+
+func (p *CMYK) SetCMYK(x, y int, c color.CMYK) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ s := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857
+ s[0] = c.C
+ s[1] = c.M
+ s[2] = c.Y
+ s[3] = c.K
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *CMYK) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &CMYK{}
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &CMYK{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: r,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *CMYK) Opaque() bool {
+ return true
+}
+
+// NewCMYK returns a new CMYK image with the given bounds.
+func NewCMYK(r Rectangle) *CMYK {
+ return &CMYK{
+ Pix: make([]uint8, pixelBufferLength(4, r, "CMYK")),
+ Stride: 4 * r.Dx(),
+ Rect: r,
+ }
+}
+
+// Paletted is an in-memory image of uint8 indices into a given palette.
+type Paletted struct {
+ // Pix holds the image's pixels, as palette indices. The pixel at
+ // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
+ Pix []uint8
+ // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
+ Stride int
+ // Rect is the image's bounds.
+ Rect Rectangle
+ // Palette is the image's palette.
+ Palette color.Palette
+}
+
+func (p *Paletted) ColorModel() color.Model { return p.Palette }
+
+func (p *Paletted) Bounds() Rectangle { return p.Rect }
+
+func (p *Paletted) At(x, y int) color.Color {
+ if len(p.Palette) == 0 {
+ return nil
+ }
+ if !(Point{x, y}.In(p.Rect)) {
+ return p.Palette[0]
+ }
+ i := p.PixOffset(x, y)
+ return p.Palette[p.Pix[i]]
+}
+
+func (p *Paletted) RGBA64At(x, y int) color.RGBA64 {
+ if len(p.Palette) == 0 {
+ return color.RGBA64{}
+ }
+ c := color.Color(nil)
+ if !(Point{x, y}.In(p.Rect)) {
+ c = p.Palette[0]
+ } else {
+ i := p.PixOffset(x, y)
+ c = p.Palette[p.Pix[i]]
+ }
+ r, g, b, a := c.RGBA()
+ return color.RGBA64{
+ uint16(r),
+ uint16(g),
+ uint16(b),
+ uint16(a),
+ }
+}
+
+// PixOffset returns the index of the first element of Pix that corresponds to
+// the pixel at (x, y).
+func (p *Paletted) PixOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1
+}
+
+func (p *Paletted) Set(x, y int, c color.Color) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = uint8(p.Palette.Index(c))
+}
+
+func (p *Paletted) SetRGBA64(x, y int, c color.RGBA64) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = uint8(p.Palette.Index(c))
+}
+
+func (p *Paletted) ColorIndexAt(x, y int) uint8 {
+ if !(Point{x, y}.In(p.Rect)) {
+ return 0
+ }
+ i := p.PixOffset(x, y)
+ return p.Pix[i]
+}
+
+func (p *Paletted) SetColorIndex(x, y int, index uint8) {
+ if !(Point{x, y}.In(p.Rect)) {
+ return
+ }
+ i := p.PixOffset(x, y)
+ p.Pix[i] = index
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *Paletted) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &Paletted{
+ Palette: p.Palette,
+ }
+ }
+ i := p.PixOffset(r.Min.X, r.Min.Y)
+ return &Paletted{
+ Pix: p.Pix[i:],
+ Stride: p.Stride,
+ Rect: p.Rect.Intersect(r),
+ Palette: p.Palette,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *Paletted) Opaque() bool {
+ var present [256]bool
+ i0, i1 := 0, p.Rect.Dx()
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for _, c := range p.Pix[i0:i1] {
+ present[c] = true
+ }
+ i0 += p.Stride
+ i1 += p.Stride
+ }
+ for i, c := range p.Palette {
+ if !present[i] {
+ continue
+ }
+ _, _, _, a := c.RGBA()
+ if a != 0xffff {
+ return false
+ }
+ }
+ return true
+}
+
+// NewPaletted returns a new [Paletted] image with the given width, height and
+// palette.
+func NewPaletted(r Rectangle, p color.Palette) *Paletted {
+ return &Paletted{
+ Pix: make([]uint8, pixelBufferLength(1, r, "Paletted")),
+ Stride: 1 * r.Dx(),
+ Rect: r,
+ Palette: p,
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/image/image_test.go b/platform/dbops/binaries/go/go/src/image/image_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7f41bcb6c7086f1eb737fdd33cac1cd8135c488a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/image_test.go
@@ -0,0 +1,458 @@
+// 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 image
+
+import (
+ "image/color"
+ "image/color/palette"
+ "testing"
+)
+
+type image interface {
+ Image
+ Opaque() bool
+ Set(int, int, color.Color)
+ SubImage(Rectangle) Image
+}
+
+func cmp(cm color.Model, c0, c1 color.Color) bool {
+ r0, g0, b0, a0 := cm.Convert(c0).RGBA()
+ r1, g1, b1, a1 := cm.Convert(c1).RGBA()
+ return r0 == r1 && g0 == g1 && b0 == b1 && a0 == a1
+}
+
+var testImages = []struct {
+ name string
+ image func() image
+}{
+ {"rgba", func() image { return NewRGBA(Rect(0, 0, 10, 10)) }},
+ {"rgba64", func() image { return NewRGBA64(Rect(0, 0, 10, 10)) }},
+ {"nrgba", func() image { return NewNRGBA(Rect(0, 0, 10, 10)) }},
+ {"nrgba64", func() image { return NewNRGBA64(Rect(0, 0, 10, 10)) }},
+ {"alpha", func() image { return NewAlpha(Rect(0, 0, 10, 10)) }},
+ {"alpha16", func() image { return NewAlpha16(Rect(0, 0, 10, 10)) }},
+ {"gray", func() image { return NewGray(Rect(0, 0, 10, 10)) }},
+ {"gray16", func() image { return NewGray16(Rect(0, 0, 10, 10)) }},
+ {"paletted", func() image {
+ return NewPaletted(Rect(0, 0, 10, 10), color.Palette{
+ Transparent,
+ Opaque,
+ })
+ }},
+}
+
+func TestImage(t *testing.T) {
+ for _, tc := range testImages {
+ m := tc.image()
+ if !Rect(0, 0, 10, 10).Eq(m.Bounds()) {
+ t.Errorf("%T: want bounds %v, got %v", m, Rect(0, 0, 10, 10), m.Bounds())
+ continue
+ }
+ if !cmp(m.ColorModel(), Transparent, m.At(6, 3)) {
+ t.Errorf("%T: at (6, 3), want a zero color, got %v", m, m.At(6, 3))
+ continue
+ }
+ m.Set(6, 3, Opaque)
+ if !cmp(m.ColorModel(), Opaque, m.At(6, 3)) {
+ t.Errorf("%T: at (6, 3), want a non-zero color, got %v", m, m.At(6, 3))
+ continue
+ }
+ if !m.SubImage(Rect(6, 3, 7, 4)).(image).Opaque() {
+ t.Errorf("%T: at (6, 3) was not opaque", m)
+ continue
+ }
+ m = m.SubImage(Rect(3, 2, 9, 8)).(image)
+ if !Rect(3, 2, 9, 8).Eq(m.Bounds()) {
+ t.Errorf("%T: sub-image want bounds %v, got %v", m, Rect(3, 2, 9, 8), m.Bounds())
+ continue
+ }
+ if !cmp(m.ColorModel(), Opaque, m.At(6, 3)) {
+ t.Errorf("%T: sub-image at (6, 3), want a non-zero color, got %v", m, m.At(6, 3))
+ continue
+ }
+ if !cmp(m.ColorModel(), Transparent, m.At(3, 3)) {
+ t.Errorf("%T: sub-image at (3, 3), want a zero color, got %v", m, m.At(3, 3))
+ continue
+ }
+ m.Set(3, 3, Opaque)
+ if !cmp(m.ColorModel(), Opaque, m.At(3, 3)) {
+ t.Errorf("%T: sub-image at (3, 3), want a non-zero color, got %v", m, m.At(3, 3))
+ continue
+ }
+ // Test that taking an empty sub-image starting at a corner does not panic.
+ m.SubImage(Rect(0, 0, 0, 0))
+ m.SubImage(Rect(10, 0, 10, 0))
+ m.SubImage(Rect(0, 10, 0, 10))
+ m.SubImage(Rect(10, 10, 10, 10))
+ }
+}
+
+func TestNewXxxBadRectangle(t *testing.T) {
+ // call calls f(r) and reports whether it ran without panicking.
+ call := func(f func(Rectangle), r Rectangle) (ok bool) {
+ defer func() {
+ if recover() != nil {
+ ok = false
+ }
+ }()
+ f(r)
+ return true
+ }
+
+ testCases := []struct {
+ name string
+ f func(Rectangle)
+ }{
+ {"RGBA", func(r Rectangle) { NewRGBA(r) }},
+ {"RGBA64", func(r Rectangle) { NewRGBA64(r) }},
+ {"NRGBA", func(r Rectangle) { NewNRGBA(r) }},
+ {"NRGBA64", func(r Rectangle) { NewNRGBA64(r) }},
+ {"Alpha", func(r Rectangle) { NewAlpha(r) }},
+ {"Alpha16", func(r Rectangle) { NewAlpha16(r) }},
+ {"Gray", func(r Rectangle) { NewGray(r) }},
+ {"Gray16", func(r Rectangle) { NewGray16(r) }},
+ {"CMYK", func(r Rectangle) { NewCMYK(r) }},
+ {"Paletted", func(r Rectangle) { NewPaletted(r, color.Palette{color.Black, color.White}) }},
+ {"YCbCr", func(r Rectangle) { NewYCbCr(r, YCbCrSubsampleRatio422) }},
+ {"NYCbCrA", func(r Rectangle) { NewNYCbCrA(r, YCbCrSubsampleRatio444) }},
+ }
+
+ for _, tc := range testCases {
+ // Calling NewXxx(r) should fail (panic, since NewXxx doesn't return an
+ // error) unless r's width and height are both non-negative.
+ for _, negDx := range []bool{false, true} {
+ for _, negDy := range []bool{false, true} {
+ r := Rectangle{
+ Min: Point{15, 28},
+ Max: Point{16, 29},
+ }
+ if negDx {
+ r.Max.X = 14
+ }
+ if negDy {
+ r.Max.Y = 27
+ }
+
+ got := call(tc.f, r)
+ want := !negDx && !negDy
+ if got != want {
+ t.Errorf("New%s: negDx=%t, negDy=%t: got %t, want %t",
+ tc.name, negDx, negDy, got, want)
+ }
+ }
+ }
+
+ // Passing a Rectangle whose width and height is MaxInt should also fail
+ // (panic), due to overflow.
+ {
+ zeroAsUint := uint(0)
+ maxUint := zeroAsUint - 1
+ maxInt := int(maxUint / 2)
+ got := call(tc.f, Rectangle{
+ Min: Point{0, 0},
+ Max: Point{maxInt, maxInt},
+ })
+ if got {
+ t.Errorf("New%s: overflow: got ok, want !ok", tc.name)
+ }
+ }
+ }
+}
+
+func Test16BitsPerColorChannel(t *testing.T) {
+ testColorModel := []color.Model{
+ color.RGBA64Model,
+ color.NRGBA64Model,
+ color.Alpha16Model,
+ color.Gray16Model,
+ }
+ for _, cm := range testColorModel {
+ c := cm.Convert(color.RGBA64{0x1234, 0x1234, 0x1234, 0x1234}) // Premultiplied alpha.
+ r, _, _, _ := c.RGBA()
+ if r != 0x1234 {
+ t.Errorf("%T: want red value 0x%04x got 0x%04x", c, 0x1234, r)
+ continue
+ }
+ }
+ testImage := []image{
+ NewRGBA64(Rect(0, 0, 10, 10)),
+ NewNRGBA64(Rect(0, 0, 10, 10)),
+ NewAlpha16(Rect(0, 0, 10, 10)),
+ NewGray16(Rect(0, 0, 10, 10)),
+ }
+ for _, m := range testImage {
+ m.Set(1, 2, color.NRGBA64{0xffff, 0xffff, 0xffff, 0x1357}) // Non-premultiplied alpha.
+ r, _, _, _ := m.At(1, 2).RGBA()
+ if r != 0x1357 {
+ t.Errorf("%T: want red value 0x%04x got 0x%04x", m, 0x1357, r)
+ continue
+ }
+ }
+}
+
+func TestRGBA64Image(t *testing.T) {
+ // memset sets every element of s to v.
+ memset := func(s []byte, v byte) {
+ for i := range s {
+ s[i] = v
+ }
+ }
+
+ r := Rect(0, 0, 3, 2)
+ testCases := []Image{
+ NewAlpha(r),
+ NewAlpha16(r),
+ NewCMYK(r),
+ NewGray(r),
+ NewGray16(r),
+ NewNRGBA(r),
+ NewNRGBA64(r),
+ NewNYCbCrA(r, YCbCrSubsampleRatio444),
+ NewPaletted(r, palette.Plan9),
+ NewRGBA(r),
+ NewRGBA64(r),
+ NewUniform(color.RGBA64{}),
+ NewYCbCr(r, YCbCrSubsampleRatio444),
+ r,
+ }
+ for _, tc := range testCases {
+ switch tc := tc.(type) {
+ // Most of the concrete image types in the testCases implement the
+ // draw.RGBA64Image interface: they have a SetRGBA64 method. We use an
+ // interface literal here, instead of importing "image/draw", to avoid
+ // an import cycle.
+ //
+ // The YCbCr and NYCbCrA types are special-cased. Chroma subsampling
+ // means that setting one pixel can modify neighboring pixels. They
+ // don't have Set or SetRGBA64 methods because that side effect could
+ // be surprising. Here, we just memset the channel buffers instead.
+ //
+ // The Uniform and Rectangle types are also special-cased, as they
+ // don't have a Set or SetRGBA64 method.
+ case interface {
+ SetRGBA64(x, y int, c color.RGBA64)
+ }:
+ tc.SetRGBA64(1, 1, color.RGBA64{0x7FFF, 0x3FFF, 0x0000, 0x7FFF})
+
+ case *NYCbCrA:
+ memset(tc.YCbCr.Y, 0x77)
+ memset(tc.YCbCr.Cb, 0x88)
+ memset(tc.YCbCr.Cr, 0x99)
+ memset(tc.A, 0xAA)
+
+ case *Uniform:
+ tc.C = color.RGBA64{0x7FFF, 0x3FFF, 0x0000, 0x7FFF}
+
+ case *YCbCr:
+ memset(tc.Y, 0x77)
+ memset(tc.Cb, 0x88)
+ memset(tc.Cr, 0x99)
+
+ case Rectangle:
+ // No-op. Rectangle pixels' colors are immutable. They're always
+ // color.Opaque.
+
+ default:
+ t.Errorf("could not initialize pixels for %T", tc)
+ continue
+ }
+
+ // Check that RGBA64At(x, y) is equivalent to At(x, y).RGBA().
+ rgba64Image, ok := tc.(RGBA64Image)
+ if !ok {
+ t.Errorf("%T is not an RGBA64Image", tc)
+ continue
+ }
+ got := rgba64Image.RGBA64At(1, 1)
+ wantR, wantG, wantB, wantA := tc.At(1, 1).RGBA()
+ if (uint32(got.R) != wantR) || (uint32(got.G) != wantG) ||
+ (uint32(got.B) != wantB) || (uint32(got.A) != wantA) {
+ t.Errorf("%T:\ngot (0x%04X, 0x%04X, 0x%04X, 0x%04X)\n"+
+ "want (0x%04X, 0x%04X, 0x%04X, 0x%04X)", tc,
+ got.R, got.G, got.B, got.A,
+ wantR, wantG, wantB, wantA)
+ continue
+ }
+ }
+}
+
+func BenchmarkAt(b *testing.B) {
+ for _, tc := range testImages {
+ b.Run(tc.name, func(b *testing.B) {
+ m := tc.image()
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ m.At(4, 5)
+ }
+ })
+ }
+}
+
+func BenchmarkSet(b *testing.B) {
+ c := color.Gray{0xff}
+ for _, tc := range testImages {
+ b.Run(tc.name, func(b *testing.B) {
+ m := tc.image()
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ m.Set(4, 5, c)
+ }
+ })
+ }
+}
+
+func BenchmarkRGBAAt(b *testing.B) {
+ m := NewRGBA(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.RGBAAt(4, 5)
+ }
+}
+
+func BenchmarkRGBASetRGBA(b *testing.B) {
+ m := NewRGBA(Rect(0, 0, 10, 10))
+ c := color.RGBA{0xff, 0xff, 0xff, 0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetRGBA(4, 5, c)
+ }
+}
+
+func BenchmarkRGBA64At(b *testing.B) {
+ m := NewRGBA64(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.RGBA64At(4, 5)
+ }
+}
+
+func BenchmarkRGBA64SetRGBA64(b *testing.B) {
+ m := NewRGBA64(Rect(0, 0, 10, 10))
+ c := color.RGBA64{0xffff, 0xffff, 0xffff, 0x1357}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetRGBA64(4, 5, c)
+ }
+}
+
+func BenchmarkNRGBAAt(b *testing.B) {
+ m := NewNRGBA(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.NRGBAAt(4, 5)
+ }
+}
+
+func BenchmarkNRGBASetNRGBA(b *testing.B) {
+ m := NewNRGBA(Rect(0, 0, 10, 10))
+ c := color.NRGBA{0xff, 0xff, 0xff, 0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetNRGBA(4, 5, c)
+ }
+}
+
+func BenchmarkNRGBA64At(b *testing.B) {
+ m := NewNRGBA64(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.NRGBA64At(4, 5)
+ }
+}
+
+func BenchmarkNRGBA64SetNRGBA64(b *testing.B) {
+ m := NewNRGBA64(Rect(0, 0, 10, 10))
+ c := color.NRGBA64{0xffff, 0xffff, 0xffff, 0x1357}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetNRGBA64(4, 5, c)
+ }
+}
+
+func BenchmarkAlphaAt(b *testing.B) {
+ m := NewAlpha(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.AlphaAt(4, 5)
+ }
+}
+
+func BenchmarkAlphaSetAlpha(b *testing.B) {
+ m := NewAlpha(Rect(0, 0, 10, 10))
+ c := color.Alpha{0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetAlpha(4, 5, c)
+ }
+}
+
+func BenchmarkAlpha16At(b *testing.B) {
+ m := NewAlpha16(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.Alpha16At(4, 5)
+ }
+}
+
+func BenchmarkAlphaSetAlpha16(b *testing.B) {
+ m := NewAlpha16(Rect(0, 0, 10, 10))
+ c := color.Alpha16{0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetAlpha16(4, 5, c)
+ }
+}
+
+func BenchmarkGrayAt(b *testing.B) {
+ m := NewGray(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.GrayAt(4, 5)
+ }
+}
+
+func BenchmarkGraySetGray(b *testing.B) {
+ m := NewGray(Rect(0, 0, 10, 10))
+ c := color.Gray{0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetGray(4, 5, c)
+ }
+}
+
+func BenchmarkGray16At(b *testing.B) {
+ m := NewGray16(Rect(0, 0, 10, 10))
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.Gray16At(4, 5)
+ }
+}
+
+func BenchmarkGraySetGray16(b *testing.B) {
+ m := NewGray16(Rect(0, 0, 10, 10))
+ c := color.Gray16{0x13}
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ m.SetGray16(4, 5, c)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/image/names.go b/platform/dbops/binaries/go/go/src/image/names.go
new file mode 100644
index 0000000000000000000000000000000000000000..a2968fabe27d275c60d336801deb1f6b26d2cd66
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/names.go
@@ -0,0 +1,58 @@
+// 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 image
+
+import (
+ "image/color"
+)
+
+var (
+ // Black is an opaque black uniform image.
+ Black = NewUniform(color.Black)
+ // White is an opaque white uniform image.
+ White = NewUniform(color.White)
+ // Transparent is a fully transparent uniform image.
+ Transparent = NewUniform(color.Transparent)
+ // Opaque is a fully opaque uniform image.
+ Opaque = NewUniform(color.Opaque)
+)
+
+// Uniform is an infinite-sized [Image] of uniform color.
+// It implements the [color.Color], [color.Model], and [Image] interfaces.
+type Uniform struct {
+ C color.Color
+}
+
+func (c *Uniform) RGBA() (r, g, b, a uint32) {
+ return c.C.RGBA()
+}
+
+func (c *Uniform) ColorModel() color.Model {
+ return c
+}
+
+func (c *Uniform) Convert(color.Color) color.Color {
+ return c.C
+}
+
+func (c *Uniform) Bounds() Rectangle { return Rectangle{Point{-1e9, -1e9}, Point{1e9, 1e9}} }
+
+func (c *Uniform) At(x, y int) color.Color { return c.C }
+
+func (c *Uniform) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := c.C.RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (c *Uniform) Opaque() bool {
+ _, _, _, a := c.C.RGBA()
+ return a == 0xffff
+}
+
+// NewUniform returns a new [Uniform] image of the given color.
+func NewUniform(c color.Color) *Uniform {
+ return &Uniform{c}
+}
diff --git a/platform/dbops/binaries/go/go/src/image/ycbcr.go b/platform/dbops/binaries/go/go/src/image/ycbcr.go
new file mode 100644
index 0000000000000000000000000000000000000000..54333119431d0f756e80b8e9aaa2443fa6c62d97
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/ycbcr.go
@@ -0,0 +1,329 @@
+// 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 image
+
+import (
+ "image/color"
+)
+
+// YCbCrSubsampleRatio is the chroma subsample ratio used in a YCbCr image.
+type YCbCrSubsampleRatio int
+
+const (
+ YCbCrSubsampleRatio444 YCbCrSubsampleRatio = iota
+ YCbCrSubsampleRatio422
+ YCbCrSubsampleRatio420
+ YCbCrSubsampleRatio440
+ YCbCrSubsampleRatio411
+ YCbCrSubsampleRatio410
+)
+
+func (s YCbCrSubsampleRatio) String() string {
+ switch s {
+ case YCbCrSubsampleRatio444:
+ return "YCbCrSubsampleRatio444"
+ case YCbCrSubsampleRatio422:
+ return "YCbCrSubsampleRatio422"
+ case YCbCrSubsampleRatio420:
+ return "YCbCrSubsampleRatio420"
+ case YCbCrSubsampleRatio440:
+ return "YCbCrSubsampleRatio440"
+ case YCbCrSubsampleRatio411:
+ return "YCbCrSubsampleRatio411"
+ case YCbCrSubsampleRatio410:
+ return "YCbCrSubsampleRatio410"
+ }
+ return "YCbCrSubsampleRatioUnknown"
+}
+
+// YCbCr is an in-memory image of Y'CbCr colors. There is one Y sample per
+// pixel, but each Cb and Cr sample can span one or more pixels.
+// YStride is the Y slice index delta between vertically adjacent pixels.
+// CStride is the Cb and Cr slice index delta between vertically adjacent pixels
+// that map to separate chroma samples.
+// It is not an absolute requirement, but YStride and len(Y) are typically
+// multiples of 8, and:
+//
+// For 4:4:4, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/1.
+// For 4:2:2, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/2.
+// For 4:2:0, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/4.
+// For 4:4:0, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/2.
+// For 4:1:1, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/4.
+// For 4:1:0, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/8.
+type YCbCr struct {
+ Y, Cb, Cr []uint8
+ YStride int
+ CStride int
+ SubsampleRatio YCbCrSubsampleRatio
+ Rect Rectangle
+}
+
+func (p *YCbCr) ColorModel() color.Model {
+ return color.YCbCrModel
+}
+
+func (p *YCbCr) Bounds() Rectangle {
+ return p.Rect
+}
+
+func (p *YCbCr) At(x, y int) color.Color {
+ return p.YCbCrAt(x, y)
+}
+
+func (p *YCbCr) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := p.YCbCrAt(x, y).RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+func (p *YCbCr) YCbCrAt(x, y int) color.YCbCr {
+ if !(Point{x, y}.In(p.Rect)) {
+ return color.YCbCr{}
+ }
+ yi := p.YOffset(x, y)
+ ci := p.COffset(x, y)
+ return color.YCbCr{
+ p.Y[yi],
+ p.Cb[ci],
+ p.Cr[ci],
+ }
+}
+
+// YOffset returns the index of the first element of Y that corresponds to
+// the pixel at (x, y).
+func (p *YCbCr) YOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.YStride + (x - p.Rect.Min.X)
+}
+
+// COffset returns the index of the first element of Cb or Cr that corresponds
+// to the pixel at (x, y).
+func (p *YCbCr) COffset(x, y int) int {
+ switch p.SubsampleRatio {
+ case YCbCrSubsampleRatio422:
+ return (y-p.Rect.Min.Y)*p.CStride + (x/2 - p.Rect.Min.X/2)
+ case YCbCrSubsampleRatio420:
+ return (y/2-p.Rect.Min.Y/2)*p.CStride + (x/2 - p.Rect.Min.X/2)
+ case YCbCrSubsampleRatio440:
+ return (y/2-p.Rect.Min.Y/2)*p.CStride + (x - p.Rect.Min.X)
+ case YCbCrSubsampleRatio411:
+ return (y-p.Rect.Min.Y)*p.CStride + (x/4 - p.Rect.Min.X/4)
+ case YCbCrSubsampleRatio410:
+ return (y/2-p.Rect.Min.Y/2)*p.CStride + (x/4 - p.Rect.Min.X/4)
+ }
+ // Default to 4:4:4 subsampling.
+ return (y-p.Rect.Min.Y)*p.CStride + (x - p.Rect.Min.X)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *YCbCr) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &YCbCr{
+ SubsampleRatio: p.SubsampleRatio,
+ }
+ }
+ yi := p.YOffset(r.Min.X, r.Min.Y)
+ ci := p.COffset(r.Min.X, r.Min.Y)
+ return &YCbCr{
+ Y: p.Y[yi:],
+ Cb: p.Cb[ci:],
+ Cr: p.Cr[ci:],
+ SubsampleRatio: p.SubsampleRatio,
+ YStride: p.YStride,
+ CStride: p.CStride,
+ Rect: r,
+ }
+}
+
+func (p *YCbCr) Opaque() bool {
+ return true
+}
+
+func yCbCrSize(r Rectangle, subsampleRatio YCbCrSubsampleRatio) (w, h, cw, ch int) {
+ w, h = r.Dx(), r.Dy()
+ switch subsampleRatio {
+ case YCbCrSubsampleRatio422:
+ cw = (r.Max.X+1)/2 - r.Min.X/2
+ ch = h
+ case YCbCrSubsampleRatio420:
+ cw = (r.Max.X+1)/2 - r.Min.X/2
+ ch = (r.Max.Y+1)/2 - r.Min.Y/2
+ case YCbCrSubsampleRatio440:
+ cw = w
+ ch = (r.Max.Y+1)/2 - r.Min.Y/2
+ case YCbCrSubsampleRatio411:
+ cw = (r.Max.X+3)/4 - r.Min.X/4
+ ch = h
+ case YCbCrSubsampleRatio410:
+ cw = (r.Max.X+3)/4 - r.Min.X/4
+ ch = (r.Max.Y+1)/2 - r.Min.Y/2
+ default:
+ // Default to 4:4:4 subsampling.
+ cw = w
+ ch = h
+ }
+ return
+}
+
+// NewYCbCr returns a new YCbCr image with the given bounds and subsample
+// ratio.
+func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr {
+ w, h, cw, ch := yCbCrSize(r, subsampleRatio)
+
+ // totalLength should be the same as i2, below, for a valid Rectangle r.
+ totalLength := add2NonNeg(
+ mul3NonNeg(1, w, h),
+ mul3NonNeg(2, cw, ch),
+ )
+ if totalLength < 0 {
+ panic("image: NewYCbCr Rectangle has huge or negative dimensions")
+ }
+
+ i0 := w*h + 0*cw*ch
+ i1 := w*h + 1*cw*ch
+ i2 := w*h + 2*cw*ch
+ b := make([]byte, i2)
+ return &YCbCr{
+ Y: b[:i0:i0],
+ Cb: b[i0:i1:i1],
+ Cr: b[i1:i2:i2],
+ SubsampleRatio: subsampleRatio,
+ YStride: w,
+ CStride: cw,
+ Rect: r,
+ }
+}
+
+// NYCbCrA is an in-memory image of non-alpha-premultiplied Y'CbCr-with-alpha
+// colors. A and AStride are analogous to the Y and YStride fields of the
+// embedded YCbCr.
+type NYCbCrA struct {
+ YCbCr
+ A []uint8
+ AStride int
+}
+
+func (p *NYCbCrA) ColorModel() color.Model {
+ return color.NYCbCrAModel
+}
+
+func (p *NYCbCrA) At(x, y int) color.Color {
+ return p.NYCbCrAAt(x, y)
+}
+
+func (p *NYCbCrA) RGBA64At(x, y int) color.RGBA64 {
+ r, g, b, a := p.NYCbCrAAt(x, y).RGBA()
+ return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)}
+}
+
+func (p *NYCbCrA) NYCbCrAAt(x, y int) color.NYCbCrA {
+ if !(Point{X: x, Y: y}.In(p.Rect)) {
+ return color.NYCbCrA{}
+ }
+ yi := p.YOffset(x, y)
+ ci := p.COffset(x, y)
+ ai := p.AOffset(x, y)
+ return color.NYCbCrA{
+ color.YCbCr{
+ Y: p.Y[yi],
+ Cb: p.Cb[ci],
+ Cr: p.Cr[ci],
+ },
+ p.A[ai],
+ }
+}
+
+// AOffset returns the index of the first element of A that corresponds to the
+// pixel at (x, y).
+func (p *NYCbCrA) AOffset(x, y int) int {
+ return (y-p.Rect.Min.Y)*p.AStride + (x - p.Rect.Min.X)
+}
+
+// SubImage returns an image representing the portion of the image p visible
+// through r. The returned value shares pixels with the original image.
+func (p *NYCbCrA) SubImage(r Rectangle) Image {
+ r = r.Intersect(p.Rect)
+ // If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
+ // either r1 or r2 if the intersection is empty. Without explicitly checking for
+ // this, the Pix[i:] expression below can panic.
+ if r.Empty() {
+ return &NYCbCrA{
+ YCbCr: YCbCr{
+ SubsampleRatio: p.SubsampleRatio,
+ },
+ }
+ }
+ yi := p.YOffset(r.Min.X, r.Min.Y)
+ ci := p.COffset(r.Min.X, r.Min.Y)
+ ai := p.AOffset(r.Min.X, r.Min.Y)
+ return &NYCbCrA{
+ YCbCr: YCbCr{
+ Y: p.Y[yi:],
+ Cb: p.Cb[ci:],
+ Cr: p.Cr[ci:],
+ SubsampleRatio: p.SubsampleRatio,
+ YStride: p.YStride,
+ CStride: p.CStride,
+ Rect: r,
+ },
+ A: p.A[ai:],
+ AStride: p.AStride,
+ }
+}
+
+// Opaque scans the entire image and reports whether it is fully opaque.
+func (p *NYCbCrA) Opaque() bool {
+ if p.Rect.Empty() {
+ return true
+ }
+ i0, i1 := 0, p.Rect.Dx()
+ for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
+ for _, a := range p.A[i0:i1] {
+ if a != 0xff {
+ return false
+ }
+ }
+ i0 += p.AStride
+ i1 += p.AStride
+ }
+ return true
+}
+
+// NewNYCbCrA returns a new [NYCbCrA] image with the given bounds and subsample
+// ratio.
+func NewNYCbCrA(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *NYCbCrA {
+ w, h, cw, ch := yCbCrSize(r, subsampleRatio)
+
+ // totalLength should be the same as i3, below, for a valid Rectangle r.
+ totalLength := add2NonNeg(
+ mul3NonNeg(2, w, h),
+ mul3NonNeg(2, cw, ch),
+ )
+ if totalLength < 0 {
+ panic("image: NewNYCbCrA Rectangle has huge or negative dimension")
+ }
+
+ i0 := 1*w*h + 0*cw*ch
+ i1 := 1*w*h + 1*cw*ch
+ i2 := 1*w*h + 2*cw*ch
+ i3 := 2*w*h + 2*cw*ch
+ b := make([]byte, i3)
+ return &NYCbCrA{
+ YCbCr: YCbCr{
+ Y: b[:i0:i0],
+ Cb: b[i0:i1:i1],
+ Cr: b[i1:i2:i2],
+ SubsampleRatio: subsampleRatio,
+ YStride: w,
+ CStride: cw,
+ Rect: r,
+ },
+ A: b[i2:],
+ AStride: w,
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/image/ycbcr_test.go b/platform/dbops/binaries/go/go/src/image/ycbcr_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4996bc8dcaeeb1d67b5adbdcbf58aa4723179c6e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/image/ycbcr_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 image
+
+import (
+ "image/color"
+ "testing"
+)
+
+func TestYCbCr(t *testing.T) {
+ rects := []Rectangle{
+ Rect(0, 0, 16, 16),
+ Rect(1, 0, 16, 16),
+ Rect(0, 1, 16, 16),
+ Rect(1, 1, 16, 16),
+ Rect(1, 1, 15, 16),
+ Rect(1, 1, 16, 15),
+ Rect(1, 1, 15, 15),
+ Rect(2, 3, 14, 15),
+ Rect(7, 0, 7, 16),
+ Rect(0, 8, 16, 8),
+ Rect(0, 0, 10, 11),
+ Rect(5, 6, 16, 16),
+ Rect(7, 7, 8, 8),
+ Rect(7, 8, 8, 9),
+ Rect(8, 7, 9, 8),
+ Rect(8, 8, 9, 9),
+ Rect(7, 7, 17, 17),
+ Rect(8, 8, 17, 17),
+ Rect(9, 9, 17, 17),
+ Rect(10, 10, 17, 17),
+ }
+ subsampleRatios := []YCbCrSubsampleRatio{
+ YCbCrSubsampleRatio444,
+ YCbCrSubsampleRatio422,
+ YCbCrSubsampleRatio420,
+ YCbCrSubsampleRatio440,
+ YCbCrSubsampleRatio411,
+ YCbCrSubsampleRatio410,
+ }
+ deltas := []Point{
+ Pt(0, 0),
+ Pt(1000, 1001),
+ Pt(5001, -400),
+ Pt(-701, -801),
+ }
+ for _, r := range rects {
+ for _, subsampleRatio := range subsampleRatios {
+ for _, delta := range deltas {
+ testYCbCr(t, r, subsampleRatio, delta)
+ }
+ }
+ if testing.Short() {
+ break
+ }
+ }
+}
+
+func testYCbCr(t *testing.T, r Rectangle, subsampleRatio YCbCrSubsampleRatio, delta Point) {
+ // Create a YCbCr image m, whose bounds are r translated by (delta.X, delta.Y).
+ r1 := r.Add(delta)
+ m := NewYCbCr(r1, subsampleRatio)
+
+ // Test that the image buffer is reasonably small even if (delta.X, delta.Y) is far from the origin.
+ if len(m.Y) > 100*100 {
+ t.Errorf("r=%v, subsampleRatio=%v, delta=%v: image buffer is too large",
+ r, subsampleRatio, delta)
+ return
+ }
+
+ // Initialize m's pixels. For 422 and 420 subsampling, some of the Cb and Cr elements
+ // will be set multiple times. That's OK. We just want to avoid a uniform image.
+ for y := r1.Min.Y; y < r1.Max.Y; y++ {
+ for x := r1.Min.X; x < r1.Max.X; x++ {
+ yi := m.YOffset(x, y)
+ ci := m.COffset(x, y)
+ m.Y[yi] = uint8(16*y + x)
+ m.Cb[ci] = uint8(y + 16*x)
+ m.Cr[ci] = uint8(y + 16*x)
+ }
+ }
+
+ // Make various sub-images of m.
+ for y0 := delta.Y + 3; y0 < delta.Y+7; y0++ {
+ for y1 := delta.Y + 8; y1 < delta.Y+13; y1++ {
+ for x0 := delta.X + 3; x0 < delta.X+7; x0++ {
+ for x1 := delta.X + 8; x1 < delta.X+13; x1++ {
+ subRect := Rect(x0, y0, x1, y1)
+ sub := m.SubImage(subRect).(*YCbCr)
+
+ // For each point in the sub-image's bounds, check that m.At(x, y) equals sub.At(x, y).
+ for y := sub.Rect.Min.Y; y < sub.Rect.Max.Y; y++ {
+ for x := sub.Rect.Min.X; x < sub.Rect.Max.X; x++ {
+ color0 := m.At(x, y).(color.YCbCr)
+ color1 := sub.At(x, y).(color.YCbCr)
+ if color0 != color1 {
+ t.Errorf("r=%v, subsampleRatio=%v, delta=%v, x=%d, y=%d, color0=%v, color1=%v",
+ r, subsampleRatio, delta, x, y, color0, color1)
+ return
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestYCbCrSlicesDontOverlap(t *testing.T) {
+ m := NewYCbCr(Rect(0, 0, 8, 8), YCbCrSubsampleRatio420)
+ names := []string{"Y", "Cb", "Cr"}
+ slices := [][]byte{
+ m.Y[:cap(m.Y)],
+ m.Cb[:cap(m.Cb)],
+ m.Cr[:cap(m.Cr)],
+ }
+ for i, slice := range slices {
+ want := uint8(10 + i)
+ for j := range slice {
+ slice[j] = want
+ }
+ }
+ for i, slice := range slices {
+ want := uint8(10 + i)
+ for j, got := range slice {
+ if got != want {
+ t.Fatalf("m.%s[%d]: got %d, want %d", names[i], j, got, want)
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/example_test.go b/platform/dbops/binaries/go/go/src/io/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..818020e9dec6dd1b11456d996f123403b8b9bcdf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/example_test.go
@@ -0,0 +1,284 @@
+// 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 io_test
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "strings"
+)
+
+func ExampleCopy() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+
+ if _, err := io.Copy(os.Stdout, r); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // some io.Reader stream to be read
+}
+
+func ExampleCopyBuffer() {
+ r1 := strings.NewReader("first reader\n")
+ r2 := strings.NewReader("second reader\n")
+ buf := make([]byte, 8)
+
+ // buf is used here...
+ if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
+ log.Fatal(err)
+ }
+
+ // ... reused here also. No need to allocate an extra buffer.
+ if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // first reader
+ // second reader
+}
+
+func ExampleCopyN() {
+ r := strings.NewReader("some io.Reader stream to be read")
+
+ if _, err := io.CopyN(os.Stdout, r, 4); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // some
+}
+
+func ExampleReadAtLeast() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+
+ buf := make([]byte, 14)
+ if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
+ log.Fatal(err)
+ }
+ fmt.Printf("%s\n", buf)
+
+ // buffer smaller than minimal read size.
+ shortBuf := make([]byte, 3)
+ if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
+ fmt.Println("error:", err)
+ }
+
+ // minimal read size bigger than io.Reader stream
+ longBuf := make([]byte, 64)
+ if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
+ fmt.Println("error:", err)
+ }
+
+ // Output:
+ // some io.Reader
+ // error: short buffer
+ // error: unexpected EOF
+}
+
+func ExampleReadFull() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+
+ buf := make([]byte, 4)
+ if _, err := io.ReadFull(r, buf); err != nil {
+ log.Fatal(err)
+ }
+ fmt.Printf("%s\n", buf)
+
+ // minimal read size bigger than io.Reader stream
+ longBuf := make([]byte, 64)
+ if _, err := io.ReadFull(r, longBuf); err != nil {
+ fmt.Println("error:", err)
+ }
+
+ // Output:
+ // some
+ // error: unexpected EOF
+}
+
+func ExampleWriteString() {
+ if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output: Hello World
+}
+
+func ExampleLimitReader() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ lr := io.LimitReader(r, 4)
+
+ if _, err := io.Copy(os.Stdout, lr); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // some
+}
+
+func ExampleMultiReader() {
+ r1 := strings.NewReader("first reader ")
+ r2 := strings.NewReader("second reader ")
+ r3 := strings.NewReader("third reader\n")
+ r := io.MultiReader(r1, r2, r3)
+
+ if _, err := io.Copy(os.Stdout, r); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // first reader second reader third reader
+}
+
+func ExampleTeeReader() {
+ var r io.Reader = strings.NewReader("some io.Reader stream to be read\n")
+
+ r = io.TeeReader(r, os.Stdout)
+
+ // Everything read from r will be copied to stdout.
+ if _, err := io.ReadAll(r); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // some io.Reader stream to be read
+}
+
+func ExampleSectionReader() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ s := io.NewSectionReader(r, 5, 17)
+
+ if _, err := io.Copy(os.Stdout, s); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // io.Reader stream
+}
+
+func ExampleSectionReader_Read() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ s := io.NewSectionReader(r, 5, 17)
+
+ buf := make([]byte, 9)
+ if _, err := s.Read(buf); err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s\n", buf)
+
+ // Output:
+ // io.Reader
+}
+
+func ExampleSectionReader_ReadAt() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ s := io.NewSectionReader(r, 5, 17)
+
+ buf := make([]byte, 6)
+ if _, err := s.ReadAt(buf, 10); err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("%s\n", buf)
+
+ // Output:
+ // stream
+}
+
+func ExampleSectionReader_Seek() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ s := io.NewSectionReader(r, 5, 17)
+
+ if _, err := s.Seek(10, io.SeekStart); err != nil {
+ log.Fatal(err)
+ }
+
+ if _, err := io.Copy(os.Stdout, s); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // stream
+}
+
+func ExampleSectionReader_Size() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+ s := io.NewSectionReader(r, 5, 17)
+
+ fmt.Println(s.Size())
+
+ // Output:
+ // 17
+}
+
+func ExampleSeeker_Seek() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+
+ r.Seek(5, io.SeekStart) // move to the 5th char from the start
+ if _, err := io.Copy(os.Stdout, r); err != nil {
+ log.Fatal(err)
+ }
+
+ r.Seek(-5, io.SeekEnd)
+ if _, err := io.Copy(os.Stdout, r); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // io.Reader stream to be read
+ // read
+}
+
+func ExampleMultiWriter() {
+ r := strings.NewReader("some io.Reader stream to be read\n")
+
+ var buf1, buf2 strings.Builder
+ w := io.MultiWriter(&buf1, &buf2)
+
+ if _, err := io.Copy(w, r); err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Print(buf1.String())
+ fmt.Print(buf2.String())
+
+ // Output:
+ // some io.Reader stream to be read
+ // some io.Reader stream to be read
+}
+
+func ExamplePipe() {
+ r, w := io.Pipe()
+
+ go func() {
+ fmt.Fprint(w, "some io.Reader stream to be read\n")
+ w.Close()
+ }()
+
+ if _, err := io.Copy(os.Stdout, r); err != nil {
+ log.Fatal(err)
+ }
+
+ // Output:
+ // some io.Reader stream to be read
+}
+
+func ExampleReadAll() {
+ r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
+
+ b, err := io.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.
+}
diff --git a/platform/dbops/binaries/go/go/src/io/export_test.go b/platform/dbops/binaries/go/go/src/io/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..06853f975f577f15c3b3a2f532a195ce8b4679e6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/export_test.go
@@ -0,0 +1,10 @@
+// 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 io
+
+// exported for test
+var ErrInvalidWrite = errInvalidWrite
+var ErrWhence = errWhence
+var ErrOffset = errOffset
diff --git a/platform/dbops/binaries/go/go/src/io/io.go b/platform/dbops/binaries/go/go/src/io/io.go
new file mode 100644
index 0000000000000000000000000000000000000000..7f16e18d7d1baadce7b1d0413b53b97990578836
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/io.go
@@ -0,0 +1,726 @@
+// 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 io provides basic interfaces to I/O primitives.
+// Its primary job is to wrap existing implementations of such primitives,
+// such as those in package os, into shared public interfaces that
+// abstract the functionality, plus some other related primitives.
+//
+// Because these interfaces and primitives wrap lower-level operations with
+// various implementations, unless otherwise informed clients should not
+// assume they are safe for parallel execution.
+package io
+
+import (
+ "errors"
+ "sync"
+)
+
+// Seek whence values.
+const (
+ SeekStart = 0 // seek relative to the origin of the file
+ SeekCurrent = 1 // seek relative to the current offset
+ SeekEnd = 2 // seek relative to the end
+)
+
+// ErrShortWrite means that a write accepted fewer bytes than requested
+// but failed to return an explicit error.
+var ErrShortWrite = errors.New("short write")
+
+// errInvalidWrite means that a write returned an impossible count.
+var errInvalidWrite = errors.New("invalid write result")
+
+// ErrShortBuffer means that a read required a longer buffer than was provided.
+var ErrShortBuffer = errors.New("short buffer")
+
+// EOF is the error returned by Read when no more input is available.
+// (Read must return EOF itself, not an error wrapping EOF,
+// because callers will test for EOF using ==.)
+// Functions should return EOF only to signal a graceful end of input.
+// If the EOF occurs unexpectedly in a structured data stream,
+// the appropriate error is either [ErrUnexpectedEOF] or some other error
+// giving more detail.
+var EOF = errors.New("EOF")
+
+// ErrUnexpectedEOF means that EOF was encountered in the
+// middle of reading a fixed-size block or data structure.
+var ErrUnexpectedEOF = errors.New("unexpected EOF")
+
+// ErrNoProgress is returned by some clients of a [Reader] when
+// many calls to Read have failed to return any data or error,
+// usually the sign of a broken [Reader] implementation.
+var ErrNoProgress = errors.New("multiple Read calls return no data or error")
+
+// Reader is the interface that wraps the basic Read method.
+//
+// Read reads up to len(p) bytes into p. It returns the number of bytes
+// read (0 <= n <= len(p)) and any error encountered. Even if Read
+// returns n < len(p), it may use all of p as scratch space during the call.
+// If some data is available but not len(p) bytes, Read conventionally
+// returns what is available instead of waiting for more.
+//
+// When Read encounters an error or end-of-file condition after
+// successfully reading n > 0 bytes, it returns the number of
+// bytes read. It may return the (non-nil) error from the same call
+// or return the error (and n == 0) from a subsequent call.
+// An instance of this general case is that a Reader returning
+// a non-zero number of bytes at the end of the input stream may
+// return either err == EOF or err == nil. The next Read should
+// return 0, EOF.
+//
+// Callers should always process the n > 0 bytes returned before
+// considering the error err. Doing so correctly handles I/O errors
+// that happen after reading some bytes and also both of the
+// allowed EOF behaviors.
+//
+// If len(p) == 0, Read should always return n == 0. It may return a
+// non-nil error if some error condition is known, such as EOF.
+//
+// Implementations of Read are discouraged from returning a
+// zero byte count with a nil error, except when len(p) == 0.
+// Callers should treat a return of 0 and nil as indicating that
+// nothing happened; in particular it does not indicate EOF.
+//
+// Implementations must not retain p.
+type Reader interface {
+ Read(p []byte) (n int, err error)
+}
+
+// Writer is the interface that wraps the basic Write method.
+//
+// Write writes len(p) bytes from p to the underlying data stream.
+// It returns the number of bytes written from p (0 <= n <= len(p))
+// and any error encountered that caused the write to stop early.
+// Write must return a non-nil error if it returns n < len(p).
+// Write must not modify the slice data, even temporarily.
+//
+// Implementations must not retain p.
+type Writer interface {
+ Write(p []byte) (n int, err error)
+}
+
+// Closer is the interface that wraps the basic Close method.
+//
+// The behavior of Close after the first call is undefined.
+// Specific implementations may document their own behavior.
+type Closer interface {
+ Close() error
+}
+
+// Seeker is the interface that wraps the basic Seek method.
+//
+// Seek sets the offset for the next Read or Write to offset,
+// interpreted according to whence:
+// [SeekStart] means relative to the start of the file,
+// [SeekCurrent] means relative to the current offset, and
+// [SeekEnd] means relative to the end
+// (for example, offset = -2 specifies the penultimate byte of the file).
+// Seek returns the new offset relative to the start of the
+// file or an error, if any.
+//
+// Seeking to an offset before the start of the file is an error.
+// Seeking to any positive offset may be allowed, but if the new offset exceeds
+// the size of the underlying object the behavior of subsequent I/O operations
+// is implementation-dependent.
+type Seeker interface {
+ Seek(offset int64, whence int) (int64, error)
+}
+
+// ReadWriter is the interface that groups the basic Read and Write methods.
+type ReadWriter interface {
+ Reader
+ Writer
+}
+
+// ReadCloser is the interface that groups the basic Read and Close methods.
+type ReadCloser interface {
+ Reader
+ Closer
+}
+
+// WriteCloser is the interface that groups the basic Write and Close methods.
+type WriteCloser interface {
+ Writer
+ Closer
+}
+
+// ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.
+type ReadWriteCloser interface {
+ Reader
+ Writer
+ Closer
+}
+
+// ReadSeeker is the interface that groups the basic Read and Seek methods.
+type ReadSeeker interface {
+ Reader
+ Seeker
+}
+
+// ReadSeekCloser is the interface that groups the basic Read, Seek and Close
+// methods.
+type ReadSeekCloser interface {
+ Reader
+ Seeker
+ Closer
+}
+
+// WriteSeeker is the interface that groups the basic Write and Seek methods.
+type WriteSeeker interface {
+ Writer
+ Seeker
+}
+
+// ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.
+type ReadWriteSeeker interface {
+ Reader
+ Writer
+ Seeker
+}
+
+// ReaderFrom is the interface that wraps the ReadFrom method.
+//
+// ReadFrom reads data from r until EOF or error.
+// The return value n is the number of bytes read.
+// Any error except EOF encountered during the read is also returned.
+//
+// The [Copy] function uses [ReaderFrom] if available.
+type ReaderFrom interface {
+ ReadFrom(r Reader) (n int64, err error)
+}
+
+// WriterTo is the interface that wraps the WriteTo method.
+//
+// WriteTo writes data to w until there's no more data to write or
+// when an error occurs. The return value n is the number of bytes
+// written. Any error encountered during the write is also returned.
+//
+// The Copy function uses WriterTo if available.
+type WriterTo interface {
+ WriteTo(w Writer) (n int64, err error)
+}
+
+// ReaderAt is the interface that wraps the basic ReadAt method.
+//
+// ReadAt reads len(p) bytes into p starting at offset off in the
+// underlying input source. It returns the number of bytes
+// read (0 <= n <= len(p)) and any error encountered.
+//
+// When ReadAt returns n < len(p), it returns a non-nil error
+// explaining why more bytes were not returned. In this respect,
+// ReadAt is stricter than Read.
+//
+// Even if ReadAt returns n < len(p), it may use all of p as scratch
+// space during the call. If some data is available but not len(p) bytes,
+// ReadAt blocks until either all the data is available or an error occurs.
+// In this respect ReadAt is different from Read.
+//
+// If the n = len(p) bytes returned by ReadAt are at the end of the
+// input source, ReadAt may return either err == EOF or err == nil.
+//
+// If ReadAt is reading from an input source with a seek offset,
+// ReadAt should not affect nor be affected by the underlying
+// seek offset.
+//
+// Clients of ReadAt can execute parallel ReadAt calls on the
+// same input source.
+//
+// Implementations must not retain p.
+type ReaderAt interface {
+ ReadAt(p []byte, off int64) (n int, err error)
+}
+
+// WriterAt is the interface that wraps the basic WriteAt method.
+//
+// WriteAt writes len(p) bytes from p to the underlying data stream
+// at offset off. It returns the number of bytes written from p (0 <= n <= len(p))
+// and any error encountered that caused the write to stop early.
+// WriteAt must return a non-nil error if it returns n < len(p).
+//
+// If WriteAt is writing to a destination with a seek offset,
+// WriteAt should not affect nor be affected by the underlying
+// seek offset.
+//
+// Clients of WriteAt can execute parallel WriteAt calls on the same
+// destination if the ranges do not overlap.
+//
+// Implementations must not retain p.
+type WriterAt interface {
+ WriteAt(p []byte, off int64) (n int, err error)
+}
+
+// ByteReader is the interface that wraps the ReadByte method.
+//
+// ReadByte reads and returns the next byte from the input or
+// any error encountered. If ReadByte returns an error, no input
+// byte was consumed, and the returned byte value is undefined.
+//
+// ReadByte provides an efficient interface for byte-at-time
+// processing. A [Reader] that does not implement ByteReader
+// can be wrapped using bufio.NewReader to add this method.
+type ByteReader interface {
+ ReadByte() (byte, error)
+}
+
+// ByteScanner is the interface that adds the UnreadByte method to the
+// basic ReadByte method.
+//
+// UnreadByte causes the next call to ReadByte to return the last byte read.
+// If the last operation was not a successful call to ReadByte, UnreadByte may
+// return an error, unread the last byte read (or the byte prior to the
+// last-unread byte), or (in implementations that support the [Seeker] interface)
+// seek to one byte before the current offset.
+type ByteScanner interface {
+ ByteReader
+ UnreadByte() error
+}
+
+// ByteWriter is the interface that wraps the WriteByte method.
+type ByteWriter interface {
+ WriteByte(c byte) error
+}
+
+// RuneReader is the interface that wraps the ReadRune method.
+//
+// ReadRune reads a single encoded Unicode character
+// and returns the rune and its size in bytes. If no character is
+// available, err will be set.
+type RuneReader interface {
+ ReadRune() (r rune, size int, err error)
+}
+
+// RuneScanner is the interface that adds the UnreadRune method to the
+// basic ReadRune method.
+//
+// UnreadRune causes the next call to ReadRune to return the last rune read.
+// If the last operation was not a successful call to ReadRune, UnreadRune may
+// return an error, unread the last rune read (or the rune prior to the
+// last-unread rune), or (in implementations that support the [Seeker] interface)
+// seek to the start of the rune before the current offset.
+type RuneScanner interface {
+ RuneReader
+ UnreadRune() error
+}
+
+// StringWriter is the interface that wraps the WriteString method.
+type StringWriter interface {
+ WriteString(s string) (n int, err error)
+}
+
+// WriteString writes the contents of the string s to w, which accepts a slice of bytes.
+// If w implements [StringWriter], [StringWriter.WriteString] is invoked directly.
+// Otherwise, [Writer.Write] is called exactly once.
+func WriteString(w Writer, s string) (n int, err error) {
+ if sw, ok := w.(StringWriter); ok {
+ return sw.WriteString(s)
+ }
+ return w.Write([]byte(s))
+}
+
+// ReadAtLeast reads from r into buf until it has read at least min bytes.
+// It returns the number of bytes copied and an error if fewer bytes were read.
+// The error is EOF only if no bytes were read.
+// If an EOF happens after reading fewer than min bytes,
+// ReadAtLeast returns [ErrUnexpectedEOF].
+// If min is greater than the length of buf, ReadAtLeast returns [ErrShortBuffer].
+// On return, n >= min if and only if err == nil.
+// If r returns an error having read at least min bytes, the error is dropped.
+func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) {
+ if len(buf) < min {
+ return 0, ErrShortBuffer
+ }
+ for n < min && err == nil {
+ var nn int
+ nn, err = r.Read(buf[n:])
+ n += nn
+ }
+ if n >= min {
+ err = nil
+ } else if n > 0 && err == EOF {
+ err = ErrUnexpectedEOF
+ }
+ return
+}
+
+// ReadFull reads exactly len(buf) bytes from r into buf.
+// It returns the number of bytes copied and an error if fewer bytes were read.
+// The error is EOF only if no bytes were read.
+// If an EOF happens after reading some but not all the bytes,
+// ReadFull returns [ErrUnexpectedEOF].
+// On return, n == len(buf) if and only if err == nil.
+// If r returns an error having read at least len(buf) bytes, the error is dropped.
+func ReadFull(r Reader, buf []byte) (n int, err error) {
+ return ReadAtLeast(r, buf, len(buf))
+}
+
+// CopyN copies n bytes (or until an error) from src to dst.
+// It returns the number of bytes copied and the earliest
+// error encountered while copying.
+// On return, written == n if and only if err == nil.
+//
+// If dst implements [ReaderFrom], the copy is implemented using it.
+func CopyN(dst Writer, src Reader, n int64) (written int64, err error) {
+ written, err = Copy(dst, LimitReader(src, n))
+ if written == n {
+ return n, nil
+ }
+ if written < n && err == nil {
+ // src stopped early; must have been EOF.
+ err = EOF
+ }
+ return
+}
+
+// Copy copies from src to dst until either EOF is reached
+// on src or an error occurs. It returns the number of bytes
+// copied and the first error encountered while copying, if any.
+//
+// A successful Copy returns err == nil, not err == EOF.
+// Because Copy is defined to read from src until EOF, it does
+// not treat an EOF from Read as an error to be reported.
+//
+// If src implements [WriterTo],
+// the copy is implemented by calling src.WriteTo(dst).
+// Otherwise, if dst implements [ReaderFrom],
+// the copy is implemented by calling dst.ReadFrom(src).
+func Copy(dst Writer, src Reader) (written int64, err error) {
+ return copyBuffer(dst, src, nil)
+}
+
+// CopyBuffer is identical to Copy except that it stages through the
+// provided buffer (if one is required) rather than allocating a
+// temporary one. If buf is nil, one is allocated; otherwise if it has
+// zero length, CopyBuffer panics.
+//
+// If either src implements [WriterTo] or dst implements [ReaderFrom],
+// buf will not be used to perform the copy.
+func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
+ if buf != nil && len(buf) == 0 {
+ panic("empty buffer in CopyBuffer")
+ }
+ return copyBuffer(dst, src, buf)
+}
+
+// copyBuffer is the actual implementation of Copy and CopyBuffer.
+// if buf is nil, one is allocated.
+func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
+ // If the reader has a WriteTo method, use it to do the copy.
+ // Avoids an allocation and a copy.
+ if wt, ok := src.(WriterTo); ok {
+ return wt.WriteTo(dst)
+ }
+ // Similarly, if the writer has a ReadFrom method, use it to do the copy.
+ if rt, ok := dst.(ReaderFrom); ok {
+ return rt.ReadFrom(src)
+ }
+ if buf == nil {
+ size := 32 * 1024
+ if l, ok := src.(*LimitedReader); ok && int64(size) > l.N {
+ if l.N < 1 {
+ size = 1
+ } else {
+ size = int(l.N)
+ }
+ }
+ buf = make([]byte, size)
+ }
+ for {
+ nr, er := src.Read(buf)
+ if nr > 0 {
+ nw, ew := dst.Write(buf[0:nr])
+ if nw < 0 || nr < nw {
+ nw = 0
+ if ew == nil {
+ ew = errInvalidWrite
+ }
+ }
+ written += int64(nw)
+ if ew != nil {
+ err = ew
+ break
+ }
+ if nr != nw {
+ err = ErrShortWrite
+ break
+ }
+ }
+ if er != nil {
+ if er != EOF {
+ err = er
+ }
+ break
+ }
+ }
+ return written, err
+}
+
+// LimitReader returns a Reader that reads from r
+// but stops with EOF after n bytes.
+// The underlying implementation is a *LimitedReader.
+func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
+
+// A LimitedReader reads from R but limits the amount of
+// data returned to just N bytes. Each call to Read
+// updates N to reflect the new amount remaining.
+// Read returns EOF when N <= 0 or when the underlying R returns EOF.
+type LimitedReader struct {
+ R Reader // underlying reader
+ N int64 // max bytes remaining
+}
+
+func (l *LimitedReader) Read(p []byte) (n int, err error) {
+ if l.N <= 0 {
+ return 0, EOF
+ }
+ if int64(len(p)) > l.N {
+ p = p[0:l.N]
+ }
+ n, err = l.R.Read(p)
+ l.N -= int64(n)
+ return
+}
+
+// NewSectionReader returns a [SectionReader] that reads from r
+// starting at offset off and stops with EOF after n bytes.
+func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader {
+ var remaining int64
+ const maxint64 = 1<<63 - 1
+ if off <= maxint64-n {
+ remaining = n + off
+ } else {
+ // Overflow, with no way to return error.
+ // Assume we can read up to an offset of 1<<63 - 1.
+ remaining = maxint64
+ }
+ return &SectionReader{r, off, off, remaining, n}
+}
+
+// SectionReader implements Read, Seek, and ReadAt on a section
+// of an underlying [ReaderAt].
+type SectionReader struct {
+ r ReaderAt // constant after creation
+ base int64 // constant after creation
+ off int64
+ limit int64 // constant after creation
+ n int64 // constant after creation
+}
+
+func (s *SectionReader) Read(p []byte) (n int, err error) {
+ if s.off >= s.limit {
+ return 0, EOF
+ }
+ if max := s.limit - s.off; int64(len(p)) > max {
+ p = p[0:max]
+ }
+ n, err = s.r.ReadAt(p, s.off)
+ s.off += int64(n)
+ return
+}
+
+var errWhence = errors.New("Seek: invalid whence")
+var errOffset = errors.New("Seek: invalid offset")
+
+func (s *SectionReader) Seek(offset int64, whence int) (int64, error) {
+ switch whence {
+ default:
+ return 0, errWhence
+ case SeekStart:
+ offset += s.base
+ case SeekCurrent:
+ offset += s.off
+ case SeekEnd:
+ offset += s.limit
+ }
+ if offset < s.base {
+ return 0, errOffset
+ }
+ s.off = offset
+ return offset - s.base, nil
+}
+
+func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) {
+ if off < 0 || off >= s.Size() {
+ return 0, EOF
+ }
+ off += s.base
+ if max := s.limit - off; int64(len(p)) > max {
+ p = p[0:max]
+ n, err = s.r.ReadAt(p, off)
+ if err == nil {
+ err = EOF
+ }
+ return n, err
+ }
+ return s.r.ReadAt(p, off)
+}
+
+// Size returns the size of the section in bytes.
+func (s *SectionReader) Size() int64 { return s.limit - s.base }
+
+// Outer returns the underlying [ReaderAt] and offsets for the section.
+//
+// The returned values are the same that were passed to [NewSectionReader]
+// when the [SectionReader] was created.
+func (s *SectionReader) Outer() (r ReaderAt, off int64, n int64) {
+ return s.r, s.base, s.n
+}
+
+// An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.
+type OffsetWriter struct {
+ w WriterAt
+ base int64 // the original offset
+ off int64 // the current offset
+}
+
+// NewOffsetWriter returns an [OffsetWriter] that writes to w
+// starting at offset off.
+func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter {
+ return &OffsetWriter{w, off, off}
+}
+
+func (o *OffsetWriter) Write(p []byte) (n int, err error) {
+ n, err = o.w.WriteAt(p, o.off)
+ o.off += int64(n)
+ return
+}
+
+func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error) {
+ if off < 0 {
+ return 0, errOffset
+ }
+
+ off += o.base
+ return o.w.WriteAt(p, off)
+}
+
+func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error) {
+ switch whence {
+ default:
+ return 0, errWhence
+ case SeekStart:
+ offset += o.base
+ case SeekCurrent:
+ offset += o.off
+ }
+ if offset < o.base {
+ return 0, errOffset
+ }
+ o.off = offset
+ return offset - o.base, nil
+}
+
+// TeeReader returns a [Reader] that writes to w what it reads from r.
+// All reads from r performed through it are matched with
+// corresponding writes to w. There is no internal buffering -
+// the write must complete before the read completes.
+// Any error encountered while writing is reported as a read error.
+func TeeReader(r Reader, w Writer) Reader {
+ return &teeReader{r, w}
+}
+
+type teeReader struct {
+ r Reader
+ w Writer
+}
+
+func (t *teeReader) Read(p []byte) (n int, err error) {
+ n, err = t.r.Read(p)
+ if n > 0 {
+ if n, err := t.w.Write(p[:n]); err != nil {
+ return n, err
+ }
+ }
+ return
+}
+
+// Discard is a [Writer] on which all Write calls succeed
+// without doing anything.
+var Discard Writer = discard{}
+
+type discard struct{}
+
+// discard implements ReaderFrom as an optimization so Copy to
+// io.Discard can avoid doing unnecessary work.
+var _ ReaderFrom = discard{}
+
+func (discard) Write(p []byte) (int, error) {
+ return len(p), nil
+}
+
+func (discard) WriteString(s string) (int, error) {
+ return len(s), nil
+}
+
+var blackHolePool = sync.Pool{
+ New: func() any {
+ b := make([]byte, 8192)
+ return &b
+ },
+}
+
+func (discard) ReadFrom(r Reader) (n int64, err error) {
+ bufp := blackHolePool.Get().(*[]byte)
+ readSize := 0
+ for {
+ readSize, err = r.Read(*bufp)
+ n += int64(readSize)
+ if err != nil {
+ blackHolePool.Put(bufp)
+ if err == EOF {
+ return n, nil
+ }
+ return
+ }
+ }
+}
+
+// NopCloser returns a [ReadCloser] with a no-op Close method wrapping
+// the provided [Reader] r.
+// If r implements [WriterTo], the returned [ReadCloser] will implement [WriterTo]
+// by forwarding calls to r.
+func NopCloser(r Reader) ReadCloser {
+ if _, ok := r.(WriterTo); ok {
+ return nopCloserWriterTo{r}
+ }
+ return nopCloser{r}
+}
+
+type nopCloser struct {
+ Reader
+}
+
+func (nopCloser) Close() error { return nil }
+
+type nopCloserWriterTo struct {
+ Reader
+}
+
+func (nopCloserWriterTo) Close() error { return nil }
+
+func (c nopCloserWriterTo) WriteTo(w Writer) (n int64, err error) {
+ return c.Reader.(WriterTo).WriteTo(w)
+}
+
+// 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.
+func ReadAll(r Reader) ([]byte, error) {
+ b := make([]byte, 0, 512)
+ for {
+ n, err := r.Read(b[len(b):cap(b)])
+ b = b[:len(b)+n]
+ if err != nil {
+ if err == EOF {
+ err = nil
+ }
+ return b, err
+ }
+
+ if len(b) == cap(b) {
+ // Add more capacity (let append pick how much).
+ b = append(b, 0)[:len(b)]
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/io_test.go b/platform/dbops/binaries/go/go/src/io/io_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..9491ffae614c61603a1c914aa1ec15123a59b007
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/io_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 io_test
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ . "io"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+)
+
+// A version of bytes.Buffer without ReadFrom and WriteTo
+type Buffer struct {
+ bytes.Buffer
+ ReaderFrom // conflicts with and hides bytes.Buffer's ReaderFrom.
+ WriterTo // conflicts with and hides bytes.Buffer's WriterTo.
+}
+
+// Simple tests, primarily to verify the ReadFrom and WriteTo callouts inside Copy, CopyBuffer and CopyN.
+
+func TestCopy(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ Copy(wb, rb)
+ if wb.String() != "hello, world." {
+ t.Errorf("Copy did not work properly")
+ }
+}
+
+func TestCopyNegative(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(Buffer)
+ rb.WriteString("hello")
+ Copy(wb, &LimitedReader{R: rb, N: -1})
+ if wb.String() != "" {
+ t.Errorf("Copy on LimitedReader with N<0 copied data")
+ }
+
+ CopyN(wb, rb, -1)
+ if wb.String() != "" {
+ t.Errorf("CopyN with N<0 copied data")
+ }
+}
+
+func TestCopyBuffer(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ CopyBuffer(wb, rb, make([]byte, 1)) // Tiny buffer to keep it honest.
+ if wb.String() != "hello, world." {
+ t.Errorf("CopyBuffer did not work properly")
+ }
+}
+
+func TestCopyBufferNil(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ CopyBuffer(wb, rb, nil) // Should allocate a buffer.
+ if wb.String() != "hello, world." {
+ t.Errorf("CopyBuffer did not work properly")
+ }
+}
+
+func TestCopyReadFrom(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(bytes.Buffer) // implements ReadFrom.
+ rb.WriteString("hello, world.")
+ Copy(wb, rb)
+ if wb.String() != "hello, world." {
+ t.Errorf("Copy did not work properly")
+ }
+}
+
+func TestCopyWriteTo(t *testing.T) {
+ rb := new(bytes.Buffer) // implements WriteTo.
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ Copy(wb, rb)
+ if wb.String() != "hello, world." {
+ t.Errorf("Copy did not work properly")
+ }
+}
+
+// Version of bytes.Buffer that checks whether WriteTo was called or not
+type writeToChecker struct {
+ bytes.Buffer
+ writeToCalled bool
+}
+
+func (wt *writeToChecker) WriteTo(w Writer) (int64, error) {
+ wt.writeToCalled = true
+ return wt.Buffer.WriteTo(w)
+}
+
+// It's preferable to choose WriterTo over ReaderFrom, since a WriterTo can issue one large write,
+// while the ReaderFrom must read until EOF, potentially allocating when running out of buffer.
+// Make sure that we choose WriterTo when both are implemented.
+func TestCopyPriority(t *testing.T) {
+ rb := new(writeToChecker)
+ wb := new(bytes.Buffer)
+ rb.WriteString("hello, world.")
+ Copy(wb, rb)
+ if wb.String() != "hello, world." {
+ t.Errorf("Copy did not work properly")
+ } else if !rb.writeToCalled {
+ t.Errorf("WriteTo was not prioritized over ReadFrom")
+ }
+}
+
+type zeroErrReader struct {
+ err error
+}
+
+func (r zeroErrReader) Read(p []byte) (int, error) {
+ return copy(p, []byte{0}), r.err
+}
+
+type errWriter struct {
+ err error
+}
+
+func (w errWriter) Write([]byte) (int, error) {
+ return 0, w.err
+}
+
+// In case a Read results in an error with non-zero bytes read, and
+// the subsequent Write also results in an error, the error from Write
+// is returned, as it is the one that prevented progressing further.
+func TestCopyReadErrWriteErr(t *testing.T) {
+ er, ew := errors.New("readError"), errors.New("writeError")
+ r, w := zeroErrReader{err: er}, errWriter{err: ew}
+ n, err := Copy(w, r)
+ if n != 0 || err != ew {
+ t.Errorf("Copy(zeroErrReader, errWriter) = %d, %v; want 0, writeError", n, err)
+ }
+}
+
+func TestCopyN(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ CopyN(wb, rb, 5)
+ if wb.String() != "hello" {
+ t.Errorf("CopyN did not work properly")
+ }
+}
+
+func TestCopyNReadFrom(t *testing.T) {
+ rb := new(Buffer)
+ wb := new(bytes.Buffer) // implements ReadFrom.
+ rb.WriteString("hello")
+ CopyN(wb, rb, 5)
+ if wb.String() != "hello" {
+ t.Errorf("CopyN did not work properly")
+ }
+}
+
+func TestCopyNWriteTo(t *testing.T) {
+ rb := new(bytes.Buffer) // implements WriteTo.
+ wb := new(Buffer)
+ rb.WriteString("hello, world.")
+ CopyN(wb, rb, 5)
+ if wb.String() != "hello" {
+ t.Errorf("CopyN did not work properly")
+ }
+}
+
+func BenchmarkCopyNSmall(b *testing.B) {
+ bs := bytes.Repeat([]byte{0}, 512+1)
+ rd := bytes.NewReader(bs)
+ buf := new(Buffer)
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ CopyN(buf, rd, 512)
+ rd.Reset(bs)
+ }
+}
+
+func BenchmarkCopyNLarge(b *testing.B) {
+ bs := bytes.Repeat([]byte{0}, (32*1024)+1)
+ rd := bytes.NewReader(bs)
+ buf := new(Buffer)
+ b.ResetTimer()
+
+ for i := 0; i < b.N; i++ {
+ CopyN(buf, rd, 32*1024)
+ rd.Reset(bs)
+ }
+}
+
+type noReadFrom struct {
+ w Writer
+}
+
+func (w *noReadFrom) Write(p []byte) (n int, err error) {
+ return w.w.Write(p)
+}
+
+type wantedAndErrReader struct{}
+
+func (wantedAndErrReader) Read(p []byte) (int, error) {
+ return len(p), errors.New("wantedAndErrReader error")
+}
+
+func TestCopyNEOF(t *testing.T) {
+ // Test that EOF behavior is the same regardless of whether
+ // argument to CopyN has ReadFrom.
+
+ b := new(bytes.Buffer)
+
+ n, err := CopyN(&noReadFrom{b}, strings.NewReader("foo"), 3)
+ if n != 3 || err != nil {
+ t.Errorf("CopyN(noReadFrom, foo, 3) = %d, %v; want 3, nil", n, err)
+ }
+
+ n, err = CopyN(&noReadFrom{b}, strings.NewReader("foo"), 4)
+ if n != 3 || err != EOF {
+ t.Errorf("CopyN(noReadFrom, foo, 4) = %d, %v; want 3, EOF", n, err)
+ }
+
+ n, err = CopyN(b, strings.NewReader("foo"), 3) // b has read from
+ if n != 3 || err != nil {
+ t.Errorf("CopyN(bytes.Buffer, foo, 3) = %d, %v; want 3, nil", n, err)
+ }
+
+ n, err = CopyN(b, strings.NewReader("foo"), 4) // b has read from
+ if n != 3 || err != EOF {
+ t.Errorf("CopyN(bytes.Buffer, foo, 4) = %d, %v; want 3, EOF", n, err)
+ }
+
+ n, err = CopyN(b, wantedAndErrReader{}, 5)
+ if n != 5 || err != nil {
+ t.Errorf("CopyN(bytes.Buffer, wantedAndErrReader, 5) = %d, %v; want 5, nil", n, err)
+ }
+
+ n, err = CopyN(&noReadFrom{b}, wantedAndErrReader{}, 5)
+ if n != 5 || err != nil {
+ t.Errorf("CopyN(noReadFrom, wantedAndErrReader, 5) = %d, %v; want 5, nil", n, err)
+ }
+}
+
+func TestReadAtLeast(t *testing.T) {
+ var rb bytes.Buffer
+ testReadAtLeast(t, &rb)
+}
+
+// A version of bytes.Buffer that returns n > 0, err on Read
+// when the input is exhausted.
+type dataAndErrorBuffer struct {
+ err error
+ bytes.Buffer
+}
+
+func (r *dataAndErrorBuffer) Read(p []byte) (n int, err error) {
+ n, err = r.Buffer.Read(p)
+ if n > 0 && r.Buffer.Len() == 0 && err == nil {
+ err = r.err
+ }
+ return
+}
+
+func TestReadAtLeastWithDataAndEOF(t *testing.T) {
+ var rb dataAndErrorBuffer
+ rb.err = EOF
+ testReadAtLeast(t, &rb)
+}
+
+func TestReadAtLeastWithDataAndError(t *testing.T) {
+ var rb dataAndErrorBuffer
+ rb.err = fmt.Errorf("fake error")
+ testReadAtLeast(t, &rb)
+}
+
+func testReadAtLeast(t *testing.T, rb ReadWriter) {
+ rb.Write([]byte("0123"))
+ buf := make([]byte, 2)
+ n, err := ReadAtLeast(rb, buf, 2)
+ if err != nil {
+ t.Error(err)
+ }
+ if n != 2 {
+ t.Errorf("expected to have read 2 bytes, got %v", n)
+ }
+ n, err = ReadAtLeast(rb, buf, 4)
+ if err != ErrShortBuffer {
+ t.Errorf("expected ErrShortBuffer got %v", err)
+ }
+ if n != 0 {
+ t.Errorf("expected to have read 0 bytes, got %v", n)
+ }
+ n, err = ReadAtLeast(rb, buf, 1)
+ if err != nil {
+ t.Error(err)
+ }
+ if n != 2 {
+ t.Errorf("expected to have read 2 bytes, got %v", n)
+ }
+ n, err = ReadAtLeast(rb, buf, 2)
+ if err != EOF {
+ t.Errorf("expected EOF, got %v", err)
+ }
+ if n != 0 {
+ t.Errorf("expected to have read 0 bytes, got %v", n)
+ }
+ rb.Write([]byte("4"))
+ n, err = ReadAtLeast(rb, buf, 2)
+ want := ErrUnexpectedEOF
+ if rb, ok := rb.(*dataAndErrorBuffer); ok && rb.err != EOF {
+ want = rb.err
+ }
+ if err != want {
+ t.Errorf("expected %v, got %v", want, err)
+ }
+ if n != 1 {
+ t.Errorf("expected to have read 1 bytes, got %v", n)
+ }
+}
+
+func TestTeeReader(t *testing.T) {
+ src := []byte("hello, world")
+ dst := make([]byte, len(src))
+ rb := bytes.NewBuffer(src)
+ wb := new(bytes.Buffer)
+ r := TeeReader(rb, wb)
+ if n, err := ReadFull(r, dst); err != nil || n != len(src) {
+ t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src))
+ }
+ if !bytes.Equal(dst, src) {
+ t.Errorf("bytes read = %q want %q", dst, src)
+ }
+ if !bytes.Equal(wb.Bytes(), src) {
+ t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
+ }
+ if n, err := r.Read(dst); n != 0 || err != EOF {
+ t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err)
+ }
+ rb = bytes.NewBuffer(src)
+ pr, pw := Pipe()
+ pr.Close()
+ r = TeeReader(rb, pw)
+ if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe {
+ t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err)
+ }
+}
+
+func TestSectionReader_ReadAt(t *testing.T) {
+ dat := "a long sample data, 1234567890"
+ tests := []struct {
+ data string
+ off int
+ n int
+ bufLen int
+ at int
+ exp string
+ err error
+ }{
+ {data: "", off: 0, n: 10, bufLen: 2, at: 0, exp: "", err: EOF},
+ {data: dat, off: 0, n: len(dat), bufLen: 0, at: 0, exp: "", err: nil},
+ {data: dat, off: len(dat), n: 1, bufLen: 1, at: 0, exp: "", err: EOF},
+ {data: dat, off: 0, n: len(dat) + 2, bufLen: len(dat), at: 0, exp: dat, err: nil},
+ {data: dat, off: 0, n: len(dat), bufLen: len(dat) / 2, at: 0, exp: dat[:len(dat)/2], err: nil},
+ {data: dat, off: 0, n: len(dat), bufLen: len(dat), at: 0, exp: dat, err: nil},
+ {data: dat, off: 0, n: len(dat), bufLen: len(dat) / 2, at: 2, exp: dat[2 : 2+len(dat)/2], err: nil},
+ {data: dat, off: 3, n: len(dat), bufLen: len(dat) / 2, at: 2, exp: dat[5 : 5+len(dat)/2], err: nil},
+ {data: dat, off: 3, n: len(dat) / 2, bufLen: len(dat)/2 - 2, at: 2, exp: dat[5 : 5+len(dat)/2-2], err: nil},
+ {data: dat, off: 3, n: len(dat) / 2, bufLen: len(dat)/2 + 2, at: 2, exp: dat[5 : 5+len(dat)/2-2], err: EOF},
+ {data: dat, off: 0, n: 0, bufLen: 0, at: -1, exp: "", err: EOF},
+ {data: dat, off: 0, n: 0, bufLen: 0, at: 1, exp: "", err: EOF},
+ }
+ for i, tt := range tests {
+ r := strings.NewReader(tt.data)
+ s := NewSectionReader(r, int64(tt.off), int64(tt.n))
+ buf := make([]byte, tt.bufLen)
+ if n, err := s.ReadAt(buf, int64(tt.at)); n != len(tt.exp) || string(buf[:n]) != tt.exp || err != tt.err {
+ t.Fatalf("%d: ReadAt(%d) = %q, %v; expected %q, %v", i, tt.at, buf[:n], err, tt.exp, tt.err)
+ }
+ if _r, off, n := s.Outer(); _r != r || off != int64(tt.off) || n != int64(tt.n) {
+ t.Fatalf("%d: Outer() = %v, %d, %d; expected %v, %d, %d", i, _r, off, n, r, tt.off, tt.n)
+ }
+ }
+}
+
+func TestSectionReader_Seek(t *testing.T) {
+ // Verifies that NewSectionReader's Seeker behaves like bytes.NewReader (which is like strings.NewReader)
+ br := bytes.NewReader([]byte("foo"))
+ sr := NewSectionReader(br, 0, int64(len("foo")))
+
+ for _, whence := range []int{SeekStart, SeekCurrent, SeekEnd} {
+ for offset := int64(-3); offset <= 4; offset++ {
+ brOff, brErr := br.Seek(offset, whence)
+ srOff, srErr := sr.Seek(offset, whence)
+ if (brErr != nil) != (srErr != nil) || brOff != srOff {
+ t.Errorf("For whence %d, offset %d: bytes.Reader.Seek = (%v, %v) != SectionReader.Seek = (%v, %v)",
+ whence, offset, brOff, brErr, srErr, srOff)
+ }
+ }
+ }
+
+ // And verify we can just seek past the end and get an EOF
+ got, err := sr.Seek(100, SeekStart)
+ if err != nil || got != 100 {
+ t.Errorf("Seek = %v, %v; want 100, nil", got, err)
+ }
+
+ n, err := sr.Read(make([]byte, 10))
+ if n != 0 || err != EOF {
+ t.Errorf("Read = %v, %v; want 0, EOF", n, err)
+ }
+}
+
+func TestSectionReader_Size(t *testing.T) {
+ tests := []struct {
+ data string
+ want int64
+ }{
+ {"a long sample data, 1234567890", 30},
+ {"", 0},
+ }
+
+ for _, tt := range tests {
+ r := strings.NewReader(tt.data)
+ sr := NewSectionReader(r, 0, int64(len(tt.data)))
+ if got := sr.Size(); got != tt.want {
+ t.Errorf("Size = %v; want %v", got, tt.want)
+ }
+ }
+}
+
+func TestSectionReader_Max(t *testing.T) {
+ r := strings.NewReader("abcdef")
+ const maxint64 = 1<<63 - 1
+ sr := NewSectionReader(r, 3, maxint64)
+ n, err := sr.Read(make([]byte, 3))
+ if n != 3 || err != nil {
+ t.Errorf("Read = %v %v, want 3, nil", n, err)
+ }
+ n, err = sr.Read(make([]byte, 3))
+ if n != 0 || err != EOF {
+ t.Errorf("Read = %v, %v, want 0, EOF", n, err)
+ }
+ if _r, off, n := sr.Outer(); _r != r || off != 3 || n != maxint64 {
+ t.Fatalf("Outer = %v, %d, %d; expected %v, %d, %d", _r, off, n, r, 3, int64(maxint64))
+ }
+}
+
+// largeWriter returns an invalid count that is larger than the number
+// of bytes provided (issue 39978).
+type largeWriter struct {
+ err error
+}
+
+func (w largeWriter) Write(p []byte) (int, error) {
+ return len(p) + 1, w.err
+}
+
+func TestCopyLargeWriter(t *testing.T) {
+ want := ErrInvalidWrite
+ rb := new(Buffer)
+ wb := largeWriter{}
+ rb.WriteString("hello, world.")
+ if _, err := Copy(wb, rb); err != want {
+ t.Errorf("Copy error: got %v, want %v", err, want)
+ }
+
+ want = errors.New("largeWriterError")
+ rb = new(Buffer)
+ wb = largeWriter{err: want}
+ rb.WriteString("hello, world.")
+ if _, err := Copy(wb, rb); err != want {
+ t.Errorf("Copy error: got %v, want %v", err, want)
+ }
+}
+
+func TestNopCloserWriterToForwarding(t *testing.T) {
+ for _, tc := range [...]struct {
+ Name string
+ r Reader
+ }{
+ {"not a WriterTo", Reader(nil)},
+ {"a WriterTo", struct {
+ Reader
+ WriterTo
+ }{}},
+ } {
+ nc := NopCloser(tc.r)
+
+ _, expected := tc.r.(WriterTo)
+ _, got := nc.(WriterTo)
+ if expected != got {
+ t.Errorf("NopCloser incorrectly forwards WriterTo for %s, got %t want %t", tc.Name, got, expected)
+ }
+ }
+}
+
+func TestOffsetWriter_Seek(t *testing.T) {
+ tmpfilename := "TestOffsetWriter_Seek"
+ tmpfile, err := os.CreateTemp(t.TempDir(), tmpfilename)
+ if err != nil || tmpfile == nil {
+ t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err)
+ }
+ defer tmpfile.Close()
+ w := NewOffsetWriter(tmpfile, 0)
+
+ // Should throw error errWhence if whence is not valid
+ t.Run("errWhence", func(t *testing.T) {
+ for _, whence := range []int{-3, -2, -1, 3, 4, 5} {
+ var offset int64 = 0
+ gotOff, gotErr := w.Seek(offset, whence)
+ if gotOff != 0 || gotErr != ErrWhence {
+ t.Errorf("For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, %v)",
+ whence, offset, gotOff, gotErr, 0, ErrWhence)
+ }
+ }
+ })
+
+ // Should throw error errOffset if offset is negative
+ t.Run("errOffset", func(t *testing.T) {
+ for _, whence := range []int{SeekStart, SeekCurrent} {
+ for offset := int64(-3); offset < 0; offset++ {
+ gotOff, gotErr := w.Seek(offset, whence)
+ if gotOff != 0 || gotErr != ErrOffset {
+ t.Errorf("For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, %v)",
+ whence, offset, gotOff, gotErr, 0, ErrOffset)
+ }
+ }
+ }
+ })
+
+ // Normal tests
+ t.Run("normal", func(t *testing.T) {
+ tests := []struct {
+ offset int64
+ whence int
+ returnOff int64
+ }{
+ // keep in order
+ {whence: SeekStart, offset: 1, returnOff: 1},
+ {whence: SeekStart, offset: 2, returnOff: 2},
+ {whence: SeekStart, offset: 3, returnOff: 3},
+ {whence: SeekCurrent, offset: 1, returnOff: 4},
+ {whence: SeekCurrent, offset: 2, returnOff: 6},
+ {whence: SeekCurrent, offset: 3, returnOff: 9},
+ }
+ for idx, tt := range tests {
+ gotOff, gotErr := w.Seek(tt.offset, tt.whence)
+ if gotOff != tt.returnOff || gotErr != nil {
+ t.Errorf("%d:: For whence %d, offset %d, OffsetWriter.Seek got: (%d, %v), want: (%d, )",
+ idx+1, tt.whence, tt.offset, gotOff, gotErr, tt.returnOff)
+ }
+ }
+ })
+}
+
+func TestOffsetWriter_WriteAt(t *testing.T) {
+ const content = "0123456789ABCDEF"
+ contentSize := int64(len(content))
+ tmpdir, err := os.MkdirTemp(t.TempDir(), "TestOffsetWriter_WriteAt")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ work := func(off, at int64) {
+ position := fmt.Sprintf("off_%d_at_%d", off, at)
+ tmpfile, err := os.CreateTemp(tmpdir, position)
+ if err != nil || tmpfile == nil {
+ t.Fatalf("CreateTemp(%s) failed: %v", position, err)
+ }
+ defer tmpfile.Close()
+
+ var writeN int64
+ var wg sync.WaitGroup
+ // Concurrent writes, one byte at a time
+ for step, value := range []byte(content) {
+ wg.Add(1)
+ go func(wg *sync.WaitGroup, tmpfile *os.File, value byte, off, at int64, step int) {
+ defer wg.Done()
+
+ w := NewOffsetWriter(tmpfile, off)
+ n, e := w.WriteAt([]byte{value}, at+int64(step))
+ if e != nil {
+ t.Errorf("WriteAt failed. off: %d, at: %d, step: %d\n error: %v", off, at, step, e)
+ }
+ atomic.AddInt64(&writeN, int64(n))
+ }(&wg, tmpfile, value, off, at, step)
+ }
+ wg.Wait()
+
+ // Read one more byte to reach EOF
+ buf := make([]byte, contentSize+1)
+ readN, err := tmpfile.ReadAt(buf, off+at)
+ if err != EOF {
+ t.Fatalf("ReadAt failed: %v", err)
+ }
+ readContent := string(buf[:contentSize])
+ if writeN != int64(readN) || writeN != contentSize || readContent != content {
+ t.Fatalf("%s:: WriteAt(%s, %d) error. \ngot n: %v, content: %s \nexpected n: %v, content: %v",
+ position, content, at, readN, readContent, contentSize, content)
+ }
+ }
+ for off := int64(0); off < 2; off++ {
+ for at := int64(0); at < 2; at++ {
+ work(off, at)
+ }
+ }
+}
+
+func TestWriteAt_PositionPriorToBase(t *testing.T) {
+ tmpdir := t.TempDir()
+ tmpfilename := "TestOffsetWriter_WriteAt"
+ tmpfile, err := os.CreateTemp(tmpdir, tmpfilename)
+ if err != nil {
+ t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err)
+ }
+ defer tmpfile.Close()
+
+ // start writing position in OffsetWriter
+ offset := int64(10)
+ // position we want to write to the tmpfile
+ at := int64(-1)
+ w := NewOffsetWriter(tmpfile, offset)
+ _, e := w.WriteAt([]byte("hello"), at)
+ if e == nil {
+ t.Errorf("error expected to be not nil")
+ }
+}
+
+func TestOffsetWriter_Write(t *testing.T) {
+ const content = "0123456789ABCDEF"
+ contentSize := len(content)
+ tmpdir := t.TempDir()
+
+ makeOffsetWriter := func(name string) (*OffsetWriter, *os.File) {
+ tmpfilename := "TestOffsetWriter_Write_" + name
+ tmpfile, err := os.CreateTemp(tmpdir, tmpfilename)
+ if err != nil || tmpfile == nil {
+ t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err)
+ }
+ return NewOffsetWriter(tmpfile, 0), tmpfile
+ }
+ checkContent := func(name string, f *os.File) {
+ // Read one more byte to reach EOF
+ buf := make([]byte, contentSize+1)
+ readN, err := f.ReadAt(buf, 0)
+ if err != EOF {
+ t.Fatalf("ReadAt failed, err: %v", err)
+ }
+ readContent := string(buf[:contentSize])
+ if readN != contentSize || readContent != content {
+ t.Fatalf("%s error. \ngot n: %v, content: %s \nexpected n: %v, content: %v",
+ name, readN, readContent, contentSize, content)
+ }
+ }
+
+ var name string
+ name = "Write"
+ t.Run(name, func(t *testing.T) {
+ // Write directly (off: 0, at: 0)
+ // Write content to file
+ w, f := makeOffsetWriter(name)
+ defer f.Close()
+ for _, value := range []byte(content) {
+ n, err := w.Write([]byte{value})
+ if err != nil {
+ t.Fatalf("Write failed, n: %d, err: %v", n, err)
+ }
+ }
+ checkContent(name, f)
+
+ // Copy -> Write
+ // Copy file f to file f2
+ name = "Copy"
+ w2, f2 := makeOffsetWriter(name)
+ defer f2.Close()
+ Copy(w2, f)
+ checkContent(name, f2)
+ })
+
+ // Copy -> WriteTo -> Write
+ // Note: strings.Reader implements the io.WriterTo interface.
+ name = "Write_Of_Copy_WriteTo"
+ t.Run(name, func(t *testing.T) {
+ w, f := makeOffsetWriter(name)
+ defer f.Close()
+ Copy(w, strings.NewReader(content))
+ checkContent(name, f)
+ })
+}
diff --git a/platform/dbops/binaries/go/go/src/io/multi.go b/platform/dbops/binaries/go/go/src/io/multi.go
new file mode 100644
index 0000000000000000000000000000000000000000..07a9afffda38272d264a47af01afb37b827236c7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/multi.go
@@ -0,0 +1,137 @@
+// 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 io
+
+type eofReader struct{}
+
+func (eofReader) Read([]byte) (int, error) {
+ return 0, EOF
+}
+
+type multiReader struct {
+ readers []Reader
+}
+
+func (mr *multiReader) Read(p []byte) (n int, err error) {
+ for len(mr.readers) > 0 {
+ // Optimization to flatten nested multiReaders (Issue 13558).
+ if len(mr.readers) == 1 {
+ if r, ok := mr.readers[0].(*multiReader); ok {
+ mr.readers = r.readers
+ continue
+ }
+ }
+ n, err = mr.readers[0].Read(p)
+ if err == EOF {
+ // Use eofReader instead of nil to avoid nil panic
+ // after performing flatten (Issue 18232).
+ mr.readers[0] = eofReader{} // permit earlier GC
+ mr.readers = mr.readers[1:]
+ }
+ if n > 0 || err != EOF {
+ if err == EOF && len(mr.readers) > 0 {
+ // Don't return EOF yet. More readers remain.
+ err = nil
+ }
+ return
+ }
+ }
+ return 0, EOF
+}
+
+func (mr *multiReader) WriteTo(w Writer) (sum int64, err error) {
+ return mr.writeToWithBuffer(w, make([]byte, 1024*32))
+}
+
+func (mr *multiReader) writeToWithBuffer(w Writer, buf []byte) (sum int64, err error) {
+ for i, r := range mr.readers {
+ var n int64
+ if subMr, ok := r.(*multiReader); ok { // reuse buffer with nested multiReaders
+ n, err = subMr.writeToWithBuffer(w, buf)
+ } else {
+ n, err = copyBuffer(w, r, buf)
+ }
+ sum += n
+ if err != nil {
+ mr.readers = mr.readers[i:] // permit resume / retry after error
+ return sum, err
+ }
+ mr.readers[i] = nil // permit early GC
+ }
+ mr.readers = nil
+ return sum, nil
+}
+
+var _ WriterTo = (*multiReader)(nil)
+
+// MultiReader returns a Reader that's the logical concatenation of
+// the provided input readers. They're read sequentially. Once all
+// inputs have returned EOF, Read will return EOF. If any of the readers
+// return a non-nil, non-EOF error, Read will return that error.
+func MultiReader(readers ...Reader) Reader {
+ r := make([]Reader, len(readers))
+ copy(r, readers)
+ return &multiReader{r}
+}
+
+type multiWriter struct {
+ writers []Writer
+}
+
+func (t *multiWriter) Write(p []byte) (n int, err error) {
+ for _, w := range t.writers {
+ n, err = w.Write(p)
+ if err != nil {
+ return
+ }
+ if n != len(p) {
+ err = ErrShortWrite
+ return
+ }
+ }
+ return len(p), nil
+}
+
+var _ StringWriter = (*multiWriter)(nil)
+
+func (t *multiWriter) WriteString(s string) (n int, err error) {
+ var p []byte // lazily initialized if/when needed
+ for _, w := range t.writers {
+ if sw, ok := w.(StringWriter); ok {
+ n, err = sw.WriteString(s)
+ } else {
+ if p == nil {
+ p = []byte(s)
+ }
+ n, err = w.Write(p)
+ }
+ if err != nil {
+ return
+ }
+ if n != len(s) {
+ err = ErrShortWrite
+ return
+ }
+ }
+ return len(s), nil
+}
+
+// MultiWriter creates a writer that duplicates its writes to all the
+// provided writers, similar to the Unix tee(1) command.
+//
+// Each write is written to each listed writer, one at a time.
+// If a listed writer returns an error, that overall write operation
+// stops and returns the error; it does not continue down the list.
+func MultiWriter(writers ...Writer) Writer {
+ allWriters := make([]Writer, 0, len(writers))
+ for _, w := range writers {
+ if mw, ok := w.(*multiWriter); ok {
+ allWriters = append(allWriters, mw.writers...)
+ } else {
+ allWriters = append(allWriters, w)
+ }
+ }
+ return &multiWriter{allWriters}
+}
diff --git a/platform/dbops/binaries/go/go/src/io/multi_test.go b/platform/dbops/binaries/go/go/src/io/multi_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7a24a8afc5a419ba433791536602366b00e0158d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/multi_test.go
@@ -0,0 +1,379 @@
+// 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 io_test
+
+import (
+ "bytes"
+ "crypto/sha1"
+ "errors"
+ "fmt"
+ . "io"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestMultiReader(t *testing.T) {
+ var mr Reader
+ var buf []byte
+ nread := 0
+ withFooBar := func(tests func()) {
+ r1 := strings.NewReader("foo ")
+ r2 := strings.NewReader("")
+ r3 := strings.NewReader("bar")
+ mr = MultiReader(r1, r2, r3)
+ buf = make([]byte, 20)
+ tests()
+ }
+ expectRead := func(size int, expected string, eerr error) {
+ nread++
+ n, gerr := mr.Read(buf[0:size])
+ if n != len(expected) {
+ t.Errorf("#%d, expected %d bytes; got %d",
+ nread, len(expected), n)
+ }
+ got := string(buf[0:n])
+ if got != expected {
+ t.Errorf("#%d, expected %q; got %q",
+ nread, expected, got)
+ }
+ if gerr != eerr {
+ t.Errorf("#%d, expected error %v; got %v",
+ nread, eerr, gerr)
+ }
+ buf = buf[n:]
+ }
+ withFooBar(func() {
+ expectRead(2, "fo", nil)
+ expectRead(5, "o ", nil)
+ expectRead(5, "bar", nil)
+ expectRead(5, "", EOF)
+ })
+ withFooBar(func() {
+ expectRead(4, "foo ", nil)
+ expectRead(1, "b", nil)
+ expectRead(3, "ar", nil)
+ expectRead(1, "", EOF)
+ })
+ withFooBar(func() {
+ expectRead(5, "foo ", nil)
+ })
+}
+
+func TestMultiReaderAsWriterTo(t *testing.T) {
+ mr := MultiReader(
+ strings.NewReader("foo "),
+ MultiReader( // Tickle the buffer reusing codepath
+ strings.NewReader(""),
+ strings.NewReader("bar"),
+ ),
+ )
+ mrAsWriterTo, ok := mr.(WriterTo)
+ if !ok {
+ t.Fatalf("expected cast to WriterTo to succeed")
+ }
+ sink := &strings.Builder{}
+ n, err := mrAsWriterTo.WriteTo(sink)
+ if err != nil {
+ t.Fatalf("expected no error; got %v", err)
+ }
+ if n != 7 {
+ t.Errorf("expected read 7 bytes; got %d", n)
+ }
+ if result := sink.String(); result != "foo bar" {
+ t.Errorf(`expected "foo bar"; got %q`, result)
+ }
+}
+
+func TestMultiWriter(t *testing.T) {
+ sink := new(bytes.Buffer)
+ // Hide bytes.Buffer's WriteString method:
+ testMultiWriter(t, struct {
+ Writer
+ fmt.Stringer
+ }{sink, sink})
+}
+
+func TestMultiWriter_String(t *testing.T) {
+ testMultiWriter(t, new(bytes.Buffer))
+}
+
+// Test that a multiWriter.WriteString calls results in at most 1 allocation,
+// even if multiple targets don't support WriteString.
+func TestMultiWriter_WriteStringSingleAlloc(t *testing.T) {
+ var sink1, sink2 bytes.Buffer
+ type simpleWriter struct { // hide bytes.Buffer's WriteString
+ Writer
+ }
+ mw := MultiWriter(simpleWriter{&sink1}, simpleWriter{&sink2})
+ allocs := int(testing.AllocsPerRun(1000, func() {
+ WriteString(mw, "foo")
+ }))
+ if allocs != 1 {
+ t.Errorf("num allocations = %d; want 1", allocs)
+ }
+}
+
+type writeStringChecker struct{ called bool }
+
+func (c *writeStringChecker) WriteString(s string) (n int, err error) {
+ c.called = true
+ return len(s), nil
+}
+
+func (c *writeStringChecker) Write(p []byte) (n int, err error) {
+ return len(p), nil
+}
+
+func TestMultiWriter_StringCheckCall(t *testing.T) {
+ var c writeStringChecker
+ mw := MultiWriter(&c)
+ WriteString(mw, "foo")
+ if !c.called {
+ t.Error("did not see WriteString call to writeStringChecker")
+ }
+}
+
+func testMultiWriter(t *testing.T, sink interface {
+ Writer
+ fmt.Stringer
+}) {
+ sha1 := sha1.New()
+ mw := MultiWriter(sha1, sink)
+
+ sourceString := "My input text."
+ source := strings.NewReader(sourceString)
+ written, err := Copy(mw, source)
+
+ if written != int64(len(sourceString)) {
+ t.Errorf("short write of %d, not %d", written, len(sourceString))
+ }
+
+ if err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+
+ sha1hex := fmt.Sprintf("%x", sha1.Sum(nil))
+ if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" {
+ t.Error("incorrect sha1 value")
+ }
+
+ if sink.String() != sourceString {
+ t.Errorf("expected %q; got %q", sourceString, sink.String())
+ }
+}
+
+// writerFunc is a Writer implemented by the underlying func.
+type writerFunc func(p []byte) (int, error)
+
+func (f writerFunc) Write(p []byte) (int, error) {
+ return f(p)
+}
+
+// Test that MultiWriter properly flattens chained multiWriters.
+func TestMultiWriterSingleChainFlatten(t *testing.T) {
+ pc := make([]uintptr, 1000) // 1000 should fit the full stack
+ n := runtime.Callers(0, pc)
+ var myDepth = callDepth(pc[:n])
+ var writeDepth int // will contain the depth from which writerFunc.Writer was called
+ var w Writer = MultiWriter(writerFunc(func(p []byte) (int, error) {
+ n := runtime.Callers(1, pc)
+ writeDepth += callDepth(pc[:n])
+ return 0, nil
+ }))
+
+ mw := w
+ // chain a bunch of multiWriters
+ for i := 0; i < 100; i++ {
+ mw = MultiWriter(w)
+ }
+
+ mw = MultiWriter(w, mw, w, mw)
+ mw.Write(nil) // don't care about errors, just want to check the call-depth for Write
+
+ if writeDepth != 4*(myDepth+2) { // 2 should be multiWriter.Write and writerFunc.Write
+ t.Errorf("multiWriter did not flatten chained multiWriters: expected writeDepth %d, got %d",
+ 4*(myDepth+2), writeDepth)
+ }
+}
+
+func TestMultiWriterError(t *testing.T) {
+ f1 := writerFunc(func(p []byte) (int, error) {
+ return len(p) / 2, ErrShortWrite
+ })
+ f2 := writerFunc(func(p []byte) (int, error) {
+ t.Errorf("MultiWriter called f2.Write")
+ return len(p), nil
+ })
+ w := MultiWriter(f1, f2)
+ n, err := w.Write(make([]byte, 100))
+ if n != 50 || err != ErrShortWrite {
+ t.Errorf("Write = %d, %v, want 50, ErrShortWrite", n, err)
+ }
+}
+
+// Test that MultiReader copies the input slice and is insulated from future modification.
+func TestMultiReaderCopy(t *testing.T) {
+ slice := []Reader{strings.NewReader("hello world")}
+ r := MultiReader(slice...)
+ slice[0] = nil
+ data, err := ReadAll(r)
+ if err != nil || string(data) != "hello world" {
+ t.Errorf("ReadAll() = %q, %v, want %q, nil", data, err, "hello world")
+ }
+}
+
+// Test that MultiWriter copies the input slice and is insulated from future modification.
+func TestMultiWriterCopy(t *testing.T) {
+ var buf strings.Builder
+ slice := []Writer{&buf}
+ w := MultiWriter(slice...)
+ slice[0] = nil
+ n, err := w.Write([]byte("hello world"))
+ if err != nil || n != 11 {
+ t.Errorf("Write(`hello world`) = %d, %v, want 11, nil", n, err)
+ }
+ if buf.String() != "hello world" {
+ t.Errorf("buf.String() = %q, want %q", buf.String(), "hello world")
+ }
+}
+
+// readerFunc is a Reader implemented by the underlying func.
+type readerFunc func(p []byte) (int, error)
+
+func (f readerFunc) Read(p []byte) (int, error) {
+ return f(p)
+}
+
+// callDepth returns the logical call depth for the given PCs.
+func callDepth(callers []uintptr) (depth int) {
+ frames := runtime.CallersFrames(callers)
+ more := true
+ for more {
+ _, more = frames.Next()
+ depth++
+ }
+ return
+}
+
+// Test that MultiReader properly flattens chained multiReaders when Read is called
+func TestMultiReaderFlatten(t *testing.T) {
+ pc := make([]uintptr, 1000) // 1000 should fit the full stack
+ n := runtime.Callers(0, pc)
+ var myDepth = callDepth(pc[:n])
+ var readDepth int // will contain the depth from which fakeReader.Read was called
+ var r Reader = MultiReader(readerFunc(func(p []byte) (int, error) {
+ n := runtime.Callers(1, pc)
+ readDepth = callDepth(pc[:n])
+ return 0, errors.New("irrelevant")
+ }))
+
+ // chain a bunch of multiReaders
+ for i := 0; i < 100; i++ {
+ r = MultiReader(r)
+ }
+
+ r.Read(nil) // don't care about errors, just want to check the call-depth for Read
+
+ if readDepth != myDepth+2 { // 2 should be multiReader.Read and fakeReader.Read
+ t.Errorf("multiReader did not flatten chained multiReaders: expected readDepth %d, got %d",
+ myDepth+2, readDepth)
+ }
+}
+
+// byteAndEOFReader is a Reader which reads one byte (the underlying
+// byte) and EOF at once in its Read call.
+type byteAndEOFReader byte
+
+func (b byteAndEOFReader) Read(p []byte) (n int, err error) {
+ if len(p) == 0 {
+ // Read(0 bytes) is useless. We expect no such useless
+ // calls in this test.
+ panic("unexpected call")
+ }
+ p[0] = byte(b)
+ return 1, EOF
+}
+
+// This used to yield bytes forever; issue 16795.
+func TestMultiReaderSingleByteWithEOF(t *testing.T) {
+ got, err := ReadAll(LimitReader(MultiReader(byteAndEOFReader('a'), byteAndEOFReader('b')), 10))
+ if err != nil {
+ t.Fatal(err)
+ }
+ const want = "ab"
+ if string(got) != want {
+ t.Errorf("got %q; want %q", got, want)
+ }
+}
+
+// Test that a reader returning (n, EOF) at the end of a MultiReader
+// chain continues to return EOF on its final read, rather than
+// yielding a (0, EOF).
+func TestMultiReaderFinalEOF(t *testing.T) {
+ r := MultiReader(bytes.NewReader(nil), byteAndEOFReader('a'))
+ buf := make([]byte, 2)
+ n, err := r.Read(buf)
+ if n != 1 || err != EOF {
+ t.Errorf("got %v, %v; want 1, EOF", n, err)
+ }
+}
+
+func TestMultiReaderFreesExhaustedReaders(t *testing.T) {
+ var mr Reader
+ closed := make(chan struct{})
+ // The closure ensures that we don't have a live reference to buf1
+ // on our stack after MultiReader is inlined (Issue 18819). This
+ // is a work around for a limitation in liveness analysis.
+ func() {
+ buf1 := bytes.NewReader([]byte("foo"))
+ buf2 := bytes.NewReader([]byte("bar"))
+ mr = MultiReader(buf1, buf2)
+ runtime.SetFinalizer(buf1, func(*bytes.Reader) {
+ close(closed)
+ })
+ }()
+
+ buf := make([]byte, 4)
+ if n, err := ReadFull(mr, buf); err != nil || string(buf) != "foob" {
+ t.Fatalf(`ReadFull = %d (%q), %v; want 3, "foo", nil`, n, buf[:n], err)
+ }
+
+ runtime.GC()
+ select {
+ case <-closed:
+ case <-time.After(5 * time.Second):
+ t.Fatal("timeout waiting for collection of buf1")
+ }
+
+ if n, err := ReadFull(mr, buf[:2]); err != nil || string(buf[:2]) != "ar" {
+ t.Fatalf(`ReadFull = %d (%q), %v; want 2, "ar", nil`, n, buf[:n], err)
+ }
+}
+
+func TestInterleavedMultiReader(t *testing.T) {
+ r1 := strings.NewReader("123")
+ r2 := strings.NewReader("45678")
+
+ mr1 := MultiReader(r1, r2)
+ mr2 := MultiReader(mr1)
+
+ buf := make([]byte, 4)
+
+ // Have mr2 use mr1's []Readers.
+ // Consume r1 (and clear it for GC to handle) and consume part of r2.
+ n, err := ReadFull(mr2, buf)
+ if got := string(buf[:n]); got != "1234" || err != nil {
+ t.Errorf(`ReadFull(mr2) = (%q, %v), want ("1234", nil)`, got, err)
+ }
+
+ // Consume the rest of r2 via mr1.
+ // This should not panic even though mr2 cleared r1.
+ n, err = ReadFull(mr1, buf)
+ if got := string(buf[:n]); got != "5678" || err != nil {
+ t.Errorf(`ReadFull(mr1) = (%q, %v), want ("5678", nil)`, got, err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/io/pipe.go b/platform/dbops/binaries/go/go/src/io/pipe.go
new file mode 100644
index 0000000000000000000000000000000000000000..f34cf25e9de5bdf1a4843b39ceccb45cc4d74950
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/pipe.go
@@ -0,0 +1,202 @@
+// 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.
+
+// Pipe adapter to connect code expecting an io.Reader
+// with code expecting an io.Writer.
+
+package io
+
+import (
+ "errors"
+ "sync"
+)
+
+// onceError is an object that will only store an error once.
+type onceError struct {
+ sync.Mutex // guards following
+ err error
+}
+
+func (a *onceError) Store(err error) {
+ a.Lock()
+ defer a.Unlock()
+ if a.err != nil {
+ return
+ }
+ a.err = err
+}
+func (a *onceError) Load() error {
+ a.Lock()
+ defer a.Unlock()
+ return a.err
+}
+
+// ErrClosedPipe is the error used for read or write operations on a closed pipe.
+var ErrClosedPipe = errors.New("io: read/write on closed pipe")
+
+// A pipe is the shared pipe structure underlying PipeReader and PipeWriter.
+type pipe struct {
+ wrMu sync.Mutex // Serializes Write operations
+ wrCh chan []byte
+ rdCh chan int
+
+ once sync.Once // Protects closing done
+ done chan struct{}
+ rerr onceError
+ werr onceError
+}
+
+func (p *pipe) read(b []byte) (n int, err error) {
+ select {
+ case <-p.done:
+ return 0, p.readCloseError()
+ default:
+ }
+
+ select {
+ case bw := <-p.wrCh:
+ nr := copy(b, bw)
+ p.rdCh <- nr
+ return nr, nil
+ case <-p.done:
+ return 0, p.readCloseError()
+ }
+}
+
+func (p *pipe) closeRead(err error) error {
+ if err == nil {
+ err = ErrClosedPipe
+ }
+ p.rerr.Store(err)
+ p.once.Do(func() { close(p.done) })
+ return nil
+}
+
+func (p *pipe) write(b []byte) (n int, err error) {
+ select {
+ case <-p.done:
+ return 0, p.writeCloseError()
+ default:
+ p.wrMu.Lock()
+ defer p.wrMu.Unlock()
+ }
+
+ for once := true; once || len(b) > 0; once = false {
+ select {
+ case p.wrCh <- b:
+ nw := <-p.rdCh
+ b = b[nw:]
+ n += nw
+ case <-p.done:
+ return n, p.writeCloseError()
+ }
+ }
+ return n, nil
+}
+
+func (p *pipe) closeWrite(err error) error {
+ if err == nil {
+ err = EOF
+ }
+ p.werr.Store(err)
+ p.once.Do(func() { close(p.done) })
+ return nil
+}
+
+// readCloseError is considered internal to the pipe type.
+func (p *pipe) readCloseError() error {
+ rerr := p.rerr.Load()
+ if werr := p.werr.Load(); rerr == nil && werr != nil {
+ return werr
+ }
+ return ErrClosedPipe
+}
+
+// writeCloseError is considered internal to the pipe type.
+func (p *pipe) writeCloseError() error {
+ werr := p.werr.Load()
+ if rerr := p.rerr.Load(); werr == nil && rerr != nil {
+ return rerr
+ }
+ return ErrClosedPipe
+}
+
+// A PipeReader is the read half of a pipe.
+type PipeReader struct{ pipe }
+
+// Read implements the standard Read interface:
+// it reads data from the pipe, blocking until a writer
+// arrives or the write end is closed.
+// If the write end is closed with an error, that error is
+// returned as err; otherwise err is EOF.
+func (r *PipeReader) Read(data []byte) (n int, err error) {
+ return r.pipe.read(data)
+}
+
+// Close closes the reader; subsequent writes to the
+// write half of the pipe will return the error [ErrClosedPipe].
+func (r *PipeReader) Close() error {
+ return r.CloseWithError(nil)
+}
+
+// CloseWithError closes the reader; subsequent writes
+// to the write half of the pipe will return the error err.
+//
+// CloseWithError never overwrites the previous error if it exists
+// and always returns nil.
+func (r *PipeReader) CloseWithError(err error) error {
+ return r.pipe.closeRead(err)
+}
+
+// A PipeWriter is the write half of a pipe.
+type PipeWriter struct{ r PipeReader }
+
+// Write implements the standard Write interface:
+// it writes data to the pipe, blocking until one or more readers
+// have consumed all the data or the read end is closed.
+// If the read end is closed with an error, that err is
+// returned as err; otherwise err is [ErrClosedPipe].
+func (w *PipeWriter) Write(data []byte) (n int, err error) {
+ return w.r.pipe.write(data)
+}
+
+// Close closes the writer; subsequent reads from the
+// read half of the pipe will return no bytes and EOF.
+func (w *PipeWriter) Close() error {
+ return w.CloseWithError(nil)
+}
+
+// CloseWithError closes the writer; subsequent reads from the
+// read half of the pipe will return no bytes and the error err,
+// or EOF if err is nil.
+//
+// CloseWithError never overwrites the previous error if it exists
+// and always returns nil.
+func (w *PipeWriter) CloseWithError(err error) error {
+ return w.r.pipe.closeWrite(err)
+}
+
+// Pipe creates a synchronous in-memory pipe.
+// It can be used to connect code expecting an [io.Reader]
+// with code expecting an [io.Writer].
+//
+// Reads and Writes on the pipe are matched one to one
+// except when multiple Reads are needed to consume a single Write.
+// That is, each Write to the [PipeWriter] blocks until it has satisfied
+// one or more Reads from the [PipeReader] that fully consume
+// the written data.
+// The data is copied directly from the Write to the corresponding
+// Read (or Reads); there is no internal buffering.
+//
+// It is safe to call Read and Write in parallel with each other or with Close.
+// Parallel calls to Read and parallel calls to Write are also safe:
+// the individual calls will be gated sequentially.
+func Pipe() (*PipeReader, *PipeWriter) {
+ pw := &PipeWriter{r: PipeReader{pipe: pipe{
+ wrCh: make(chan []byte),
+ rdCh: make(chan int),
+ done: make(chan struct{}),
+ }}}
+ return &pw.r, pw
+}
diff --git a/platform/dbops/binaries/go/go/src/io/pipe_test.go b/platform/dbops/binaries/go/go/src/io/pipe_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8973360740181ba0579e966d840c2f4d10c18f9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/io/pipe_test.go
@@ -0,0 +1,423 @@
+// 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 io_test
+
+import (
+ "bytes"
+ "fmt"
+ . "io"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+func checkWrite(t *testing.T, w Writer, data []byte, c chan int) {
+ n, err := w.Write(data)
+ if err != nil {
+ t.Errorf("write: %v", err)
+ }
+ if n != len(data) {
+ t.Errorf("short write: %d != %d", n, len(data))
+ }
+ c <- 0
+}
+
+// Test a single read/write pair.
+func TestPipe1(t *testing.T) {
+ c := make(chan int)
+ r, w := Pipe()
+ var buf = make([]byte, 64)
+ go checkWrite(t, w, []byte("hello, world"), c)
+ n, err := r.Read(buf)
+ if err != nil {
+ t.Errorf("read: %v", err)
+ } else if n != 12 || string(buf[0:12]) != "hello, world" {
+ t.Errorf("bad read: got %q", buf[0:n])
+ }
+ <-c
+ r.Close()
+ w.Close()
+}
+
+func reader(t *testing.T, r Reader, c chan int) {
+ var buf = make([]byte, 64)
+ for {
+ n, err := r.Read(buf)
+ if err == EOF {
+ c <- 0
+ break
+ }
+ if err != nil {
+ t.Errorf("read: %v", err)
+ }
+ c <- n
+ }
+}
+
+// Test a sequence of read/write pairs.
+func TestPipe2(t *testing.T) {
+ c := make(chan int)
+ r, w := Pipe()
+ go reader(t, r, c)
+ var buf = make([]byte, 64)
+ for i := 0; i < 5; i++ {
+ p := buf[0 : 5+i*10]
+ n, err := w.Write(p)
+ if n != len(p) {
+ t.Errorf("wrote %d, got %d", len(p), n)
+ }
+ if err != nil {
+ t.Errorf("write: %v", err)
+ }
+ nn := <-c
+ if nn != n {
+ t.Errorf("wrote %d, read got %d", n, nn)
+ }
+ }
+ w.Close()
+ nn := <-c
+ if nn != 0 {
+ t.Errorf("final read got %d", nn)
+ }
+}
+
+type pipeReturn struct {
+ n int
+ err error
+}
+
+// Test a large write that requires multiple reads to satisfy.
+func writer(w WriteCloser, buf []byte, c chan pipeReturn) {
+ n, err := w.Write(buf)
+ w.Close()
+ c <- pipeReturn{n, err}
+}
+
+func TestPipe3(t *testing.T) {
+ c := make(chan pipeReturn)
+ r, w := Pipe()
+ var wdat = make([]byte, 128)
+ for i := 0; i < len(wdat); i++ {
+ wdat[i] = byte(i)
+ }
+ go writer(w, wdat, c)
+ var rdat = make([]byte, 1024)
+ tot := 0
+ for n := 1; n <= 256; n *= 2 {
+ nn, err := r.Read(rdat[tot : tot+n])
+ if err != nil && err != EOF {
+ t.Fatalf("read: %v", err)
+ }
+
+ // only final two reads should be short - 1 byte, then 0
+ expect := n
+ if n == 128 {
+ expect = 1
+ } else if n == 256 {
+ expect = 0
+ if err != EOF {
+ t.Fatalf("read at end: %v", err)
+ }
+ }
+ if nn != expect {
+ t.Fatalf("read %d, expected %d, got %d", n, expect, nn)
+ }
+ tot += nn
+ }
+ pr := <-c
+ if pr.n != 128 || pr.err != nil {
+ t.Fatalf("write 128: %d, %v", pr.n, pr.err)
+ }
+ if tot != 128 {
+ t.Fatalf("total read %d != 128", tot)
+ }
+ for i := 0; i < 128; i++ {
+ if rdat[i] != byte(i) {
+ t.Fatalf("rdat[%d] = %d", i, rdat[i])
+ }
+ }
+}
+
+// Test read after/before writer close.
+
+type closer interface {
+ CloseWithError(error) error
+ Close() error
+}
+
+type pipeTest struct {
+ async bool
+ err error
+ closeWithError bool
+}
+
+func (p pipeTest) String() string {
+ return fmt.Sprintf("async=%v err=%v closeWithError=%v", p.async, p.err, p.closeWithError)
+}
+
+var pipeTests = []pipeTest{
+ {true, nil, false},
+ {true, nil, true},
+ {true, ErrShortWrite, true},
+ {false, nil, false},
+ {false, nil, true},
+ {false, ErrShortWrite, true},
+}
+
+func delayClose(t *testing.T, cl closer, ch chan int, tt pipeTest) {
+ time.Sleep(1 * time.Millisecond)
+ var err error
+ if tt.closeWithError {
+ err = cl.CloseWithError(tt.err)
+ } else {
+ err = cl.Close()
+ }
+ if err != nil {
+ t.Errorf("delayClose: %v", err)
+ }
+ ch <- 0
+}
+
+func TestPipeReadClose(t *testing.T) {
+ for _, tt := range pipeTests {
+ c := make(chan int, 1)
+ r, w := Pipe()
+ if tt.async {
+ go delayClose(t, w, c, tt)
+ } else {
+ delayClose(t, w, c, tt)
+ }
+ var buf = make([]byte, 64)
+ n, err := r.Read(buf)
+ <-c
+ want := tt.err
+ if want == nil {
+ want = EOF
+ }
+ if err != want {
+ t.Errorf("read from closed pipe: %v want %v", err, want)
+ }
+ if n != 0 {
+ t.Errorf("read on closed pipe returned %d", n)
+ }
+ if err = r.Close(); err != nil {
+ t.Errorf("r.Close: %v", err)
+ }
+ }
+}
+
+// Test close on Read side during Read.
+func TestPipeReadClose2(t *testing.T) {
+ c := make(chan int, 1)
+ r, _ := Pipe()
+ go delayClose(t, r, c, pipeTest{})
+ n, err := r.Read(make([]byte, 64))
+ <-c
+ if n != 0 || err != ErrClosedPipe {
+ t.Errorf("read from closed pipe: %v, %v want %v, %v", n, err, 0, ErrClosedPipe)
+ }
+}
+
+// Test write after/before reader close.
+
+func TestPipeWriteClose(t *testing.T) {
+ for _, tt := range pipeTests {
+ c := make(chan int, 1)
+ r, w := Pipe()
+ if tt.async {
+ go delayClose(t, r, c, tt)
+ } else {
+ delayClose(t, r, c, tt)
+ }
+ n, err := WriteString(w, "hello, world")
+ <-c
+ expect := tt.err
+ if expect == nil {
+ expect = ErrClosedPipe
+ }
+ if err != expect {
+ t.Errorf("write on closed pipe: %v want %v", err, expect)
+ }
+ if n != 0 {
+ t.Errorf("write on closed pipe returned %d", n)
+ }
+ if err = w.Close(); err != nil {
+ t.Errorf("w.Close: %v", err)
+ }
+ }
+}
+
+// Test close on Write side during Write.
+func TestPipeWriteClose2(t *testing.T) {
+ c := make(chan int, 1)
+ _, w := Pipe()
+ go delayClose(t, w, c, pipeTest{})
+ n, err := w.Write(make([]byte, 64))
+ <-c
+ if n != 0 || err != ErrClosedPipe {
+ t.Errorf("write to closed pipe: %v, %v want %v, %v", n, err, 0, ErrClosedPipe)
+ }
+}
+
+func TestWriteEmpty(t *testing.T) {
+ r, w := Pipe()
+ go func() {
+ w.Write([]byte{})
+ w.Close()
+ }()
+ var b [2]byte
+ ReadFull(r, b[0:2])
+ r.Close()
+}
+
+func TestWriteNil(t *testing.T) {
+ r, w := Pipe()
+ go func() {
+ w.Write(nil)
+ w.Close()
+ }()
+ var b [2]byte
+ ReadFull(r, b[0:2])
+ r.Close()
+}
+
+func TestWriteAfterWriterClose(t *testing.T) {
+ r, w := Pipe()
+
+ done := make(chan bool)
+ var writeErr error
+ go func() {
+ _, err := w.Write([]byte("hello"))
+ if err != nil {
+ t.Errorf("got error: %q; expected none", err)
+ }
+ w.Close()
+ _, writeErr = w.Write([]byte("world"))
+ done <- true
+ }()
+
+ buf := make([]byte, 100)
+ var result string
+ n, err := ReadFull(r, buf)
+ if err != nil && err != ErrUnexpectedEOF {
+ t.Fatalf("got: %q; want: %q", err, ErrUnexpectedEOF)
+ }
+ result = string(buf[0:n])
+ <-done
+
+ if result != "hello" {
+ t.Errorf("got: %q; want: %q", result, "hello")
+ }
+ if writeErr != ErrClosedPipe {
+ t.Errorf("got: %q; want: %q", writeErr, ErrClosedPipe)
+ }
+}
+
+func TestPipeCloseError(t *testing.T) {
+ type testError1 struct{ error }
+ type testError2 struct{ error }
+
+ r, w := Pipe()
+ r.CloseWithError(testError1{})
+ if _, err := w.Write(nil); err != (testError1{}) {
+ t.Errorf("Write error: got %T, want testError1", err)
+ }
+ r.CloseWithError(testError2{})
+ if _, err := w.Write(nil); err != (testError1{}) {
+ t.Errorf("Write error: got %T, want testError1", err)
+ }
+
+ r, w = Pipe()
+ w.CloseWithError(testError1{})
+ if _, err := r.Read(nil); err != (testError1{}) {
+ t.Errorf("Read error: got %T, want testError1", err)
+ }
+ w.CloseWithError(testError2{})
+ if _, err := r.Read(nil); err != (testError1{}) {
+ t.Errorf("Read error: got %T, want testError1", err)
+ }
+}
+
+func TestPipeConcurrent(t *testing.T) {
+ const (
+ input = "0123456789abcdef"
+ count = 8
+ readSize = 2
+ )
+
+ t.Run("Write", func(t *testing.T) {
+ r, w := Pipe()
+
+ for i := 0; i < count; i++ {
+ go func() {
+ time.Sleep(time.Millisecond) // Increase probability of race
+ if n, err := w.Write([]byte(input)); n != len(input) || err != nil {
+ t.Errorf("Write() = (%d, %v); want (%d, nil)", n, err, len(input))
+ }
+ }()
+ }
+
+ buf := make([]byte, count*len(input))
+ for i := 0; i < len(buf); i += readSize {
+ if n, err := r.Read(buf[i : i+readSize]); n != readSize || err != nil {
+ t.Errorf("Read() = (%d, %v); want (%d, nil)", n, err, readSize)
+ }
+ }
+
+ // Since each Write is fully gated, if multiple Read calls were needed,
+ // the contents of Write should still appear together in the output.
+ got := string(buf)
+ want := strings.Repeat(input, count)
+ if got != want {
+ t.Errorf("got: %q; want: %q", got, want)
+ }
+ })
+
+ t.Run("Read", func(t *testing.T) {
+ r, w := Pipe()
+
+ c := make(chan []byte, count*len(input)/readSize)
+ for i := 0; i < cap(c); i++ {
+ go func() {
+ time.Sleep(time.Millisecond) // Increase probability of race
+ buf := make([]byte, readSize)
+ if n, err := r.Read(buf); n != readSize || err != nil {
+ t.Errorf("Read() = (%d, %v); want (%d, nil)", n, err, readSize)
+ }
+ c <- buf
+ }()
+ }
+
+ for i := 0; i < count; i++ {
+ if n, err := w.Write([]byte(input)); n != len(input) || err != nil {
+ t.Errorf("Write() = (%d, %v); want (%d, nil)", n, err, len(input))
+ }
+ }
+
+ // Since each read is independent, the only guarantee about the output
+ // is that it is a permutation of the input in readSized groups.
+ got := make([]byte, 0, count*len(input))
+ for i := 0; i < cap(c); i++ {
+ got = append(got, (<-c)...)
+ }
+ got = sortBytesInGroups(got, readSize)
+ want := bytes.Repeat([]byte(input), count)
+ want = sortBytesInGroups(want, readSize)
+ if string(got) != string(want) {
+ t.Errorf("got: %q; want: %q", got, want)
+ }
+ })
+}
+
+func sortBytesInGroups(b []byte, n int) []byte {
+ var groups [][]byte
+ for len(b) > 0 {
+ groups = append(groups, b[:n])
+ b = b[n:]
+ }
+ sort.Slice(groups, func(i, j int) bool { return bytes.Compare(groups[i], groups[j]) < 0 })
+ return bytes.Join(groups, nil)
+}
diff --git a/platform/dbops/binaries/go/go/src/iter/iter.go b/platform/dbops/binaries/go/go/src/iter/iter.go
new file mode 100644
index 0000000000000000000000000000000000000000..40e47703479347aa32af2ce6d2a8b768f6581ded
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/iter/iter.go
@@ -0,0 +1,169 @@
+// 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 goexperiment.rangefunc
+
+// Package iter provides basic definitions and operations
+// related to iteration in Go.
+//
+// This package is experimental and can only be imported
+// when building with GOEXPERIMENT=rangefunc.
+package iter
+
+import (
+ "internal/race"
+ "unsafe"
+)
+
+// Seq is an iterator over sequences of individual values.
+// When called as seq(yield), seq calls yield(v) for each value v in the sequence,
+// stopping early if yield returns false.
+type Seq[V any] func(yield func(V) bool)
+
+// Seq2 is an iterator over sequences of pairs of values, most commonly key-value pairs.
+// When called as seq(yield), seq calls yield(k, v) for each pair (k, v) in the sequence,
+// stopping early if yield returns false.
+type Seq2[K, V any] func(yield func(K, V) bool)
+
+type coro struct{}
+
+//go:linkname newcoro runtime.newcoro
+func newcoro(func(*coro)) *coro
+
+//go:linkname coroswitch runtime.coroswitch
+func coroswitch(*coro)
+
+// Pull converts the “push-style” iterator sequence seq
+// into a “pull-style” iterator accessed by the two functions
+// next and stop.
+//
+// Next returns the next value in the sequence
+// and a boolean indicating whether the value is valid.
+// When the sequence is over, next returns the zero V and false.
+// It is valid to call next after reaching the end of the sequence
+// or after calling stop. These calls will continue
+// to return the zero V and false.
+//
+// Stop ends the iteration. It must be called when the caller is
+// no longer interested in next values and next has not yet
+// signaled that the sequence is over (with a false boolean return).
+// It is valid to call stop multiple times and when next has
+// already returned false.
+//
+// It is an error to call next or stop from multiple goroutines
+// simultaneously.
+func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func()) {
+ var (
+ v V
+ ok bool
+ done bool
+ racer int
+ )
+ c := newcoro(func(c *coro) {
+ race.Acquire(unsafe.Pointer(&racer))
+ yield := func(v1 V) bool {
+ if done {
+ return false
+ }
+ v, ok = v1, true
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ return !done
+ }
+ seq(yield)
+ var v0 V
+ v, ok = v0, false
+ done = true
+ race.Release(unsafe.Pointer(&racer))
+ })
+ next = func() (v1 V, ok1 bool) {
+ race.Write(unsafe.Pointer(&racer)) // detect races
+ if done {
+ return
+ }
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ return v, ok
+ }
+ stop = func() {
+ race.Write(unsafe.Pointer(&racer)) // detect races
+ if !done {
+ done = true
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ }
+ }
+ return next, stop
+}
+
+// Pull2 converts the “push-style” iterator sequence seq
+// into a “pull-style” iterator accessed by the two functions
+// next and stop.
+//
+// Next returns the next pair in the sequence
+// and a boolean indicating whether the pair is valid.
+// When the sequence is over, next returns a pair of zero values and false.
+// It is valid to call next after reaching the end of the sequence
+// or after calling stop. These calls will continue
+// to return a pair of zero values and false.
+//
+// Stop ends the iteration. It must be called when the caller is
+// no longer interested in next values and next has not yet
+// signaled that the sequence is over (with a false boolean return).
+// It is valid to call stop multiple times and when next has
+// already returned false.
+//
+// It is an error to call next or stop from multiple goroutines
+// simultaneously.
+func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func()) {
+ var (
+ k K
+ v V
+ ok bool
+ done bool
+ racer int
+ )
+ c := newcoro(func(c *coro) {
+ race.Acquire(unsafe.Pointer(&racer))
+ yield := func(k1 K, v1 V) bool {
+ if done {
+ return false
+ }
+ k, v, ok = k1, v1, true
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ return !done
+ }
+ seq(yield)
+ var k0 K
+ var v0 V
+ k, v, ok = k0, v0, false
+ done = true
+ race.Release(unsafe.Pointer(&racer))
+ })
+ next = func() (k1 K, v1 V, ok1 bool) {
+ race.Write(unsafe.Pointer(&racer)) // detect races
+ if done {
+ return
+ }
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ return k, v, ok
+ }
+ stop = func() {
+ race.Write(unsafe.Pointer(&racer)) // detect races
+ if !done {
+ done = true
+ race.Release(unsafe.Pointer(&racer))
+ coroswitch(c)
+ race.Acquire(unsafe.Pointer(&racer))
+ }
+ }
+ return next, stop
+}
diff --git a/platform/dbops/binaries/go/go/src/iter/pull_test.go b/platform/dbops/binaries/go/go/src/iter/pull_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..38e0ee993a190490a7167e41f742e06d52b05698
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/iter/pull_test.go
@@ -0,0 +1,118 @@
+// 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 goexperiment.rangefunc
+
+package iter
+
+import (
+ "fmt"
+ "runtime"
+ "testing"
+)
+
+func count(n int) Seq[int] {
+ return func(yield func(int) bool) {
+ for i := range n {
+ if !yield(i) {
+ break
+ }
+ }
+ }
+}
+
+func squares(n int) Seq2[int, int64] {
+ return func(yield func(int, int64) bool) {
+ for i := range n {
+ if !yield(i, int64(i)*int64(i)) {
+ break
+ }
+ }
+ }
+}
+
+func TestPull(t *testing.T) {
+
+ for end := 0; end <= 3; end++ {
+ t.Run(fmt.Sprint(end), func(t *testing.T) {
+ ng := runtime.NumGoroutine()
+ wantNG := func(want int) {
+ if xg := runtime.NumGoroutine() - ng; xg != want {
+ t.Helper()
+ t.Errorf("have %d extra goroutines, want %d", xg, want)
+ }
+ }
+ wantNG(0)
+ next, stop := Pull(count(3))
+ wantNG(1)
+ for i := range end {
+ v, ok := next()
+ if v != i || ok != true {
+ t.Fatalf("next() = %d, %v, want %d, %v", v, ok, i, true)
+ }
+ wantNG(1)
+ }
+ wantNG(1)
+ if end < 3 {
+ stop()
+ wantNG(0)
+ }
+ for range 2 {
+ v, ok := next()
+ if v != 0 || ok != false {
+ t.Fatalf("next() = %d, %v, want %d, %v", v, ok, 0, false)
+ }
+ wantNG(0)
+ }
+ wantNG(0)
+
+ stop()
+ stop()
+ stop()
+ wantNG(0)
+ })
+ }
+}
+
+func TestPull2(t *testing.T) {
+ for end := 0; end <= 3; end++ {
+ t.Run(fmt.Sprint(end), func(t *testing.T) {
+ ng := runtime.NumGoroutine()
+ wantNG := func(want int) {
+ if xg := runtime.NumGoroutine() - ng; xg != want {
+ t.Helper()
+ t.Errorf("have %d extra goroutines, want %d", xg, want)
+ }
+ }
+ wantNG(0)
+ next, stop := Pull2(squares(3))
+ wantNG(1)
+ for i := range end {
+ k, v, ok := next()
+ if k != i || v != int64(i*i) || ok != true {
+ t.Fatalf("next() = %d, %d, %v, want %d, %d, %v", k, v, ok, i, i*i, true)
+ }
+ wantNG(1)
+ }
+ wantNG(1)
+ if end < 3 {
+ stop()
+ wantNG(0)
+ }
+ for range 2 {
+ k, v, ok := next()
+ if v != 0 || ok != false {
+ t.Fatalf("next() = %d, %d, %v, want %d, %d, %v", k, v, ok, 0, 0, false)
+ }
+ wantNG(0)
+ }
+ wantNG(0)
+
+ stop()
+ stop()
+ stop()
+ wantNG(0)
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/log/example_test.go b/platform/dbops/binaries/go/go/src/log/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..769d076e9d59870bc93cacee20dd5e57d08ebd70
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/example_test.go
@@ -0,0 +1,41 @@
+// 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 log_test
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+)
+
+func ExampleLogger() {
+ var (
+ buf bytes.Buffer
+ logger = log.New(&buf, "logger: ", log.Lshortfile)
+ )
+
+ logger.Print("Hello, log file!")
+
+ fmt.Print(&buf)
+ // Output:
+ // logger: example_test.go:19: Hello, log file!
+}
+
+func ExampleLogger_Output() {
+ var (
+ buf bytes.Buffer
+ logger = log.New(&buf, "INFO: ", log.Lshortfile)
+
+ infof = func(info string) {
+ logger.Output(2, info)
+ }
+ )
+
+ infof("Hello world")
+
+ fmt.Print(&buf)
+ // Output:
+ // INFO: example_test.go:36: Hello world
+}
diff --git a/platform/dbops/binaries/go/go/src/log/log.go b/platform/dbops/binaries/go/go/src/log/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..d4c9c1378fe15f483dbd4e7aa633cc13532154db
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/log.go
@@ -0,0 +1,458 @@
+// 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 log implements a simple logging package. It defines a type, [Logger],
+// with methods for formatting output. It also has a predefined 'standard'
+// Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
+// Panic[f|ln], which are easier to use than creating a Logger manually.
+// That logger writes to standard error and prints the date and time
+// of each logged message.
+// Every log message is output on a separate line: if the message being
+// printed does not end in a newline, the logger will add one.
+// The Fatal functions call [os.Exit](1) after writing the log message.
+// The Panic functions call panic after writing the log message.
+package log
+
+import (
+ "fmt"
+ "io"
+ "log/internal"
+ "os"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// These flags define which text to prefix to each log entry generated by the [Logger].
+// Bits are or'ed together to control what's printed.
+// With the exception of the Lmsgprefix flag, there is no
+// control over the order they appear (the order listed here)
+// or the format they present (as described in the comments).
+// The prefix is followed by a colon only when Llongfile or Lshortfile
+// is specified.
+// For example, flags Ldate | Ltime (or LstdFlags) produce,
+//
+// 2009/01/23 01:23:23 message
+//
+// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
+//
+// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
+const (
+ Ldate = 1 << iota // the date in the local time zone: 2009/01/23
+ Ltime // the time in the local time zone: 01:23:23
+ Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
+ Llongfile // full file name and line number: /a/b/c/d.go:23
+ Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
+ LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone
+ Lmsgprefix // move the "prefix" from the beginning of the line to before the message
+ LstdFlags = Ldate | Ltime // initial values for the standard logger
+)
+
+// A Logger represents an active logging object that generates lines of
+// output to an [io.Writer]. Each logging operation makes a single call to
+// the Writer's Write method. A Logger can be used simultaneously from
+// multiple goroutines; it guarantees to serialize access to the Writer.
+type Logger struct {
+ outMu sync.Mutex
+ out io.Writer // destination for output
+
+ prefix atomic.Pointer[string] // prefix on each line to identify the logger (but see Lmsgprefix)
+ flag atomic.Int32 // properties
+ isDiscard atomic.Bool
+}
+
+// New creates a new [Logger]. The out variable sets the
+// destination to which log data will be written.
+// The prefix appears at the beginning of each generated log line, or
+// after the log header if the [Lmsgprefix] flag is provided.
+// The flag argument defines the logging properties.
+func New(out io.Writer, prefix string, flag int) *Logger {
+ l := new(Logger)
+ l.SetOutput(out)
+ l.SetPrefix(prefix)
+ l.SetFlags(flag)
+ return l
+}
+
+// SetOutput sets the output destination for the logger.
+func (l *Logger) SetOutput(w io.Writer) {
+ l.outMu.Lock()
+ defer l.outMu.Unlock()
+ l.out = w
+ l.isDiscard.Store(w == io.Discard)
+}
+
+var std = New(os.Stderr, "", LstdFlags)
+
+// Default returns the standard logger used by the package-level output functions.
+func Default() *Logger { return std }
+
+// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
+func itoa(buf *[]byte, i int, wid int) {
+ // Assemble decimal in reverse order.
+ var b [20]byte
+ bp := len(b) - 1
+ for i >= 10 || wid > 1 {
+ wid--
+ q := i / 10
+ b[bp] = byte('0' + i - q*10)
+ bp--
+ i = q
+ }
+ // i < 10
+ b[bp] = byte('0' + i)
+ *buf = append(*buf, b[bp:]...)
+}
+
+// formatHeader writes log header to buf in following order:
+// - l.prefix (if it's not blank and Lmsgprefix is unset),
+// - date and/or time (if corresponding flags are provided),
+// - file and line number (if corresponding flags are provided),
+// - l.prefix (if it's not blank and Lmsgprefix is set).
+func formatHeader(buf *[]byte, t time.Time, prefix string, flag int, file string, line int) {
+ if flag&Lmsgprefix == 0 {
+ *buf = append(*buf, prefix...)
+ }
+ if flag&(Ldate|Ltime|Lmicroseconds) != 0 {
+ if flag&LUTC != 0 {
+ t = t.UTC()
+ }
+ if flag&Ldate != 0 {
+ year, month, day := t.Date()
+ itoa(buf, year, 4)
+ *buf = append(*buf, '/')
+ itoa(buf, int(month), 2)
+ *buf = append(*buf, '/')
+ itoa(buf, day, 2)
+ *buf = append(*buf, ' ')
+ }
+ if flag&(Ltime|Lmicroseconds) != 0 {
+ hour, min, sec := t.Clock()
+ itoa(buf, hour, 2)
+ *buf = append(*buf, ':')
+ itoa(buf, min, 2)
+ *buf = append(*buf, ':')
+ itoa(buf, sec, 2)
+ if flag&Lmicroseconds != 0 {
+ *buf = append(*buf, '.')
+ itoa(buf, t.Nanosecond()/1e3, 6)
+ }
+ *buf = append(*buf, ' ')
+ }
+ }
+ if flag&(Lshortfile|Llongfile) != 0 {
+ if flag&Lshortfile != 0 {
+ short := file
+ for i := len(file) - 1; i > 0; i-- {
+ if file[i] == '/' {
+ short = file[i+1:]
+ break
+ }
+ }
+ file = short
+ }
+ *buf = append(*buf, file...)
+ *buf = append(*buf, ':')
+ itoa(buf, line, -1)
+ *buf = append(*buf, ": "...)
+ }
+ if flag&Lmsgprefix != 0 {
+ *buf = append(*buf, prefix...)
+ }
+}
+
+var bufferPool = sync.Pool{New: func() any { return new([]byte) }}
+
+func getBuffer() *[]byte {
+ p := bufferPool.Get().(*[]byte)
+ *p = (*p)[:0]
+ return p
+}
+
+func putBuffer(p *[]byte) {
+ // Proper usage of a sync.Pool requires each entry to have approximately
+ // the same memory cost. To obtain this property when the stored type
+ // contains a variably-sized buffer, we add a hard limit on the maximum buffer
+ // to place back in the pool.
+ //
+ // See https://go.dev/issue/23199
+ if cap(*p) > 64<<10 {
+ *p = nil
+ }
+ bufferPool.Put(p)
+}
+
+// Output writes the output for a logging event. The string s contains
+// the text to print after the prefix specified by the flags of the
+// Logger. A newline is appended if the last character of s is not
+// already a newline. Calldepth is used to recover the PC and is
+// provided for generality, although at the moment on all pre-defined
+// paths it will be 2.
+func (l *Logger) Output(calldepth int, s string) error {
+ calldepth++ // +1 for this frame.
+ return l.output(0, calldepth, func(b []byte) []byte {
+ return append(b, s...)
+ })
+}
+
+// output can take either a calldepth or a pc to get source line information.
+// It uses the pc if it is non-zero.
+func (l *Logger) output(pc uintptr, calldepth int, appendOutput func([]byte) []byte) error {
+ if l.isDiscard.Load() {
+ return nil
+ }
+
+ now := time.Now() // get this early.
+
+ // Load prefix and flag once so that their value is consistent within
+ // this call regardless of any concurrent changes to their value.
+ prefix := l.Prefix()
+ flag := l.Flags()
+
+ var file string
+ var line int
+ if flag&(Lshortfile|Llongfile) != 0 {
+ if pc == 0 {
+ var ok bool
+ _, file, line, ok = runtime.Caller(calldepth)
+ if !ok {
+ file = "???"
+ line = 0
+ }
+ } else {
+ fs := runtime.CallersFrames([]uintptr{pc})
+ f, _ := fs.Next()
+ file = f.File
+ if file == "" {
+ file = "???"
+ }
+ line = f.Line
+ }
+ }
+
+ buf := getBuffer()
+ defer putBuffer(buf)
+ formatHeader(buf, now, prefix, flag, file, line)
+ *buf = appendOutput(*buf)
+ if len(*buf) == 0 || (*buf)[len(*buf)-1] != '\n' {
+ *buf = append(*buf, '\n')
+ }
+
+ l.outMu.Lock()
+ defer l.outMu.Unlock()
+ _, err := l.out.Write(*buf)
+ return err
+}
+
+func init() {
+ internal.DefaultOutput = func(pc uintptr, data []byte) error {
+ return std.output(pc, 0, func(buf []byte) []byte {
+ return append(buf, data...)
+ })
+ }
+}
+
+// Print calls l.Output to print to the logger.
+// Arguments are handled in the manner of [fmt.Print].
+func (l *Logger) Print(v ...any) {
+ l.output(0, 2, func(b []byte) []byte {
+ return fmt.Append(b, v...)
+ })
+}
+
+// Printf calls l.Output to print to the logger.
+// Arguments are handled in the manner of [fmt.Printf].
+func (l *Logger) Printf(format string, v ...any) {
+ l.output(0, 2, func(b []byte) []byte {
+ return fmt.Appendf(b, format, v...)
+ })
+}
+
+// Println calls l.Output to print to the logger.
+// Arguments are handled in the manner of [fmt.Println].
+func (l *Logger) Println(v ...any) {
+ l.output(0, 2, func(b []byte) []byte {
+ return fmt.Appendln(b, v...)
+ })
+}
+
+// Fatal is equivalent to l.Print() followed by a call to [os.Exit](1).
+func (l *Logger) Fatal(v ...any) {
+ l.Output(2, fmt.Sprint(v...))
+ os.Exit(1)
+}
+
+// Fatalf is equivalent to l.Printf() followed by a call to [os.Exit](1).
+func (l *Logger) Fatalf(format string, v ...any) {
+ l.Output(2, fmt.Sprintf(format, v...))
+ os.Exit(1)
+}
+
+// Fatalln is equivalent to l.Println() followed by a call to [os.Exit](1).
+func (l *Logger) Fatalln(v ...any) {
+ l.Output(2, fmt.Sprintln(v...))
+ os.Exit(1)
+}
+
+// Panic is equivalent to l.Print() followed by a call to panic().
+func (l *Logger) Panic(v ...any) {
+ s := fmt.Sprint(v...)
+ l.Output(2, s)
+ panic(s)
+}
+
+// Panicf is equivalent to l.Printf() followed by a call to panic().
+func (l *Logger) Panicf(format string, v ...any) {
+ s := fmt.Sprintf(format, v...)
+ l.Output(2, s)
+ panic(s)
+}
+
+// Panicln is equivalent to l.Println() followed by a call to panic().
+func (l *Logger) Panicln(v ...any) {
+ s := fmt.Sprintln(v...)
+ l.Output(2, s)
+ panic(s)
+}
+
+// Flags returns the output flags for the logger.
+// The flag bits are [Ldate], [Ltime], and so on.
+func (l *Logger) Flags() int {
+ return int(l.flag.Load())
+}
+
+// SetFlags sets the output flags for the logger.
+// The flag bits are [Ldate], [Ltime], and so on.
+func (l *Logger) SetFlags(flag int) {
+ l.flag.Store(int32(flag))
+}
+
+// Prefix returns the output prefix for the logger.
+func (l *Logger) Prefix() string {
+ if p := l.prefix.Load(); p != nil {
+ return *p
+ }
+ return ""
+}
+
+// SetPrefix sets the output prefix for the logger.
+func (l *Logger) SetPrefix(prefix string) {
+ l.prefix.Store(&prefix)
+}
+
+// Writer returns the output destination for the logger.
+func (l *Logger) Writer() io.Writer {
+ l.outMu.Lock()
+ defer l.outMu.Unlock()
+ return l.out
+}
+
+// SetOutput sets the output destination for the standard logger.
+func SetOutput(w io.Writer) {
+ std.SetOutput(w)
+}
+
+// Flags returns the output flags for the standard logger.
+// The flag bits are [Ldate], [Ltime], and so on.
+func Flags() int {
+ return std.Flags()
+}
+
+// SetFlags sets the output flags for the standard logger.
+// The flag bits are [Ldate], [Ltime], and so on.
+func SetFlags(flag int) {
+ std.SetFlags(flag)
+}
+
+// Prefix returns the output prefix for the standard logger.
+func Prefix() string {
+ return std.Prefix()
+}
+
+// SetPrefix sets the output prefix for the standard logger.
+func SetPrefix(prefix string) {
+ std.SetPrefix(prefix)
+}
+
+// Writer returns the output destination for the standard logger.
+func Writer() io.Writer {
+ return std.Writer()
+}
+
+// These functions write to the standard logger.
+
+// Print calls Output to print to the standard logger.
+// Arguments are handled in the manner of [fmt.Print].
+func Print(v ...any) {
+ std.output(0, 2, func(b []byte) []byte {
+ return fmt.Append(b, v...)
+ })
+}
+
+// Printf calls Output to print to the standard logger.
+// Arguments are handled in the manner of [fmt.Printf].
+func Printf(format string, v ...any) {
+ std.output(0, 2, func(b []byte) []byte {
+ return fmt.Appendf(b, format, v...)
+ })
+}
+
+// Println calls Output to print to the standard logger.
+// Arguments are handled in the manner of [fmt.Println].
+func Println(v ...any) {
+ std.output(0, 2, func(b []byte) []byte {
+ return fmt.Appendln(b, v...)
+ })
+}
+
+// Fatal is equivalent to [Print] followed by a call to [os.Exit](1).
+func Fatal(v ...any) {
+ std.Output(2, fmt.Sprint(v...))
+ os.Exit(1)
+}
+
+// Fatalf is equivalent to [Printf] followed by a call to [os.Exit](1).
+func Fatalf(format string, v ...any) {
+ std.Output(2, fmt.Sprintf(format, v...))
+ os.Exit(1)
+}
+
+// Fatalln is equivalent to [Println] followed by a call to [os.Exit](1).
+func Fatalln(v ...any) {
+ std.Output(2, fmt.Sprintln(v...))
+ os.Exit(1)
+}
+
+// Panic is equivalent to [Print] followed by a call to panic().
+func Panic(v ...any) {
+ s := fmt.Sprint(v...)
+ std.Output(2, s)
+ panic(s)
+}
+
+// Panicf is equivalent to [Printf] followed by a call to panic().
+func Panicf(format string, v ...any) {
+ s := fmt.Sprintf(format, v...)
+ std.Output(2, s)
+ panic(s)
+}
+
+// Panicln is equivalent to [Println] followed by a call to panic().
+func Panicln(v ...any) {
+ s := fmt.Sprintln(v...)
+ std.Output(2, s)
+ panic(s)
+}
+
+// Output writes the output for a logging event. The string s contains
+// the text to print after the prefix specified by the flags of the
+// Logger. A newline is appended if the last character of s is not
+// already a newline. Calldepth is the count of the number of
+// frames to skip when computing the file name and line number
+// if [Llongfile] or [Lshortfile] is set; a value of 1 will print the details
+// for the caller of Output.
+func Output(calldepth int, s string) error {
+ return std.Output(calldepth+1, s) // +1 for this frame.
+}
diff --git a/platform/dbops/binaries/go/go/src/log/log_test.go b/platform/dbops/binaries/go/go/src/log/log_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c7fa78f5ad95be6ddfa7fc8a7af93c19f87106d6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/log/log_test.go
@@ -0,0 +1,280 @@
+// 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 log
+
+// These tests are too simple.
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "regexp"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+const (
+ Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
+ Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
+ Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
+ Rline = `(63|65):` // must update if the calls to l.Printf / l.Print below move
+ Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
+ Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline
+)
+
+type tester struct {
+ flag int
+ prefix string
+ pattern string // regexp that log output must match; we add ^ and expected_text$ always
+}
+
+var tests = []tester{
+ // individual pieces:
+ {0, "", ""},
+ {0, "XXX", "XXX"},
+ {Ldate, "", Rdate + " "},
+ {Ltime, "", Rtime + " "},
+ {Ltime | Lmsgprefix, "XXX", Rtime + " XXX"},
+ {Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "},
+ {Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time
+ {Llongfile, "", Rlongfile + " "},
+ {Lshortfile, "", Rshortfile + " "},
+ {Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile
+ // everything at once:
+ {Ldate | Ltime | Lmicroseconds | Llongfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "},
+ {Ldate | Ltime | Lmicroseconds | Lshortfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "},
+ {Ldate | Ltime | Lmicroseconds | Llongfile | Lmsgprefix, "XXX", Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " XXX"},
+ {Ldate | Ltime | Lmicroseconds | Lshortfile | Lmsgprefix, "XXX", Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " XXX"},
+}
+
+// Test using Println("hello", 23, "world") or using Printf("hello %d world", 23)
+func testPrint(t *testing.T, flag int, prefix string, pattern string, useFormat bool) {
+ buf := new(strings.Builder)
+ SetOutput(buf)
+ SetFlags(flag)
+ SetPrefix(prefix)
+ if useFormat {
+ Printf("hello %d world", 23)
+ } else {
+ Println("hello", 23, "world")
+ }
+ line := buf.String()
+ line = line[0 : len(line)-1]
+ pattern = "^" + pattern + "hello 23 world$"
+ matched, err := regexp.MatchString(pattern, line)
+ if err != nil {
+ t.Fatal("pattern did not compile:", err)
+ }
+ if !matched {
+ t.Errorf("log output should match %q is %q", pattern, line)
+ }
+ SetOutput(os.Stderr)
+}
+
+func TestDefault(t *testing.T) {
+ if got := Default(); got != std {
+ t.Errorf("Default [%p] should be std [%p]", got, std)
+ }
+}
+
+func TestAll(t *testing.T) {
+ for _, testcase := range tests {
+ testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, false)
+ testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, true)
+ }
+}
+
+func TestOutput(t *testing.T) {
+ const testString = "test"
+ var b strings.Builder
+ l := New(&b, "", 0)
+ l.Println(testString)
+ if expect := testString + "\n"; b.String() != expect {
+ t.Errorf("log output should match %q is %q", expect, b.String())
+ }
+}
+
+func TestNonNewLogger(t *testing.T) {
+ var l Logger
+ l.SetOutput(new(bytes.Buffer)) // minimal work to initialize a Logger
+ l.Print("hello")
+}
+
+func TestOutputRace(t *testing.T) {
+ var b bytes.Buffer
+ l := New(&b, "", 0)
+ var wg sync.WaitGroup
+ wg.Add(100)
+ for i := 0; i < 100; i++ {
+ go func() {
+ defer wg.Done()
+ l.SetFlags(0)
+ l.Output(0, "")
+ }()
+ }
+ wg.Wait()
+}
+
+func TestFlagAndPrefixSetting(t *testing.T) {
+ var b bytes.Buffer
+ l := New(&b, "Test:", LstdFlags)
+ f := l.Flags()
+ if f != LstdFlags {
+ t.Errorf("Flags 1: expected %x got %x", LstdFlags, f)
+ }
+ l.SetFlags(f | Lmicroseconds)
+ f = l.Flags()
+ if f != LstdFlags|Lmicroseconds {
+ t.Errorf("Flags 2: expected %x got %x", LstdFlags|Lmicroseconds, f)
+ }
+ p := l.Prefix()
+ if p != "Test:" {
+ t.Errorf(`Prefix: expected "Test:" got %q`, p)
+ }
+ l.SetPrefix("Reality:")
+ p = l.Prefix()
+ if p != "Reality:" {
+ t.Errorf(`Prefix: expected "Reality:" got %q`, p)
+ }
+ // Verify a log message looks right, with our prefix and microseconds present.
+ l.Print("hello")
+ pattern := "^Reality:" + Rdate + " " + Rtime + Rmicroseconds + " hello\n"
+ matched, err := regexp.Match(pattern, b.Bytes())
+ if err != nil {
+ t.Fatalf("pattern %q did not compile: %s", pattern, err)
+ }
+ if !matched {
+ t.Error("message did not match pattern")
+ }
+
+ // Ensure that a newline is added only if the buffer lacks a newline suffix.
+ b.Reset()
+ l.SetFlags(0)
+ l.SetPrefix("\n")
+ l.Output(0, "")
+ if got := b.String(); got != "\n" {
+ t.Errorf("message mismatch:\ngot %q\nwant %q", got, "\n")
+ }
+}
+
+func TestUTCFlag(t *testing.T) {
+ var b strings.Builder
+ l := New(&b, "Test:", LstdFlags)
+ l.SetFlags(Ldate | Ltime | LUTC)
+ // Verify a log message looks right in the right time zone. Quantize to the second only.
+ now := time.Now().UTC()
+ l.Print("hello")
+ want := fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
+ now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
+ got := b.String()
+ if got == want {
+ return
+ }
+ // It's possible we crossed a second boundary between getting now and logging,
+ // so add a second and try again. This should very nearly always work.
+ now = now.Add(time.Second)
+ want = fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
+ now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
+ if got == want {
+ return
+ }
+ t.Errorf("got %q; want %q", got, want)
+}
+
+func TestEmptyPrintCreatesLine(t *testing.T) {
+ var b strings.Builder
+ l := New(&b, "Header:", LstdFlags)
+ l.Print()
+ l.Println("non-empty")
+ output := b.String()
+ if n := strings.Count(output, "Header"); n != 2 {
+ t.Errorf("expected 2 headers, got %d", n)
+ }
+ if n := strings.Count(output, "\n"); n != 2 {
+ t.Errorf("expected 2 lines, got %d", n)
+ }
+}
+
+func TestDiscard(t *testing.T) {
+ l := New(io.Discard, "", 0)
+ s := strings.Repeat("a", 102400)
+ c := testing.AllocsPerRun(100, func() { l.Printf("%s", s) })
+ // One allocation for slice passed to Printf,
+ // but none for formatting of long string.
+ if c > 1 {
+ t.Errorf("got %v allocs, want at most 1", c)
+ }
+}
+
+func BenchmarkItoa(b *testing.B) {
+ dst := make([]byte, 0, 64)
+ for i := 0; i < b.N; i++ {
+ dst = dst[0:0]
+ itoa(&dst, 2015, 4) // year
+ itoa(&dst, 1, 2) // month
+ itoa(&dst, 30, 2) // day
+ itoa(&dst, 12, 2) // hour
+ itoa(&dst, 56, 2) // minute
+ itoa(&dst, 0, 2) // second
+ itoa(&dst, 987654, 6) // microsecond
+ }
+}
+
+func BenchmarkPrintln(b *testing.B) {
+ const testString = "test"
+ var buf bytes.Buffer
+ l := New(&buf, "", LstdFlags)
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ l.Println(testString)
+ }
+}
+
+func BenchmarkPrintlnNoFlags(b *testing.B) {
+ const testString = "test"
+ var buf bytes.Buffer
+ l := New(&buf, "", 0)
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ l.Println(testString)
+ }
+}
+
+// discard is identical to io.Discard,
+// but copied here to avoid the io.Discard optimization in Logger.
+type discard struct{}
+
+func (discard) Write(p []byte) (int, error) {
+ return len(p), nil
+}
+
+func BenchmarkConcurrent(b *testing.B) {
+ l := New(discard{}, "prefix: ", Ldate|Ltime|Lmicroseconds|Llongfile|Lmsgprefix)
+ var group sync.WaitGroup
+ for i := runtime.NumCPU(); i > 0; i-- {
+ group.Add(1)
+ go func() {
+ for i := 0; i < b.N; i++ {
+ l.Output(0, "hello, world!")
+ }
+ defer group.Done()
+ }()
+ }
+ group.Wait()
+}
+
+func BenchmarkDiscard(b *testing.B) {
+ l := New(io.Discard, "", LstdFlags|Lshortfile)
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ l.Printf("processing %d objects from bucket %q", 1234, "fizzbuzz")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/maps/example_test.go b/platform/dbops/binaries/go/go/src/maps/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..3d6b7d1ba09b6d66ca42964542c688c0f9ea62c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/maps/example_test.go
@@ -0,0 +1,135 @@
+// 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 maps_test
+
+import (
+ "fmt"
+ "maps"
+ "strings"
+)
+
+func ExampleClone() {
+ m1 := map[string]int{
+ "key": 1,
+ }
+ m2 := maps.Clone(m1)
+ m2["key"] = 100
+ fmt.Println(m1["key"])
+ fmt.Println(m2["key"])
+
+ m3 := map[string][]int{
+ "key": {1, 2, 3},
+ }
+ m4 := maps.Clone(m3)
+ fmt.Println(m4["key"][0])
+ m4["key"][0] = 100
+ fmt.Println(m3["key"][0])
+ fmt.Println(m4["key"][0])
+
+ // Output:
+ // 1
+ // 100
+ // 1
+ // 100
+ // 100
+}
+
+func ExampleCopy() {
+ m1 := map[string]int{
+ "one": 1,
+ "two": 2,
+ }
+ m2 := map[string]int{
+ "one": 10,
+ }
+
+ maps.Copy(m2, m1)
+ fmt.Println("m2 is:", m2)
+
+ m2["one"] = 100
+ fmt.Println("m1 is:", m1)
+ fmt.Println("m2 is:", m2)
+
+ m3 := map[string][]int{
+ "one": {1, 2, 3},
+ "two": {4, 5, 6},
+ }
+ m4 := map[string][]int{
+ "one": {7, 8, 9},
+ }
+
+ maps.Copy(m4, m3)
+ fmt.Println("m4 is:", m4)
+
+ m4["one"][0] = 100
+ fmt.Println("m3 is:", m3)
+ fmt.Println("m4 is:", m4)
+
+ // Output:
+ // m2 is: map[one:1 two:2]
+ // m1 is: map[one:1 two:2]
+ // m2 is: map[one:100 two:2]
+ // m4 is: map[one:[1 2 3] two:[4 5 6]]
+ // m3 is: map[one:[100 2 3] two:[4 5 6]]
+ // m4 is: map[one:[100 2 3] two:[4 5 6]]
+}
+
+func ExampleDeleteFunc() {
+ m := map[string]int{
+ "one": 1,
+ "two": 2,
+ "three": 3,
+ "four": 4,
+ }
+ maps.DeleteFunc(m, func(k string, v int) bool {
+ return v%2 != 0 // delete odd values
+ })
+ fmt.Println(m)
+ // Output:
+ // map[four:4 two:2]
+}
+
+func ExampleEqual() {
+ m1 := map[int]string{
+ 1: "one",
+ 10: "Ten",
+ 1000: "THOUSAND",
+ }
+ m2 := map[int]string{
+ 1: "one",
+ 10: "Ten",
+ 1000: "THOUSAND",
+ }
+ m3 := map[int]string{
+ 1: "one",
+ 10: "ten",
+ 1000: "thousand",
+ }
+
+ fmt.Println(maps.Equal(m1, m2))
+ fmt.Println(maps.Equal(m1, m3))
+ // Output:
+ // true
+ // false
+}
+
+func ExampleEqualFunc() {
+ m1 := map[int]string{
+ 1: "one",
+ 10: "Ten",
+ 1000: "THOUSAND",
+ }
+ m2 := map[int][]byte{
+ 1: []byte("One"),
+ 10: []byte("Ten"),
+ 1000: []byte("Thousand"),
+ }
+ eq := maps.EqualFunc(m1, m2, func(v1 string, v2 []byte) bool {
+ return strings.ToLower(v1) == strings.ToLower(string(v2))
+ })
+ fmt.Println(eq)
+ // Output:
+ // true
+}
diff --git a/platform/dbops/binaries/go/go/src/maps/maps.go b/platform/dbops/binaries/go/go/src/maps/maps.go
new file mode 100644
index 0000000000000000000000000000000000000000..befde18c9c973433cd3fecfc0a3982371c77c06c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/maps/maps.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.
+
+// Package maps defines various functions useful with maps of any type.
+package maps
+
+// Equal reports whether two maps contain the same key/value pairs.
+// Values are compared using ==.
+func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
+ if len(m1) != len(m2) {
+ return false
+ }
+ for k, v1 := range m1 {
+ if v2, ok := m2[k]; !ok || v1 != v2 {
+ return false
+ }
+ }
+ return true
+}
+
+// EqualFunc is like Equal, but compares values using eq.
+// Keys are still compared with ==.
+func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool {
+ if len(m1) != len(m2) {
+ return false
+ }
+ for k, v1 := range m1 {
+ if v2, ok := m2[k]; !ok || !eq(v1, v2) {
+ return false
+ }
+ }
+ return true
+}
+
+// clone is implemented in the runtime package.
+func clone(m any) any
+
+// Clone returns a copy of m. This is a shallow clone:
+// the new keys and values are set using ordinary assignment.
+func Clone[M ~map[K]V, K comparable, V any](m M) M {
+ // Preserve nil in case it matters.
+ if m == nil {
+ return nil
+ }
+ return clone(m).(M)
+}
+
+// Copy copies all key/value pairs in src adding them to dst.
+// When a key in src is already present in dst,
+// the value in dst will be overwritten by the value associated
+// with the key in src.
+func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
+ for k, v := range src {
+ dst[k] = v
+ }
+}
+
+// DeleteFunc deletes any key/value pairs from m for which del returns true.
+func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
+ for k, v := range m {
+ if del(k, v) {
+ delete(m, k)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/maps/maps.s b/platform/dbops/binaries/go/go/src/maps/maps.s
new file mode 100644
index 0000000000000000000000000000000000000000..4e5577892d7195ce0b9089aea4d7f7b0f6cad4ee
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/maps/maps.s
@@ -0,0 +1,5 @@
+// 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.
+
+// need this empty asm file to enable linkname.
\ No newline at end of file
diff --git a/platform/dbops/binaries/go/go/src/maps/maps_test.go b/platform/dbops/binaries/go/go/src/maps/maps_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..fa30fe8c2bcb239a328a3c0adaa3e630fb9bffa9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/maps/maps_test.go
@@ -0,0 +1,242 @@
+// 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 maps
+
+import (
+ "math"
+ "strconv"
+ "testing"
+)
+
+var m1 = map[int]int{1: 2, 2: 4, 4: 8, 8: 16}
+var m2 = map[int]string{1: "2", 2: "4", 4: "8", 8: "16"}
+
+func TestEqual(t *testing.T) {
+ if !Equal(m1, m1) {
+ t.Errorf("Equal(%v, %v) = false, want true", m1, m1)
+ }
+ if Equal(m1, (map[int]int)(nil)) {
+ t.Errorf("Equal(%v, nil) = true, want false", m1)
+ }
+ if Equal((map[int]int)(nil), m1) {
+ t.Errorf("Equal(nil, %v) = true, want false", m1)
+ }
+ if !Equal[map[int]int, map[int]int](nil, nil) {
+ t.Error("Equal(nil, nil) = false, want true")
+ }
+ if ms := map[int]int{1: 2}; Equal(m1, ms) {
+ t.Errorf("Equal(%v, %v) = true, want false", m1, ms)
+ }
+
+ // Comparing NaN for equality is expected to fail.
+ mf := map[int]float64{1: 0, 2: math.NaN()}
+ if Equal(mf, mf) {
+ t.Errorf("Equal(%v, %v) = true, want false", mf, mf)
+ }
+}
+
+// equal is simply ==.
+func equal[T comparable](v1, v2 T) bool {
+ return v1 == v2
+}
+
+// equalNaN is like == except that all NaNs are equal.
+func equalNaN[T comparable](v1, v2 T) bool {
+ isNaN := func(f T) bool { return f != f }
+ return v1 == v2 || (isNaN(v1) && isNaN(v2))
+}
+
+// equalStr compares ints and strings.
+func equalIntStr(v1 int, v2 string) bool {
+ return strconv.Itoa(v1) == v2
+}
+
+func TestEqualFunc(t *testing.T) {
+ if !EqualFunc(m1, m1, equal[int]) {
+ t.Errorf("EqualFunc(%v, %v, equal) = false, want true", m1, m1)
+ }
+ if EqualFunc(m1, (map[int]int)(nil), equal[int]) {
+ t.Errorf("EqualFunc(%v, nil, equal) = true, want false", m1)
+ }
+ if EqualFunc((map[int]int)(nil), m1, equal[int]) {
+ t.Errorf("EqualFunc(nil, %v, equal) = true, want false", m1)
+ }
+ if !EqualFunc[map[int]int, map[int]int](nil, nil, equal[int]) {
+ t.Error("EqualFunc(nil, nil, equal) = false, want true")
+ }
+ if ms := map[int]int{1: 2}; EqualFunc(m1, ms, equal[int]) {
+ t.Errorf("EqualFunc(%v, %v, equal) = true, want false", m1, ms)
+ }
+
+ // Comparing NaN for equality is expected to fail.
+ mf := map[int]float64{1: 0, 2: math.NaN()}
+ if EqualFunc(mf, mf, equal[float64]) {
+ t.Errorf("EqualFunc(%v, %v, equal) = true, want false", mf, mf)
+ }
+ // But it should succeed using equalNaN.
+ if !EqualFunc(mf, mf, equalNaN[float64]) {
+ t.Errorf("EqualFunc(%v, %v, equalNaN) = false, want true", mf, mf)
+ }
+
+ if !EqualFunc(m1, m2, equalIntStr) {
+ t.Errorf("EqualFunc(%v, %v, equalIntStr) = false, want true", m1, m2)
+ }
+}
+
+func TestClone(t *testing.T) {
+ mc := Clone(m1)
+ if !Equal(mc, m1) {
+ t.Errorf("Clone(%v) = %v, want %v", m1, mc, m1)
+ }
+ mc[16] = 32
+ if Equal(mc, m1) {
+ t.Errorf("Equal(%v, %v) = true, want false", mc, m1)
+ }
+}
+
+func TestCloneNil(t *testing.T) {
+ var m1 map[string]int
+ mc := Clone(m1)
+ if mc != nil {
+ t.Errorf("Clone(%v) = %v, want %v", m1, mc, m1)
+ }
+}
+
+func TestCopy(t *testing.T) {
+ mc := Clone(m1)
+ Copy(mc, mc)
+ if !Equal(mc, m1) {
+ t.Errorf("Copy(%v, %v) = %v, want %v", m1, m1, mc, m1)
+ }
+ Copy(mc, map[int]int{16: 32})
+ want := map[int]int{1: 2, 2: 4, 4: 8, 8: 16, 16: 32}
+ if !Equal(mc, want) {
+ t.Errorf("Copy result = %v, want %v", mc, want)
+ }
+
+ type M1 map[int]bool
+ type M2 map[int]bool
+ Copy(make(M1), make(M2))
+}
+
+func TestDeleteFunc(t *testing.T) {
+ mc := Clone(m1)
+ DeleteFunc(mc, func(int, int) bool { return false })
+ if !Equal(mc, m1) {
+ t.Errorf("DeleteFunc(%v, true) = %v, want %v", m1, mc, m1)
+ }
+ DeleteFunc(mc, func(k, v int) bool { return k > 3 })
+ want := map[int]int{1: 2, 2: 4}
+ if !Equal(mc, want) {
+ t.Errorf("DeleteFunc result = %v, want %v", mc, want)
+ }
+}
+
+var n map[int]int
+
+func BenchmarkMapClone(b *testing.B) {
+ var m = make(map[int]int)
+ for i := 0; i < 1000000; i++ {
+ m[i] = i
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ n = Clone(m)
+ }
+}
+
+func TestCloneWithDelete(t *testing.T) {
+ var m = make(map[int]int)
+ for i := 0; i < 32; i++ {
+ m[i] = i
+ }
+ for i := 8; i < 32; i++ {
+ delete(m, i)
+ }
+ m2 := Clone(m)
+ if len(m2) != 8 {
+ t.Errorf("len2(m2) = %d, want %d", len(m2), 8)
+ }
+ for i := 0; i < 8; i++ {
+ if m2[i] != m[i] {
+ t.Errorf("m2[%d] = %d, want %d", i, m2[i], m[i])
+ }
+ }
+}
+
+func TestCloneWithMapAssign(t *testing.T) {
+ var m = make(map[int]int)
+ const N = 25
+ for i := 0; i < N; i++ {
+ m[i] = i
+ }
+ m2 := Clone(m)
+ if len(m2) != N {
+ t.Errorf("len2(m2) = %d, want %d", len(m2), N)
+ }
+ for i := 0; i < N; i++ {
+ if m2[i] != m[i] {
+ t.Errorf("m2[%d] = %d, want %d", i, m2[i], m[i])
+ }
+ }
+}
+
+func TestCloneLarge(t *testing.T) {
+ // See issue 64474.
+ type K [17]float64 // > 128 bytes
+ type V [17]float64
+
+ var zero float64
+ negZero := -zero
+
+ for tst := 0; tst < 3; tst++ {
+ // Initialize m with a key and value.
+ m := map[K]V{}
+ var k1 K
+ var v1 V
+ m[k1] = v1
+
+ switch tst {
+ case 0: // nothing, just a 1-entry map
+ case 1:
+ // Add more entries to make it 2 buckets
+ // 1 entry already
+ // 7 more fill up 1 bucket
+ // 1 more to grow to 2 buckets
+ for i := 0; i < 7+1; i++ {
+ m[K{float64(i) + 1}] = V{}
+ }
+ case 2:
+ // Capture the map mid-grow
+ // 1 entry already
+ // 7 more fill up 1 bucket
+ // 5 more (13 total) fill up 2 buckets
+ // 13 more (26 total) fill up 4 buckets
+ // 1 more to start the 4->8 bucket grow
+ for i := 0; i < 7+5+13+1; i++ {
+ m[K{float64(i) + 1}] = V{}
+ }
+ }
+
+ // Clone m, which should freeze the map's contents.
+ c := Clone(m)
+
+ // Update m with new key and value.
+ k2, v2 := k1, v1
+ k2[0] = negZero
+ v2[0] = 1.0
+ m[k2] = v2
+
+ // Make sure c still has its old key and value.
+ for k, v := range c {
+ if math.Signbit(k[0]) {
+ t.Errorf("tst%d: sign bit of key changed; got %v want %v", tst, k, k1)
+ }
+ if v != v1 {
+ t.Errorf("tst%d: value changed; got %v want %v", tst, v, v1)
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/abs.go b/platform/dbops/binaries/go/go/src/math/abs.go
new file mode 100644
index 0000000000000000000000000000000000000000..08be14548dd778c37411864ad119e859e8855151
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/abs.go
@@ -0,0 +1,15 @@
+// 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 math
+
+// Abs returns the absolute value of x.
+//
+// Special cases are:
+//
+// Abs(±Inf) = +Inf
+// Abs(NaN) = NaN
+func Abs(x float64) float64 {
+ return Float64frombits(Float64bits(x) &^ (1 << 63))
+}
diff --git a/platform/dbops/binaries/go/go/src/math/acos_s390x.s b/platform/dbops/binaries/go/go/src/math/acos_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..d2288b8cd8e6b155bfc4562eb25d51266841feb5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/acos_s390x.s
@@ -0,0 +1,144 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·acosrodataL13<> + 0(SB)/8, $0.314159265358979323E+01 //pi
+DATA ·acosrodataL13<> + 8(SB)/8, $-0.0
+DATA ·acosrodataL13<> + 16(SB)/8, $0x7ff8000000000000 //Nan
+DATA ·acosrodataL13<> + 24(SB)/8, $-1.0
+DATA ·acosrodataL13<> + 32(SB)/8, $1.0
+DATA ·acosrodataL13<> + 40(SB)/8, $0.166666666666651626E+00
+DATA ·acosrodataL13<> + 48(SB)/8, $0.750000000042621169E-01
+DATA ·acosrodataL13<> + 56(SB)/8, $0.446428567178116477E-01
+DATA ·acosrodataL13<> + 64(SB)/8, $0.303819660378071894E-01
+DATA ·acosrodataL13<> + 72(SB)/8, $0.223715011892010405E-01
+DATA ·acosrodataL13<> + 80(SB)/8, $0.173659424522364952E-01
+DATA ·acosrodataL13<> + 88(SB)/8, $0.137810186504372266E-01
+DATA ·acosrodataL13<> + 96(SB)/8, $0.134066870961173521E-01
+DATA ·acosrodataL13<> + 104(SB)/8, $-.412335502831898721E-02
+DATA ·acosrodataL13<> + 112(SB)/8, $0.867383739532082719E-01
+DATA ·acosrodataL13<> + 120(SB)/8, $-.328765950607171649E+00
+DATA ·acosrodataL13<> + 128(SB)/8, $0.110401073869414626E+01
+DATA ·acosrodataL13<> + 136(SB)/8, $-.270694366992537307E+01
+DATA ·acosrodataL13<> + 144(SB)/8, $0.500196500770928669E+01
+DATA ·acosrodataL13<> + 152(SB)/8, $-.665866959108585165E+01
+DATA ·acosrodataL13<> + 160(SB)/8, $-.344895269334086578E+01
+DATA ·acosrodataL13<> + 168(SB)/8, $0.927437952918301659E+00
+DATA ·acosrodataL13<> + 176(SB)/8, $0.610487478874645653E+01
+DATA ·acosrodataL13<> + 184(SB)/8, $0.157079632679489656e+01
+DATA ·acosrodataL13<> + 192(SB)/8, $0.0
+GLOBL ·acosrodataL13<> + 0(SB), RODATA, $200
+
+// Acos returns the arccosine, in radians, of the argument.
+//
+// Special case is:
+// Acos(x) = NaN if x < -1 or x > 1
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·acosAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·acosrodataL13<>+0(SB), R9
+ LGDR F0, R12
+ FMOVD F0, F10
+ SRAD $32, R12
+ WORD $0xC0293FE6 //iilf %r2,1072079005
+ BYTE $0xA0
+ BYTE $0x9D
+ WORD $0xB917001C //llgtr %r1,%r12
+ CMPW R1,R2
+ BGT L2
+ FMOVD 192(R9), F8
+ FMADD F0, F0, F8
+ FMOVD 184(R9), F1
+L3:
+ WFMDB V8, V8, V2
+ FMOVD 176(R9), F6
+ FMOVD 168(R9), F0
+ FMOVD 160(R9), F4
+ WFMADB V2, V0, V6, V0
+ FMOVD 152(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 144(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 136(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 128(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 120(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 112(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 104(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 96(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 88(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 80(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 72(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 64(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 56(R9), F6
+ WFMADB V2, V4, V6, V4
+ FMOVD 48(R9), F6
+ WFMADB V2, V0, V6, V0
+ FMOVD 40(R9), F6
+ WFMADB V2, V4, V6, V2
+ FMOVD 192(R9), F4
+ WFMADB V8, V0, V2, V0
+ WFMADB V10, V8, V4, V8
+ FMADD F0, F8, F10
+ WFSDB V10, V1, V10
+L1:
+ FMOVD F10, ret+8(FP)
+ RET
+
+L2:
+ WORD $0xC0293FEF //iilf %r2,1072693247
+ BYTE $0xFF
+ BYTE $0xFF
+ CMPW R1, R2
+ BLE L12
+L4:
+ WORD $0xED009020 //cdb %f0,.L34-.L13(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L8
+ WORD $0xED009018 //cdb %f0,.L35-.L13(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L9
+ WFCEDBS V10, V10, V0
+ BVS L1
+ FMOVD 16(R9), F10
+ BR L1
+L12:
+ FMOVD 24(R9), F0
+ FMADD F10, F10, F0
+ WORD $0xB3130080 //lcdbr %f8,%f0
+ WORD $0xED009008 //cdb %f0,.L37-.L13(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ FSQRT F8, F10
+L5:
+ MOVW R12, R4
+ CMPBLE R4, $0, L7
+ WORD $0xB31300AA //lcdbr %f10,%f10
+ FMOVD $0, F1
+ BR L3
+L9:
+ FMOVD 0(R9), F10
+ BR L1
+L8:
+ FMOVD $0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L7:
+ FMOVD 0(R9), F1
+ BR L3
diff --git a/platform/dbops/binaries/go/go/src/math/acosh.go b/platform/dbops/binaries/go/go/src/math/acosh.go
new file mode 100644
index 0000000000000000000000000000000000000000..a85d003d3eabe768995aaa7a6976b155dbfe6836
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/acosh.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 math
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/e_acosh.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// __ieee754_acosh(x)
+// Method :
+// Based on
+// acosh(x) = log [ x + sqrt(x*x-1) ]
+// we have
+// acosh(x) := log(x)+ln2, if x is large; else
+// acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
+// acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
+//
+// Special cases:
+// acosh(x) is NaN with signal if x<1.
+// acosh(NaN) is NaN without signal.
+//
+
+// Acosh returns the inverse hyperbolic cosine of x.
+//
+// Special cases are:
+//
+// Acosh(+Inf) = +Inf
+// Acosh(x) = NaN if x < 1
+// Acosh(NaN) = NaN
+func Acosh(x float64) float64 {
+ if haveArchAcosh {
+ return archAcosh(x)
+ }
+ return acosh(x)
+}
+
+func acosh(x float64) float64 {
+ const Large = 1 << 28 // 2**28
+ // first case is special case
+ switch {
+ case x < 1 || IsNaN(x):
+ return NaN()
+ case x == 1:
+ return 0
+ case x >= Large:
+ return Log(x) + Ln2 // x > 2**28
+ case x > 2:
+ return Log(2*x - 1/(x+Sqrt(x*x-1))) // 2**28 > x > 2
+ }
+ t := x - 1
+ return Log1p(t + Sqrt(2*t+t*t)) // 2 >= x > 1
+}
diff --git a/platform/dbops/binaries/go/go/src/math/acosh_s390x.s b/platform/dbops/binaries/go/go/src/math/acosh_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..9294c48e6b92b3e8669d076ad4881bc7fa98aa82
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/acosh_s390x.s
@@ -0,0 +1,158 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·acoshrodataL11<> + 0(SB)/8, $-1.0
+DATA ·acoshrodataL11<> + 8(SB)/8, $.41375273347623353626
+DATA ·acoshrodataL11<> + 16(SB)/8, $.51487302528619766235E+04
+DATA ·acoshrodataL11<> + 24(SB)/8, $-1.67526912689208984375
+DATA ·acoshrodataL11<> + 32(SB)/8, $0.181818181818181826E+00
+DATA ·acoshrodataL11<> + 40(SB)/8, $-.165289256198351540E-01
+DATA ·acoshrodataL11<> + 48(SB)/8, $0.200350613573012186E-02
+DATA ·acoshrodataL11<> + 56(SB)/8, $-.273205381970859341E-03
+DATA ·acoshrodataL11<> + 64(SB)/8, $0.397389654305194527E-04
+DATA ·acoshrodataL11<> + 72(SB)/8, $0.938370938292558173E-06
+DATA ·acoshrodataL11<> + 80(SB)/8, $-.602107458843052029E-05
+DATA ·acoshrodataL11<> + 88(SB)/8, $0.212881813645679599E-07
+DATA ·acoshrodataL11<> + 96(SB)/8, $-.148682720127920854E-06
+DATA ·acoshrodataL11<> + 104(SB)/8, $-5.5
+DATA ·acoshrodataL11<> + 112(SB)/8, $0x7ff8000000000000 //Nan
+GLOBL ·acoshrodataL11<> + 0(SB), RODATA, $120
+
+// Table of log correction terms
+DATA ·acoshtab2068<> + 0(SB)/8, $0.585235384085551248E-01
+DATA ·acoshtab2068<> + 8(SB)/8, $0.412206153771168640E-01
+DATA ·acoshtab2068<> + 16(SB)/8, $0.273839003221648339E-01
+DATA ·acoshtab2068<> + 24(SB)/8, $0.166383778368856480E-01
+DATA ·acoshtab2068<> + 32(SB)/8, $0.866678223433169637E-02
+DATA ·acoshtab2068<> + 40(SB)/8, $0.319831684989627514E-02
+DATA ·acoshtab2068<> + 48(SB)/8, $0.0
+DATA ·acoshtab2068<> + 56(SB)/8, $-.113006378583725549E-02
+DATA ·acoshtab2068<> + 64(SB)/8, $-.367979419636602491E-03
+DATA ·acoshtab2068<> + 72(SB)/8, $0.213172484510484979E-02
+DATA ·acoshtab2068<> + 80(SB)/8, $0.623271047682013536E-02
+DATA ·acoshtab2068<> + 88(SB)/8, $0.118140812789696885E-01
+DATA ·acoshtab2068<> + 96(SB)/8, $0.187681358930914206E-01
+DATA ·acoshtab2068<> + 104(SB)/8, $0.269985148668178992E-01
+DATA ·acoshtab2068<> + 112(SB)/8, $0.364186619761331328E-01
+DATA ·acoshtab2068<> + 120(SB)/8, $0.469505379381388441E-01
+GLOBL ·acoshtab2068<> + 0(SB), RODATA, $128
+
+// Acosh returns the inverse hyperbolic cosine of the argument.
+//
+// Special cases are:
+// Acosh(+Inf) = +Inf
+// Acosh(x) = NaN if x < 1
+// Acosh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·acoshAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·acoshrodataL11<>+0(SB), R9
+ LGDR F0, R1
+ WORD $0xC0295FEF //iilf %r2,1609564159
+ BYTE $0xFF
+ BYTE $0xFF
+ SRAD $32, R1
+ CMPW R1, R2
+ BGT L2
+ WORD $0xC0293FEF //iilf %r2,1072693247
+ BYTE $0xFF
+ BYTE $0xFF
+ CMPW R1, R2
+ BGT L10
+L3:
+ WFCEDBS V0, V0, V2
+ BVS L1
+ FMOVD 112(R9), F0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+L2:
+ WORD $0xC0297FEF //iilf %r2,2146435071
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R1, R6
+ MOVW R2, R7
+ CMPBGT R6, R7, L1
+ FMOVD F0, F8
+ FMOVD $0, F0
+ WFADB V0, V8, V0
+ WORD $0xC0398006 //iilf %r3,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ LGDR F0, R5
+ SRAD $32, R5
+ MOVH $0x0, R1
+ SUBW R5, R3
+ FMOVD $0, F10
+ RISBGZ $32, $47, $0, R3, R4
+ RISBGZ $57, $60, $51, R3, R3
+ BYTE $0x18 //lr %r2,%r4
+ BYTE $0x24
+ RISBGN $0, $31, $32, R4, R1
+ SUBW $0x100000, R2
+ SRAW $8, R2, R2
+ ORW $0x45000000, R2
+L5:
+ LDGR R1, F0
+ FMOVD 104(R9), F2
+ FMADD F8, F0, F2
+ FMOVD 96(R9), F4
+ WFMADB V10, V0, V2, V0
+ FMOVD 88(R9), F6
+ FMOVD 80(R9), F2
+ WFMADB V0, V6, V4, V6
+ FMOVD 72(R9), F1
+ WFMDB V0, V0, V4
+ WFMADB V0, V1, V2, V1
+ FMOVD 64(R9), F2
+ WFMADB V6, V4, V1, V6
+ FMOVD 56(R9), F1
+ RISBGZ $57, $60, $0, R3, R3
+ WFMADB V0, V2, V1, V2
+ FMOVD 48(R9), F1
+ WFMADB V4, V6, V2, V6
+ FMOVD 40(R9), F2
+ WFMADB V0, V1, V2, V1
+ VLVGF $0, R2, V2
+ WFMADB V4, V6, V1, V4
+ LDEBR F2, F2
+ FMOVD 32(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 24(R9), F1
+ FMOVD 16(R9), F6
+ MOVD $·acoshtab2068<>+0(SB), R1
+ WFMADB V2, V1, V6, V2
+ FMOVD 0(R3)(R1*1), F3
+ WFMADB V0, V4, V3, V0
+ FMOVD 8(R9), F4
+ FMADD F4, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L10:
+ FMOVD F0, F8
+ FMOVD 0(R9), F0
+ FMADD F8, F8, F0
+ LTDBR F0, F0
+ FSQRT F0, F10
+L4:
+ WFADB V10, V8, V0
+ WORD $0xC0398006 //iilf %r3,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ LGDR F0, R5
+ SRAD $32, R5
+ MOVH $0x0, R1
+ SUBW R5, R3
+ SRAW $8, R3, R2
+ RISBGZ $32, $47, $0, R3, R4
+ ANDW $0xFFFFFF00, R2
+ RISBGZ $57, $60, $51, R3, R3
+ ORW $0x45000000, R2
+ RISBGN $0, $31, $32, R4, R1
+ BR L5
diff --git a/platform/dbops/binaries/go/go/src/math/all_test.go b/platform/dbops/binaries/go/go/src/math/all_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..af3c38c2a690dda7da30e189bc58861c7c737849
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/all_test.go
@@ -0,0 +1,3913 @@
+// 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 math_test
+
+import (
+ "fmt"
+ . "math"
+ "testing"
+ "unsafe"
+)
+
+var vf = []float64{
+ 4.9790119248836735e+00,
+ 7.7388724745781045e+00,
+ -2.7688005719200159e-01,
+ -5.0106036182710749e+00,
+ 9.6362937071984173e+00,
+ 2.9263772392439646e+00,
+ 5.2290834314593066e+00,
+ 2.7279399104360102e+00,
+ 1.8253080916808550e+00,
+ -8.6859247685756013e+00,
+}
+
+// The expected results below were computed by the high precision calculators
+// at https://keisan.casio.com/. More exact input values (array vf[], 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 acos = []float64{
+ 1.0496193546107222142571536e+00,
+ 6.8584012813664425171660692e-01,
+ 1.5984878714577160325521819e+00,
+ 2.0956199361475859327461799e+00,
+ 2.7053008467824138592616927e-01,
+ 1.2738121680361776018155625e+00,
+ 1.0205369421140629186287407e+00,
+ 1.2945003481781246062157835e+00,
+ 1.3872364345374451433846657e+00,
+ 2.6231510803970463967294145e+00,
+}
+var acosh = []float64{
+ 2.4743347004159012494457618e+00,
+ 2.8576385344292769649802701e+00,
+ 7.2796961502981066190593175e-01,
+ 2.4796794418831451156471977e+00,
+ 3.0552020742306061857212962e+00,
+ 2.044238592688586588942468e+00,
+ 2.5158701513104513595766636e+00,
+ 1.99050839282411638174299e+00,
+ 1.6988625798424034227205445e+00,
+ 2.9611454842470387925531875e+00,
+}
+var asin = []float64{
+ 5.2117697218417440497416805e-01,
+ 8.8495619865825236751471477e-01,
+ -02.769154466281941332086016e-02,
+ -5.2482360935268931351485822e-01,
+ 1.3002662421166552333051524e+00,
+ 2.9698415875871901741575922e-01,
+ 5.5025938468083370060258102e-01,
+ 2.7629597861677201301553823e-01,
+ 1.83559892257451475846656e-01,
+ -1.0523547536021497774980928e+00,
+}
+var asinh = []float64{
+ 2.3083139124923523427628243e+00,
+ 2.743551594301593620039021e+00,
+ -2.7345908534880091229413487e-01,
+ -2.3145157644718338650499085e+00,
+ 2.9613652154015058521951083e+00,
+ 1.7949041616585821933067568e+00,
+ 2.3564032905983506405561554e+00,
+ 1.7287118790768438878045346e+00,
+ 1.3626658083714826013073193e+00,
+ -2.8581483626513914445234004e+00,
+}
+var atan = []float64{
+ 1.372590262129621651920085e+00,
+ 1.442290609645298083020664e+00,
+ -2.7011324359471758245192595e-01,
+ -1.3738077684543379452781531e+00,
+ 1.4673921193587666049154681e+00,
+ 1.2415173565870168649117764e+00,
+ 1.3818396865615168979966498e+00,
+ 1.2194305844639670701091426e+00,
+ 1.0696031952318783760193244e+00,
+ -1.4561721938838084990898679e+00,
+}
+var atanh = []float64{
+ 5.4651163712251938116878204e-01,
+ 1.0299474112843111224914709e+00,
+ -2.7695084420740135145234906e-02,
+ -5.5072096119207195480202529e-01,
+ 1.9943940993171843235906642e+00,
+ 3.01448604578089708203017e-01,
+ 5.8033427206942188834370595e-01,
+ 2.7987997499441511013958297e-01,
+ 1.8459947964298794318714228e-01,
+ -1.3273186910532645867272502e+00,
+}
+var atan2 = []float64{
+ 1.1088291730037004444527075e+00,
+ 9.1218183188715804018797795e-01,
+ 1.5984772603216203736068915e+00,
+ 2.0352918654092086637227327e+00,
+ 8.0391819139044720267356014e-01,
+ 1.2861075249894661588866752e+00,
+ 1.0889904479131695712182587e+00,
+ 1.3044821793397925293797357e+00,
+ 1.3902530903455392306872261e+00,
+ 2.2859857424479142655411058e+00,
+}
+var cbrt = []float64{
+ 1.7075799841925094446722675e+00,
+ 1.9779982212970353936691498e+00,
+ -6.5177429017779910853339447e-01,
+ -1.7111838886544019873338113e+00,
+ 2.1279920909827937423960472e+00,
+ 1.4303536770460741452312367e+00,
+ 1.7357021059106154902341052e+00,
+ 1.3972633462554328350552916e+00,
+ 1.2221149580905388454977636e+00,
+ -2.0556003730500069110343596e+00,
+}
+var ceil = []float64{
+ 5.0000000000000000e+00,
+ 8.0000000000000000e+00,
+ Copysign(0, -1),
+ -5.0000000000000000e+00,
+ 1.0000000000000000e+01,
+ 3.0000000000000000e+00,
+ 6.0000000000000000e+00,
+ 3.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ -8.0000000000000000e+00,
+}
+var copysign = []float64{
+ -4.9790119248836735e+00,
+ -7.7388724745781045e+00,
+ -2.7688005719200159e-01,
+ -5.0106036182710749e+00,
+ -9.6362937071984173e+00,
+ -2.9263772392439646e+00,
+ -5.2290834314593066e+00,
+ -2.7279399104360102e+00,
+ -1.8253080916808550e+00,
+ -8.6859247685756013e+00,
+}
+var cos = []float64{
+ 2.634752140995199110787593e-01,
+ 1.148551260848219865642039e-01,
+ 9.6191297325640768154550453e-01,
+ 2.938141150061714816890637e-01,
+ -9.777138189897924126294461e-01,
+ -9.7693041344303219127199518e-01,
+ 4.940088096948647263961162e-01,
+ -9.1565869021018925545016502e-01,
+ -2.517729313893103197176091e-01,
+ -7.39241351595676573201918e-01,
+}
+
+// Results for 100000 * Pi + vf[i]
+var cosLarge = []float64{
+ 2.634752141185559426744e-01,
+ 1.14855126055543100712e-01,
+ 9.61912973266488928113e-01,
+ 2.9381411499556122552e-01,
+ -9.777138189880161924641e-01,
+ -9.76930413445147608049e-01,
+ 4.940088097314976789841e-01,
+ -9.15658690217517835002e-01,
+ -2.51772931436786954751e-01,
+ -7.3924135157173099849e-01,
+}
+
+var cosh = []float64{
+ 7.2668796942212842775517446e+01,
+ 1.1479413465659254502011135e+03,
+ 1.0385767908766418550935495e+00,
+ 7.5000957789658051428857788e+01,
+ 7.655246669605357888468613e+03,
+ 9.3567491758321272072888257e+00,
+ 9.331351599270605471131735e+01,
+ 7.6833430994624643209296404e+00,
+ 3.1829371625150718153881164e+00,
+ 2.9595059261916188501640911e+03,
+}
+var erf = []float64{
+ 5.1865354817738701906913566e-01,
+ 7.2623875834137295116929844e-01,
+ -3.123458688281309990629839e-02,
+ -5.2143121110253302920437013e-01,
+ 8.2704742671312902508629582e-01,
+ 3.2101767558376376743993945e-01,
+ 5.403990312223245516066252e-01,
+ 3.0034702916738588551174831e-01,
+ 2.0369924417882241241559589e-01,
+ -7.8069386968009226729944677e-01,
+}
+var erfc = []float64{
+ 4.8134645182261298093086434e-01,
+ 2.7376124165862704883070156e-01,
+ 1.0312345868828130999062984e+00,
+ 1.5214312111025330292043701e+00,
+ 1.7295257328687097491370418e-01,
+ 6.7898232441623623256006055e-01,
+ 4.596009687776754483933748e-01,
+ 6.9965297083261411448825169e-01,
+ 7.9630075582117758758440411e-01,
+ 1.7806938696800922672994468e+00,
+}
+var erfinv = []float64{
+ 4.746037673358033586786350696e-01,
+ 8.559054432692110956388764172e-01,
+ -2.45427830571707336251331946e-02,
+ -4.78116683518973366268905506e-01,
+ 1.479804430319470983648120853e+00,
+ 2.654485787128896161882650211e-01,
+ 5.027444534221520197823192493e-01,
+ 2.466703532707627818954585670e-01,
+ 1.632011465103005426240343116e-01,
+ -1.06672334642196900710000389e+00,
+}
+var exp = []float64{
+ 1.4533071302642137507696589e+02,
+ 2.2958822575694449002537581e+03,
+ 7.5814542574851666582042306e-01,
+ 6.6668778421791005061482264e-03,
+ 1.5310493273896033740861206e+04,
+ 1.8659907517999328638667732e+01,
+ 1.8662167355098714543942057e+02,
+ 1.5301332413189378961665788e+01,
+ 6.2047063430646876349125085e+00,
+ 1.6894712385826521111610438e-04,
+}
+var expm1 = []float64{
+ 5.105047796122957327384770212e-02,
+ 8.046199708567344080562675439e-02,
+ -2.764970978891639815187418703e-03,
+ -4.8871434888875355394330300273e-02,
+ 1.0115864277221467777117227494e-01,
+ 2.969616407795910726014621657e-02,
+ 5.368214487944892300914037972e-02,
+ 2.765488851131274068067445335e-02,
+ 1.842068661871398836913874273e-02,
+ -8.3193870863553801814961137573e-02,
+}
+var expm1Large = []float64{
+ 4.2031418113550844e+21,
+ 4.0690789717473863e+33,
+ -0.9372627915981363e+00,
+ -1.0,
+ 7.077694784145933e+41,
+ 5.117936223839153e+12,
+ 5.124137759001189e+22,
+ 7.03546003972584e+11,
+ 8.456921800389698e+07,
+ -1.0,
+}
+var exp2 = []float64{
+ 3.1537839463286288034313104e+01,
+ 2.1361549283756232296144849e+02,
+ 8.2537402562185562902577219e-01,
+ 3.1021158628740294833424229e-02,
+ 7.9581744110252191462569661e+02,
+ 7.6019905892596359262696423e+00,
+ 3.7506882048388096973183084e+01,
+ 6.6250893439173561733216375e+00,
+ 3.5438267900243941544605339e+00,
+ 2.4281533133513300984289196e-03,
+}
+var fabs = []float64{
+ 4.9790119248836735e+00,
+ 7.7388724745781045e+00,
+ 2.7688005719200159e-01,
+ 5.0106036182710749e+00,
+ 9.6362937071984173e+00,
+ 2.9263772392439646e+00,
+ 5.2290834314593066e+00,
+ 2.7279399104360102e+00,
+ 1.8253080916808550e+00,
+ 8.6859247685756013e+00,
+}
+var fdim = []float64{
+ 4.9790119248836735e+00,
+ 7.7388724745781045e+00,
+ 0.0000000000000000e+00,
+ 0.0000000000000000e+00,
+ 9.6362937071984173e+00,
+ 2.9263772392439646e+00,
+ 5.2290834314593066e+00,
+ 2.7279399104360102e+00,
+ 1.8253080916808550e+00,
+ 0.0000000000000000e+00,
+}
+var floor = []float64{
+ 4.0000000000000000e+00,
+ 7.0000000000000000e+00,
+ -1.0000000000000000e+00,
+ -6.0000000000000000e+00,
+ 9.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 5.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 1.0000000000000000e+00,
+ -9.0000000000000000e+00,
+}
+var fmod = []float64{
+ 4.197615023265299782906368e-02,
+ 2.261127525421895434476482e+00,
+ 3.231794108794261433104108e-02,
+ 4.989396381728925078391512e+00,
+ 3.637062928015826201999516e-01,
+ 1.220868282268106064236690e+00,
+ 4.770916568540693347699744e+00,
+ 1.816180268691969246219742e+00,
+ 8.734595415957246977711748e-01,
+ 1.314075231424398637614104e+00,
+}
+
+type fi struct {
+ f float64
+ i int
+}
+
+var frexp = []fi{
+ {6.2237649061045918750e-01, 3},
+ {9.6735905932226306250e-01, 3},
+ {-5.5376011438400318000e-01, -1},
+ {-6.2632545228388436250e-01, 3},
+ {6.02268356699901081250e-01, 4},
+ {7.3159430981099115000e-01, 2},
+ {6.5363542893241332500e-01, 3},
+ {6.8198497760900255000e-01, 2},
+ {9.1265404584042750000e-01, 1},
+ {-5.4287029803597508250e-01, 4},
+}
+var gamma = []float64{
+ 2.3254348370739963835386613898e+01,
+ 2.991153837155317076427529816e+03,
+ -4.561154336726758060575129109e+00,
+ 7.719403468842639065959210984e-01,
+ 1.6111876618855418534325755566e+05,
+ 1.8706575145216421164173224946e+00,
+ 3.4082787447257502836734201635e+01,
+ 1.579733951448952054898583387e+00,
+ 9.3834586598354592860187267089e-01,
+ -2.093995902923148389186189429e-05,
+}
+var j0 = []float64{
+ -1.8444682230601672018219338e-01,
+ 2.27353668906331975435892e-01,
+ 9.809259936157051116270273e-01,
+ -1.741170131426226587841181e-01,
+ -2.1389448451144143352039069e-01,
+ -2.340905848928038763337414e-01,
+ -1.0029099691890912094586326e-01,
+ -1.5466726714884328135358907e-01,
+ 3.252650187653420388714693e-01,
+ -8.72218484409407250005360235e-03,
+}
+var j1 = []float64{
+ -3.251526395295203422162967e-01,
+ 1.893581711430515718062564e-01,
+ -1.3711761352467242914491514e-01,
+ 3.287486536269617297529617e-01,
+ 1.3133899188830978473849215e-01,
+ 3.660243417832986825301766e-01,
+ -3.4436769271848174665420672e-01,
+ 4.329481396640773768835036e-01,
+ 5.8181350531954794639333955e-01,
+ -2.7030574577733036112996607e-01,
+}
+var j2 = []float64{
+ 5.3837518920137802565192769e-02,
+ -1.7841678003393207281244667e-01,
+ 9.521746934916464142495821e-03,
+ 4.28958355470987397983072e-02,
+ 2.4115371837854494725492872e-01,
+ 4.842458532394520316844449e-01,
+ -3.142145220618633390125946e-02,
+ 4.720849184745124761189957e-01,
+ 3.122312022520957042957497e-01,
+ 7.096213118930231185707277e-02,
+}
+var jM3 = []float64{
+ -3.684042080996403091021151e-01,
+ 2.8157665936340887268092661e-01,
+ 4.401005480841948348343589e-04,
+ 3.629926999056814081597135e-01,
+ 3.123672198825455192489266e-02,
+ -2.958805510589623607540455e-01,
+ -3.2033177696533233403289416e-01,
+ -2.592737332129663376736604e-01,
+ -1.0241334641061485092351251e-01,
+ -2.3762660886100206491674503e-01,
+}
+var lgamma = []fi{
+ {3.146492141244545774319734e+00, 1},
+ {8.003414490659126375852113e+00, 1},
+ {1.517575735509779707488106e+00, -1},
+ {-2.588480028182145853558748e-01, 1},
+ {1.1989897050205555002007985e+01, 1},
+ {6.262899811091257519386906e-01, 1},
+ {3.5287924899091566764846037e+00, 1},
+ {4.5725644770161182299423372e-01, 1},
+ {-6.363667087767961257654854e-02, 1},
+ {-1.077385130910300066425564e+01, -1},
+}
+var log = []float64{
+ 1.605231462693062999102599e+00,
+ 2.0462560018708770653153909e+00,
+ -1.2841708730962657801275038e+00,
+ 1.6115563905281545116286206e+00,
+ 2.2655365644872016636317461e+00,
+ 1.0737652208918379856272735e+00,
+ 1.6542360106073546632707956e+00,
+ 1.0035467127723465801264487e+00,
+ 6.0174879014578057187016475e-01,
+ 2.161703872847352815363655e+00,
+}
+var logb = []float64{
+ 2.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ -2.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 3.0000000000000000e+00,
+ 1.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 1.0000000000000000e+00,
+ 0.0000000000000000e+00,
+ 3.0000000000000000e+00,
+}
+var log10 = []float64{
+ 6.9714316642508290997617083e-01,
+ 8.886776901739320576279124e-01,
+ -5.5770832400658929815908236e-01,
+ 6.998900476822994346229723e-01,
+ 9.8391002850684232013281033e-01,
+ 4.6633031029295153334285302e-01,
+ 7.1842557117242328821552533e-01,
+ 4.3583479968917773161304553e-01,
+ 2.6133617905227038228626834e-01,
+ 9.3881606348649405716214241e-01,
+}
+var log1p = []float64{
+ 4.8590257759797794104158205e-02,
+ 7.4540265965225865330849141e-02,
+ -2.7726407903942672823234024e-03,
+ -5.1404917651627649094953380e-02,
+ 9.1998280672258624681335010e-02,
+ 2.8843762576593352865894824e-02,
+ 5.0969534581863707268992645e-02,
+ 2.6913947602193238458458594e-02,
+ 1.8088493239630770262045333e-02,
+ -9.0865245631588989681559268e-02,
+}
+var log2 = []float64{
+ 2.3158594707062190618898251e+00,
+ 2.9521233862883917703341018e+00,
+ -1.8526669502700329984917062e+00,
+ 2.3249844127278861543568029e+00,
+ 3.268478366538305087466309e+00,
+ 1.5491157592596970278166492e+00,
+ 2.3865580889631732407886495e+00,
+ 1.447811865817085365540347e+00,
+ 8.6813999540425116282815557e-01,
+ 3.118679457227342224364709e+00,
+}
+var modf = [][2]float64{
+ {4.0000000000000000e+00, 9.7901192488367350108546816e-01},
+ {7.0000000000000000e+00, 7.3887247457810456552351752e-01},
+ {Copysign(0, -1), -2.7688005719200159404635997e-01},
+ {-5.0000000000000000e+00, -1.060361827107492160848778e-02},
+ {9.0000000000000000e+00, 6.3629370719841737980004837e-01},
+ {2.0000000000000000e+00, 9.2637723924396464525443662e-01},
+ {5.0000000000000000e+00, 2.2908343145930665230025625e-01},
+ {2.0000000000000000e+00, 7.2793991043601025126008608e-01},
+ {1.0000000000000000e+00, 8.2530809168085506044576505e-01},
+ {-8.0000000000000000e+00, -6.8592476857560136238589621e-01},
+}
+var nextafter32 = []float32{
+ 4.979012489318848e+00,
+ 7.738873004913330e+00,
+ -2.768800258636475e-01,
+ -5.010602951049805e+00,
+ 9.636294364929199e+00,
+ 2.926377534866333e+00,
+ 5.229084014892578e+00,
+ 2.727940082550049e+00,
+ 1.825308203697205e+00,
+ -8.685923576354980e+00,
+}
+var nextafter64 = []float64{
+ 4.97901192488367438926388786e+00,
+ 7.73887247457810545370193722e+00,
+ -2.7688005719200153853520874e-01,
+ -5.01060361827107403343006808e+00,
+ 9.63629370719841915615688777e+00,
+ 2.92637723924396508934364647e+00,
+ 5.22908343145930754047867595e+00,
+ 2.72793991043601069534929593e+00,
+ 1.82530809168085528249036997e+00,
+ -8.68592476857559958602905681e+00,
+}
+var pow = []float64{
+ 9.5282232631648411840742957e+04,
+ 5.4811599352999901232411871e+07,
+ 5.2859121715894396531132279e-01,
+ 9.7587991957286474464259698e-06,
+ 4.328064329346044846740467e+09,
+ 8.4406761805034547437659092e+02,
+ 1.6946633276191194947742146e+05,
+ 5.3449040147551939075312879e+02,
+ 6.688182138451414936380374e+01,
+ 2.0609869004248742886827439e-09,
+}
+var remainder = []float64{
+ 4.197615023265299782906368e-02,
+ 2.261127525421895434476482e+00,
+ 3.231794108794261433104108e-02,
+ -2.120723654214984321697556e-02,
+ 3.637062928015826201999516e-01,
+ 1.220868282268106064236690e+00,
+ -4.581668629186133046005125e-01,
+ -9.117596417440410050403443e-01,
+ 8.734595415957246977711748e-01,
+ 1.314075231424398637614104e+00,
+}
+var round = []float64{
+ 5,
+ 8,
+ Copysign(0, -1),
+ -5,
+ 10,
+ 3,
+ 5,
+ 3,
+ 2,
+ -9,
+}
+var signbit = []bool{
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+}
+var sin = []float64{
+ -9.6466616586009283766724726e-01,
+ 9.9338225271646545763467022e-01,
+ -2.7335587039794393342449301e-01,
+ 9.5586257685042792878173752e-01,
+ -2.099421066779969164496634e-01,
+ 2.135578780799860532750616e-01,
+ -8.694568971167362743327708e-01,
+ 4.019566681155577786649878e-01,
+ 9.6778633541687993721617774e-01,
+ -6.734405869050344734943028e-01,
+}
+
+// Results for 100000 * Pi + vf[i]
+var sinLarge = []float64{
+ -9.646661658548936063912e-01,
+ 9.933822527198506903752e-01,
+ -2.7335587036246899796e-01,
+ 9.55862576853689321268e-01,
+ -2.099421066862688873691e-01,
+ 2.13557878070308981163e-01,
+ -8.694568970959221300497e-01,
+ 4.01956668098863248917e-01,
+ 9.67786335404528727927e-01,
+ -6.7344058693131973066e-01,
+}
+var sinh = []float64{
+ 7.2661916084208532301448439e+01,
+ 1.1479409110035194500526446e+03,
+ -2.8043136512812518927312641e-01,
+ -7.499429091181587232835164e+01,
+ 7.6552466042906758523925934e+03,
+ 9.3031583421672014313789064e+00,
+ 9.330815755828109072810322e+01,
+ 7.6179893137269146407361477e+00,
+ 3.021769180549615819524392e+00,
+ -2.95950575724449499189888e+03,
+}
+var sqrt = []float64{
+ 2.2313699659365484748756904e+00,
+ 2.7818829009464263511285458e+00,
+ 5.2619393496314796848143251e-01,
+ 2.2384377628763938724244104e+00,
+ 3.1042380236055381099288487e+00,
+ 1.7106657298385224403917771e+00,
+ 2.286718922705479046148059e+00,
+ 1.6516476350711159636222979e+00,
+ 1.3510396336454586262419247e+00,
+ 2.9471892997524949215723329e+00,
+}
+var tan = []float64{
+ -3.661316565040227801781974e+00,
+ 8.64900232648597589369854e+00,
+ -2.8417941955033612725238097e-01,
+ 3.253290185974728640827156e+00,
+ 2.147275640380293804770778e-01,
+ -2.18600910711067004921551e-01,
+ -1.760002817872367935518928e+00,
+ -4.389808914752818126249079e-01,
+ -3.843885560201130679995041e+00,
+ 9.10988793377685105753416e-01,
+}
+
+// Results for 100000 * Pi + vf[i]
+var tanLarge = []float64{
+ -3.66131656475596512705e+00,
+ 8.6490023287202547927e+00,
+ -2.841794195104782406e-01,
+ 3.2532901861033120983e+00,
+ 2.14727564046880001365e-01,
+ -2.18600910700688062874e-01,
+ -1.760002817699722747043e+00,
+ -4.38980891453536115952e-01,
+ -3.84388555942723509071e+00,
+ 9.1098879344275101051e-01,
+}
+var tanh = []float64{
+ 9.9990531206936338549262119e-01,
+ 9.9999962057085294197613294e-01,
+ -2.7001505097318677233756845e-01,
+ -9.9991110943061718603541401e-01,
+ 9.9999999146798465745022007e-01,
+ 9.9427249436125236705001048e-01,
+ 9.9994257600983138572705076e-01,
+ 9.9149409509772875982054701e-01,
+ 9.4936501296239685514466577e-01,
+ -9.9999994291374030946055701e-01,
+}
+var trunc = []float64{
+ 4.0000000000000000e+00,
+ 7.0000000000000000e+00,
+ Copysign(0, -1),
+ -5.0000000000000000e+00,
+ 9.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 5.0000000000000000e+00,
+ 2.0000000000000000e+00,
+ 1.0000000000000000e+00,
+ -8.0000000000000000e+00,
+}
+var y0 = []float64{
+ -3.053399153780788357534855e-01,
+ 1.7437227649515231515503649e-01,
+ -8.6221781263678836910392572e-01,
+ -3.100664880987498407872839e-01,
+ 1.422200649300982280645377e-01,
+ 4.000004067997901144239363e-01,
+ -3.3340749753099352392332536e-01,
+ 4.5399790746668954555205502e-01,
+ 4.8290004112497761007536522e-01,
+ 2.7036697826604756229601611e-01,
+}
+var y1 = []float64{
+ 0.15494213737457922210218611,
+ -0.2165955142081145245075746,
+ -2.4644949631241895201032829,
+ 0.1442740489541836405154505,
+ 0.2215379960518984777080163,
+ 0.3038800915160754150565448,
+ 0.0691107642452362383808547,
+ 0.2380116417809914424860165,
+ -0.20849492979459761009678934,
+ 0.0242503179793232308250804,
+}
+var y2 = []float64{
+ 0.3675780219390303613394936,
+ -0.23034826393250119879267257,
+ -16.939677983817727205631397,
+ 0.367653980523052152867791,
+ -0.0962401471767804440353136,
+ -0.1923169356184851105200523,
+ 0.35984072054267882391843766,
+ -0.2794987252299739821654982,
+ -0.7113490692587462579757954,
+ -0.2647831587821263302087457,
+}
+var yM3 = []float64{
+ -0.14035984421094849100895341,
+ -0.097535139617792072703973,
+ 242.25775994555580176377379,
+ -0.1492267014802818619511046,
+ 0.26148702629155918694500469,
+ 0.56675383593895176530394248,
+ -0.206150264009006981070575,
+ 0.64784284687568332737963658,
+ 1.3503631555901938037008443,
+ 0.1461869756579956803341844,
+}
+
+// arguments and expected results for special cases
+var vfacosSC = []float64{
+ -Pi,
+ 1,
+ Pi,
+ NaN(),
+}
+var acosSC = []float64{
+ NaN(),
+ 0,
+ NaN(),
+ NaN(),
+}
+
+var vfacoshSC = []float64{
+ Inf(-1),
+ 0.5,
+ 1,
+ Inf(1),
+ NaN(),
+}
+var acoshSC = []float64{
+ NaN(),
+ NaN(),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vfasinSC = []float64{
+ -Pi,
+ Copysign(0, -1),
+ 0,
+ Pi,
+ NaN(),
+}
+var asinSC = []float64{
+ NaN(),
+ Copysign(0, -1),
+ 0,
+ NaN(),
+ NaN(),
+}
+
+var vfasinhSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var asinhSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vfatanSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var atanSC = []float64{
+ -Pi / 2,
+ Copysign(0, -1),
+ 0,
+ Pi / 2,
+ NaN(),
+}
+
+var vfatanhSC = []float64{
+ Inf(-1),
+ -Pi,
+ -1,
+ Copysign(0, -1),
+ 0,
+ 1,
+ Pi,
+ Inf(1),
+ NaN(),
+}
+var atanhSC = []float64{
+ NaN(),
+ NaN(),
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ NaN(),
+ NaN(),
+}
+var vfatan2SC = [][2]float64{
+ {Inf(-1), Inf(-1)},
+ {Inf(-1), -Pi},
+ {Inf(-1), 0},
+ {Inf(-1), +Pi},
+ {Inf(-1), Inf(1)},
+ {Inf(-1), NaN()},
+ {-Pi, Inf(-1)},
+ {-Pi, 0},
+ {-Pi, Inf(1)},
+ {-Pi, NaN()},
+ {Copysign(0, -1), Inf(-1)},
+ {Copysign(0, -1), -Pi},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Copysign(0, -1), 0},
+ {Copysign(0, -1), +Pi},
+ {Copysign(0, -1), Inf(1)},
+ {Copysign(0, -1), NaN()},
+ {0, Inf(-1)},
+ {0, -Pi},
+ {0, Copysign(0, -1)},
+ {0, 0},
+ {0, +Pi},
+ {0, Inf(1)},
+ {0, NaN()},
+ {+Pi, Inf(-1)},
+ {+Pi, 0},
+ {+Pi, Inf(1)},
+ {1.0, Inf(1)},
+ {-1.0, Inf(1)},
+ {+Pi, NaN()},
+ {Inf(1), Inf(-1)},
+ {Inf(1), -Pi},
+ {Inf(1), 0},
+ {Inf(1), +Pi},
+ {Inf(1), Inf(1)},
+ {Inf(1), NaN()},
+ {NaN(), NaN()},
+}
+var atan2SC = []float64{
+ -3 * Pi / 4, // atan2(-Inf, -Inf)
+ -Pi / 2, // atan2(-Inf, -Pi)
+ -Pi / 2, // atan2(-Inf, +0)
+ -Pi / 2, // atan2(-Inf, +Pi)
+ -Pi / 4, // atan2(-Inf, +Inf)
+ NaN(), // atan2(-Inf, NaN)
+ -Pi, // atan2(-Pi, -Inf)
+ -Pi / 2, // atan2(-Pi, +0)
+ Copysign(0, -1), // atan2(-Pi, Inf)
+ NaN(), // atan2(-Pi, NaN)
+ -Pi, // atan2(-0, -Inf)
+ -Pi, // atan2(-0, -Pi)
+ -Pi, // atan2(-0, -0)
+ Copysign(0, -1), // atan2(-0, +0)
+ Copysign(0, -1), // atan2(-0, +Pi)
+ Copysign(0, -1), // atan2(-0, +Inf)
+ NaN(), // atan2(-0, NaN)
+ Pi, // atan2(+0, -Inf)
+ Pi, // atan2(+0, -Pi)
+ Pi, // atan2(+0, -0)
+ 0, // atan2(+0, +0)
+ 0, // atan2(+0, +Pi)
+ 0, // atan2(+0, +Inf)
+ NaN(), // atan2(+0, NaN)
+ Pi, // atan2(+Pi, -Inf)
+ Pi / 2, // atan2(+Pi, +0)
+ 0, // atan2(+Pi, +Inf)
+ 0, // atan2(+1, +Inf)
+ Copysign(0, -1), // atan2(-1, +Inf)
+ NaN(), // atan2(+Pi, NaN)
+ 3 * Pi / 4, // atan2(+Inf, -Inf)
+ Pi / 2, // atan2(+Inf, -Pi)
+ Pi / 2, // atan2(+Inf, +0)
+ Pi / 2, // atan2(+Inf, +Pi)
+ Pi / 4, // atan2(+Inf, +Inf)
+ NaN(), // atan2(+Inf, NaN)
+ NaN(), // atan2(NaN, NaN)
+}
+
+var vfcbrtSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var cbrtSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vfceilSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var ceilSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vfcopysignSC = []float64{
+ Inf(-1),
+ Inf(1),
+ NaN(),
+}
+var copysignSC = []float64{
+ Inf(-1),
+ Inf(-1),
+ NaN(),
+}
+
+var vfcosSC = []float64{
+ Inf(-1),
+ Inf(1),
+ NaN(),
+}
+var cosSC = []float64{
+ NaN(),
+ NaN(),
+ NaN(),
+}
+
+var vfcoshSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var coshSC = []float64{
+ Inf(1),
+ 1,
+ 1,
+ Inf(1),
+ NaN(),
+}
+
+var vferfSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ -1000,
+ 1000,
+}
+var erfSC = []float64{
+ -1,
+ Copysign(0, -1),
+ 0,
+ 1,
+ NaN(),
+ -1,
+ 1,
+}
+
+var vferfcSC = []float64{
+ Inf(-1),
+ Inf(1),
+ NaN(),
+ -1000,
+ 1000,
+}
+var erfcSC = []float64{
+ 2,
+ 0,
+ NaN(),
+ 2,
+ 0,
+}
+
+var vferfinvSC = []float64{
+ 1,
+ -1,
+ 0,
+ Inf(-1),
+ Inf(1),
+ NaN(),
+}
+var erfinvSC = []float64{
+ Inf(+1),
+ Inf(-1),
+ 0,
+ NaN(),
+ NaN(),
+ NaN(),
+}
+
+var vferfcinvSC = []float64{
+ 0,
+ 2,
+ 1,
+ Inf(1),
+ Inf(-1),
+ NaN(),
+}
+var erfcinvSC = []float64{
+ Inf(+1),
+ Inf(-1),
+ 0,
+ NaN(),
+ NaN(),
+ NaN(),
+}
+
+var vfexpSC = []float64{
+ Inf(-1),
+ -2000,
+ 2000,
+ Inf(1),
+ NaN(),
+ // smallest float64 that overflows Exp(x)
+ 7.097827128933841e+02,
+ // Issue 18912
+ 1.48852223e+09,
+ 1.4885222e+09,
+ 1,
+ // near zero
+ 3.725290298461915e-09,
+ // denormal
+ -740,
+}
+var expSC = []float64{
+ 0,
+ 0,
+ Inf(1),
+ Inf(1),
+ NaN(),
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ 2.718281828459045,
+ 1.0000000037252903,
+ 4.2e-322,
+}
+
+var vfexp2SC = []float64{
+ Inf(-1),
+ -2000,
+ 2000,
+ Inf(1),
+ NaN(),
+ // smallest float64 that overflows Exp2(x)
+ 1024,
+ // near underflow
+ -1.07399999999999e+03,
+ // near zero
+ 3.725290298461915e-09,
+}
+var exp2SC = []float64{
+ 0,
+ 0,
+ Inf(1),
+ Inf(1),
+ NaN(),
+ Inf(1),
+ 5e-324,
+ 1.0000000025821745,
+}
+
+var vfexpm1SC = []float64{
+ Inf(-1),
+ -710,
+ Copysign(0, -1),
+ 0,
+ 710,
+ Inf(1),
+ NaN(),
+}
+var expm1SC = []float64{
+ -1,
+ -1,
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ Inf(1),
+ NaN(),
+}
+
+var vffabsSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var fabsSC = []float64{
+ Inf(1),
+ 0,
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vffdimSC = [][2]float64{
+ {Inf(-1), Inf(-1)},
+ {Inf(-1), Inf(1)},
+ {Inf(-1), NaN()},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Copysign(0, -1), 0},
+ {0, Copysign(0, -1)},
+ {0, 0},
+ {Inf(1), Inf(-1)},
+ {Inf(1), Inf(1)},
+ {Inf(1), NaN()},
+ {NaN(), Inf(-1)},
+ {NaN(), Copysign(0, -1)},
+ {NaN(), 0},
+ {NaN(), Inf(1)},
+ {NaN(), NaN()},
+}
+var nan = Float64frombits(0xFFF8000000000000) // SSE2 DIVSD 0/0
+var vffdim2SC = [][2]float64{
+ {Inf(-1), Inf(-1)},
+ {Inf(-1), Inf(1)},
+ {Inf(-1), nan},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Copysign(0, -1), 0},
+ {0, Copysign(0, -1)},
+ {0, 0},
+ {Inf(1), Inf(-1)},
+ {Inf(1), Inf(1)},
+ {Inf(1), nan},
+ {nan, Inf(-1)},
+ {nan, Copysign(0, -1)},
+ {nan, 0},
+ {nan, Inf(1)},
+ {nan, nan},
+}
+var fdimSC = []float64{
+ NaN(),
+ 0,
+ NaN(),
+ 0,
+ 0,
+ 0,
+ 0,
+ Inf(1),
+ NaN(),
+ NaN(),
+ NaN(),
+ NaN(),
+ NaN(),
+ NaN(),
+ NaN(),
+}
+var fmaxSC = []float64{
+ Inf(-1),
+ Inf(1),
+ NaN(),
+ Copysign(0, -1),
+ 0,
+ 0,
+ 0,
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ NaN(),
+ NaN(),
+ NaN(),
+ Inf(1),
+ NaN(),
+}
+var fminSC = []float64{
+ Inf(-1),
+ Inf(-1),
+ Inf(-1),
+ Copysign(0, -1),
+ Copysign(0, -1),
+ Copysign(0, -1),
+ 0,
+ Inf(-1),
+ Inf(1),
+ NaN(),
+ Inf(-1),
+ NaN(),
+ NaN(),
+ NaN(),
+ NaN(),
+}
+
+var vffmodSC = [][2]float64{
+ {Inf(-1), Inf(-1)},
+ {Inf(-1), -Pi},
+ {Inf(-1), 0},
+ {Inf(-1), Pi},
+ {Inf(-1), Inf(1)},
+ {Inf(-1), NaN()},
+ {-Pi, Inf(-1)},
+ {-Pi, 0},
+ {-Pi, Inf(1)},
+ {-Pi, NaN()},
+ {Copysign(0, -1), Inf(-1)},
+ {Copysign(0, -1), 0},
+ {Copysign(0, -1), Inf(1)},
+ {Copysign(0, -1), NaN()},
+ {0, Inf(-1)},
+ {0, 0},
+ {0, Inf(1)},
+ {0, NaN()},
+ {Pi, Inf(-1)},
+ {Pi, 0},
+ {Pi, Inf(1)},
+ {Pi, NaN()},
+ {Inf(1), Inf(-1)},
+ {Inf(1), -Pi},
+ {Inf(1), 0},
+ {Inf(1), Pi},
+ {Inf(1), Inf(1)},
+ {Inf(1), NaN()},
+ {NaN(), Inf(-1)},
+ {NaN(), -Pi},
+ {NaN(), 0},
+ {NaN(), Pi},
+ {NaN(), Inf(1)},
+ {NaN(), NaN()},
+}
+var fmodSC = []float64{
+ NaN(), // fmod(-Inf, -Inf)
+ NaN(), // fmod(-Inf, -Pi)
+ NaN(), // fmod(-Inf, 0)
+ NaN(), // fmod(-Inf, Pi)
+ NaN(), // fmod(-Inf, +Inf)
+ NaN(), // fmod(-Inf, NaN)
+ -Pi, // fmod(-Pi, -Inf)
+ NaN(), // fmod(-Pi, 0)
+ -Pi, // fmod(-Pi, +Inf)
+ NaN(), // fmod(-Pi, NaN)
+ Copysign(0, -1), // fmod(-0, -Inf)
+ NaN(), // fmod(-0, 0)
+ Copysign(0, -1), // fmod(-0, Inf)
+ NaN(), // fmod(-0, NaN)
+ 0, // fmod(0, -Inf)
+ NaN(), // fmod(0, 0)
+ 0, // fmod(0, +Inf)
+ NaN(), // fmod(0, NaN)
+ Pi, // fmod(Pi, -Inf)
+ NaN(), // fmod(Pi, 0)
+ Pi, // fmod(Pi, +Inf)
+ NaN(), // fmod(Pi, NaN)
+ NaN(), // fmod(+Inf, -Inf)
+ NaN(), // fmod(+Inf, -Pi)
+ NaN(), // fmod(+Inf, 0)
+ NaN(), // fmod(+Inf, Pi)
+ NaN(), // fmod(+Inf, +Inf)
+ NaN(), // fmod(+Inf, NaN)
+ NaN(), // fmod(NaN, -Inf)
+ NaN(), // fmod(NaN, -Pi)
+ NaN(), // fmod(NaN, 0)
+ NaN(), // fmod(NaN, Pi)
+ NaN(), // fmod(NaN, +Inf)
+ NaN(), // fmod(NaN, NaN)
+}
+
+var vffrexpSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var frexpSC = []fi{
+ {Inf(-1), 0},
+ {Copysign(0, -1), 0},
+ {0, 0},
+ {Inf(1), 0},
+ {NaN(), 0},
+}
+
+var vfgamma = [][2]float64{
+ {Inf(1), Inf(1)},
+ {Inf(-1), NaN()},
+ {0, Inf(1)},
+ {Copysign(0, -1), Inf(-1)},
+ {NaN(), NaN()},
+ {-1, NaN()},
+ {-2, NaN()},
+ {-3, NaN()},
+ {-1e16, NaN()},
+ {-1e300, NaN()},
+ {1.7e308, Inf(1)},
+
+ // Test inputs inspired by Python test suite.
+ // Outputs computed at high precision by PARI/GP.
+ // If recomputing table entries, be careful to use
+ // high-precision (%.1000g) formatting of the float64 inputs.
+ // For example, -2.0000000000000004 is the float64 with exact value
+ // -2.00000000000000044408920985626161695, and
+ // gamma(-2.0000000000000004) = -1249999999999999.5386078562728167651513, while
+ // gamma(-2.00000000000000044408920985626161695) = -1125899906826907.2044875028130093136826.
+ // Thus the table lists -1.1258999068426235e+15 as the answer.
+ {0.5, 1.772453850905516},
+ {1.5, 0.886226925452758},
+ {2.5, 1.329340388179137},
+ {3.5, 3.3233509704478426},
+ {-0.5, -3.544907701811032},
+ {-1.5, 2.363271801207355},
+ {-2.5, -0.9453087204829419},
+ {-3.5, 0.2700882058522691},
+ {0.1, 9.51350769866873},
+ {0.01, 99.4325851191506},
+ {1e-08, 9.999999942278434e+07},
+ {1e-16, 1e+16},
+ {0.001, 999.4237724845955},
+ {1e-16, 1e+16},
+ {1e-308, 1e+308},
+ {5.6e-309, 1.7857142857142864e+308},
+ {5.5e-309, Inf(1)},
+ {1e-309, Inf(1)},
+ {1e-323, Inf(1)},
+ {5e-324, Inf(1)},
+ {-0.1, -10.686287021193193},
+ {-0.01, -100.58719796441078},
+ {-1e-08, -1.0000000057721567e+08},
+ {-1e-16, -1e+16},
+ {-0.001, -1000.5782056293586},
+ {-1e-16, -1e+16},
+ {-1e-308, -1e+308},
+ {-5.6e-309, -1.7857142857142864e+308},
+ {-5.5e-309, Inf(-1)},
+ {-1e-309, Inf(-1)},
+ {-1e-323, Inf(-1)},
+ {-5e-324, Inf(-1)},
+ {-0.9999999999999999, -9.007199254740992e+15},
+ {-1.0000000000000002, 4.5035996273704955e+15},
+ {-1.9999999999999998, 2.2517998136852485e+15},
+ {-2.0000000000000004, -1.1258999068426235e+15},
+ {-100.00000000000001, -7.540083334883109e-145},
+ {-99.99999999999999, 7.540083334884096e-145},
+ {17, 2.0922789888e+13},
+ {171, 7.257415615307999e+306},
+ {171.6, 1.5858969096672565e+308},
+ {171.624, 1.7942117599248104e+308},
+ {171.625, Inf(1)},
+ {172, Inf(1)},
+ {2000, Inf(1)},
+ {-100.5, -3.3536908198076787e-159},
+ {-160.5, -5.255546447007829e-286},
+ {-170.5, -3.3127395215386074e-308},
+ {-171.5, 1.9316265431712e-310},
+ {-176.5, -1.196e-321},
+ {-177.5, 5e-324},
+ {-178.5, Copysign(0, -1)},
+ {-179.5, 0},
+ {-201.0001, 0},
+ {-202.9999, Copysign(0, -1)},
+ {-1000.5, Copysign(0, -1)},
+ {-1.0000000003e+09, Copysign(0, -1)},
+ {-4.5035996273704955e+15, 0},
+ {-63.349078729022985, 4.177797167776188e-88},
+ {-127.45117632943295, 1.183111089623681e-214},
+}
+
+var vfhypotSC = [][2]float64{
+ {Inf(-1), Inf(-1)},
+ {Inf(-1), 0},
+ {Inf(-1), Inf(1)},
+ {Inf(-1), NaN()},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Copysign(0, -1), 0},
+ {0, Copysign(0, -1)},
+ {0, 0}, // +0, +0
+ {0, Inf(-1)},
+ {0, Inf(1)},
+ {0, NaN()},
+ {Inf(1), Inf(-1)},
+ {Inf(1), 0},
+ {Inf(1), Inf(1)},
+ {Inf(1), NaN()},
+ {NaN(), Inf(-1)},
+ {NaN(), 0},
+ {NaN(), Inf(1)},
+ {NaN(), NaN()},
+}
+var hypotSC = []float64{
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ 0,
+ 0,
+ 0,
+ 0,
+ Inf(1),
+ Inf(1),
+ NaN(),
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ Inf(1),
+ NaN(),
+ Inf(1),
+ NaN(),
+}
+
+var ilogbSC = []int{
+ MaxInt32,
+ MinInt32,
+ MaxInt32,
+ MaxInt32,
+}
+
+var vfj0SC = []float64{
+ Inf(-1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var j0SC = []float64{
+ 0,
+ 1,
+ 0,
+ NaN(),
+}
+var j1SC = []float64{
+ 0,
+ 0,
+ 0,
+ NaN(),
+}
+var j2SC = []float64{
+ 0,
+ 0,
+ 0,
+ NaN(),
+}
+var jM3SC = []float64{
+ 0,
+ 0,
+ 0,
+ NaN(),
+}
+
+var vfldexpSC = []fi{
+ {0, 0},
+ {0, -1075},
+ {0, 1024},
+ {Copysign(0, -1), 0},
+ {Copysign(0, -1), -1075},
+ {Copysign(0, -1), 1024},
+ {Inf(1), 0},
+ {Inf(1), -1024},
+ {Inf(-1), 0},
+ {Inf(-1), -1024},
+ {NaN(), -1024},
+ {10, int(1) << (uint64(unsafe.Sizeof(0)-1) * 8)},
+ {10, -(int(1) << (uint64(unsafe.Sizeof(0)-1) * 8))},
+}
+var ldexpSC = []float64{
+ 0,
+ 0,
+ 0,
+ Copysign(0, -1),
+ Copysign(0, -1),
+ Copysign(0, -1),
+ Inf(1),
+ Inf(1),
+ Inf(-1),
+ Inf(-1),
+ NaN(),
+ Inf(1),
+ 0,
+}
+
+var vflgammaSC = []float64{
+ Inf(-1),
+ -3,
+ 0,
+ 1,
+ 2,
+ Inf(1),
+ NaN(),
+}
+var lgammaSC = []fi{
+ {Inf(-1), 1},
+ {Inf(1), 1},
+ {Inf(1), 1},
+ {0, 1},
+ {0, 1},
+ {Inf(1), 1},
+ {NaN(), 1},
+}
+
+var vflogSC = []float64{
+ Inf(-1),
+ -Pi,
+ Copysign(0, -1),
+ 0,
+ 1,
+ Inf(1),
+ NaN(),
+}
+var logSC = []float64{
+ NaN(),
+ NaN(),
+ Inf(-1),
+ Inf(-1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vflogbSC = []float64{
+ Inf(-1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var logbSC = []float64{
+ Inf(1),
+ Inf(-1),
+ Inf(1),
+ NaN(),
+}
+
+var vflog1pSC = []float64{
+ Inf(-1),
+ -Pi,
+ -1,
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ 4503599627370496.5, // Issue #29488
+}
+var log1pSC = []float64{
+ NaN(),
+ NaN(),
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ 36.04365338911715, // Issue #29488
+}
+
+var vfmodfSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ Inf(1),
+ NaN(),
+}
+var modfSC = [][2]float64{
+ {Inf(-1), NaN()}, // [2]float64{Copysign(0, -1), Inf(-1)},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Inf(1), NaN()}, // [2]float64{0, Inf(1)},
+ {NaN(), NaN()},
+}
+
+var vfnextafter32SC = [][2]float32{
+ {0, 0},
+ {0, float32(Copysign(0, -1))},
+ {0, -1},
+ {0, float32(NaN())},
+ {float32(Copysign(0, -1)), 1},
+ {float32(Copysign(0, -1)), 0},
+ {float32(Copysign(0, -1)), float32(Copysign(0, -1))},
+ {float32(Copysign(0, -1)), -1},
+ {float32(NaN()), 0},
+ {float32(NaN()), float32(NaN())},
+}
+var nextafter32SC = []float32{
+ 0,
+ 0,
+ -1.401298464e-45, // Float32frombits(0x80000001)
+ float32(NaN()),
+ 1.401298464e-45, // Float32frombits(0x00000001)
+ float32(Copysign(0, -1)),
+ float32(Copysign(0, -1)),
+ -1.401298464e-45, // Float32frombits(0x80000001)
+ float32(NaN()),
+ float32(NaN()),
+}
+
+var vfnextafter64SC = [][2]float64{
+ {0, 0},
+ {0, Copysign(0, -1)},
+ {0, -1},
+ {0, NaN()},
+ {Copysign(0, -1), 1},
+ {Copysign(0, -1), 0},
+ {Copysign(0, -1), Copysign(0, -1)},
+ {Copysign(0, -1), -1},
+ {NaN(), 0},
+ {NaN(), NaN()},
+}
+var nextafter64SC = []float64{
+ 0,
+ 0,
+ -4.9406564584124654418e-324, // Float64frombits(0x8000000000000001)
+ NaN(),
+ 4.9406564584124654418e-324, // Float64frombits(0x0000000000000001)
+ Copysign(0, -1),
+ Copysign(0, -1),
+ -4.9406564584124654418e-324, // Float64frombits(0x8000000000000001)
+ NaN(),
+ NaN(),
+}
+
+var vfpowSC = [][2]float64{
+ {Inf(-1), -Pi},
+ {Inf(-1), -3},
+ {Inf(-1), Copysign(0, -1)},
+ {Inf(-1), 0},
+ {Inf(-1), 1},
+ {Inf(-1), 3},
+ {Inf(-1), Pi},
+ {Inf(-1), 0.5},
+ {Inf(-1), NaN()},
+
+ {-Pi, Inf(-1)},
+ {-Pi, -Pi},
+ {-Pi, Copysign(0, -1)},
+ {-Pi, 0},
+ {-Pi, 1},
+ {-Pi, Pi},
+ {-Pi, Inf(1)},
+ {-Pi, NaN()},
+
+ {-1, Inf(-1)},
+ {-1, Inf(1)},
+ {-1, NaN()},
+ {-0.5, Inf(-1)},
+ {-0.5, Inf(1)},
+ {Copysign(0, -1), Inf(-1)},
+ {Copysign(0, -1), -Pi},
+ {Copysign(0, -1), -0.5},
+ {Copysign(0, -1), -3},
+ {Copysign(0, -1), 3},
+ {Copysign(0, -1), Pi},
+ {Copysign(0, -1), 0.5},
+ {Copysign(0, -1), Inf(1)},
+
+ {0, Inf(-1)},
+ {0, -Pi},
+ {0, -3},
+ {0, Copysign(0, -1)},
+ {0, 0},
+ {0, 3},
+ {0, Pi},
+ {0, Inf(1)},
+ {0, NaN()},
+
+ {0.5, Inf(-1)},
+ {0.5, Inf(1)},
+ {1, Inf(-1)},
+ {1, Inf(1)},
+ {1, NaN()},
+
+ {Pi, Inf(-1)},
+ {Pi, Copysign(0, -1)},
+ {Pi, 0},
+ {Pi, 1},
+ {Pi, Inf(1)},
+ {Pi, NaN()},
+ {Inf(1), -Pi},
+ {Inf(1), Copysign(0, -1)},
+ {Inf(1), 0},
+ {Inf(1), 1},
+ {Inf(1), Pi},
+ {Inf(1), NaN()},
+ {NaN(), -Pi},
+ {NaN(), Copysign(0, -1)},
+ {NaN(), 0},
+ {NaN(), 1},
+ {NaN(), Pi},
+ {NaN(), NaN()},
+
+ // Issue #7394 overflow checks
+ {2, float64(1 << 32)},
+ {2, -float64(1 << 32)},
+ {-2, float64(1<<32 + 1)},
+ {0.5, float64(1 << 45)},
+ {0.5, -float64(1 << 45)},
+ {Nextafter(1, 2), float64(1 << 63)},
+ {Nextafter(1, -2), float64(1 << 63)},
+ {Nextafter(-1, 2), float64(1 << 63)},
+ {Nextafter(-1, -2), float64(1 << 63)},
+
+ // Issue #57465
+ {Copysign(0, -1), 1e19},
+ {Copysign(0, -1), -1e19},
+ {Copysign(0, -1), 1<<53 - 1},
+ {Copysign(0, -1), -(1<<53 - 1)},
+}
+var powSC = []float64{
+ 0, // pow(-Inf, -Pi)
+ Copysign(0, -1), // pow(-Inf, -3)
+ 1, // pow(-Inf, -0)
+ 1, // pow(-Inf, +0)
+ Inf(-1), // pow(-Inf, 1)
+ Inf(-1), // pow(-Inf, 3)
+ Inf(1), // pow(-Inf, Pi)
+ Inf(1), // pow(-Inf, 0.5)
+ NaN(), // pow(-Inf, NaN)
+ 0, // pow(-Pi, -Inf)
+ NaN(), // pow(-Pi, -Pi)
+ 1, // pow(-Pi, -0)
+ 1, // pow(-Pi, +0)
+ -Pi, // pow(-Pi, 1)
+ NaN(), // pow(-Pi, Pi)
+ Inf(1), // pow(-Pi, +Inf)
+ NaN(), // pow(-Pi, NaN)
+ 1, // pow(-1, -Inf) IEEE 754-2008
+ 1, // pow(-1, +Inf) IEEE 754-2008
+ NaN(), // pow(-1, NaN)
+ Inf(1), // pow(-1/2, -Inf)
+ 0, // pow(-1/2, +Inf)
+ Inf(1), // pow(-0, -Inf)
+ Inf(1), // pow(-0, -Pi)
+ Inf(1), // pow(-0, -0.5)
+ Inf(-1), // pow(-0, -3) IEEE 754-2008
+ Copysign(0, -1), // pow(-0, 3) IEEE 754-2008
+ 0, // pow(-0, +Pi)
+ 0, // pow(-0, 0.5)
+ 0, // pow(-0, +Inf)
+ Inf(1), // pow(+0, -Inf)
+ Inf(1), // pow(+0, -Pi)
+ Inf(1), // pow(+0, -3)
+ 1, // pow(+0, -0)
+ 1, // pow(+0, +0)
+ 0, // pow(+0, 3)
+ 0, // pow(+0, +Pi)
+ 0, // pow(+0, +Inf)
+ NaN(), // pow(+0, NaN)
+ Inf(1), // pow(1/2, -Inf)
+ 0, // pow(1/2, +Inf)
+ 1, // pow(1, -Inf) IEEE 754-2008
+ 1, // pow(1, +Inf) IEEE 754-2008
+ 1, // pow(1, NaN) IEEE 754-2008
+ 0, // pow(+Pi, -Inf)
+ 1, // pow(+Pi, -0)
+ 1, // pow(+Pi, +0)
+ Pi, // pow(+Pi, 1)
+ Inf(1), // pow(+Pi, +Inf)
+ NaN(), // pow(+Pi, NaN)
+ 0, // pow(+Inf, -Pi)
+ 1, // pow(+Inf, -0)
+ 1, // pow(+Inf, +0)
+ Inf(1), // pow(+Inf, 1)
+ Inf(1), // pow(+Inf, Pi)
+ NaN(), // pow(+Inf, NaN)
+ NaN(), // pow(NaN, -Pi)
+ 1, // pow(NaN, -0)
+ 1, // pow(NaN, +0)
+ NaN(), // pow(NaN, 1)
+ NaN(), // pow(NaN, +Pi)
+ NaN(), // pow(NaN, NaN)
+
+ // Issue #7394 overflow checks
+ Inf(1), // pow(2, float64(1 << 32))
+ 0, // pow(2, -float64(1 << 32))
+ Inf(-1), // pow(-2, float64(1<<32 + 1))
+ 0, // pow(1/2, float64(1 << 45))
+ Inf(1), // pow(1/2, -float64(1 << 45))
+ Inf(1), // pow(Nextafter(1, 2), float64(1 << 63))
+ 0, // pow(Nextafter(1, -2), float64(1 << 63))
+ 0, // pow(Nextafter(-1, 2), float64(1 << 63))
+ Inf(1), // pow(Nextafter(-1, -2), float64(1 << 63))
+
+ // Issue #57465
+ 0, // pow(-0, 1e19)
+ Inf(1), // pow(-0, -1e19)
+ Copysign(0, -1), // pow(-0, 1<<53 -1)
+ Inf(-1), // pow(-0, -(1<<53 -1))
+}
+
+var vfpow10SC = []int{
+ MinInt32,
+ -324,
+ -323,
+ -50,
+ -22,
+ -1,
+ 0,
+ 1,
+ 22,
+ 50,
+ 100,
+ 200,
+ 308,
+ 309,
+ MaxInt32,
+}
+
+var pow10SC = []float64{
+ 0, // pow10(MinInt32)
+ 0, // pow10(-324)
+ 1.0e-323, // pow10(-323)
+ 1.0e-50, // pow10(-50)
+ 1.0e-22, // pow10(-22)
+ 1.0e-1, // pow10(-1)
+ 1.0e0, // pow10(0)
+ 1.0e1, // pow10(1)
+ 1.0e22, // pow10(22)
+ 1.0e50, // pow10(50)
+ 1.0e100, // pow10(100)
+ 1.0e200, // pow10(200)
+ 1.0e308, // pow10(308)
+ Inf(1), // pow10(309)
+ Inf(1), // pow10(MaxInt32)
+}
+
+var vfroundSC = [][2]float64{
+ {0, 0},
+ {1.390671161567e-309, 0}, // denormal
+ {0.49999999999999994, 0}, // 0.5-epsilon
+ {0.5, 1},
+ {0.5000000000000001, 1}, // 0.5+epsilon
+ {-1.5, -2},
+ {-2.5, -3},
+ {NaN(), NaN()},
+ {Inf(1), Inf(1)},
+ {2251799813685249.5, 2251799813685250}, // 1 bit fraction
+ {2251799813685250.5, 2251799813685251},
+ {4503599627370495.5, 4503599627370496}, // 1 bit fraction, rounding to 0 bit fraction
+ {4503599627370497, 4503599627370497}, // large integer
+}
+var vfroundEvenSC = [][2]float64{
+ {0, 0},
+ {1.390671161567e-309, 0}, // denormal
+ {0.49999999999999994, 0}, // 0.5-epsilon
+ {0.5, 0},
+ {0.5000000000000001, 1}, // 0.5+epsilon
+ {-1.5, -2},
+ {-2.5, -2},
+ {NaN(), NaN()},
+ {Inf(1), Inf(1)},
+ {2251799813685249.5, 2251799813685250}, // 1 bit fraction
+ {2251799813685250.5, 2251799813685250},
+ {4503599627370495.5, 4503599627370496}, // 1 bit fraction, rounding to 0 bit fraction
+ {4503599627370497, 4503599627370497}, // large integer
+}
+
+var vfsignbitSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var signbitSC = []bool{
+ true,
+ true,
+ false,
+ false,
+ false,
+}
+
+var vfsinSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var sinSC = []float64{
+ NaN(),
+ Copysign(0, -1),
+ 0,
+ NaN(),
+ NaN(),
+}
+
+var vfsinhSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var sinhSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+
+var vfsqrtSC = []float64{
+ Inf(-1),
+ -Pi,
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ Float64frombits(2), // subnormal; see https://golang.org/issue/13013
+}
+var sqrtSC = []float64{
+ NaN(),
+ NaN(),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+ 3.1434555694052576e-162,
+}
+
+var vftanhSC = []float64{
+ Inf(-1),
+ Copysign(0, -1),
+ 0,
+ Inf(1),
+ NaN(),
+}
+var tanhSC = []float64{
+ -1,
+ Copysign(0, -1),
+ 0,
+ 1,
+ NaN(),
+}
+
+var vfy0SC = []float64{
+ Inf(-1),
+ 0,
+ Inf(1),
+ NaN(),
+ -1,
+}
+var y0SC = []float64{
+ NaN(),
+ Inf(-1),
+ 0,
+ NaN(),
+ NaN(),
+}
+var y1SC = []float64{
+ NaN(),
+ Inf(-1),
+ 0,
+ NaN(),
+ NaN(),
+}
+var y2SC = []float64{
+ NaN(),
+ Inf(-1),
+ 0,
+ NaN(),
+ NaN(),
+}
+var yM3SC = []float64{
+ NaN(),
+ Inf(1),
+ 0,
+ NaN(),
+ NaN(),
+}
+
+// arguments and expected results for boundary cases
+const (
+ SmallestNormalFloat64 = 2.2250738585072014e-308 // 2**-1022
+ LargestSubnormalFloat64 = SmallestNormalFloat64 - SmallestNonzeroFloat64
+)
+
+var vffrexpBC = []float64{
+ SmallestNormalFloat64,
+ LargestSubnormalFloat64,
+ SmallestNonzeroFloat64,
+ MaxFloat64,
+ -SmallestNormalFloat64,
+ -LargestSubnormalFloat64,
+ -SmallestNonzeroFloat64,
+ -MaxFloat64,
+}
+var frexpBC = []fi{
+ {0.5, -1021},
+ {0.99999999999999978, -1022},
+ {0.5, -1073},
+ {0.99999999999999989, 1024},
+ {-0.5, -1021},
+ {-0.99999999999999978, -1022},
+ {-0.5, -1073},
+ {-0.99999999999999989, 1024},
+}
+
+var vfldexpBC = []fi{
+ {SmallestNormalFloat64, -52},
+ {LargestSubnormalFloat64, -51},
+ {SmallestNonzeroFloat64, 1074},
+ {MaxFloat64, -(1023 + 1074)},
+ {1, -1075},
+ {-1, -1075},
+ {1, 1024},
+ {-1, 1024},
+ {1.0000000000000002, -1075},
+ {1, -1075},
+}
+var ldexpBC = []float64{
+ SmallestNonzeroFloat64,
+ 1e-323, // 2**-1073
+ 1,
+ 1e-323, // 2**-1073
+ 0,
+ Copysign(0, -1),
+ Inf(1),
+ Inf(-1),
+ SmallestNonzeroFloat64,
+ 0,
+}
+
+var logbBC = []float64{
+ -1022,
+ -1023,
+ -1074,
+ 1023,
+ -1022,
+ -1023,
+ -1074,
+ 1023,
+}
+
+// Test cases were generated with Berkeley TestFloat-3e/testfloat_gen.
+// http://www.jhauser.us/arithmetic/TestFloat.html.
+// The default rounding mode is selected (nearest/even), and exception flags are ignored.
+var fmaC = []struct{ x, y, z, want float64 }{
+ // Large exponent spread
+ {-3.999999999999087, -1.1123914289620494e-16, -7.999877929687506, -7.999877929687505},
+ {-262112.0000004768, -0.06251525855623184, 1.1102230248837136e-16, 16385.99945072085},
+ {-6.462348523533467e-27, -2.3763644720331857e-211, 4.000000000931324, 4.000000000931324},
+
+ // Effective addition
+ {-2.0000000037252907, 6.7904383376e-313, -3.3951933161e-313, -1.697607001654e-312},
+ {-0.12499999999999999, 512.007568359375, -1.4193627164960366e-16, -64.00094604492188},
+ {-2.7550648847397148e-39, -3.4028301595800694e+38, 0.9960937495343386, 1.9335955376735676},
+ {5.723369164769208e+24, 3.8149300927159385e-06, 1.84489958778182e+19, 4.028324913621874e+19},
+ {-0.4843749999990904, -3.6893487872543293e+19, 9.223653786709391e+18, 2.7093936974938993e+19},
+ {-3.8146972665201165e-06, 4.2949672959999385e+09, -2.2204460489938386e-16, -16384.000003844263},
+ {6.98156394130982e-309, -1.1072962560000002e+09, -4.4414561548793455e-308, -7.73065965765153e-300},
+
+ // Effective subtraction
+ {5e-324, 4.5, -2e-323, 0},
+ {5e-324, 7, -3.5e-323, 0},
+ {5e-324, 0.5000000000000001, -5e-324, Copysign(0, -1)},
+ {-2.1240680525e-314, -1.233647078189316e+308, -0.25781249999954525, -0.25780987964919844},
+ {8.579992955364441e-308, 0.6037391876780558, -4.4501307410480706e-308, 7.29947236107098e-309},
+ {-4.450143471986689e-308, -0.9960937499927239, -4.450419332475649e-308, -1.7659233458788e-310},
+ {1.4932076393918112, -2.2248022430460833e-308, 4.449875571054211e-308, 1.127783865601762e-308},
+
+ // Overflow
+ {-2.288020632214759e+38, -8.98846570988901e+307, 1.7696041796300924e+308, Inf(0)},
+ {1.4888652783208255e+308, -9.007199254742012e+15, -6.807282911929205e+38, Inf(-1)},
+ {9.142703268902826e+192, -1.3504889569802838e+296, -1.9082200803806996e-89, Inf(-1)},
+
+ // Finite x and y, but non-finite z.
+ {31.99218749627471, -1.7976930544991702e+308, Inf(0), Inf(0)},
+ {-1.7976931281784667e+308, -2.0009765625002265, Inf(-1), Inf(-1)},
+
+ // Special
+ {0, 0, 0, 0},
+ {Copysign(0, -1), 0, 0, 0},
+ {0, 0, Copysign(0, -1), 0},
+ {Copysign(0, -1), 0, Copysign(0, -1), Copysign(0, -1)},
+ {-1.1754226043408471e-38, NaN(), Inf(0), NaN()},
+ {0, 0, 2.22507385643494e-308, 2.22507385643494e-308},
+ {-8.65697792e+09, NaN(), -7.516192799999999e+09, NaN()},
+ {-0.00012207403779029757, 3.221225471996093e+09, NaN(), NaN()},
+ {Inf(-1), 0.1252441407414153, -1.387184532981584e-76, Inf(-1)},
+ {Inf(0), 1.525878907671432e-05, -9.214364835452549e+18, Inf(0)},
+
+ // Random
+ {0.1777916152213626, -32.000015266239636, -2.2204459148334633e-16, -5.689334401293007},
+ {-2.0816681711722314e-16, -0.4997558592585846, -0.9465627129124969, -0.9465627129124968},
+ {-1.9999997615814211, 1.8518819259933516e+19, 16.874999999999996, -3.703763410463646e+19},
+ {-0.12499994039717421, 32767.99999976135, -2.0752587082923246e+19, -2.075258708292325e+19},
+ {7.705600568510257e-34, -1.801432979000528e+16, -0.17224197722973714, -0.17224197722973716},
+ {3.8988133103758913e-308, -0.9848632812499999, 3.893879244098556e-308, 5.40811742605814e-310},
+ {-0.012651981190687427, 6.911985574912436e+38, 6.669240527007144e+18, -8.745031148409496e+36},
+ {4.612811918325842e+18, 1.4901161193847641e-08, 2.6077032311277997e-08, 6.873625395187494e+10},
+ {-9.094947033611148e-13, 4.450691014249257e-308, 2.086006742350485e-308, 2.086006742346437e-308},
+ {-7.751454006381804e-05, 5.588653777189071e-308, -2.2207280111272877e-308, -2.2211612130544025e-308},
+
+ // Issue #61130
+ {-1, 1, 1, 0},
+ {1, 1, -1, 0},
+}
+
+var sqrt32 = []float32{
+ 0,
+ float32(Copysign(0, -1)),
+ float32(NaN()),
+ float32(Inf(1)),
+ float32(Inf(-1)),
+ 1,
+ 2,
+ -2,
+ 4.9790119248836735e+00,
+ 7.7388724745781045e+00,
+ -2.7688005719200159e-01,
+ -5.0106036182710749e+00,
+}
+
+func tolerance(a, b, e float64) bool {
+ // Multiplying by e here can underflow denormal values to zero.
+ // Check a==b so that at least if a and b are small and identical
+ // we say they match.
+ if a == b {
+ return true
+ }
+ 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 close(a, b float64) bool { return tolerance(a, b, 1e-14) }
+func veryclose(a, b float64) bool { return tolerance(a, b, 4e-16) }
+func soclose(a, b, e float64) bool { return tolerance(a, b, e) }
+func alike(a, b float64) bool {
+ switch {
+ case IsNaN(a) && IsNaN(b):
+ return true
+ case a == b:
+ return Signbit(a) == Signbit(b)
+ }
+ return false
+}
+
+func TestNaN(t *testing.T) {
+ f64 := NaN()
+ if f64 == f64 {
+ t.Fatalf("NaN() returns %g, expected NaN", f64)
+ }
+ f32 := float32(f64)
+ if f32 == f32 {
+ t.Fatalf("float32(NaN()) is %g, expected NaN", f32)
+ }
+}
+
+func TestAcos(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Acos(a); !close(acos[i], f) {
+ t.Errorf("Acos(%g) = %g, want %g", a, f, acos[i])
+ }
+ }
+ for i := 0; i < len(vfacosSC); i++ {
+ if f := Acos(vfacosSC[i]); !alike(acosSC[i], f) {
+ t.Errorf("Acos(%g) = %g, want %g", vfacosSC[i], f, acosSC[i])
+ }
+ }
+}
+
+func TestAcosh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := 1 + Abs(vf[i])
+ if f := Acosh(a); !veryclose(acosh[i], f) {
+ t.Errorf("Acosh(%g) = %g, want %g", a, f, acosh[i])
+ }
+ }
+ for i := 0; i < len(vfacoshSC); i++ {
+ if f := Acosh(vfacoshSC[i]); !alike(acoshSC[i], f) {
+ t.Errorf("Acosh(%g) = %g, want %g", vfacoshSC[i], f, acoshSC[i])
+ }
+ }
+}
+
+func TestAsin(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Asin(a); !veryclose(asin[i], f) {
+ t.Errorf("Asin(%g) = %g, want %g", a, f, asin[i])
+ }
+ }
+ for i := 0; i < len(vfasinSC); i++ {
+ if f := Asin(vfasinSC[i]); !alike(asinSC[i], f) {
+ t.Errorf("Asin(%g) = %g, want %g", vfasinSC[i], f, asinSC[i])
+ }
+ }
+}
+
+func TestAsinh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Asinh(vf[i]); !veryclose(asinh[i], f) {
+ t.Errorf("Asinh(%g) = %g, want %g", vf[i], f, asinh[i])
+ }
+ }
+ for i := 0; i < len(vfasinhSC); i++ {
+ if f := Asinh(vfasinhSC[i]); !alike(asinhSC[i], f) {
+ t.Errorf("Asinh(%g) = %g, want %g", vfasinhSC[i], f, asinhSC[i])
+ }
+ }
+}
+
+func TestAtan(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Atan(vf[i]); !veryclose(atan[i], f) {
+ t.Errorf("Atan(%g) = %g, want %g", vf[i], f, atan[i])
+ }
+ }
+ for i := 0; i < len(vfatanSC); i++ {
+ if f := Atan(vfatanSC[i]); !alike(atanSC[i], f) {
+ t.Errorf("Atan(%g) = %g, want %g", vfatanSC[i], f, atanSC[i])
+ }
+ }
+}
+
+func TestAtanh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Atanh(a); !veryclose(atanh[i], f) {
+ t.Errorf("Atanh(%g) = %g, want %g", a, f, atanh[i])
+ }
+ }
+ for i := 0; i < len(vfatanhSC); i++ {
+ if f := Atanh(vfatanhSC[i]); !alike(atanhSC[i], f) {
+ t.Errorf("Atanh(%g) = %g, want %g", vfatanhSC[i], f, atanhSC[i])
+ }
+ }
+}
+
+func TestAtan2(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Atan2(10, vf[i]); !veryclose(atan2[i], f) {
+ t.Errorf("Atan2(10, %g) = %g, want %g", vf[i], f, atan2[i])
+ }
+ }
+ for i := 0; i < len(vfatan2SC); i++ {
+ if f := Atan2(vfatan2SC[i][0], vfatan2SC[i][1]); !alike(atan2SC[i], f) {
+ t.Errorf("Atan2(%g, %g) = %g, want %g", vfatan2SC[i][0], vfatan2SC[i][1], f, atan2SC[i])
+ }
+ }
+}
+
+func TestCbrt(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Cbrt(vf[i]); !veryclose(cbrt[i], f) {
+ t.Errorf("Cbrt(%g) = %g, want %g", vf[i], f, cbrt[i])
+ }
+ }
+ for i := 0; i < len(vfcbrtSC); i++ {
+ if f := Cbrt(vfcbrtSC[i]); !alike(cbrtSC[i], f) {
+ t.Errorf("Cbrt(%g) = %g, want %g", vfcbrtSC[i], f, cbrtSC[i])
+ }
+ }
+}
+
+func TestCeil(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Ceil(vf[i]); !alike(ceil[i], f) {
+ t.Errorf("Ceil(%g) = %g, want %g", vf[i], f, ceil[i])
+ }
+ }
+ for i := 0; i < len(vfceilSC); i++ {
+ if f := Ceil(vfceilSC[i]); !alike(ceilSC[i], f) {
+ t.Errorf("Ceil(%g) = %g, want %g", vfceilSC[i], f, ceilSC[i])
+ }
+ }
+}
+
+func TestCopysign(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Copysign(vf[i], -1); copysign[i] != f {
+ t.Errorf("Copysign(%g, -1) = %g, want %g", vf[i], f, copysign[i])
+ }
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := Copysign(vf[i], 1); -copysign[i] != f {
+ t.Errorf("Copysign(%g, 1) = %g, want %g", vf[i], f, -copysign[i])
+ }
+ }
+ for i := 0; i < len(vfcopysignSC); i++ {
+ if f := Copysign(vfcopysignSC[i], -1); !alike(copysignSC[i], f) {
+ t.Errorf("Copysign(%g, -1) = %g, want %g", vfcopysignSC[i], f, copysignSC[i])
+ }
+ }
+}
+
+func TestCos(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Cos(vf[i]); !veryclose(cos[i], f) {
+ t.Errorf("Cos(%g) = %g, want %g", vf[i], f, cos[i])
+ }
+ }
+ for i := 0; i < len(vfcosSC); i++ {
+ if f := Cos(vfcosSC[i]); !alike(cosSC[i], f) {
+ t.Errorf("Cos(%g) = %g, want %g", vfcosSC[i], f, cosSC[i])
+ }
+ }
+}
+
+func TestCosh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Cosh(vf[i]); !close(cosh[i], f) {
+ t.Errorf("Cosh(%g) = %g, want %g", vf[i], f, cosh[i])
+ }
+ }
+ for i := 0; i < len(vfcoshSC); i++ {
+ if f := Cosh(vfcoshSC[i]); !alike(coshSC[i], f) {
+ t.Errorf("Cosh(%g) = %g, want %g", vfcoshSC[i], f, coshSC[i])
+ }
+ }
+}
+
+func TestErf(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Erf(a); !veryclose(erf[i], f) {
+ t.Errorf("Erf(%g) = %g, want %g", a, f, erf[i])
+ }
+ }
+ for i := 0; i < len(vferfSC); i++ {
+ if f := Erf(vferfSC[i]); !alike(erfSC[i], f) {
+ t.Errorf("Erf(%g) = %g, want %g", vferfSC[i], f, erfSC[i])
+ }
+ }
+}
+
+func TestErfc(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Erfc(a); !veryclose(erfc[i], f) {
+ t.Errorf("Erfc(%g) = %g, want %g", a, f, erfc[i])
+ }
+ }
+ for i := 0; i < len(vferfcSC); i++ {
+ if f := Erfc(vferfcSC[i]); !alike(erfcSC[i], f) {
+ t.Errorf("Erfc(%g) = %g, want %g", vferfcSC[i], f, erfcSC[i])
+ }
+ }
+}
+
+func TestErfinv(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := Erfinv(a); !veryclose(erfinv[i], f) {
+ t.Errorf("Erfinv(%g) = %g, want %g", a, f, erfinv[i])
+ }
+ }
+ for i := 0; i < len(vferfinvSC); i++ {
+ if f := Erfinv(vferfinvSC[i]); !alike(erfinvSC[i], f) {
+ t.Errorf("Erfinv(%g) = %g, want %g", vferfinvSC[i], f, erfinvSC[i])
+ }
+ }
+ for x := -0.9; x <= 0.90; x += 1e-2 {
+ if f := Erf(Erfinv(x)); !close(x, f) {
+ t.Errorf("Erf(Erfinv(%g)) = %g, want %g", x, f, x)
+ }
+ }
+ for x := -0.9; x <= 0.90; x += 1e-2 {
+ if f := Erfinv(Erf(x)); !close(x, f) {
+ t.Errorf("Erfinv(Erf(%g)) = %g, want %g", x, f, x)
+ }
+ }
+}
+
+func TestErfcinv(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := 1.0 - (vf[i] / 10)
+ if f := Erfcinv(a); !veryclose(erfinv[i], f) {
+ t.Errorf("Erfcinv(%g) = %g, want %g", a, f, erfinv[i])
+ }
+ }
+ for i := 0; i < len(vferfcinvSC); i++ {
+ if f := Erfcinv(vferfcinvSC[i]); !alike(erfcinvSC[i], f) {
+ t.Errorf("Erfcinv(%g) = %g, want %g", vferfcinvSC[i], f, erfcinvSC[i])
+ }
+ }
+ for x := 0.1; x <= 1.9; x += 1e-2 {
+ if f := Erfc(Erfcinv(x)); !close(x, f) {
+ t.Errorf("Erfc(Erfcinv(%g)) = %g, want %g", x, f, x)
+ }
+ }
+ for x := 0.1; x <= 1.9; x += 1e-2 {
+ if f := Erfcinv(Erfc(x)); !close(x, f) {
+ t.Errorf("Erfcinv(Erfc(%g)) = %g, want %g", x, f, x)
+ }
+ }
+}
+
+func TestExp(t *testing.T) {
+ testExp(t, Exp, "Exp")
+ testExp(t, ExpGo, "ExpGo")
+}
+
+func testExp(t *testing.T, Exp func(float64) float64, name string) {
+ for i := 0; i < len(vf); i++ {
+ if f := Exp(vf[i]); !veryclose(exp[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp[i])
+ }
+ }
+ for i := 0; i < len(vfexpSC); i++ {
+ if f := Exp(vfexpSC[i]); !alike(expSC[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vfexpSC[i], f, expSC[i])
+ }
+ }
+}
+
+func TestExpm1(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 100
+ if f := Expm1(a); !veryclose(expm1[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1[i])
+ }
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] * 10
+ if f := Expm1(a); !close(expm1Large[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1Large[i])
+ }
+ }
+ for i := 0; i < len(vfexpm1SC); i++ {
+ if f := Expm1(vfexpm1SC[i]); !alike(expm1SC[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", vfexpm1SC[i], f, expm1SC[i])
+ }
+ }
+}
+
+func TestExp2(t *testing.T) {
+ testExp2(t, Exp2, "Exp2")
+ testExp2(t, Exp2Go, "Exp2Go")
+}
+
+func testExp2(t *testing.T, Exp2 func(float64) float64, name string) {
+ for i := 0; i < len(vf); i++ {
+ if f := Exp2(vf[i]); !close(exp2[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp2[i])
+ }
+ }
+ for i := 0; i < len(vfexp2SC); i++ {
+ if f := Exp2(vfexp2SC[i]); !alike(exp2SC[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vfexp2SC[i], f, exp2SC[i])
+ }
+ }
+ for n := -1074; n < 1024; n++ {
+ f := Exp2(float64(n))
+ vf := Ldexp(1, n)
+ if f != vf {
+ t.Errorf("%s(%d) = %g, want %g", name, n, f, vf)
+ }
+ }
+}
+
+func TestAbs(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Abs(vf[i]); fabs[i] != f {
+ t.Errorf("Abs(%g) = %g, want %g", vf[i], f, fabs[i])
+ }
+ }
+ for i := 0; i < len(vffabsSC); i++ {
+ if f := Abs(vffabsSC[i]); !alike(fabsSC[i], f) {
+ t.Errorf("Abs(%g) = %g, want %g", vffabsSC[i], f, fabsSC[i])
+ }
+ }
+}
+
+func TestDim(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Dim(vf[i], 0); fdim[i] != f {
+ t.Errorf("Dim(%g, %g) = %g, want %g", vf[i], 0.0, f, fdim[i])
+ }
+ }
+ for i := 0; i < len(vffdimSC); i++ {
+ if f := Dim(vffdimSC[i][0], vffdimSC[i][1]); !alike(fdimSC[i], f) {
+ t.Errorf("Dim(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fdimSC[i])
+ }
+ }
+ for i := 0; i < len(vffdim2SC); i++ {
+ if f := Dim(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fdimSC[i], f) {
+ t.Errorf("Dim(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fdimSC[i])
+ }
+ }
+}
+
+func TestFloor(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Floor(vf[i]); !alike(floor[i], f) {
+ t.Errorf("Floor(%g) = %g, want %g", vf[i], f, floor[i])
+ }
+ }
+ for i := 0; i < len(vfceilSC); i++ {
+ if f := Floor(vfceilSC[i]); !alike(ceilSC[i], f) {
+ t.Errorf("Floor(%g) = %g, want %g", vfceilSC[i], f, ceilSC[i])
+ }
+ }
+}
+
+func TestMax(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Max(vf[i], ceil[i]); ceil[i] != f {
+ t.Errorf("Max(%g, %g) = %g, want %g", vf[i], ceil[i], f, ceil[i])
+ }
+ }
+ for i := 0; i < len(vffdimSC); i++ {
+ if f := Max(vffdimSC[i][0], vffdimSC[i][1]); !alike(fmaxSC[i], f) {
+ t.Errorf("Max(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fmaxSC[i])
+ }
+ }
+ for i := 0; i < len(vffdim2SC); i++ {
+ if f := Max(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fmaxSC[i], f) {
+ t.Errorf("Max(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fmaxSC[i])
+ }
+ }
+}
+
+func TestMin(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Min(vf[i], floor[i]); floor[i] != f {
+ t.Errorf("Min(%g, %g) = %g, want %g", vf[i], floor[i], f, floor[i])
+ }
+ }
+ for i := 0; i < len(vffdimSC); i++ {
+ if f := Min(vffdimSC[i][0], vffdimSC[i][1]); !alike(fminSC[i], f) {
+ t.Errorf("Min(%g, %g) = %g, want %g", vffdimSC[i][0], vffdimSC[i][1], f, fminSC[i])
+ }
+ }
+ for i := 0; i < len(vffdim2SC); i++ {
+ if f := Min(vffdim2SC[i][0], vffdim2SC[i][1]); !alike(fminSC[i], f) {
+ t.Errorf("Min(%g, %g) = %g, want %g", vffdim2SC[i][0], vffdim2SC[i][1], f, fminSC[i])
+ }
+ }
+}
+
+func TestMod(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Mod(10, vf[i]); fmod[i] != f {
+ t.Errorf("Mod(10, %g) = %g, want %g", vf[i], f, fmod[i])
+ }
+ }
+ for i := 0; i < len(vffmodSC); i++ {
+ if f := Mod(vffmodSC[i][0], vffmodSC[i][1]); !alike(fmodSC[i], f) {
+ t.Errorf("Mod(%g, %g) = %g, want %g", vffmodSC[i][0], vffmodSC[i][1], f, fmodSC[i])
+ }
+ }
+ // verify precision of result for extreme inputs
+ if f := Mod(5.9790119248836734e+200, 1.1258465975523544); 0.6447968302508578 != f {
+ t.Errorf("Remainder(5.9790119248836734e+200, 1.1258465975523544) = %g, want 0.6447968302508578", f)
+ }
+}
+
+func TestFrexp(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f, j := Frexp(vf[i]); !veryclose(frexp[i].f, f) || frexp[i].i != j {
+ t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vf[i], f, j, frexp[i].f, frexp[i].i)
+ }
+ }
+ for i := 0; i < len(vffrexpSC); i++ {
+ if f, j := Frexp(vffrexpSC[i]); !alike(frexpSC[i].f, f) || frexpSC[i].i != j {
+ t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vffrexpSC[i], f, j, frexpSC[i].f, frexpSC[i].i)
+ }
+ }
+ for i := 0; i < len(vffrexpBC); i++ {
+ if f, j := Frexp(vffrexpBC[i]); !alike(frexpBC[i].f, f) || frexpBC[i].i != j {
+ t.Errorf("Frexp(%g) = %g, %d, want %g, %d", vffrexpBC[i], f, j, frexpBC[i].f, frexpBC[i].i)
+ }
+ }
+}
+
+func TestGamma(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Gamma(vf[i]); !close(gamma[i], f) {
+ t.Errorf("Gamma(%g) = %g, want %g", vf[i], f, gamma[i])
+ }
+ }
+ for _, g := range vfgamma {
+ f := Gamma(g[0])
+ var ok bool
+ if IsNaN(g[1]) || IsInf(g[1], 0) || g[1] == 0 || f == 0 {
+ ok = alike(g[1], f)
+ } else if g[0] > -50 && g[0] <= 171 {
+ ok = veryclose(g[1], f)
+ } else {
+ ok = close(g[1], f)
+ }
+ if !ok {
+ t.Errorf("Gamma(%g) = %g, want %g", g[0], f, g[1])
+ }
+ }
+}
+
+func TestHypot(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(1e200 * tanh[i] * Sqrt(2))
+ if f := Hypot(1e200*tanh[i], 1e200*tanh[i]); !veryclose(a, f) {
+ t.Errorf("Hypot(%g, %g) = %g, want %g", 1e200*tanh[i], 1e200*tanh[i], f, a)
+ }
+ }
+ for i := 0; i < len(vfhypotSC); i++ {
+ if f := Hypot(vfhypotSC[i][0], vfhypotSC[i][1]); !alike(hypotSC[i], f) {
+ t.Errorf("Hypot(%g, %g) = %g, want %g", vfhypotSC[i][0], vfhypotSC[i][1], f, hypotSC[i])
+ }
+ }
+}
+
+func TestHypotGo(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(1e200 * tanh[i] * Sqrt(2))
+ if f := HypotGo(1e200*tanh[i], 1e200*tanh[i]); !veryclose(a, f) {
+ t.Errorf("HypotGo(%g, %g) = %g, want %g", 1e200*tanh[i], 1e200*tanh[i], f, a)
+ }
+ }
+ for i := 0; i < len(vfhypotSC); i++ {
+ if f := HypotGo(vfhypotSC[i][0], vfhypotSC[i][1]); !alike(hypotSC[i], f) {
+ t.Errorf("HypotGo(%g, %g) = %g, want %g", vfhypotSC[i][0], vfhypotSC[i][1], f, hypotSC[i])
+ }
+ }
+}
+
+func TestIlogb(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := frexp[i].i - 1 // adjust because fr in the interval [½, 1)
+ if e := Ilogb(vf[i]); a != e {
+ t.Errorf("Ilogb(%g) = %d, want %d", vf[i], e, a)
+ }
+ }
+ for i := 0; i < len(vflogbSC); i++ {
+ if e := Ilogb(vflogbSC[i]); ilogbSC[i] != e {
+ t.Errorf("Ilogb(%g) = %d, want %d", vflogbSC[i], e, ilogbSC[i])
+ }
+ }
+ for i := 0; i < len(vffrexpBC); i++ {
+ if e := Ilogb(vffrexpBC[i]); int(logbBC[i]) != e {
+ t.Errorf("Ilogb(%g) = %d, want %d", vffrexpBC[i], e, int(logbBC[i]))
+ }
+ }
+}
+
+func TestJ0(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := J0(vf[i]); !soclose(j0[i], f, 4e-14) {
+ t.Errorf("J0(%g) = %g, want %g", vf[i], f, j0[i])
+ }
+ }
+ for i := 0; i < len(vfj0SC); i++ {
+ if f := J0(vfj0SC[i]); !alike(j0SC[i], f) {
+ t.Errorf("J0(%g) = %g, want %g", vfj0SC[i], f, j0SC[i])
+ }
+ }
+}
+
+func TestJ1(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := J1(vf[i]); !close(j1[i], f) {
+ t.Errorf("J1(%g) = %g, want %g", vf[i], f, j1[i])
+ }
+ }
+ for i := 0; i < len(vfj0SC); i++ {
+ if f := J1(vfj0SC[i]); !alike(j1SC[i], f) {
+ t.Errorf("J1(%g) = %g, want %g", vfj0SC[i], f, j1SC[i])
+ }
+ }
+}
+
+func TestJn(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Jn(2, vf[i]); !close(j2[i], f) {
+ t.Errorf("Jn(2, %g) = %g, want %g", vf[i], f, j2[i])
+ }
+ if f := Jn(-3, vf[i]); !close(jM3[i], f) {
+ t.Errorf("Jn(-3, %g) = %g, want %g", vf[i], f, jM3[i])
+ }
+ }
+ for i := 0; i < len(vfj0SC); i++ {
+ if f := Jn(2, vfj0SC[i]); !alike(j2SC[i], f) {
+ t.Errorf("Jn(2, %g) = %g, want %g", vfj0SC[i], f, j2SC[i])
+ }
+ if f := Jn(-3, vfj0SC[i]); !alike(jM3SC[i], f) {
+ t.Errorf("Jn(-3, %g) = %g, want %g", vfj0SC[i], f, jM3SC[i])
+ }
+ }
+}
+
+func TestLdexp(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Ldexp(frexp[i].f, frexp[i].i); !veryclose(vf[i], f) {
+ t.Errorf("Ldexp(%g, %d) = %g, want %g", frexp[i].f, frexp[i].i, f, vf[i])
+ }
+ }
+ for i := 0; i < len(vffrexpSC); i++ {
+ if f := Ldexp(frexpSC[i].f, frexpSC[i].i); !alike(vffrexpSC[i], f) {
+ t.Errorf("Ldexp(%g, %d) = %g, want %g", frexpSC[i].f, frexpSC[i].i, f, vffrexpSC[i])
+ }
+ }
+ for i := 0; i < len(vfldexpSC); i++ {
+ if f := Ldexp(vfldexpSC[i].f, vfldexpSC[i].i); !alike(ldexpSC[i], f) {
+ t.Errorf("Ldexp(%g, %d) = %g, want %g", vfldexpSC[i].f, vfldexpSC[i].i, f, ldexpSC[i])
+ }
+ }
+ for i := 0; i < len(vffrexpBC); i++ {
+ if f := Ldexp(frexpBC[i].f, frexpBC[i].i); !alike(vffrexpBC[i], f) {
+ t.Errorf("Ldexp(%g, %d) = %g, want %g", frexpBC[i].f, frexpBC[i].i, f, vffrexpBC[i])
+ }
+ }
+ for i := 0; i < len(vfldexpBC); i++ {
+ if f := Ldexp(vfldexpBC[i].f, vfldexpBC[i].i); !alike(ldexpBC[i], f) {
+ t.Errorf("Ldexp(%g, %d) = %g, want %g", vfldexpBC[i].f, vfldexpBC[i].i, f, ldexpBC[i])
+ }
+ }
+}
+
+func TestLgamma(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f, s := Lgamma(vf[i]); !close(lgamma[i].f, f) || lgamma[i].i != s {
+ t.Errorf("Lgamma(%g) = %g, %d, want %g, %d", vf[i], f, s, lgamma[i].f, lgamma[i].i)
+ }
+ }
+ for i := 0; i < len(vflgammaSC); i++ {
+ if f, s := Lgamma(vflgammaSC[i]); !alike(lgammaSC[i].f, f) || lgammaSC[i].i != s {
+ t.Errorf("Lgamma(%g) = %g, %d, want %g, %d", vflgammaSC[i], f, s, lgammaSC[i].f, lgammaSC[i].i)
+ }
+ }
+}
+
+func TestLog(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Log(a); log[i] != f {
+ t.Errorf("Log(%g) = %g, want %g", a, f, log[i])
+ }
+ }
+ if f := Log(10); f != Ln10 {
+ t.Errorf("Log(%g) = %g, want %g", 10.0, f, Ln10)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log(vflogSC[i]); !alike(logSC[i], f) {
+ t.Errorf("Log(%g) = %g, want %g", vflogSC[i], f, logSC[i])
+ }
+ }
+}
+
+func TestLogb(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Logb(vf[i]); logb[i] != f {
+ t.Errorf("Logb(%g) = %g, want %g", vf[i], f, logb[i])
+ }
+ }
+ for i := 0; i < len(vflogbSC); i++ {
+ if f := Logb(vflogbSC[i]); !alike(logbSC[i], f) {
+ t.Errorf("Logb(%g) = %g, want %g", vflogbSC[i], f, logbSC[i])
+ }
+ }
+ for i := 0; i < len(vffrexpBC); i++ {
+ if f := Logb(vffrexpBC[i]); !alike(logbBC[i], f) {
+ t.Errorf("Logb(%g) = %g, want %g", vffrexpBC[i], f, logbBC[i])
+ }
+ }
+}
+
+func TestLog10(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Log10(a); !veryclose(log10[i], f) {
+ t.Errorf("Log10(%g) = %g, want %g", a, f, log10[i])
+ }
+ }
+ if f := Log10(E); f != Log10E {
+ t.Errorf("Log10(%g) = %g, want %g", E, f, Log10E)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log10(vflogSC[i]); !alike(logSC[i], f) {
+ t.Errorf("Log10(%g) = %g, want %g", vflogSC[i], f, logSC[i])
+ }
+ }
+}
+
+func TestLog1p(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 100
+ if f := Log1p(a); !veryclose(log1p[i], f) {
+ t.Errorf("Log1p(%g) = %g, want %g", a, f, log1p[i])
+ }
+ }
+ a := 9.0
+ if f := Log1p(a); f != Ln10 {
+ t.Errorf("Log1p(%g) = %g, want %g", a, f, Ln10)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log1p(vflog1pSC[i]); !alike(log1pSC[i], f) {
+ t.Errorf("Log1p(%g) = %g, want %g", vflog1pSC[i], f, log1pSC[i])
+ }
+ }
+}
+
+func TestLog2(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Log2(a); !veryclose(log2[i], f) {
+ t.Errorf("Log2(%g) = %g, want %g", a, f, log2[i])
+ }
+ }
+ if f := Log2(E); f != Log2E {
+ t.Errorf("Log2(%g) = %g, want %g", E, f, Log2E)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log2(vflogSC[i]); !alike(logSC[i], f) {
+ t.Errorf("Log2(%g) = %g, want %g", vflogSC[i], f, logSC[i])
+ }
+ }
+ for i := -1074; i <= 1023; i++ {
+ f := Ldexp(1, i)
+ l := Log2(f)
+ if l != float64(i) {
+ t.Errorf("Log2(2**%d) = %g, want %d", i, l, i)
+ }
+ }
+}
+
+func TestModf(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f, g := Modf(vf[i]); !veryclose(modf[i][0], f) || !veryclose(modf[i][1], g) {
+ t.Errorf("Modf(%g) = %g, %g, want %g, %g", vf[i], f, g, modf[i][0], modf[i][1])
+ }
+ }
+ for i := 0; i < len(vfmodfSC); i++ {
+ if f, g := Modf(vfmodfSC[i]); !alike(modfSC[i][0], f) || !alike(modfSC[i][1], g) {
+ t.Errorf("Modf(%g) = %g, %g, want %g, %g", vfmodfSC[i], f, g, modfSC[i][0], modfSC[i][1])
+ }
+ }
+}
+
+func TestNextafter32(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ vfi := float32(vf[i])
+ if f := Nextafter32(vfi, 10); nextafter32[i] != f {
+ t.Errorf("Nextafter32(%g, %g) = %g want %g", vfi, 10.0, f, nextafter32[i])
+ }
+ }
+ for i := 0; i < len(vfnextafter32SC); i++ {
+ if f := Nextafter32(vfnextafter32SC[i][0], vfnextafter32SC[i][1]); !alike(float64(nextafter32SC[i]), float64(f)) {
+ t.Errorf("Nextafter32(%g, %g) = %g want %g", vfnextafter32SC[i][0], vfnextafter32SC[i][1], f, nextafter32SC[i])
+ }
+ }
+}
+
+func TestNextafter64(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Nextafter(vf[i], 10); nextafter64[i] != f {
+ t.Errorf("Nextafter64(%g, %g) = %g want %g", vf[i], 10.0, f, nextafter64[i])
+ }
+ }
+ for i := 0; i < len(vfnextafter64SC); i++ {
+ if f := Nextafter(vfnextafter64SC[i][0], vfnextafter64SC[i][1]); !alike(nextafter64SC[i], f) {
+ t.Errorf("Nextafter64(%g, %g) = %g want %g", vfnextafter64SC[i][0], vfnextafter64SC[i][1], f, nextafter64SC[i])
+ }
+ }
+}
+
+func TestPow(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Pow(10, vf[i]); !close(pow[i], f) {
+ t.Errorf("Pow(10, %g) = %g, want %g", vf[i], f, pow[i])
+ }
+ }
+ for i := 0; i < len(vfpowSC); i++ {
+ if f := Pow(vfpowSC[i][0], vfpowSC[i][1]); !alike(powSC[i], f) {
+ t.Errorf("Pow(%g, %g) = %g, want %g", vfpowSC[i][0], vfpowSC[i][1], f, powSC[i])
+ }
+ }
+}
+
+func TestPow10(t *testing.T) {
+ for i := 0; i < len(vfpow10SC); i++ {
+ if f := Pow10(vfpow10SC[i]); !alike(pow10SC[i], f) {
+ t.Errorf("Pow10(%d) = %g, want %g", vfpow10SC[i], f, pow10SC[i])
+ }
+ }
+}
+
+func TestRemainder(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Remainder(10, vf[i]); remainder[i] != f {
+ t.Errorf("Remainder(10, %g) = %g, want %g", vf[i], f, remainder[i])
+ }
+ }
+ for i := 0; i < len(vffmodSC); i++ {
+ if f := Remainder(vffmodSC[i][0], vffmodSC[i][1]); !alike(fmodSC[i], f) {
+ t.Errorf("Remainder(%g, %g) = %g, want %g", vffmodSC[i][0], vffmodSC[i][1], f, fmodSC[i])
+ }
+ }
+ // verify precision of result for extreme inputs
+ if f := Remainder(5.9790119248836734e+200, 1.1258465975523544); -0.4810497673014966 != f {
+ t.Errorf("Remainder(5.9790119248836734e+200, 1.1258465975523544) = %g, want -0.4810497673014966", f)
+ }
+ // verify that sign is correct when r == 0.
+ test := func(x, y float64) {
+ if r := Remainder(x, y); r == 0 && Signbit(r) != Signbit(x) {
+ t.Errorf("Remainder(x=%f, y=%f) = %f, sign of (zero) result should agree with sign of x", x, y, r)
+ }
+ }
+ for x := 0.0; x <= 3.0; x += 1 {
+ for y := 1.0; y <= 3.0; y += 1 {
+ test(x, y)
+ test(x, -y)
+ test(-x, y)
+ test(-x, -y)
+ }
+ }
+}
+
+func TestRound(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Round(vf[i]); !alike(round[i], f) {
+ t.Errorf("Round(%g) = %g, want %g", vf[i], f, round[i])
+ }
+ }
+ for i := 0; i < len(vfroundSC); i++ {
+ if f := Round(vfroundSC[i][0]); !alike(vfroundSC[i][1], f) {
+ t.Errorf("Round(%g) = %g, want %g", vfroundSC[i][0], f, vfroundSC[i][1])
+ }
+ }
+}
+
+func TestRoundToEven(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := RoundToEven(vf[i]); !alike(round[i], f) {
+ t.Errorf("RoundToEven(%g) = %g, want %g", vf[i], f, round[i])
+ }
+ }
+ for i := 0; i < len(vfroundEvenSC); i++ {
+ if f := RoundToEven(vfroundEvenSC[i][0]); !alike(vfroundEvenSC[i][1], f) {
+ t.Errorf("RoundToEven(%g) = %g, want %g", vfroundEvenSC[i][0], f, vfroundEvenSC[i][1])
+ }
+ }
+}
+
+func TestSignbit(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Signbit(vf[i]); signbit[i] != f {
+ t.Errorf("Signbit(%g) = %t, want %t", vf[i], f, signbit[i])
+ }
+ }
+ for i := 0; i < len(vfsignbitSC); i++ {
+ if f := Signbit(vfsignbitSC[i]); signbitSC[i] != f {
+ t.Errorf("Signbit(%g) = %t, want %t", vfsignbitSC[i], f, signbitSC[i])
+ }
+ }
+}
+func TestSin(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Sin(vf[i]); !veryclose(sin[i], f) {
+ t.Errorf("Sin(%g) = %g, want %g", vf[i], f, sin[i])
+ }
+ }
+ for i := 0; i < len(vfsinSC); i++ {
+ if f := Sin(vfsinSC[i]); !alike(sinSC[i], f) {
+ t.Errorf("Sin(%g) = %g, want %g", vfsinSC[i], f, sinSC[i])
+ }
+ }
+}
+
+func TestSincos(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if s, c := Sincos(vf[i]); !veryclose(sin[i], s) || !veryclose(cos[i], c) {
+ t.Errorf("Sincos(%g) = %g, %g want %g, %g", vf[i], s, c, sin[i], cos[i])
+ }
+ }
+}
+
+func TestSinh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Sinh(vf[i]); !close(sinh[i], f) {
+ t.Errorf("Sinh(%g) = %g, want %g", vf[i], f, sinh[i])
+ }
+ }
+ for i := 0; i < len(vfsinhSC); i++ {
+ if f := Sinh(vfsinhSC[i]); !alike(sinhSC[i], f) {
+ t.Errorf("Sinh(%g) = %g, want %g", vfsinhSC[i], f, sinhSC[i])
+ }
+ }
+}
+
+func TestSqrt(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := SqrtGo(a); sqrt[i] != f {
+ t.Errorf("SqrtGo(%g) = %g, want %g", a, f, sqrt[i])
+ }
+ a = Abs(vf[i])
+ if f := Sqrt(a); sqrt[i] != f {
+ t.Errorf("Sqrt(%g) = %g, want %g", a, f, sqrt[i])
+ }
+ }
+ for i := 0; i < len(vfsqrtSC); i++ {
+ if f := SqrtGo(vfsqrtSC[i]); !alike(sqrtSC[i], f) {
+ t.Errorf("SqrtGo(%g) = %g, want %g", vfsqrtSC[i], f, sqrtSC[i])
+ }
+ if f := Sqrt(vfsqrtSC[i]); !alike(sqrtSC[i], f) {
+ t.Errorf("Sqrt(%g) = %g, want %g", vfsqrtSC[i], f, sqrtSC[i])
+ }
+ }
+}
+
+func TestTan(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Tan(vf[i]); !veryclose(tan[i], f) {
+ t.Errorf("Tan(%g) = %g, want %g", vf[i], f, tan[i])
+ }
+ }
+ // same special cases as Sin
+ for i := 0; i < len(vfsinSC); i++ {
+ if f := Tan(vfsinSC[i]); !alike(sinSC[i], f) {
+ t.Errorf("Tan(%g) = %g, want %g", vfsinSC[i], f, sinSC[i])
+ }
+ }
+}
+
+func TestTanh(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Tanh(vf[i]); !veryclose(tanh[i], f) {
+ t.Errorf("Tanh(%g) = %g, want %g", vf[i], f, tanh[i])
+ }
+ }
+ for i := 0; i < len(vftanhSC); i++ {
+ if f := Tanh(vftanhSC[i]); !alike(tanhSC[i], f) {
+ t.Errorf("Tanh(%g) = %g, want %g", vftanhSC[i], f, tanhSC[i])
+ }
+ }
+}
+
+func TestTrunc(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ if f := Trunc(vf[i]); !alike(trunc[i], f) {
+ t.Errorf("Trunc(%g) = %g, want %g", vf[i], f, trunc[i])
+ }
+ }
+ for i := 0; i < len(vfceilSC); i++ {
+ if f := Trunc(vfceilSC[i]); !alike(ceilSC[i], f) {
+ t.Errorf("Trunc(%g) = %g, want %g", vfceilSC[i], f, ceilSC[i])
+ }
+ }
+}
+
+func TestY0(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Y0(a); !close(y0[i], f) {
+ t.Errorf("Y0(%g) = %g, want %g", a, f, y0[i])
+ }
+ }
+ for i := 0; i < len(vfy0SC); i++ {
+ if f := Y0(vfy0SC[i]); !alike(y0SC[i], f) {
+ t.Errorf("Y0(%g) = %g, want %g", vfy0SC[i], f, y0SC[i])
+ }
+ }
+}
+
+func TestY1(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Y1(a); !soclose(y1[i], f, 2e-14) {
+ t.Errorf("Y1(%g) = %g, want %g", a, f, y1[i])
+ }
+ }
+ for i := 0; i < len(vfy0SC); i++ {
+ if f := Y1(vfy0SC[i]); !alike(y1SC[i], f) {
+ t.Errorf("Y1(%g) = %g, want %g", vfy0SC[i], f, y1SC[i])
+ }
+ }
+}
+
+func TestYn(t *testing.T) {
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Yn(2, a); !close(y2[i], f) {
+ t.Errorf("Yn(2, %g) = %g, want %g", a, f, y2[i])
+ }
+ if f := Yn(-3, a); !close(yM3[i], f) {
+ t.Errorf("Yn(-3, %g) = %g, want %g", a, f, yM3[i])
+ }
+ }
+ for i := 0; i < len(vfy0SC); i++ {
+ if f := Yn(2, vfy0SC[i]); !alike(y2SC[i], f) {
+ t.Errorf("Yn(2, %g) = %g, want %g", vfy0SC[i], f, y2SC[i])
+ }
+ if f := Yn(-3, vfy0SC[i]); !alike(yM3SC[i], f) {
+ t.Errorf("Yn(-3, %g) = %g, want %g", vfy0SC[i], f, yM3SC[i])
+ }
+ }
+ if f := Yn(0, 0); !alike(Inf(-1), f) {
+ t.Errorf("Yn(0, 0) = %g, want %g", f, Inf(-1))
+ }
+}
+
+var PortableFMA = FMA // hide call from compiler intrinsic; falls back to portable code
+
+func TestFMA(t *testing.T) {
+ for _, c := range fmaC {
+ got := FMA(c.x, c.y, c.z)
+ if !alike(got, c.want) {
+ t.Errorf("FMA(%g,%g,%g) == %g; want %g", c.x, c.y, c.z, got, c.want)
+ }
+ got = PortableFMA(c.x, c.y, c.z)
+ if !alike(got, c.want) {
+ t.Errorf("PortableFMA(%g,%g,%g) == %g; want %g", c.x, c.y, c.z, got, c.want)
+ }
+ }
+}
+
+//go:noinline
+func fmsub(x, y, z float64) float64 {
+ return FMA(x, y, -z)
+}
+
+//go:noinline
+func fnmsub(x, y, z float64) float64 {
+ return FMA(-x, y, z)
+}
+
+//go:noinline
+func fnmadd(x, y, z float64) float64 {
+ return FMA(-x, y, -z)
+}
+
+func TestFMANegativeArgs(t *testing.T) {
+ // Some architectures have instructions for fused multiply-subtract and
+ // also negated variants of fused multiply-add and subtract. This test
+ // aims to check that the optimizations that generate those instructions
+ // are applied correctly, if they exist.
+ for _, c := range fmaC {
+ want := PortableFMA(c.x, c.y, -c.z)
+ got := fmsub(c.x, c.y, c.z)
+ if !alike(got, want) {
+ t.Errorf("FMA(%g, %g, -(%g)) == %g, want %g", c.x, c.y, c.z, got, want)
+ }
+ want = PortableFMA(-c.x, c.y, c.z)
+ got = fnmsub(c.x, c.y, c.z)
+ if !alike(got, want) {
+ t.Errorf("FMA(-(%g), %g, %g) == %g, want %g", c.x, c.y, c.z, got, want)
+ }
+ want = PortableFMA(-c.x, c.y, -c.z)
+ got = fnmadd(c.x, c.y, c.z)
+ if !alike(got, want) {
+ t.Errorf("FMA(-(%g), %g, -(%g)) == %g, want %g", c.x, c.y, c.z, got, want)
+ }
+ }
+}
+
+// Check that math functions of high angle values
+// return accurate results. [Since (vf[i] + large) - large != vf[i],
+// testing for Trig(vf[i] + large) == Trig(vf[i]), where large is
+// a multiple of 2*Pi, is misleading.]
+func TestLargeCos(t *testing.T) {
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := cosLarge[i]
+ f2 := Cos(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Cos(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+func TestLargeSin(t *testing.T) {
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := sinLarge[i]
+ f2 := Sin(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Sin(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+func TestLargeSincos(t *testing.T) {
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1, g1 := sinLarge[i], cosLarge[i]
+ f2, g2 := Sincos(vf[i] + large)
+ if !close(f1, f2) || !close(g1, g2) {
+ t.Errorf("Sincos(%g) = %g, %g, want %g, %g", vf[i]+large, f2, g2, f1, g1)
+ }
+ }
+}
+
+func TestLargeTan(t *testing.T) {
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := tanLarge[i]
+ f2 := Tan(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Tan(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+// Check that trigReduce matches the standard reduction results for input values
+// below reduceThreshold.
+func TestTrigReduce(t *testing.T) {
+ inputs := make([]float64, len(vf))
+ // all of the standard inputs
+ copy(inputs, vf)
+ // all of the large inputs
+ large := float64(100000 * Pi)
+ for _, v := range vf {
+ inputs = append(inputs, v+large)
+ }
+ // Also test some special inputs, Pi and right below the reduceThreshold
+ inputs = append(inputs, Pi, Nextafter(ReduceThreshold, 0))
+ for _, x := range inputs {
+ // reduce the value to compare
+ j, z := TrigReduce(x)
+ xred := float64(j)*(Pi/4) + z
+
+ if f, fred := Sin(x), Sin(xred); !close(f, fred) {
+ t.Errorf("Sin(trigReduce(%g)) != Sin(%g), got %g, want %g", x, x, fred, f)
+ }
+ if f, fred := Cos(x), Cos(xred); !close(f, fred) {
+ t.Errorf("Cos(trigReduce(%g)) != Cos(%g), got %g, want %g", x, x, fred, f)
+ }
+ if f, fred := Tan(x), Tan(xred); !close(f, fred) {
+ t.Errorf(" Tan(trigReduce(%g)) != Tan(%g), got %g, want %g", x, x, fred, f)
+ }
+ f, g := Sincos(x)
+ fred, gred := Sincos(xred)
+ if !close(f, fred) || !close(g, gred) {
+ t.Errorf(" Sincos(trigReduce(%g)) != Sincos(%g), got %g, %g, want %g, %g", x, x, fred, gred, f, g)
+ }
+ }
+}
+
+// Check that math constants are accepted by compiler
+// and have right value (assumes strconv.ParseFloat works).
+// https://golang.org/issue/201
+
+type floatTest struct {
+ val any
+ name string
+ str string
+}
+
+var floatTests = []floatTest{
+ {float64(MaxFloat64), "MaxFloat64", "1.7976931348623157e+308"},
+ {float64(SmallestNonzeroFloat64), "SmallestNonzeroFloat64", "5e-324"},
+ {float32(MaxFloat32), "MaxFloat32", "3.4028235e+38"},
+ {float32(SmallestNonzeroFloat32), "SmallestNonzeroFloat32", "1e-45"},
+}
+
+func TestFloatMinMax(t *testing.T) {
+ for _, tt := range floatTests {
+ s := fmt.Sprint(tt.val)
+ if s != tt.str {
+ t.Errorf("Sprint(%v) = %s, want %s", tt.name, s, tt.str)
+ }
+ }
+}
+
+func TestFloatMinima(t *testing.T) {
+ if q := float32(SmallestNonzeroFloat32 / 2); q != 0 {
+ t.Errorf("float32(SmallestNonzeroFloat32 / 2) = %g, want 0", q)
+ }
+ if q := float64(SmallestNonzeroFloat64 / 2); q != 0 {
+ t.Errorf("float64(SmallestNonzeroFloat64 / 2) = %g, want 0", q)
+ }
+}
+
+var indirectSqrt = Sqrt
+
+// TestFloat32Sqrt checks the correctness of the float32 square root optimization result.
+func TestFloat32Sqrt(t *testing.T) {
+ for _, v := range sqrt32 {
+ want := float32(indirectSqrt(float64(v)))
+ got := float32(Sqrt(float64(v)))
+ if IsNaN(float64(want)) {
+ if !IsNaN(float64(got)) {
+ t.Errorf("got=%#v want=NaN, v=%#v", got, v)
+ }
+ continue
+ }
+ if got != want {
+ t.Errorf("got=%#v want=%#v, v=%#v", got, want, v)
+ }
+ }
+}
+
+// Benchmarks
+
+// Global exported variables are used to store the
+// return values of functions measured in the benchmarks.
+// Storing the results in these variables prevents the compiler
+// from completely optimizing the benchmarked functions away.
+var (
+ GlobalI int
+ GlobalB bool
+ GlobalF float64
+)
+
+func BenchmarkAcos(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Acos(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAcosh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Acosh(1.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAsin(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Asin(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAsinh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Asinh(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAtan(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Atan(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAtanh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Atanh(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkAtan2(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Atan2(.5, 1)
+ }
+ GlobalF = x
+}
+
+func BenchmarkCbrt(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Cbrt(10)
+ }
+ GlobalF = x
+}
+
+func BenchmarkCeil(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Ceil(.5)
+ }
+ GlobalF = x
+}
+
+var copysignNeg = -1.0
+
+func BenchmarkCopysign(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Copysign(.5, copysignNeg)
+ }
+ GlobalF = x
+}
+
+func BenchmarkCos(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Cos(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkCosh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Cosh(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkErf(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Erf(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkErfc(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Erfc(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkErfinv(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Erfinv(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkErfcinv(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Erfcinv(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkExp(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Exp(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkExpGo(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = ExpGo(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkExpm1(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Expm1(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkExp2(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Exp2(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkExp2Go(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Exp2Go(.5)
+ }
+ GlobalF = x
+}
+
+var absPos = .5
+
+func BenchmarkAbs(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Abs(absPos)
+ }
+ GlobalF = x
+
+}
+
+func BenchmarkDim(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Dim(GlobalF, x)
+ }
+ GlobalF = x
+}
+
+func BenchmarkFloor(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Floor(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkMax(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Max(10, 3)
+ }
+ GlobalF = x
+}
+
+func BenchmarkMin(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Min(10, 3)
+ }
+ GlobalF = x
+}
+
+func BenchmarkMod(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Mod(10, 3)
+ }
+ GlobalF = x
+}
+
+func BenchmarkFrexp(b *testing.B) {
+ x := 0.0
+ y := 0
+ for i := 0; i < b.N; i++ {
+ x, y = Frexp(8)
+ }
+ GlobalF = x
+ GlobalI = y
+}
+
+func BenchmarkGamma(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Gamma(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkHypot(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Hypot(3, 4)
+ }
+ GlobalF = x
+}
+
+func BenchmarkHypotGo(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = HypotGo(3, 4)
+ }
+ GlobalF = x
+}
+
+func BenchmarkIlogb(b *testing.B) {
+ x := 0
+ for i := 0; i < b.N; i++ {
+ x = Ilogb(.5)
+ }
+ GlobalI = x
+}
+
+func BenchmarkJ0(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = J0(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkJ1(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = J1(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkJn(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Jn(2, 2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLdexp(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Ldexp(.5, 2)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLgamma(b *testing.B) {
+ x := 0.0
+ y := 0
+ for i := 0; i < b.N; i++ {
+ x, y = Lgamma(2.5)
+ }
+ GlobalF = x
+ GlobalI = y
+}
+
+func BenchmarkLog(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Log(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLogb(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Logb(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLog1p(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Log1p(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLog10(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Log10(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkLog2(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Log2(.5)
+ }
+ GlobalF += x
+}
+
+func BenchmarkModf(b *testing.B) {
+ x := 0.0
+ y := 0.0
+ for i := 0; i < b.N; i++ {
+ x, y = Modf(1.5)
+ }
+ GlobalF += x
+ GlobalF += y
+}
+
+func BenchmarkNextafter32(b *testing.B) {
+ x := float32(0.0)
+ for i := 0; i < b.N; i++ {
+ x = Nextafter32(.5, 1)
+ }
+ GlobalF = float64(x)
+}
+
+func BenchmarkNextafter64(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Nextafter(.5, 1)
+ }
+ GlobalF = x
+}
+
+func BenchmarkPowInt(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Pow(2, 2)
+ }
+ GlobalF = x
+}
+
+func BenchmarkPowFrac(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Pow(2.5, 1.5)
+ }
+ GlobalF = x
+}
+
+var pow10pos = int(300)
+
+func BenchmarkPow10Pos(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Pow10(pow10pos)
+ }
+ GlobalF = x
+}
+
+var pow10neg = int(-300)
+
+func BenchmarkPow10Neg(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Pow10(pow10neg)
+ }
+ GlobalF = x
+}
+
+var roundNeg = float64(-2.5)
+
+func BenchmarkRound(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Round(roundNeg)
+ }
+ GlobalF = x
+}
+
+func BenchmarkRoundToEven(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = RoundToEven(roundNeg)
+ }
+ GlobalF = x
+}
+
+func BenchmarkRemainder(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Remainder(10, 3)
+ }
+ GlobalF = x
+}
+
+var signbitPos = 2.5
+
+func BenchmarkSignbit(b *testing.B) {
+ x := false
+ for i := 0; i < b.N; i++ {
+ x = Signbit(signbitPos)
+ }
+ GlobalB = x
+}
+
+func BenchmarkSin(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Sin(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkSincos(b *testing.B) {
+ x := 0.0
+ y := 0.0
+ for i := 0; i < b.N; i++ {
+ x, y = Sincos(.5)
+ }
+ GlobalF += x
+ GlobalF += y
+}
+
+func BenchmarkSinh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Sinh(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkSqrtIndirect(b *testing.B) {
+ x, y := 0.0, 10.0
+ f := Sqrt
+ for i := 0; i < b.N; i++ {
+ x += f(y)
+ }
+ GlobalF = x
+}
+
+func BenchmarkSqrtLatency(b *testing.B) {
+ x := 10.0
+ for i := 0; i < b.N; i++ {
+ x = Sqrt(x)
+ }
+ GlobalF = x
+}
+
+func BenchmarkSqrtIndirectLatency(b *testing.B) {
+ x := 10.0
+ f := Sqrt
+ for i := 0; i < b.N; i++ {
+ x = f(x)
+ }
+ GlobalF = x
+}
+
+func BenchmarkSqrtGoLatency(b *testing.B) {
+ x := 10.0
+ for i := 0; i < b.N; i++ {
+ x = SqrtGo(x)
+ }
+ GlobalF = x
+}
+
+func isPrime(i int) bool {
+ // Yes, this is a dumb way to write this code,
+ // but calling Sqrt repeatedly in this way demonstrates
+ // the benefit of using a direct SQRT instruction on systems
+ // that have one, whereas the obvious loop seems not to
+ // demonstrate such a benefit.
+ for j := 2; float64(j) <= Sqrt(float64(i)); j++ {
+ if i%j == 0 {
+ return false
+ }
+ }
+ return true
+}
+
+func BenchmarkSqrtPrime(b *testing.B) {
+ x := false
+ for i := 0; i < b.N; i++ {
+ x = isPrime(100003)
+ }
+ GlobalB = x
+}
+
+func BenchmarkTan(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Tan(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkTanh(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Tanh(2.5)
+ }
+ GlobalF = x
+}
+func BenchmarkTrunc(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Trunc(.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkY0(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Y0(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkY1(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Y1(2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkYn(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Yn(2, 2.5)
+ }
+ GlobalF = x
+}
+
+func BenchmarkFloat64bits(b *testing.B) {
+ y := uint64(0)
+ for i := 0; i < b.N; i++ {
+ y = Float64bits(roundNeg)
+ }
+ GlobalI = int(y)
+}
+
+var roundUint64 = uint64(5)
+
+func BenchmarkFloat64frombits(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = Float64frombits(roundUint64)
+ }
+ GlobalF = x
+}
+
+var roundFloat32 = float32(-2.5)
+
+func BenchmarkFloat32bits(b *testing.B) {
+ y := uint32(0)
+ for i := 0; i < b.N; i++ {
+ y = Float32bits(roundFloat32)
+ }
+ GlobalI = int(y)
+}
+
+var roundUint32 = uint32(5)
+
+func BenchmarkFloat32frombits(b *testing.B) {
+ x := float32(0.0)
+ for i := 0; i < b.N; i++ {
+ x = Float32frombits(roundUint32)
+ }
+ GlobalF = float64(x)
+}
+
+func BenchmarkFMA(b *testing.B) {
+ x := 0.0
+ for i := 0; i < b.N; i++ {
+ x = FMA(E, Pi, x)
+ }
+ GlobalF = x
+}
diff --git a/platform/dbops/binaries/go/go/src/math/arith_s390x.go b/platform/dbops/binaries/go/go/src/math/arith_s390x.go
new file mode 100644
index 0000000000000000000000000000000000000000..129156a9f6d5940705c43425ed9f5ef3529608cc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/arith_s390x.go
@@ -0,0 +1,170 @@
+// 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 math
+
+import "internal/cpu"
+
+func expTrampolineSetup(x float64) float64
+func expAsm(x float64) float64
+
+func logTrampolineSetup(x float64) float64
+func logAsm(x float64) float64
+
+// Below here all functions are grouped in stubs.go for other
+// architectures.
+
+const haveArchLog10 = true
+
+func archLog10(x float64) float64
+func log10TrampolineSetup(x float64) float64
+func log10Asm(x float64) float64
+
+const haveArchCos = true
+
+func archCos(x float64) float64
+func cosTrampolineSetup(x float64) float64
+func cosAsm(x float64) float64
+
+const haveArchCosh = true
+
+func archCosh(x float64) float64
+func coshTrampolineSetup(x float64) float64
+func coshAsm(x float64) float64
+
+const haveArchSin = true
+
+func archSin(x float64) float64
+func sinTrampolineSetup(x float64) float64
+func sinAsm(x float64) float64
+
+const haveArchSinh = true
+
+func archSinh(x float64) float64
+func sinhTrampolineSetup(x float64) float64
+func sinhAsm(x float64) float64
+
+const haveArchTanh = true
+
+func archTanh(x float64) float64
+func tanhTrampolineSetup(x float64) float64
+func tanhAsm(x float64) float64
+
+const haveArchLog1p = true
+
+func archLog1p(x float64) float64
+func log1pTrampolineSetup(x float64) float64
+func log1pAsm(x float64) float64
+
+const haveArchAtanh = true
+
+func archAtanh(x float64) float64
+func atanhTrampolineSetup(x float64) float64
+func atanhAsm(x float64) float64
+
+const haveArchAcos = true
+
+func archAcos(x float64) float64
+func acosTrampolineSetup(x float64) float64
+func acosAsm(x float64) float64
+
+const haveArchAcosh = true
+
+func archAcosh(x float64) float64
+func acoshTrampolineSetup(x float64) float64
+func acoshAsm(x float64) float64
+
+const haveArchAsin = true
+
+func archAsin(x float64) float64
+func asinTrampolineSetup(x float64) float64
+func asinAsm(x float64) float64
+
+const haveArchAsinh = true
+
+func archAsinh(x float64) float64
+func asinhTrampolineSetup(x float64) float64
+func asinhAsm(x float64) float64
+
+const haveArchErf = true
+
+func archErf(x float64) float64
+func erfTrampolineSetup(x float64) float64
+func erfAsm(x float64) float64
+
+const haveArchErfc = true
+
+func archErfc(x float64) float64
+func erfcTrampolineSetup(x float64) float64
+func erfcAsm(x float64) float64
+
+const haveArchAtan = true
+
+func archAtan(x float64) float64
+func atanTrampolineSetup(x float64) float64
+func atanAsm(x float64) float64
+
+const haveArchAtan2 = true
+
+func archAtan2(y, x float64) float64
+func atan2TrampolineSetup(x, y float64) float64
+func atan2Asm(x, y float64) float64
+
+const haveArchCbrt = true
+
+func archCbrt(x float64) float64
+func cbrtTrampolineSetup(x float64) float64
+func cbrtAsm(x float64) float64
+
+const haveArchTan = true
+
+func archTan(x float64) float64
+func tanTrampolineSetup(x float64) float64
+func tanAsm(x float64) float64
+
+const haveArchExpm1 = true
+
+func archExpm1(x float64) float64
+func expm1TrampolineSetup(x float64) float64
+func expm1Asm(x float64) float64
+
+const haveArchPow = true
+
+func archPow(x, y float64) float64
+func powTrampolineSetup(x, y float64) float64
+func powAsm(x, y float64) float64
+
+const haveArchFrexp = false
+
+func archFrexp(x float64) (float64, int) {
+ panic("not implemented")
+}
+
+const haveArchLdexp = false
+
+func archLdexp(frac float64, exp int) float64 {
+ panic("not implemented")
+}
+
+const haveArchLog2 = false
+
+func archLog2(x float64) float64 {
+ panic("not implemented")
+}
+
+const haveArchMod = false
+
+func archMod(x, y float64) float64 {
+ panic("not implemented")
+}
+
+const haveArchRemainder = false
+
+func archRemainder(x, y float64) float64 {
+ panic("not implemented")
+}
+
+// hasVX reports whether the machine has the z/Architecture
+// vector facility installed and enabled.
+var hasVX = cpu.S390X.HasVX
diff --git a/platform/dbops/binaries/go/go/src/math/arith_s390x_test.go b/platform/dbops/binaries/go/go/src/math/arith_s390x_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..cfbc7b7823a93c3a3ae7457607c13e1b4f5ce640
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/arith_s390x_test.go
@@ -0,0 +1,442 @@
+// 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.
+
+// Tests whether the non vector routines are working, even when the tests are run on a
+// vector-capable machine.
+package math_test
+
+import (
+ . "math"
+ "testing"
+)
+
+func TestCosNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := CosNoVec(vf[i]); !veryclose(cos[i], f) {
+ t.Errorf("Cos(%g) = %g, want %g", vf[i], f, cos[i])
+ }
+ }
+ for i := 0; i < len(vfcosSC); i++ {
+ if f := CosNoVec(vfcosSC[i]); !alike(cosSC[i], f) {
+ t.Errorf("Cos(%g) = %g, want %g", vfcosSC[i], f, cosSC[i])
+ }
+ }
+}
+
+func TestCoshNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := CoshNoVec(vf[i]); !close(cosh[i], f) {
+ t.Errorf("Cosh(%g) = %g, want %g", vf[i], f, cosh[i])
+ }
+ }
+ for i := 0; i < len(vfcoshSC); i++ {
+ if f := CoshNoVec(vfcoshSC[i]); !alike(coshSC[i], f) {
+ t.Errorf("Cosh(%g) = %g, want %g", vfcoshSC[i], f, coshSC[i])
+ }
+ }
+}
+func TestSinNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := SinNoVec(vf[i]); !veryclose(sin[i], f) {
+ t.Errorf("Sin(%g) = %g, want %g", vf[i], f, sin[i])
+ }
+ }
+ for i := 0; i < len(vfsinSC); i++ {
+ if f := SinNoVec(vfsinSC[i]); !alike(sinSC[i], f) {
+ t.Errorf("Sin(%g) = %g, want %g", vfsinSC[i], f, sinSC[i])
+ }
+ }
+}
+
+func TestSinhNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := SinhNoVec(vf[i]); !close(sinh[i], f) {
+ t.Errorf("Sinh(%g) = %g, want %g", vf[i], f, sinh[i])
+ }
+ }
+ for i := 0; i < len(vfsinhSC); i++ {
+ if f := SinhNoVec(vfsinhSC[i]); !alike(sinhSC[i], f) {
+ t.Errorf("Sinh(%g) = %g, want %g", vfsinhSC[i], f, sinhSC[i])
+ }
+ }
+}
+
+// Check that math functions of high angle values
+// return accurate results. [Since (vf[i] + large) - large != vf[i],
+// testing for Trig(vf[i] + large) == Trig(vf[i]), where large is
+// a multiple of 2*Pi, is misleading.]
+func TestLargeCosNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := cosLarge[i]
+ f2 := CosNoVec(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Cos(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+func TestLargeSinNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := sinLarge[i]
+ f2 := SinNoVec(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Sin(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+func TestLargeTanNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ large := float64(100000 * Pi)
+ for i := 0; i < len(vf); i++ {
+ f1 := tanLarge[i]
+ f2 := TanNovec(vf[i] + large)
+ if !close(f1, f2) {
+ t.Errorf("Tan(%g) = %g, want %g", vf[i]+large, f2, f1)
+ }
+ }
+}
+
+func TestTanNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := TanNovec(vf[i]); !veryclose(tan[i], f) {
+ t.Errorf("Tan(%g) = %g, want %g", vf[i], f, tan[i])
+ }
+ }
+ // same special cases as Sin
+ for i := 0; i < len(vfsinSC); i++ {
+ if f := TanNovec(vfsinSC[i]); !alike(sinSC[i], f) {
+ t.Errorf("Tan(%g) = %g, want %g", vfsinSC[i], f, sinSC[i])
+ }
+ }
+}
+
+func TestTanhNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := TanhNoVec(vf[i]); !veryclose(tanh[i], f) {
+ t.Errorf("Tanh(%g) = %g, want %g", vf[i], f, tanh[i])
+ }
+ }
+ for i := 0; i < len(vftanhSC); i++ {
+ if f := TanhNoVec(vftanhSC[i]); !alike(tanhSC[i], f) {
+ t.Errorf("Tanh(%g) = %g, want %g", vftanhSC[i], f, tanhSC[i])
+ }
+ }
+
+}
+
+func TestLog10Novec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := Log10NoVec(a); !veryclose(log10[i], f) {
+ t.Errorf("Log10(%g) = %g, want %g", a, f, log10[i])
+ }
+ }
+ if f := Log10NoVec(E); f != Log10E {
+ t.Errorf("Log10(%g) = %g, want %g", E, f, Log10E)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log10NoVec(vflogSC[i]); !alike(logSC[i], f) {
+ t.Errorf("Log10(%g) = %g, want %g", vflogSC[i], f, logSC[i])
+ }
+ }
+}
+
+func TestLog1pNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 100
+ if f := Log1pNovec(a); !veryclose(log1p[i], f) {
+ t.Errorf("Log1p(%g) = %g, want %g", a, f, log1p[i])
+ }
+ }
+ a := 9.0
+ if f := Log1pNovec(a); f != Ln10 {
+ t.Errorf("Log1p(%g) = %g, want %g", a, f, Ln10)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := Log1pNovec(vflog1pSC[i]); !alike(log1pSC[i], f) {
+ t.Errorf("Log1p(%g) = %g, want %g", vflog1pSC[i], f, log1pSC[i])
+ }
+ }
+}
+
+func TestAtanhNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := AtanhNovec(a); !veryclose(atanh[i], f) {
+ t.Errorf("Atanh(%g) = %g, want %g", a, f, atanh[i])
+ }
+ }
+ for i := 0; i < len(vfatanhSC); i++ {
+ if f := AtanhNovec(vfatanhSC[i]); !alike(atanhSC[i], f) {
+ t.Errorf("Atanh(%g) = %g, want %g", vfatanhSC[i], f, atanhSC[i])
+ }
+ }
+}
+
+func TestAcosNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := AcosNovec(a); !close(acos[i], f) {
+ t.Errorf("Acos(%g) = %g, want %g", a, f, acos[i])
+ }
+ }
+ for i := 0; i < len(vfacosSC); i++ {
+ if f := AcosNovec(vfacosSC[i]); !alike(acosSC[i], f) {
+ t.Errorf("Acos(%g) = %g, want %g", vfacosSC[i], f, acosSC[i])
+ }
+ }
+}
+
+func TestAsinNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := AsinNovec(a); !veryclose(asin[i], f) {
+ t.Errorf("Asin(%g) = %g, want %g", a, f, asin[i])
+ }
+ }
+ for i := 0; i < len(vfasinSC); i++ {
+ if f := AsinNovec(vfasinSC[i]); !alike(asinSC[i], f) {
+ t.Errorf("Asin(%g) = %g, want %g", vfasinSC[i], f, asinSC[i])
+ }
+ }
+}
+
+func TestAcoshNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := 1 + Abs(vf[i])
+ if f := AcoshNovec(a); !veryclose(acosh[i], f) {
+ t.Errorf("Acosh(%g) = %g, want %g", a, f, acosh[i])
+ }
+ }
+ for i := 0; i < len(vfacoshSC); i++ {
+ if f := AcoshNovec(vfacoshSC[i]); !alike(acoshSC[i], f) {
+ t.Errorf("Acosh(%g) = %g, want %g", vfacoshSC[i], f, acoshSC[i])
+ }
+ }
+}
+
+func TestAsinhNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := AsinhNovec(vf[i]); !veryclose(asinh[i], f) {
+ t.Errorf("Asinh(%g) = %g, want %g", vf[i], f, asinh[i])
+ }
+ }
+ for i := 0; i < len(vfasinhSC); i++ {
+ if f := AsinhNovec(vfasinhSC[i]); !alike(asinhSC[i], f) {
+ t.Errorf("Asinh(%g) = %g, want %g", vfasinhSC[i], f, asinhSC[i])
+ }
+ }
+}
+
+func TestErfNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := ErfNovec(a); !veryclose(erf[i], f) {
+ t.Errorf("Erf(%g) = %g, want %g", a, f, erf[i])
+ }
+ }
+ for i := 0; i < len(vferfSC); i++ {
+ if f := ErfNovec(vferfSC[i]); !alike(erfSC[i], f) {
+ t.Errorf("Erf(%g) = %g, want %g", vferfSC[i], f, erfSC[i])
+ }
+ }
+}
+
+func TestErfcNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 10
+ if f := ErfcNovec(a); !veryclose(erfc[i], f) {
+ t.Errorf("Erfc(%g) = %g, want %g", a, f, erfc[i])
+ }
+ }
+ for i := 0; i < len(vferfcSC); i++ {
+ if f := ErfcNovec(vferfcSC[i]); !alike(erfcSC[i], f) {
+ t.Errorf("Erfc(%g) = %g, want %g", vferfcSC[i], f, erfcSC[i])
+ }
+ }
+}
+
+func TestAtanNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := AtanNovec(vf[i]); !veryclose(atan[i], f) {
+ t.Errorf("Atan(%g) = %g, want %g", vf[i], f, atan[i])
+ }
+ }
+ for i := 0; i < len(vfatanSC); i++ {
+ if f := AtanNovec(vfatanSC[i]); !alike(atanSC[i], f) {
+ t.Errorf("Atan(%g) = %g, want %g", vfatanSC[i], f, atanSC[i])
+ }
+ }
+}
+
+func TestAtan2Novec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := Atan2Novec(10, vf[i]); !veryclose(atan2[i], f) {
+ t.Errorf("Atan2(10, %g) = %g, want %g", vf[i], f, atan2[i])
+ }
+ }
+ for i := 0; i < len(vfatan2SC); i++ {
+ if f := Atan2Novec(vfatan2SC[i][0], vfatan2SC[i][1]); !alike(atan2SC[i], f) {
+ t.Errorf("Atan2(%g, %g) = %g, want %g", vfatan2SC[i][0], vfatan2SC[i][1], f, atan2SC[i])
+ }
+ }
+}
+
+func TestCbrtNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := CbrtNovec(vf[i]); !veryclose(cbrt[i], f) {
+ t.Errorf("Cbrt(%g) = %g, want %g", vf[i], f, cbrt[i])
+ }
+ }
+ for i := 0; i < len(vfcbrtSC); i++ {
+ if f := CbrtNovec(vfcbrtSC[i]); !alike(cbrtSC[i], f) {
+ t.Errorf("Cbrt(%g) = %g, want %g", vfcbrtSC[i], f, cbrtSC[i])
+ }
+ }
+}
+
+func TestLogNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := Abs(vf[i])
+ if f := LogNovec(a); log[i] != f {
+ t.Errorf("Log(%g) = %g, want %g", a, f, log[i])
+ }
+ }
+ if f := LogNovec(10); f != Ln10 {
+ t.Errorf("Log(%g) = %g, want %g", 10.0, f, Ln10)
+ }
+ for i := 0; i < len(vflogSC); i++ {
+ if f := LogNovec(vflogSC[i]); !alike(logSC[i], f) {
+ t.Errorf("Log(%g) = %g, want %g", vflogSC[i], f, logSC[i])
+ }
+ }
+}
+
+func TestExpNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ testExpNovec(t, Exp, "Exp")
+ testExpNovec(t, ExpGo, "ExpGo")
+}
+
+func testExpNovec(t *testing.T, Exp func(float64) float64, name string) {
+ for i := 0; i < len(vf); i++ {
+ if f := ExpNovec(vf[i]); !veryclose(exp[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vf[i], f, exp[i])
+ }
+ }
+ for i := 0; i < len(vfexpSC); i++ {
+ if f := ExpNovec(vfexpSC[i]); !alike(expSC[i], f) {
+ t.Errorf("%s(%g) = %g, want %g", name, vfexpSC[i], f, expSC[i])
+ }
+ }
+}
+
+func TestExpm1Novec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] / 100
+ if f := Expm1Novec(a); !veryclose(expm1[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1[i])
+ }
+ }
+ for i := 0; i < len(vf); i++ {
+ a := vf[i] * 10
+ if f := Expm1Novec(a); !close(expm1Large[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", a, f, expm1Large[i])
+ }
+ }
+ for i := 0; i < len(vfexpm1SC); i++ {
+ if f := Expm1Novec(vfexpm1SC[i]); !alike(expm1SC[i], f) {
+ t.Errorf("Expm1(%g) = %g, want %g", vfexpm1SC[i], f, expm1SC[i])
+ }
+ }
+}
+
+func TestPowNovec(t *testing.T) {
+ if !HasVX {
+ t.Skipf("no vector support")
+ }
+ for i := 0; i < len(vf); i++ {
+ if f := PowNovec(10, vf[i]); !close(pow[i], f) {
+ t.Errorf("Pow(10, %g) = %g, want %g", vf[i], f, pow[i])
+ }
+ }
+ for i := 0; i < len(vfpowSC); i++ {
+ if f := PowNovec(vfpowSC[i][0], vfpowSC[i][1]); !alike(powSC[i], f) {
+ t.Errorf("Pow(%g, %g) = %g, want %g", vfpowSC[i][0], vfpowSC[i][1], f, powSC[i])
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/asin.go b/platform/dbops/binaries/go/go/src/math/asin.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e1b2ab4916ed13202df297981a0346b6a51277a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/asin.go
@@ -0,0 +1,67 @@
+// 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 math
+
+/*
+ Floating-point arcsine and arccosine.
+
+ They are implemented by computing the arctangent
+ after appropriate range reduction.
+*/
+
+// Asin returns the arcsine, in radians, of x.
+//
+// Special cases are:
+//
+// Asin(±0) = ±0
+// Asin(x) = NaN if x < -1 or x > 1
+func Asin(x float64) float64 {
+ if haveArchAsin {
+ return archAsin(x)
+ }
+ return asin(x)
+}
+
+func asin(x float64) float64 {
+ if x == 0 {
+ return x // special case
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ if x > 1 {
+ return NaN() // special case
+ }
+
+ temp := Sqrt(1 - x*x)
+ if x > 0.7 {
+ temp = Pi/2 - satan(temp/x)
+ } else {
+ temp = satan(x / temp)
+ }
+
+ if sign {
+ temp = -temp
+ }
+ return temp
+}
+
+// Acos returns the arccosine, in radians, of x.
+//
+// Special case is:
+//
+// Acos(x) = NaN if x < -1 or x > 1
+func Acos(x float64) float64 {
+ if haveArchAcos {
+ return archAcos(x)
+ }
+ return acos(x)
+}
+
+func acos(x float64) float64 {
+ return Pi/2 - Asin(x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/asin_s390x.s b/platform/dbops/binaries/go/go/src/math/asin_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..dc54d053f1cab9f576a342e2a46bd72186da2bc0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/asin_s390x.s
@@ -0,0 +1,162 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·asinrodataL15<> + 0(SB)/8, $-1.309611320495605469
+DATA ·asinrodataL15<> + 8(SB)/8, $0x3ff921fb54442d18
+DATA ·asinrodataL15<> + 16(SB)/8, $0xbff921fb54442d18
+DATA ·asinrodataL15<> + 24(SB)/8, $1.309611320495605469
+DATA ·asinrodataL15<> + 32(SB)/8, $-0.0
+DATA ·asinrodataL15<> + 40(SB)/8, $1.199437040755305217
+DATA ·asinrodataL15<> + 48(SB)/8, $0.166666666666651626E+00
+DATA ·asinrodataL15<> + 56(SB)/8, $0.750000000042621169E-01
+DATA ·asinrodataL15<> + 64(SB)/8, $0.446428567178116477E-01
+DATA ·asinrodataL15<> + 72(SB)/8, $0.303819660378071894E-01
+DATA ·asinrodataL15<> + 80(SB)/8, $0.223715011892010405E-01
+DATA ·asinrodataL15<> + 88(SB)/8, $0.173659424522364952E-01
+DATA ·asinrodataL15<> + 96(SB)/8, $0.137810186504372266E-01
+DATA ·asinrodataL15<> + 104(SB)/8, $0.134066870961173521E-01
+DATA ·asinrodataL15<> + 112(SB)/8, $-.412335502831898721E-02
+DATA ·asinrodataL15<> + 120(SB)/8, $0.867383739532082719E-01
+DATA ·asinrodataL15<> + 128(SB)/8, $-.328765950607171649E+00
+DATA ·asinrodataL15<> + 136(SB)/8, $0.110401073869414626E+01
+DATA ·asinrodataL15<> + 144(SB)/8, $-.270694366992537307E+01
+DATA ·asinrodataL15<> + 152(SB)/8, $0.500196500770928669E+01
+DATA ·asinrodataL15<> + 160(SB)/8, $-.665866959108585165E+01
+DATA ·asinrodataL15<> + 168(SB)/8, $-.344895269334086578E+01
+DATA ·asinrodataL15<> + 176(SB)/8, $0.927437952918301659E+00
+DATA ·asinrodataL15<> + 184(SB)/8, $0.610487478874645653E+01
+DATA ·asinrodataL15<> + 192(SB)/8, $0x7ff8000000000000 //+Inf
+DATA ·asinrodataL15<> + 200(SB)/8, $-1.0
+DATA ·asinrodataL15<> + 208(SB)/8, $1.0
+DATA ·asinrodataL15<> + 216(SB)/8, $1.00000000000000000e-20
+GLOBL ·asinrodataL15<> + 0(SB), RODATA, $224
+
+// Asin returns the arcsine, in radians, of the argument.
+//
+// Special cases are:
+// Asin(±0) = ±0=
+// Asin(x) = NaN if x < -1 or x > 1
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·asinAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·asinrodataL15<>+0(SB), R9
+ LGDR F0, R7
+ FMOVD F0, F8
+ SRAD $32, R7
+ WORD $0xC0193FE6 //iilf %r1,1072079005
+ BYTE $0xA0
+ BYTE $0x9D
+ WORD $0xB91700C7 //llgtr %r12,%r7
+ MOVW R12, R8
+ MOVW R1, R6
+ CMPBGT R8, R6, L2
+ WORD $0xC0193BFF //iilf %r1,1006632959
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R1, R6
+ CMPBGT R8, R6, L13
+L3:
+ FMOVD 216(R9), F0
+ FMADD F0, F8, F8
+L1:
+ FMOVD F8, ret+8(FP)
+ RET
+L2:
+ WORD $0xC0193FEF //iilf %r1,1072693247
+ BYTE $0xFF
+ BYTE $0xFF
+ CMPW R12, R1
+ BLE L14
+L5:
+ WORD $0xED0090D0 //cdb %f0,.L17-.L15(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L9
+ WORD $0xED0090C8 //cdb %f0,.L18-.L15(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L10
+ WFCEDBS V8, V8, V0
+ BVS L1
+ FMOVD 192(R9), F8
+ BR L1
+L13:
+ WFMDB V0, V0, V10
+L4:
+ WFMDB V10, V10, V0
+ FMOVD 184(R9), F6
+ FMOVD 176(R9), F2
+ FMOVD 168(R9), F4
+ WFMADB V0, V2, V6, V2
+ FMOVD 160(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 152(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 144(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 136(R9), F6
+ WFMADB V0, V2, V6, V2
+ WORD $0xC0193FE6 //iilf %r1,1072079005
+ BYTE $0xA0
+ BYTE $0x9D
+ FMOVD 128(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 120(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 112(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 104(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 96(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 88(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 80(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 72(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 64(R9), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD 56(R9), F6
+ WFMADB V0, V2, V6, V2
+ FMOVD 48(R9), F6
+ WFMADB V0, V4, V6, V0
+ WFMDB V8, V10, V4
+ FMADD F2, F10, F0
+ FMADD F0, F4, F8
+ CMPW R12, R1
+ BLE L1
+ FMOVD 40(R9), F0
+ FMADD F0, F1, F8
+ FMOVD F8, ret+8(FP)
+ RET
+L14:
+ FMOVD 200(R9), F0
+ FMADD F8, F8, F0
+ WORD $0xB31300A0 //lcdbr %f10,%f0
+ WORD $0xED009020 //cdb %f0,.L39-.L15(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ FSQRT F10, F8
+L6:
+ MOVW R7, R6
+ CMPBLE R6, $0, L8
+ WORD $0xB3130088 //lcdbr %f8,%f8
+ FMOVD 24(R9), F1
+ BR L4
+L10:
+ FMOVD 16(R9), F8
+ BR L1
+L9:
+ FMOVD 8(R9), F8
+ FMOVD F8, ret+8(FP)
+ RET
+L8:
+ FMOVD 0(R9), F1
+ BR L4
diff --git a/platform/dbops/binaries/go/go/src/math/asinh.go b/platform/dbops/binaries/go/go/src/math/asinh.go
new file mode 100644
index 0000000000000000000000000000000000000000..d913239d1e2c681f34005f527e301a5bcdbbe8e4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/asinh.go
@@ -0,0 +1,77 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/s_asinh.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// asinh(x)
+// Method :
+// Based on
+// asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
+// we have
+// asinh(x) := x if 1+x*x=1,
+// := sign(x)*(log(x)+ln2) for large |x|, else
+// := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
+// := sign(x)*log1p(|x| + x**2/(1 + sqrt(1+x**2)))
+//
+
+// Asinh returns the inverse hyperbolic sine of x.
+//
+// Special cases are:
+//
+// Asinh(±0) = ±0
+// Asinh(±Inf) = ±Inf
+// Asinh(NaN) = NaN
+func Asinh(x float64) float64 {
+ if haveArchAsinh {
+ return archAsinh(x)
+ }
+ return asinh(x)
+}
+
+func asinh(x float64) float64 {
+ const (
+ Ln2 = 6.93147180559945286227e-01 // 0x3FE62E42FEFA39EF
+ NearZero = 1.0 / (1 << 28) // 2**-28
+ Large = 1 << 28 // 2**28
+ )
+ // special cases
+ if IsNaN(x) || IsInf(x, 0) {
+ return x
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ var temp float64
+ switch {
+ case x > Large:
+ temp = Log(x) + Ln2 // |x| > 2**28
+ case x > 2:
+ temp = Log(2*x + 1/(Sqrt(x*x+1)+x)) // 2**28 > |x| > 2.0
+ case x < NearZero:
+ temp = x // |x| < 2**-28
+ default:
+ temp = Log1p(x + x*x/(1+Sqrt(1+x*x))) // 2.0 > |x| > 2**-28
+ }
+ if sign {
+ temp = -temp
+ }
+ return temp
+}
diff --git a/platform/dbops/binaries/go/go/src/math/asinh_s390x.s b/platform/dbops/binaries/go/go/src/math/asinh_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..1bcf2954c44d65f4f3ee6667866d1e9d1a8abb5d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/asinh_s390x.s
@@ -0,0 +1,213 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·asinhrodataL18<> + 0(SB)/8, $0.749999999977387502E-01
+DATA ·asinhrodataL18<> + 8(SB)/8, $-.166666666666657082E+00
+DATA ·asinhrodataL18<> + 16(SB)/8, $0.303819368237360639E-01
+DATA ·asinhrodataL18<> + 24(SB)/8, $-.446428569571752982E-01
+DATA ·asinhrodataL18<> + 32(SB)/8, $0.173500047922695924E-01
+DATA ·asinhrodataL18<> + 40(SB)/8, $-.223719767210027185E-01
+DATA ·asinhrodataL18<> + 48(SB)/8, $0.113655037946822130E-01
+DATA ·asinhrodataL18<> + 56(SB)/8, $0.579747490622448943E-02
+DATA ·asinhrodataL18<> + 64(SB)/8, $-.139372433914359122E-01
+DATA ·asinhrodataL18<> + 72(SB)/8, $-.218674325255800840E-02
+DATA ·asinhrodataL18<> + 80(SB)/8, $-.891074277756961157E-02
+DATA ·asinhrodataL18<> + 88(SB)/8, $.41375273347623353626
+DATA ·asinhrodataL18<> + 96(SB)/8, $.51487302528619766235E+04
+DATA ·asinhrodataL18<> + 104(SB)/8, $-1.67526912689208984375
+DATA ·asinhrodataL18<> + 112(SB)/8, $0.181818181818181826E+00
+DATA ·asinhrodataL18<> + 120(SB)/8, $-.165289256198351540E-01
+DATA ·asinhrodataL18<> + 128(SB)/8, $0.200350613573012186E-02
+DATA ·asinhrodataL18<> + 136(SB)/8, $-.273205381970859341E-03
+DATA ·asinhrodataL18<> + 144(SB)/8, $0.397389654305194527E-04
+DATA ·asinhrodataL18<> + 152(SB)/8, $0.938370938292558173E-06
+DATA ·asinhrodataL18<> + 160(SB)/8, $0.212881813645679599E-07
+DATA ·asinhrodataL18<> + 168(SB)/8, $-.602107458843052029E-05
+DATA ·asinhrodataL18<> + 176(SB)/8, $-.148682720127920854E-06
+DATA ·asinhrodataL18<> + 184(SB)/8, $-5.5
+DATA ·asinhrodataL18<> + 192(SB)/8, $1.0
+DATA ·asinhrodataL18<> + 200(SB)/8, $1.0E-20
+GLOBL ·asinhrodataL18<> + 0(SB), RODATA, $208
+
+// Table of log correction terms
+DATA ·asinhtab2080<> + 0(SB)/8, $0.585235384085551248E-01
+DATA ·asinhtab2080<> + 8(SB)/8, $0.412206153771168640E-01
+DATA ·asinhtab2080<> + 16(SB)/8, $0.273839003221648339E-01
+DATA ·asinhtab2080<> + 24(SB)/8, $0.166383778368856480E-01
+DATA ·asinhtab2080<> + 32(SB)/8, $0.866678223433169637E-02
+DATA ·asinhtab2080<> + 40(SB)/8, $0.319831684989627514E-02
+DATA ·asinhtab2080<> + 48(SB)/8, $0.0
+DATA ·asinhtab2080<> + 56(SB)/8, $-.113006378583725549E-02
+DATA ·asinhtab2080<> + 64(SB)/8, $-.367979419636602491E-03
+DATA ·asinhtab2080<> + 72(SB)/8, $0.213172484510484979E-02
+DATA ·asinhtab2080<> + 80(SB)/8, $0.623271047682013536E-02
+DATA ·asinhtab2080<> + 88(SB)/8, $0.118140812789696885E-01
+DATA ·asinhtab2080<> + 96(SB)/8, $0.187681358930914206E-01
+DATA ·asinhtab2080<> + 104(SB)/8, $0.269985148668178992E-01
+DATA ·asinhtab2080<> + 112(SB)/8, $0.364186619761331328E-01
+DATA ·asinhtab2080<> + 120(SB)/8, $0.469505379381388441E-01
+GLOBL ·asinhtab2080<> + 0(SB), RODATA, $128
+
+// Asinh returns the inverse hyperbolic sine of the argument.
+//
+// Special cases are:
+// Asinh(±0) = ±0
+// Asinh(±Inf) = ±Inf
+// Asinh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·asinhAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·asinhrodataL18<>+0(SB), R9
+ LGDR F0, R12
+ WORD $0xC0293FDF //iilf %r2,1071644671
+ BYTE $0xFF
+ BYTE $0xFF
+ SRAD $32, R12
+ WORD $0xB917001C //llgtr %r1,%r12
+ MOVW R1, R6
+ MOVW R2, R7
+ CMPBLE R6, R7, L2
+ WORD $0xC0295FEF //iilf %r2,1609564159
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R2, R7
+ CMPBLE R6, R7, L14
+L3:
+ WORD $0xC0297FEF //iilf %r2,2146435071
+ BYTE $0xFF
+ BYTE $0xFF
+ CMPW R1, R2
+ BGT L1
+ LTDBR F0, F0
+ FMOVD F0, F10
+ BLTU L15
+L9:
+ FMOVD $0, F0
+ WFADB V0, V10, V0
+ WORD $0xC0398006 //iilf %r3,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ LGDR F0, R5
+ SRAD $32, R5
+ MOVH $0x0, R2
+ SUBW R5, R3
+ FMOVD $0, F8
+ RISBGZ $32, $47, $0, R3, R4
+ BYTE $0x18 //lr %r1,%r4
+ BYTE $0x14
+ RISBGN $0, $31, $32, R4, R2
+ SUBW $0x100000, R1
+ SRAW $8, R1, R1
+ ORW $0x45000000, R1
+ BR L6
+L2:
+ MOVD $0x30000000, R2
+ CMPW R1, R2
+ BGT L16
+ FMOVD 200(R9), F2
+ FMADD F2, F0, F0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+L14:
+ LTDBR F0, F0
+ BLTU L17
+ FMOVD F0, F10
+L4:
+ FMOVD 192(R9), F2
+ WFMADB V0, V0, V2, V0
+ LTDBR F0, F0
+ FSQRT F0, F8
+L5:
+ WFADB V8, V10, V0
+ WORD $0xC0398006 //iilf %r3,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ LGDR F0, R5
+ SRAD $32, R5
+ MOVH $0x0, R2
+ SUBW R5, R3
+ RISBGZ $32, $47, $0, R3, R4
+ SRAW $8, R4, R1
+ RISBGN $0, $31, $32, R4, R2
+ ORW $0x45000000, R1
+L6:
+ LDGR R2, F2
+ FMOVD 184(R9), F0
+ WFMADB V8, V2, V0, V8
+ FMOVD 176(R9), F4
+ WFMADB V10, V2, V8, V2
+ FMOVD 168(R9), F0
+ FMOVD 160(R9), F6
+ FMOVD 152(R9), F1
+ WFMADB V2, V6, V4, V6
+ WFMADB V2, V1, V0, V1
+ WFMDB V2, V2, V4
+ FMOVD 144(R9), F0
+ WFMADB V6, V4, V1, V6
+ FMOVD 136(R9), F1
+ RISBGZ $57, $60, $51, R3, R3
+ WFMADB V2, V0, V1, V0
+ FMOVD 128(R9), F1
+ WFMADB V4, V6, V0, V6
+ FMOVD 120(R9), F0
+ WFMADB V2, V1, V0, V1
+ VLVGF $0, R1, V0
+ WFMADB V4, V6, V1, V4
+ LDEBR F0, F0
+ FMOVD 112(R9), F6
+ WFMADB V2, V4, V6, V4
+ MOVD $·asinhtab2080<>+0(SB), R1
+ FMOVD 104(R9), F1
+ WORD $0x68331000 //ld %f3,0(%r3,%r1)
+ FMOVD 96(R9), F6
+ WFMADB V2, V4, V3, V2
+ WFMADB V0, V1, V6, V0
+ FMOVD 88(R9), F4
+ WFMADB V0, V4, V2, V0
+ MOVD R12, R6
+ CMPBGT R6, $0, L1
+
+ WORD $0xB3130000 //lcdbr %f0,%f0
+ FMOVD F0, ret+8(FP)
+ RET
+L16:
+ WFMDB V0, V0, V1
+ FMOVD 80(R9), F6
+ WFMDB V1, V1, V4
+ FMOVD 72(R9), F2
+ WFMADB V4, V2, V6, V2
+ FMOVD 64(R9), F3
+ FMOVD 56(R9), F6
+ WFMADB V4, V2, V3, V2
+ FMOVD 48(R9), F3
+ WFMADB V4, V6, V3, V6
+ FMOVD 40(R9), F5
+ FMOVD 32(R9), F3
+ WFMADB V4, V2, V5, V2
+ WFMADB V4, V6, V3, V6
+ FMOVD 24(R9), F5
+ FMOVD 16(R9), F3
+ WFMADB V4, V2, V5, V2
+ WFMADB V4, V6, V3, V6
+ FMOVD 8(R9), F5
+ FMOVD 0(R9), F3
+ WFMADB V4, V2, V5, V2
+ WFMADB V4, V6, V3, V4
+ WFMDB V0, V1, V6
+ WFMADB V1, V4, V2, V4
+ FMADD F4, F6, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L17:
+ WORD $0xB31300A0 //lcdbr %f10,%f0
+ BR L4
+L15:
+ WORD $0xB31300A0 //lcdbr %f10,%f0
+ BR L9
diff --git a/platform/dbops/binaries/go/go/src/math/atan.go b/platform/dbops/binaries/go/go/src/math/atan.go
new file mode 100644
index 0000000000000000000000000000000000000000..e722e99757fd2048f4d80fc6941b2c93f0b81442
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atan.go
@@ -0,0 +1,111 @@
+// 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 math
+
+/*
+ Floating-point arctangent.
+*/
+
+// The original C code, the long comment, and the constants below were
+// from http://netlib.sandia.gov/cephes/cmath/atan.c, available from
+// http://www.netlib.org/cephes/cmath.tgz.
+// The go code is a version of the original C.
+//
+// atan.c
+// Inverse circular tangent (arctangent)
+//
+// SYNOPSIS:
+// double x, y, atan();
+// y = atan( x );
+//
+// DESCRIPTION:
+// Returns radian angle between -pi/2 and +pi/2 whose tangent is x.
+//
+// Range reduction is from three intervals into the interval from zero to 0.66.
+// The approximant uses a rational function of degree 4/5 of the form
+// x + x**3 P(x)/Q(x).
+//
+// ACCURACY:
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -10, 10 50000 2.4e-17 8.3e-18
+// IEEE -10, 10 10^6 1.8e-16 5.0e-17
+//
+// 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
+
+// xatan evaluates a series valid in the range [0, 0.66].
+func xatan(x float64) float64 {
+ const (
+ P0 = -8.750608600031904122785e-01
+ P1 = -1.615753718733365076637e+01
+ P2 = -7.500855792314704667340e+01
+ P3 = -1.228866684490136173410e+02
+ P4 = -6.485021904942025371773e+01
+ Q0 = +2.485846490142306297962e+01
+ Q1 = +1.650270098316988542046e+02
+ Q2 = +4.328810604912902668951e+02
+ Q3 = +4.853903996359136964868e+02
+ Q4 = +1.945506571482613964425e+02
+ )
+ z := x * x
+ z = z * ((((P0*z+P1)*z+P2)*z+P3)*z + P4) / (((((z+Q0)*z+Q1)*z+Q2)*z+Q3)*z + Q4)
+ z = x*z + x
+ return z
+}
+
+// satan reduces its argument (known to be positive)
+// to the range [0, 0.66] and calls xatan.
+func satan(x float64) float64 {
+ const (
+ Morebits = 6.123233995736765886130e-17 // pi/2 = PIO2 + Morebits
+ Tan3pio8 = 2.41421356237309504880 // tan(3*pi/8)
+ )
+ if x <= 0.66 {
+ return xatan(x)
+ }
+ if x > Tan3pio8 {
+ return Pi/2 - xatan(1/x) + Morebits
+ }
+ return Pi/4 + xatan((x-1)/(x+1)) + 0.5*Morebits
+}
+
+// Atan returns the arctangent, in radians, of x.
+//
+// Special cases are:
+//
+// Atan(±0) = ±0
+// Atan(±Inf) = ±Pi/2
+func Atan(x float64) float64 {
+ if haveArchAtan {
+ return archAtan(x)
+ }
+ return atan(x)
+}
+
+func atan(x float64) float64 {
+ if x == 0 {
+ return x
+ }
+ if x > 0 {
+ return satan(x)
+ }
+ return -satan(-x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/atan2.go b/platform/dbops/binaries/go/go/src/math/atan2.go
new file mode 100644
index 0000000000000000000000000000000000000000..c324ed0a1578a25195586ebc448d11374824e23d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atan2.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.
+
+package math
+
+// Atan2 returns the arc tangent of y/x, using
+// the signs of the two to determine the quadrant
+// of the return value.
+//
+// Special cases are (in order):
+//
+// Atan2(y, NaN) = NaN
+// Atan2(NaN, x) = NaN
+// Atan2(+0, x>=0) = +0
+// Atan2(-0, x>=0) = -0
+// Atan2(+0, x<=-0) = +Pi
+// Atan2(-0, x<=-0) = -Pi
+// Atan2(y>0, 0) = +Pi/2
+// Atan2(y<0, 0) = -Pi/2
+// Atan2(+Inf, +Inf) = +Pi/4
+// Atan2(-Inf, +Inf) = -Pi/4
+// Atan2(+Inf, -Inf) = 3Pi/4
+// Atan2(-Inf, -Inf) = -3Pi/4
+// Atan2(y, +Inf) = 0
+// Atan2(y>0, -Inf) = +Pi
+// Atan2(y<0, -Inf) = -Pi
+// Atan2(+Inf, x) = +Pi/2
+// Atan2(-Inf, x) = -Pi/2
+func Atan2(y, x float64) float64 {
+ if haveArchAtan2 {
+ return archAtan2(y, x)
+ }
+ return atan2(y, x)
+}
+
+func atan2(y, x float64) float64 {
+ // special cases
+ switch {
+ case IsNaN(y) || IsNaN(x):
+ return NaN()
+ case y == 0:
+ if x >= 0 && !Signbit(x) {
+ return Copysign(0, y)
+ }
+ return Copysign(Pi, y)
+ case x == 0:
+ return Copysign(Pi/2, y)
+ case IsInf(x, 0):
+ if IsInf(x, 1) {
+ switch {
+ case IsInf(y, 0):
+ return Copysign(Pi/4, y)
+ default:
+ return Copysign(0, y)
+ }
+ }
+ switch {
+ case IsInf(y, 0):
+ return Copysign(3*Pi/4, y)
+ default:
+ return Copysign(Pi, y)
+ }
+ case IsInf(y, 0):
+ return Copysign(Pi/2, y)
+ }
+
+ // Call atan and determine the quadrant.
+ q := Atan(y / x)
+ if x < 0 {
+ if q <= 0 {
+ return q + Pi
+ }
+ return q - Pi
+ }
+ return q
+}
diff --git a/platform/dbops/binaries/go/go/src/math/atan2_s390x.s b/platform/dbops/binaries/go/go/src/math/atan2_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..587b89e9b5bec0dd861d9dc14a0857e73463db7a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atan2_s390x.s
@@ -0,0 +1,297 @@
+// 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.
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NegInf 0xFFF0000000000000
+#define NegZero 0x8000000000000000
+#define Pi 0x400921FB54442D18
+#define NegPi 0xC00921FB54442D18
+#define Pi3Div4 0x4002D97C7F3321D2 // 3Pi/4
+#define NegPi3Div4 0xC002D97C7F3321D2 // -3Pi/4
+#define PiDiv4 0x3FE921FB54442D18 // Pi/4
+#define NegPiDiv4 0xBFE921FB54442D18 // -Pi/4
+
+// Minimax polynomial coefficients and other constants
+DATA ·atan2rodataL25<> + 0(SB)/8, $0.199999999999554423E+00
+DATA ·atan2rodataL25<> + 8(SB)/8, $-.333333333333330928E+00
+DATA ·atan2rodataL25<> + 16(SB)/8, $0.111111110136634272E+00
+DATA ·atan2rodataL25<> + 24(SB)/8, $-.142857142828026806E+00
+DATA ·atan2rodataL25<> + 32(SB)/8, $0.769228118888682505E-01
+DATA ·atan2rodataL25<> + 40(SB)/8, $0.588059263575587687E-01
+DATA ·atan2rodataL25<> + 48(SB)/8, $-.909090711945939878E-01
+DATA ·atan2rodataL25<> + 56(SB)/8, $-.666641501287528609E-01
+DATA ·atan2rodataL25<> + 64(SB)/8, $0.472329433805024762E-01
+DATA ·atan2rodataL25<> + 72(SB)/8, $-.525380587584426406E-01
+DATA ·atan2rodataL25<> + 80(SB)/8, $-.422172007412067035E-01
+DATA ·atan2rodataL25<> + 88(SB)/8, $0.366935664549587481E-01
+DATA ·atan2rodataL25<> + 96(SB)/8, $0.220852012160300086E-01
+DATA ·atan2rodataL25<> + 104(SB)/8, $-.299856214685512712E-01
+DATA ·atan2rodataL25<> + 112(SB)/8, $0.726338160757602439E-02
+DATA ·atan2rodataL25<> + 120(SB)/8, $0.134893651284712515E-04
+DATA ·atan2rodataL25<> + 128(SB)/8, $-.291935324869629616E-02
+DATA ·atan2rodataL25<> + 136(SB)/8, $-.154797890856877418E-03
+DATA ·atan2rodataL25<> + 144(SB)/8, $0.843488472994227321E-03
+DATA ·atan2rodataL25<> + 152(SB)/8, $-.139950258898989925E-01
+GLOBL ·atan2rodataL25<> + 0(SB), RODATA, $160
+
+DATA ·atan2xpi2h<> + 0(SB)/8, $0x3ff330e4e4fa7b1b
+DATA ·atan2xpi2h<> + 8(SB)/8, $0xbff330e4e4fa7b1b
+DATA ·atan2xpi2h<> + 16(SB)/8, $0x400330e4e4fa7b1b
+DATA ·atan2xpi2h<> + 24(SB)/8, $0xc00330e4e4fa7b1b
+GLOBL ·atan2xpi2h<> + 0(SB), RODATA, $32
+DATA ·atan2xpim<> + 0(SB)/8, $0x3ff4f42b00000000
+GLOBL ·atan2xpim<> + 0(SB), RODATA, $8
+
+// Atan2 returns the arc tangent of y/x, using
+// the signs of the two to determine the quadrant
+// of the return value.
+//
+// Special cases are (in order):
+// Atan2(y, NaN) = NaN
+// Atan2(NaN, x) = NaN
+// Atan2(+0, x>=0) = +0
+// Atan2(-0, x>=0) = -0
+// Atan2(+0, x<=-0) = +Pi
+// Atan2(-0, x<=-0) = -Pi
+// Atan2(y>0, 0) = +Pi/2
+// Atan2(y<0, 0) = -Pi/2
+// Atan2(+Inf, +Inf) = +Pi/4
+// Atan2(-Inf, +Inf) = -Pi/4
+// Atan2(+Inf, -Inf) = 3Pi/4
+// Atan2(-Inf, -Inf) = -3Pi/4
+// Atan2(y, +Inf) = 0
+// Atan2(y>0, -Inf) = +Pi
+// Atan2(y<0, -Inf) = -Pi
+// Atan2(+Inf, x) = +Pi/2
+// Atan2(-Inf, x) = -Pi/2
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·atan2Asm(SB), NOSPLIT, $0-24
+ // special case
+ MOVD x+0(FP), R1
+ MOVD y+8(FP), R2
+
+ // special case Atan2(NaN, y) = NaN
+ MOVD $~(1<<63), R5
+ AND R1, R5 // x = |x|
+ MOVD $PosInf, R3
+ CMPUBLT R3, R5, returnX
+
+ // special case Atan2(x, NaN) = NaN
+ MOVD $~(1<<63), R5
+ AND R2, R5
+ CMPUBLT R3, R5, returnY
+
+ MOVD $NegZero, R3
+ CMPUBEQ R3, R1, xIsNegZero
+
+ MOVD $0, R3
+ CMPUBEQ R3, R1, xIsPosZero
+
+ MOVD $PosInf, R4
+ CMPUBEQ R4, R2, yIsPosInf
+
+ MOVD $NegInf, R4
+ CMPUBEQ R4, R2, yIsNegInf
+ BR Normal
+xIsNegZero:
+ // special case Atan(-0, y>=0) = -0
+ MOVD $0, R4
+ CMPBLE R4, R2, returnX
+
+ //special case Atan2(-0, y<=-0) = -Pi
+ MOVD $NegZero, R4
+ CMPBGE R4, R2, returnNegPi
+ BR Normal
+xIsPosZero:
+ //special case Atan2(0, 0) = 0
+ MOVD $0, R4
+ CMPUBEQ R4, R2, returnX
+
+ //special case Atan2(0, y<=-0) = Pi
+ MOVD $NegZero, R4
+ CMPBGE R4, R2, returnPi
+ BR Normal
+yIsNegInf:
+ //special case Atan2(+Inf, -Inf) = 3Pi/4
+ MOVD $PosInf, R3
+ CMPUBEQ R3, R1, posInfNegInf
+
+ //special case Atan2(-Inf, -Inf) = -3Pi/4
+ MOVD $NegInf, R3
+ CMPUBEQ R3, R1, negInfNegInf
+ BR Normal
+yIsPosInf:
+ //special case Atan2(+Inf, +Inf) = Pi/4
+ MOVD $PosInf, R3
+ CMPUBEQ R3, R1, posInfPosInf
+
+ //special case Atan2(-Inf, +Inf) = -Pi/4
+ MOVD $NegInf, R3
+ CMPUBEQ R3, R1, negInfPosInf
+
+ //special case Atan2(x, +Inf) = Copysign(0, x)
+ CMPBLT R1, $0, returnNegZero
+ BR returnPosZero
+
+Normal:
+ FMOVD x+0(FP), F0
+ FMOVD y+8(FP), F2
+ MOVD $·atan2rodataL25<>+0(SB), R9
+ LGDR F0, R2
+ LGDR F2, R1
+ RISBGNZ $32, $63, $32, R2, R2
+ RISBGNZ $32, $63, $32, R1, R1
+ WORD $0xB9170032 //llgtr %r3,%r2
+ RISBGZ $63, $63, $33, R2, R5
+ WORD $0xB9170041 //llgtr %r4,%r1
+ WFLCDB V0, V20
+ MOVW R4, R6
+ MOVW R3, R7
+ CMPUBLT R6, R7, L17
+ WFDDB V2, V0, V3
+ ADDW $2, R5, R2
+ MOVW R4, R6
+ MOVW R3, R7
+ CMPUBLE R6, R7, L20
+L3:
+ WFMDB V3, V3, V4
+ VLEG $0, 152(R9), V18
+ VLEG $0, 144(R9), V16
+ FMOVD 136(R9), F1
+ FMOVD 128(R9), F5
+ FMOVD 120(R9), F6
+ WFMADB V4, V16, V5, V16
+ WFMADB V4, V6, V1, V6
+ FMOVD 112(R9), F7
+ WFMDB V4, V4, V1
+ WFMADB V4, V7, V18, V7
+ VLEG $0, 104(R9), V18
+ WFMADB V1, V6, V16, V6
+ CMPWU R4, R3
+ FMOVD 96(R9), F5
+ VLEG $0, 88(R9), V16
+ WFMADB V4, V5, V18, V5
+ VLEG $0, 80(R9), V18
+ VLEG $0, 72(R9), V22
+ WFMADB V4, V16, V18, V16
+ VLEG $0, 64(R9), V18
+ WFMADB V1, V7, V5, V7
+ WFMADB V4, V18, V22, V18
+ WFMDB V1, V1, V5
+ WFMADB V1, V16, V18, V16
+ VLEG $0, 56(R9), V18
+ WFMADB V5, V6, V7, V6
+ VLEG $0, 48(R9), V22
+ FMOVD 40(R9), F7
+ WFMADB V4, V7, V18, V7
+ VLEG $0, 32(R9), V18
+ WFMADB V5, V6, V16, V6
+ WFMADB V4, V18, V22, V18
+ VLEG $0, 24(R9), V16
+ WFMADB V1, V7, V18, V7
+ VLEG $0, 16(R9), V18
+ VLEG $0, 8(R9), V22
+ WFMADB V4, V18, V16, V18
+ VLEG $0, 0(R9), V16
+ WFMADB V5, V6, V7, V6
+ WFMADB V4, V16, V22, V16
+ FMUL F3, F4
+ WFMADB V1, V18, V16, V1
+ FMADD F6, F5, F1
+ WFMADB V4, V1, V3, V4
+ BLT L18
+ BGT L7
+ LTDBR F2, F2
+ BLTU L21
+L8:
+ LTDBR F0, F0
+ BLTU L22
+L9:
+ WFCHDBS V2, V0, V0
+ BNE L18
+L7:
+ MOVW R1, R6
+ CMPBGE R6, $0, L1
+L18:
+ RISBGZ $58, $60, $3, R2, R2
+ MOVD $·atan2xpi2h<>+0(SB), R1
+ MOVD ·atan2xpim<>+0(SB), R3
+ LDGR R3, F0
+ WORD $0xED021000 //madb %f4,%f0,0(%r2,%r1)
+ BYTE $0x40
+ BYTE $0x1E
+L1:
+ FMOVD F4, ret+16(FP)
+ RET
+
+L20:
+ LTDBR F2, F2
+ BLTU L23
+ FMOVD F2, F6
+L4:
+ LTDBR F0, F0
+ BLTU L24
+ FMOVD F0, F4
+L5:
+ WFCHDBS V6, V4, V4
+ BEQ L3
+L17:
+ WFDDB V0, V2, V4
+ BYTE $0x18 //lr %r2,%r5
+ BYTE $0x25
+ WORD $0xB3130034 //lcdbr %f3,%f4
+ BR L3
+L23:
+ WORD $0xB3130062 //lcdbr %f6,%f2
+ BR L4
+L22:
+ VLR V20, V0
+ BR L9
+L21:
+ WORD $0xB3130022 //lcdbr %f2,%f2
+ BR L8
+L24:
+ VLR V20, V4
+ BR L5
+returnX: //the result is same as the first argument
+ MOVD R1, ret+16(FP)
+ RET
+returnY: //the result is same as the second argument
+ MOVD R2, ret+16(FP)
+ RET
+returnPi:
+ MOVD $Pi, R1
+ MOVD R1, ret+16(FP)
+ RET
+returnNegPi:
+ MOVD $NegPi, R1
+ MOVD R1, ret+16(FP)
+ RET
+posInfNegInf:
+ MOVD $Pi3Div4, R1
+ MOVD R1, ret+16(FP)
+ RET
+negInfNegInf:
+ MOVD $NegPi3Div4, R1
+ MOVD R1, ret+16(FP)
+ RET
+posInfPosInf:
+ MOVD $PiDiv4, R1
+ MOVD R1, ret+16(FP)
+ RET
+negInfPosInf:
+ MOVD $NegPiDiv4, R1
+ MOVD R1, ret+16(FP)
+ RET
+returnNegZero:
+ MOVD $NegZero, R1
+ MOVD R1, ret+16(FP)
+ RET
+returnPosZero:
+ MOVD $0, ret+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/atan_s390x.s b/platform/dbops/binaries/go/go/src/math/atan_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..3a7e59bb1ac62852663cbcbdee31c72e9ad11428
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atan_s390x.s
@@ -0,0 +1,128 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·atanrodataL8<> + 0(SB)/8, $0.199999999999554423E+00
+DATA ·atanrodataL8<> + 8(SB)/8, $0.111111110136634272E+00
+DATA ·atanrodataL8<> + 16(SB)/8, $-.142857142828026806E+00
+DATA ·atanrodataL8<> + 24(SB)/8, $-.333333333333330928E+00
+DATA ·atanrodataL8<> + 32(SB)/8, $0.769228118888682505E-01
+DATA ·atanrodataL8<> + 40(SB)/8, $0.588059263575587687E-01
+DATA ·atanrodataL8<> + 48(SB)/8, $-.666641501287528609E-01
+DATA ·atanrodataL8<> + 56(SB)/8, $-.909090711945939878E-01
+DATA ·atanrodataL8<> + 64(SB)/8, $0.472329433805024762E-01
+DATA ·atanrodataL8<> + 72(SB)/8, $0.366935664549587481E-01
+DATA ·atanrodataL8<> + 80(SB)/8, $-.422172007412067035E-01
+DATA ·atanrodataL8<> + 88(SB)/8, $-.299856214685512712E-01
+DATA ·atanrodataL8<> + 96(SB)/8, $0.220852012160300086E-01
+DATA ·atanrodataL8<> + 104(SB)/8, $0.726338160757602439E-02
+DATA ·atanrodataL8<> + 112(SB)/8, $0.843488472994227321E-03
+DATA ·atanrodataL8<> + 120(SB)/8, $0.134893651284712515E-04
+DATA ·atanrodataL8<> + 128(SB)/8, $-.525380587584426406E-01
+DATA ·atanrodataL8<> + 136(SB)/8, $-.139950258898989925E-01
+DATA ·atanrodataL8<> + 144(SB)/8, $-.291935324869629616E-02
+DATA ·atanrodataL8<> + 152(SB)/8, $-.154797890856877418E-03
+GLOBL ·atanrodataL8<> + 0(SB), RODATA, $160
+
+DATA ·atanxpi2h<> + 0(SB)/8, $0x3ff330e4e4fa7b1b
+DATA ·atanxpi2h<> + 8(SB)/8, $0xbff330e4e4fa7b1b
+DATA ·atanxpi2h<> + 16(SB)/8, $0x400330e4e4fa7b1b
+DATA ·atanxpi2h<> + 24(SB)/4, $0xc00330e4e4fa7b1b
+GLOBL ·atanxpi2h<> + 0(SB), RODATA, $32
+DATA ·atanxpim<> + 0(SB)/8, $0x3ff4f42b00000000
+GLOBL ·atanxpim<> + 0(SB), RODATA, $8
+DATA ·atanxmone<> + 0(SB)/8, $-1.0
+GLOBL ·atanxmone<> + 0(SB), RODATA, $8
+
+// Atan returns the arctangent, in radians, of the argument.
+//
+// Special cases are:
+// Atan(±0) = ±0
+// Atan(±Inf) = ±Pi/2Pi
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·atanAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ //special case Atan(±0) = ±0
+ FMOVD $(0.0), F1
+ FCMPU F0, F1
+ BEQ atanIsZero
+
+ MOVD $·atanrodataL8<>+0(SB), R5
+ MOVH $0x3FE0, R3
+ LGDR F0, R1
+ RISBGNZ $32, $63, $32, R1, R1
+ RLL $16, R1, R2
+ ANDW $0x7FF0, R2
+ MOVW R2, R6
+ MOVW R3, R7
+ CMPUBLE R6, R7, L6
+ MOVD $·atanxmone<>+0(SB), R3
+ FMOVD 0(R3), F2
+ WFDDB V0, V2, V0
+ RISBGZ $63, $63, $33, R1, R1
+ MOVD $·atanxpi2h<>+0(SB), R3
+ MOVWZ R1, R1
+ SLD $3, R1, R1
+ WORD $0x68813000 //ld %f8,0(%r1,%r3)
+L6:
+ WFMDB V0, V0, V2
+ FMOVD 152(R5), F6
+ FMOVD 144(R5), F1
+ FMOVD 136(R5), F7
+ VLEG $0, 128(R5), V16
+ FMOVD 120(R5), F4
+ FMOVD 112(R5), F5
+ WFMADB V2, V4, V6, V4
+ WFMADB V2, V5, V1, V5
+ WFMDB V2, V2, V6
+ FMOVD 104(R5), F3
+ FMOVD 96(R5), F1
+ WFMADB V2, V3, V7, V3
+ MOVH $0x3FE0, R1
+ FMOVD 88(R5), F7
+ WFMADB V2, V1, V7, V1
+ FMOVD 80(R5), F7
+ WFMADB V6, V3, V1, V3
+ WFMADB V6, V4, V5, V4
+ WFMDB V6, V6, V1
+ FMOVD 72(R5), F5
+ WFMADB V2, V5, V7, V5
+ FMOVD 64(R5), F7
+ WFMADB V2, V7, V16, V7
+ VLEG $0, 56(R5), V16
+ WFMADB V6, V5, V7, V5
+ WFMADB V1, V4, V3, V4
+ FMOVD 48(R5), F7
+ FMOVD 40(R5), F3
+ WFMADB V2, V3, V7, V3
+ FMOVD 32(R5), F7
+ WFMADB V2, V7, V16, V7
+ VLEG $0, 24(R5), V16
+ WFMADB V1, V4, V5, V4
+ FMOVD 16(R5), F5
+ WFMADB V6, V3, V7, V3
+ FMOVD 8(R5), F7
+ WFMADB V2, V7, V5, V7
+ FMOVD 0(R5), F5
+ WFMADB V2, V5, V16, V5
+ WFMADB V1, V4, V3, V4
+ WFMADB V6, V7, V5, V6
+ FMUL F0, F2
+ FMADD F4, F1, F6
+ FMADD F6, F2, F0
+ MOVW R2, R6
+ MOVW R1, R7
+ CMPUBLE R6, R7, L1
+ MOVD $·atanxpim<>+0(SB), R1
+ WORD $0xED801000 //madb %f0,%f8,0(%r1)
+ BYTE $0x00
+ BYTE $0x1E
+L1:
+atanIsZero:
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/atanh.go b/platform/dbops/binaries/go/go/src/math/atanh.go
new file mode 100644
index 0000000000000000000000000000000000000000..9d594625a5c04a41954d3bf2fbef2d078751ad11
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atanh.go
@@ -0,0 +1,85 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/e_atanh.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// __ieee754_atanh(x)
+// Method :
+// 1. Reduce x to positive by atanh(-x) = -atanh(x)
+// 2. For x>=0.5
+// 1 2x x
+// atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
+// 2 1 - x 1 - x
+//
+// For x<0.5
+// atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
+//
+// Special cases:
+// atanh(x) is NaN if |x| > 1 with signal;
+// atanh(NaN) is that NaN with no signal;
+// atanh(+-1) is +-INF with signal.
+//
+
+// Atanh returns the inverse hyperbolic tangent of x.
+//
+// Special cases are:
+//
+// Atanh(1) = +Inf
+// Atanh(±0) = ±0
+// Atanh(-1) = -Inf
+// Atanh(x) = NaN if x < -1 or x > 1
+// Atanh(NaN) = NaN
+func Atanh(x float64) float64 {
+ if haveArchAtanh {
+ return archAtanh(x)
+ }
+ return atanh(x)
+}
+
+func atanh(x float64) float64 {
+ const NearZero = 1.0 / (1 << 28) // 2**-28
+ // special cases
+ switch {
+ case x < -1 || x > 1 || IsNaN(x):
+ return NaN()
+ case x == 1:
+ return Inf(1)
+ case x == -1:
+ return Inf(-1)
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ var temp float64
+ switch {
+ case x < NearZero:
+ temp = x
+ case x < 0.5:
+ temp = x + x
+ temp = 0.5 * Log1p(temp+temp*x/(1-x))
+ default:
+ temp = 0.5 * Log1p((x+x)/(1-x))
+ }
+ if sign {
+ temp = -temp
+ }
+ return temp
+}
diff --git a/platform/dbops/binaries/go/go/src/math/atanh_s390x.s b/platform/dbops/binaries/go/go/src/math/atanh_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..ba0e92696720b3c95c1ebfd5a99594b42c17afe8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/atanh_s390x.s
@@ -0,0 +1,174 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·atanhrodataL10<> + 0(SB)/8, $.41375273347623353626
+DATA ·atanhrodataL10<> + 8(SB)/8, $.51487302528619766235E+04
+DATA ·atanhrodataL10<> + 16(SB)/8, $-1.67526912689208984375
+DATA ·atanhrodataL10<> + 24(SB)/8, $0.181818181818181826E+00
+DATA ·atanhrodataL10<> + 32(SB)/8, $-.165289256198351540E-01
+DATA ·atanhrodataL10<> + 40(SB)/8, $0.200350613573012186E-02
+DATA ·atanhrodataL10<> + 48(SB)/8, $0.397389654305194527E-04
+DATA ·atanhrodataL10<> + 56(SB)/8, $-.273205381970859341E-03
+DATA ·atanhrodataL10<> + 64(SB)/8, $0.938370938292558173E-06
+DATA ·atanhrodataL10<> + 72(SB)/8, $-.148682720127920854E-06
+DATA ·atanhrodataL10<> + 80(SB)/8, $ 0.212881813645679599E-07
+DATA ·atanhrodataL10<> + 88(SB)/8, $-.602107458843052029E-05
+DATA ·atanhrodataL10<> + 96(SB)/8, $-5.5
+DATA ·atanhrodataL10<> + 104(SB)/8, $-0.5
+DATA ·atanhrodataL10<> + 112(SB)/8, $0.0
+DATA ·atanhrodataL10<> + 120(SB)/8, $0x7ff8000000000000 //Nan
+DATA ·atanhrodataL10<> + 128(SB)/8, $-1.0
+DATA ·atanhrodataL10<> + 136(SB)/8, $1.0
+DATA ·atanhrodataL10<> + 144(SB)/8, $1.0E-20
+GLOBL ·atanhrodataL10<> + 0(SB), RODATA, $152
+
+// Table of log correction terms
+DATA ·atanhtab2076<> + 0(SB)/8, $0.585235384085551248E-01
+DATA ·atanhtab2076<> + 8(SB)/8, $0.412206153771168640E-01
+DATA ·atanhtab2076<> + 16(SB)/8, $0.273839003221648339E-01
+DATA ·atanhtab2076<> + 24(SB)/8, $0.166383778368856480E-01
+DATA ·atanhtab2076<> + 32(SB)/8, $0.866678223433169637E-02
+DATA ·atanhtab2076<> + 40(SB)/8, $0.319831684989627514E-02
+DATA ·atanhtab2076<> + 48(SB)/8, $0.000000000000000000E+00
+DATA ·atanhtab2076<> + 56(SB)/8, $-.113006378583725549E-02
+DATA ·atanhtab2076<> + 64(SB)/8, $-.367979419636602491E-03
+DATA ·atanhtab2076<> + 72(SB)/8, $0.213172484510484979E-02
+DATA ·atanhtab2076<> + 80(SB)/8, $0.623271047682013536E-02
+DATA ·atanhtab2076<> + 88(SB)/8, $0.118140812789696885E-01
+DATA ·atanhtab2076<> + 96(SB)/8, $0.187681358930914206E-01
+DATA ·atanhtab2076<> + 104(SB)/8, $0.269985148668178992E-01
+DATA ·atanhtab2076<> + 112(SB)/8, $0.364186619761331328E-01
+DATA ·atanhtab2076<> + 120(SB)/8, $0.469505379381388441E-01
+GLOBL ·atanhtab2076<> + 0(SB), RODATA, $128
+
+// Table of +/- .5
+DATA ·atanhtabh2075<> + 0(SB)/8, $0.5
+DATA ·atanhtabh2075<> + 8(SB)/8, $-.5
+GLOBL ·atanhtabh2075<> + 0(SB), RODATA, $16
+
+// Atanh returns the inverse hyperbolic tangent of the argument.
+//
+// Special cases are:
+// Atanh(1) = +Inf
+// Atanh(±0) = ±0
+// Atanh(-1) = -Inf
+// Atanh(x) = NaN if x < -1 or x > 1
+// Atanh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·atanhAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·atanhrodataL10<>+0(SB), R5
+ LGDR F0, R1
+ WORD $0xC0393FEF //iilf %r3,1072693247
+ BYTE $0xFF
+ BYTE $0xFF
+ SRAD $32, R1
+ WORD $0xB9170021 //llgtr %r2,%r1
+ MOVW R2, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L2
+ WORD $0xC0392FFF //iilf %r3,805306367
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R2, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L9
+L3:
+ FMOVD 144(R5), F2
+ FMADD F2, F0, F0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+
+L2:
+ WORD $0xED005088 //cdb %f0,.L12-.L10(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L5
+ WORD $0xED005080 //cdb %f0,.L13-.L10(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BEQ L5
+ WFCEDBS V0, V0, V2
+ BVS L1
+ FMOVD 120(R5), F0
+ BR L1
+L5:
+ WORD $0xED005070 //ddb %f0,.L15-.L10(%r5)
+ BYTE $0x00
+ BYTE $0x1D
+ FMOVD F0, ret+8(FP)
+ RET
+
+L9:
+ FMOVD F0, F2
+ MOVD $·atanhtabh2075<>+0(SB), R2
+ SRW $31, R1, R1
+ FMOVD 104(R5), F4
+ MOVW R1, R1
+ SLD $3, R1, R1
+ WORD $0x68012000 //ld %f0,0(%r1,%r2)
+ WFMADB V2, V4, V0, V4
+ VLEG $0, 96(R5), V16
+ FDIV F4, F2
+ WORD $0xC0298006 //iilf %r2,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ FMOVD 88(R5), F6
+ FMOVD 80(R5), F1
+ FMOVD 72(R5), F7
+ FMOVD 64(R5), F5
+ FMOVD F2, F4
+ WORD $0xED405088 //adb %f4,.L12-.L10(%r5)
+ BYTE $0x00
+ BYTE $0x1A
+ LGDR F4, R4
+ SRAD $32, R4
+ FMOVD F4, F3
+ WORD $0xED305088 //sdb %f3,.L12-.L10(%r5)
+ BYTE $0x00
+ BYTE $0x1B
+ SUBW R4, R2
+ WFSDB V3, V2, V3
+ RISBGZ $32, $47, $0, R2, R1
+ SLD $32, R1, R1
+ LDGR R1, F2
+ WFMADB V4, V2, V16, V4
+ SRAW $8, R2, R1
+ WFMADB V4, V5, V6, V5
+ WFMDB V4, V4, V6
+ WFMADB V4, V1, V7, V1
+ WFMADB V2, V3, V4, V2
+ WFMADB V1, V6, V5, V1
+ FMOVD 56(R5), F3
+ FMOVD 48(R5), F5
+ WFMADB V4, V5, V3, V4
+ FMOVD 40(R5), F3
+ FMADD F1, F6, F4
+ FMOVD 32(R5), F1
+ FMADD F3, F2, F1
+ ANDW $0xFFFFFF00, R1
+ WFMADB V6, V4, V1, V6
+ FMOVD 24(R5), F3
+ ORW $0x45000000, R1
+ WFMADB V2, V6, V3, V6
+ VLVGF $0, R1, V4
+ LDEBR F4, F4
+ RISBGZ $57, $60, $51, R2, R2
+ MOVD $·atanhtab2076<>+0(SB), R1
+ FMOVD 16(R5), F3
+ WORD $0x68521000 //ld %f5,0(%r2,%r1)
+ FMOVD 8(R5), F1
+ WFMADB V2, V6, V5, V2
+ WFMADB V4, V3, V1, V4
+ FMOVD 0(R5), F6
+ FMADD F6, F4, F2
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/bits.go b/platform/dbops/binaries/go/go/src/math/bits.go
new file mode 100644
index 0000000000000000000000000000000000000000..c5cb93b15945d47365865da990e93e46e430c1bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/bits.go
@@ -0,0 +1,62 @@
+// 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 math
+
+const (
+ uvnan = 0x7FF8000000000001
+ uvinf = 0x7FF0000000000000
+ uvneginf = 0xFFF0000000000000
+ uvone = 0x3FF0000000000000
+ mask = 0x7FF
+ shift = 64 - 11 - 1
+ bias = 1023
+ signMask = 1 << 63
+ fracMask = 1<= 0, negative infinity if sign < 0.
+func Inf(sign int) float64 {
+ var v uint64
+ if sign >= 0 {
+ v = uvinf
+ } else {
+ v = uvneginf
+ }
+ return Float64frombits(v)
+}
+
+// NaN returns an IEEE 754 “not-a-number” value.
+func NaN() float64 { return Float64frombits(uvnan) }
+
+// IsNaN reports whether f is an IEEE 754 “not-a-number” value.
+func IsNaN(f float64) (is bool) {
+ // IEEE 754 says that only NaNs satisfy f != f.
+ // To avoid the floating-point hardware, could use:
+ // x := Float64bits(f);
+ // return uint32(x>>shift)&mask == mask && x != uvinf && x != uvneginf
+ return f != f
+}
+
+// IsInf reports whether f is an infinity, according to sign.
+// If sign > 0, IsInf reports whether f is positive infinity.
+// If sign < 0, IsInf reports whether f is negative infinity.
+// If sign == 0, IsInf reports whether f is either infinity.
+func IsInf(f float64, sign int) bool {
+ // Test for infinity by comparing against maximum float.
+ // To avoid the floating-point hardware, could use:
+ // x := Float64bits(f);
+ // return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf;
+ return sign >= 0 && f > MaxFloat64 || sign <= 0 && f < -MaxFloat64
+}
+
+// normalize returns a normal number y and exponent exp
+// satisfying x == y × 2**exp. It assumes x is finite and non-zero.
+func normalize(x float64) (y float64, exp int) {
+ const SmallestNormal = 2.2250738585072014e-308 // 2**-1022
+ if Abs(x) < SmallestNormal {
+ return x * (1 << 52), -52
+ }
+ return x, 0
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cbrt.go b/platform/dbops/binaries/go/go/src/math/cbrt.go
new file mode 100644
index 0000000000000000000000000000000000000000..e5e9548cb1f39489df6d8185b5e8c36b6e72876e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cbrt.go
@@ -0,0 +1,85 @@
+// 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 math
+
+// The go code is a modified version of the original C code from
+// http://www.netlib.org/fdlibm/s_cbrt.c and came with this notice.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunSoft, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+
+// Cbrt returns the cube root of x.
+//
+// Special cases are:
+//
+// Cbrt(±0) = ±0
+// Cbrt(±Inf) = ±Inf
+// Cbrt(NaN) = NaN
+func Cbrt(x float64) float64 {
+ if haveArchCbrt {
+ return archCbrt(x)
+ }
+ return cbrt(x)
+}
+
+func cbrt(x float64) float64 {
+ const (
+ B1 = 715094163 // (682-0.03306235651)*2**20
+ B2 = 696219795 // (664-0.03306235651)*2**20
+ C = 5.42857142857142815906e-01 // 19/35 = 0x3FE15F15F15F15F1
+ D = -7.05306122448979611050e-01 // -864/1225 = 0xBFE691DE2532C834
+ E = 1.41428571428571436819e+00 // 99/70 = 0x3FF6A0EA0EA0EA0F
+ F = 1.60714285714285720630e+00 // 45/28 = 0x3FF9B6DB6DB6DB6E
+ G = 3.57142857142857150787e-01 // 5/14 = 0x3FD6DB6DB6DB6DB7
+ SmallestNormal = 2.22507385850720138309e-308 // 2**-1022 = 0x0010000000000000
+ )
+ // special cases
+ switch {
+ case x == 0 || IsNaN(x) || IsInf(x, 0):
+ return x
+ }
+
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+
+ // rough cbrt to 5 bits
+ t := Float64frombits(Float64bits(x)/3 + B1<<32)
+ if x < SmallestNormal {
+ // subnormal number
+ t = float64(1 << 54) // set t= 2**54
+ t *= x
+ t = Float64frombits(Float64bits(t)/3 + B2<<32)
+ }
+
+ // new cbrt to 23 bits
+ r := t * t / x
+ s := C + r*t
+ t *= G + F/(s+E+D/s)
+
+ // chop to 22 bits, make larger than cbrt(x)
+ t = Float64frombits(Float64bits(t)&(0xFFFFFFFFC<<28) + 1<<30)
+
+ // one step newton iteration to 53 bits with error less than 0.667ulps
+ s = t * t // t*t is exact
+ r = x / s
+ w := t + t
+ r = (r - t) / (w + r) // r-s is exact
+ t = t + t*r
+
+ // restore the sign bit
+ if sign {
+ t = -t
+ }
+ return t
+}
diff --git a/platform/dbops/binaries/go/go/src/math/cbrt_s390x.s b/platform/dbops/binaries/go/go/src/math/cbrt_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..87bba531b8cb8d9c38edbf650cf74d599e2c4c0e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/cbrt_s390x.s
@@ -0,0 +1,156 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·cbrtrodataL9<> + 0(SB)/8, $-.00016272731015974436E+00
+DATA ·cbrtrodataL9<> + 8(SB)/8, $0.66639548758285293179E+00
+DATA ·cbrtrodataL9<> + 16(SB)/8, $0.55519402697349815993E+00
+DATA ·cbrtrodataL9<> + 24(SB)/8, $0.49338566048766782004E+00
+DATA ·cbrtrodataL9<> + 32(SB)/8, $0.45208160036325611486E+00
+DATA ·cbrtrodataL9<> + 40(SB)/8, $0.43099892837778637816E+00
+DATA ·cbrtrodataL9<> + 48(SB)/8, $1.000244140625
+DATA ·cbrtrodataL9<> + 56(SB)/8, $0.33333333333333333333E+00
+DATA ·cbrtrodataL9<> + 64(SB)/8, $79228162514264337593543950336.
+GLOBL ·cbrtrodataL9<> + 0(SB), RODATA, $72
+
+// Index tables
+DATA ·cbrttab32069<> + 0(SB)/8, $0x404030303020202
+DATA ·cbrttab32069<> + 8(SB)/8, $0x101010101000000
+DATA ·cbrttab32069<> + 16(SB)/8, $0x808070706060605
+DATA ·cbrttab32069<> + 24(SB)/8, $0x505040404040303
+DATA ·cbrttab32069<> + 32(SB)/8, $0xe0d0c0c0b0b0b0a
+DATA ·cbrttab32069<> + 40(SB)/8, $0xa09090908080808
+DATA ·cbrttab32069<> + 48(SB)/8, $0x11111010100f0f0f
+DATA ·cbrttab32069<> + 56(SB)/8, $0xe0e0e0e0e0d0d0d
+DATA ·cbrttab32069<> + 64(SB)/8, $0x1515141413131312
+DATA ·cbrttab32069<> + 72(SB)/8, $0x1212111111111010
+GLOBL ·cbrttab32069<> + 0(SB), RODATA, $80
+
+DATA ·cbrttab22068<> + 0(SB)/8, $0x151015001420141
+DATA ·cbrttab22068<> + 8(SB)/8, $0x140013201310130
+DATA ·cbrttab22068<> + 16(SB)/8, $0x122012101200112
+DATA ·cbrttab22068<> + 24(SB)/8, $0x111011001020101
+DATA ·cbrttab22068<> + 32(SB)/8, $0x10000f200f100f0
+DATA ·cbrttab22068<> + 40(SB)/8, $0xe200e100e000d2
+DATA ·cbrttab22068<> + 48(SB)/8, $0xd100d000c200c1
+DATA ·cbrttab22068<> + 56(SB)/8, $0xc000b200b100b0
+DATA ·cbrttab22068<> + 64(SB)/8, $0xa200a100a00092
+DATA ·cbrttab22068<> + 72(SB)/8, $0x91009000820081
+DATA ·cbrttab22068<> + 80(SB)/8, $0x80007200710070
+DATA ·cbrttab22068<> + 88(SB)/8, $0x62006100600052
+DATA ·cbrttab22068<> + 96(SB)/8, $0x51005000420041
+DATA ·cbrttab22068<> + 104(SB)/8, $0x40003200310030
+DATA ·cbrttab22068<> + 112(SB)/8, $0x22002100200012
+DATA ·cbrttab22068<> + 120(SB)/8, $0x11001000020001
+GLOBL ·cbrttab22068<> + 0(SB), RODATA, $128
+
+DATA ·cbrttab12067<> + 0(SB)/8, $0x53e1529051324fe1
+DATA ·cbrttab12067<> + 8(SB)/8, $0x4e904d324be14a90
+DATA ·cbrttab12067<> + 16(SB)/8, $0x493247e146904532
+DATA ·cbrttab12067<> + 24(SB)/8, $0x43e1429041323fe1
+DATA ·cbrttab12067<> + 32(SB)/8, $0x3e903d323be13a90
+DATA ·cbrttab12067<> + 40(SB)/8, $0x393237e136903532
+DATA ·cbrttab12067<> + 48(SB)/8, $0x33e1329031322fe1
+DATA ·cbrttab12067<> + 56(SB)/8, $0x2e902d322be12a90
+DATA ·cbrttab12067<> + 64(SB)/8, $0xd3e1d290d132cfe1
+DATA ·cbrttab12067<> + 72(SB)/8, $0xce90cd32cbe1ca90
+DATA ·cbrttab12067<> + 80(SB)/8, $0xc932c7e1c690c532
+DATA ·cbrttab12067<> + 88(SB)/8, $0xc3e1c290c132bfe1
+DATA ·cbrttab12067<> + 96(SB)/8, $0xbe90bd32bbe1ba90
+DATA ·cbrttab12067<> + 104(SB)/8, $0xb932b7e1b690b532
+DATA ·cbrttab12067<> + 112(SB)/8, $0xb3e1b290b132afe1
+DATA ·cbrttab12067<> + 120(SB)/8, $0xae90ad32abe1aa90
+GLOBL ·cbrttab12067<> + 0(SB), RODATA, $128
+
+// Cbrt returns the cube root of the argument.
+//
+// Special cases are:
+// Cbrt(±0) = ±0
+// Cbrt(±Inf) = ±Inf
+// Cbrt(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·cbrtAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·cbrtrodataL9<>+0(SB), R9
+ LGDR F0, R2
+ WORD $0xC039000F //iilf %r3,1048575
+ BYTE $0xFF
+ BYTE $0xFF
+ SRAD $32, R2
+ WORD $0xB9170012 //llgtr %r1,%r2
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBLE R6, R7, L2
+ WORD $0xC0397FEF //iilf %r3,2146435071
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R3, R7
+ CMPBLE R6, R7, L8
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+L3:
+L2:
+ LTDBR F0, F0
+ BEQ L1
+ FMOVD F0, F2
+ WORD $0xED209040 //mdb %f2,.L10-.L9(%r9)
+ BYTE $0x00
+ BYTE $0x1C
+ MOVH $0x200, R4
+ LGDR F2, R2
+ SRAD $32, R2
+L4:
+ RISBGZ $57, $62, $39, R2, R3
+ MOVD $·cbrttab12067<>+0(SB), R1
+ WORD $0x48131000 //lh %r1,0(%r3,%r1)
+ RISBGZ $57, $62, $45, R2, R3
+ MOVD $·cbrttab22068<>+0(SB), R5
+ RISBGNZ $60, $63, $48, R2, R2
+ WORD $0x4A135000 //ah %r1,0(%r3,%r5)
+ BYTE $0x18 //lr %r3,%r1
+ BYTE $0x31
+ MOVD $·cbrttab32069<>+0(SB), R1
+ FMOVD 56(R9), F1
+ FMOVD 48(R9), F5
+ WORD $0xEC23393B //rosbg %r2,%r3,57,59,4
+ BYTE $0x04
+ BYTE $0x56
+ WORD $0xE3121000 //llc %r1,0(%r2,%r1)
+ BYTE $0x00
+ BYTE $0x94
+ ADDW R3, R1
+ ADDW R4, R1
+ SLW $16, R1, R1
+ SLD $32, R1, R1
+ LDGR R1, F2
+ WFMDB V2, V2, V4
+ WFMDB V4, V0, V6
+ WFMSDB V4, V6, V2, V4
+ FMOVD 40(R9), F6
+ FMSUB F1, F4, F2
+ FMOVD 32(R9), F4
+ WFMDB V2, V2, V3
+ FMOVD 24(R9), F1
+ FMUL F3, F0
+ FMOVD 16(R9), F3
+ WFMADB V2, V0, V5, V2
+ FMOVD 8(R9), F5
+ FMADD F6, F2, F4
+ WFMADB V2, V1, V3, V1
+ WFMDB V2, V2, V6
+ FMOVD 0(R9), F3
+ WFMADB V4, V6, V1, V4
+ WFMADB V2, V5, V3, V2
+ FMADD F4, F6, F2
+ FMADD F2, F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L8:
+ MOVH $0x0, R4
+ BR L4
diff --git a/platform/dbops/binaries/go/go/src/math/const.go b/platform/dbops/binaries/go/go/src/math/const.go
new file mode 100644
index 0000000000000000000000000000000000000000..b15e50e01820837acc344aa5646e1633f07dc8f1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/const.go
@@ -0,0 +1,57 @@
+// 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 math provides basic constants and mathematical functions.
+//
+// This package does not guarantee bit-identical results across architectures.
+package math
+
+// Mathematical constants.
+const (
+ E = 2.71828182845904523536028747135266249775724709369995957496696763 // https://oeis.org/A001113
+ Pi = 3.14159265358979323846264338327950288419716939937510582097494459 // https://oeis.org/A000796
+ Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // https://oeis.org/A001622
+
+ Sqrt2 = 1.41421356237309504880168872420969807856967187537694807317667974 // https://oeis.org/A002193
+ SqrtE = 1.64872127070012814684865078781416357165377610071014801157507931 // https://oeis.org/A019774
+ SqrtPi = 1.77245385090551602729816748334114518279754945612238712821380779 // https://oeis.org/A002161
+ SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // https://oeis.org/A139339
+
+ Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009 // https://oeis.org/A002162
+ Log2E = 1 / Ln2
+ Ln10 = 2.30258509299404568401799145468436420760110148862877297603332790 // https://oeis.org/A002392
+ Log10E = 1 / Ln10
+)
+
+// Floating-point limit values.
+// Max is the largest finite value representable by the type.
+// SmallestNonzero is the smallest positive, non-zero value representable by the type.
+const (
+ MaxFloat32 = 0x1p127 * (1 + (1 - 0x1p-23)) // 3.40282346638528859811704183484516925440e+38
+ SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23 // 1.401298464324817070923729583289916131280e-45
+
+ MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52)) // 1.79769313486231570814527423731704356798070e+308
+ SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52 // 4.9406564584124654417656879286822137236505980e-324
+)
+
+// Integer limit values.
+const (
+ intSize = 32 << (^uint(0) >> 63) // 32 or 64
+
+ MaxInt = 1<<(intSize-1) - 1 // MaxInt32 or MaxInt64 depending on intSize.
+ MinInt = -1 << (intSize - 1) // MinInt32 or MinInt64 depending on intSize.
+ MaxInt8 = 1<<7 - 1 // 127
+ MinInt8 = -1 << 7 // -128
+ MaxInt16 = 1<<15 - 1 // 32767
+ MinInt16 = -1 << 15 // -32768
+ MaxInt32 = 1<<31 - 1 // 2147483647
+ MinInt32 = -1 << 31 // -2147483648
+ MaxInt64 = 1<<63 - 1 // 9223372036854775807
+ MinInt64 = -1 << 63 // -9223372036854775808
+ MaxUint = 1<+0(SB)/8, $0.231904681384629956E-16
+DATA coshrodataL23<>+8(SB)/8, $0.693147180559945286E+00
+DATA coshrodataL23<>+16(SB)/8, $0.144269504088896339E+01
+DATA coshrodataL23<>+24(SB)/8, $704.E0
+GLOBL coshrodataL23<>+0(SB), RODATA, $32
+DATA coshxinf<>+0(SB)/8, $0x7FF0000000000000
+GLOBL coshxinf<>+0(SB), RODATA, $8
+DATA coshxlim1<>+0(SB)/8, $800.E0
+GLOBL coshxlim1<>+0(SB), RODATA, $8
+DATA coshxaddhy<>+0(SB)/8, $0xc2f0000100003fdf
+GLOBL coshxaddhy<>+0(SB), RODATA, $8
+DATA coshx4ff<>+0(SB)/8, $0x4ff0000000000000
+GLOBL coshx4ff<>+0(SB), RODATA, $8
+DATA coshe1<>+0(SB)/8, $0x3ff000000000000a
+GLOBL coshe1<>+0(SB), RODATA, $8
+
+// Log multiplier table
+DATA coshtab<>+0(SB)/8, $0.442737824274138381E-01
+DATA coshtab<>+8(SB)/8, $0.263602189790660309E-01
+DATA coshtab<>+16(SB)/8, $0.122565642281703586E-01
+DATA coshtab<>+24(SB)/8, $0.143757052860721398E-02
+DATA coshtab<>+32(SB)/8, $-.651375034121276075E-02
+DATA coshtab<>+40(SB)/8, $-.119317678849450159E-01
+DATA coshtab<>+48(SB)/8, $-.150868749549871069E-01
+DATA coshtab<>+56(SB)/8, $-.161992609578469234E-01
+DATA coshtab<>+64(SB)/8, $-.154492360403337917E-01
+DATA coshtab<>+72(SB)/8, $-.129850717389178721E-01
+DATA coshtab<>+80(SB)/8, $-.892902649276657891E-02
+DATA coshtab<>+88(SB)/8, $-.338202636596794887E-02
+DATA coshtab<>+96(SB)/8, $0.357266307045684762E-02
+DATA coshtab<>+104(SB)/8, $0.118665304327406698E-01
+DATA coshtab<>+112(SB)/8, $0.214434994118118914E-01
+DATA coshtab<>+120(SB)/8, $0.322580645161290314E-01
+GLOBL coshtab<>+0(SB), RODATA, $128
+
+// Minimax polynomial approximations
+DATA coshe2<>+0(SB)/8, $0.500000000000004237e+00
+GLOBL coshe2<>+0(SB), RODATA, $8
+DATA coshe3<>+0(SB)/8, $0.166666666630345592e+00
+GLOBL coshe3<>+0(SB), RODATA, $8
+DATA coshe4<>+0(SB)/8, $0.416666664838056960e-01
+GLOBL coshe4<>+0(SB), RODATA, $8
+DATA coshe5<>+0(SB)/8, $0.833349307718286047e-02
+GLOBL coshe5<>+0(SB), RODATA, $8
+DATA coshe6<>+0(SB)/8, $0.138926439368309441e-02
+GLOBL coshe6<>+0(SB), RODATA, $8
+
+// Cosh returns the hyperbolic cosine of x.
+//
+// Special cases are:
+// Cosh(±0) = 1
+// Cosh(±Inf) = +Inf
+// Cosh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·coshAsm(SB),NOSPLIT,$0-16
+ FMOVD x+0(FP), F0
+ MOVD $coshrodataL23<>+0(SB), R9
+ LTDBR F0, F0
+ MOVD $0x4086000000000000, R2
+ MOVD $0x4086000000000000, R3
+ BLTU L19
+ FMOVD F0, F4
+L2:
+ WORD $0xED409018 //cdb %f4,.L24-.L23(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L14 //jnl .L14
+ BVS L14
+ WFCEDBS V4, V4, V2
+ BEQ L20
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+
+L14:
+ WFCEDBS V4, V4, V2
+ BVS L1
+ MOVD $coshxlim1<>+0(SB), R1
+ FMOVD 0(R1), F2
+ WFCHEDBS V4, V2, V2
+ BEQ L21
+ MOVD $coshxaddhy<>+0(SB), R1
+ FMOVD coshrodataL23<>+16(SB), F5
+ FMOVD 0(R1), F2
+ WFMSDB V0, V5, V2, V5
+ FMOVD coshrodataL23<>+8(SB), F3
+ FADD F5, F2
+ MOVD $coshe6<>+0(SB), R1
+ WFMSDB V2, V3, V0, V3
+ FMOVD 0(R1), F6
+ WFMDB V3, V3, V1
+ MOVD $coshe4<>+0(SB), R1
+ FMOVD coshrodataL23<>+0(SB), F7
+ WFMADB V2, V7, V3, V2
+ FMOVD 0(R1), F3
+ MOVD $coshe5<>+0(SB), R1
+ WFMADB V1, V6, V3, V6
+ FMOVD 0(R1), F7
+ MOVD $coshe3<>+0(SB), R1
+ FMOVD 0(R1), F3
+ WFMADB V1, V7, V3, V7
+ FNEG F2, F3
+ LGDR F5, R1
+ MOVD $coshe2<>+0(SB), R3
+ WFCEDBS V4, V0, V0
+ FMOVD 0(R3), F5
+ MOVD $coshe1<>+0(SB), R3
+ WFMADB V1, V6, V5, V6
+ FMOVD 0(R3), F5
+ RISBGN $0, $15, $48, R1, R2
+ WFMADB V1, V7, V5, V1
+ BVS L22
+ RISBGZ $57, $60, $3, R1, R4
+ MOVD $coshtab<>+0(SB), R3
+ WFMADB V3, V6, V1, V6
+ WORD $0x68043000 //ld %f0,0(%r4,%r3)
+ FMSUB F0, F3, F2
+ WORD $0xA71AF000 //ahi %r1,-4096
+ WFMADB V2, V6, V0, V6
+L17:
+ RISBGN $0, $15, $48, R1, R2
+ LDGR R2, F2
+ FMADD F2, F6, F2
+ MOVD $coshx4ff<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L19:
+ FNEG F0, F4
+ BR L2
+L20:
+ MOVD $coshxaddhy<>+0(SB), R1
+ FMOVD coshrodataL23<>+16(SB), F3
+ FMOVD 0(R1), F2
+ WFMSDB V0, V3, V2, V3
+ FMOVD coshrodataL23<>+8(SB), F4
+ FADD F3, F2
+ MOVD $coshe6<>+0(SB), R1
+ FMSUB F4, F2, F0
+ FMOVD 0(R1), F6
+ WFMDB V0, V0, V1
+ MOVD $coshe4<>+0(SB), R1
+ FMOVD 0(R1), F4
+ MOVD $coshe5<>+0(SB), R1
+ FMOVD coshrodataL23<>+0(SB), F5
+ WFMADB V1, V6, V4, V6
+ FMADD F5, F2, F0
+ FMOVD 0(R1), F2
+ MOVD $coshe3<>+0(SB), R1
+ FMOVD 0(R1), F4
+ WFMADB V1, V2, V4, V2
+ MOVD $coshe2<>+0(SB), R1
+ FMOVD 0(R1), F5
+ FNEG F0, F4
+ WFMADB V1, V6, V5, V6
+ MOVD $coshe1<>+0(SB), R1
+ FMOVD 0(R1), F5
+ WFMADB V1, V2, V5, V1
+ LGDR F3, R1
+ MOVD $coshtab<>+0(SB), R5
+ WFMADB V4, V6, V1, V3
+ RISBGZ $57, $60, $3, R1, R4
+ WFMSDB V4, V6, V1, V6
+ WORD $0x68145000 //ld %f1,0(%r4,%r5)
+ WFMSDB V4, V1, V0, V2
+ WORD $0xA7487FBE //lhi %r4,32702
+ FMADD F3, F2, F1
+ SUBW R1, R4
+ RISBGZ $57, $60, $3, R4, R12
+ WORD $0x682C5000 //ld %f2,0(%r12,%r5)
+ FMSUB F2, F4, F0
+ RISBGN $0, $15, $48, R1, R2
+ WFMADB V0, V6, V2, V6
+ RISBGN $0, $15, $48, R4, R3
+ LDGR R2, F2
+ LDGR R3, F0
+ FMADD F2, F1, F2
+ FMADD F0, F6, F0
+ FADD F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L22:
+ WORD $0xA7387FBE //lhi %r3,32702
+ MOVD $coshtab<>+0(SB), R4
+ SUBW R1, R3
+ WFMSDB V3, V6, V1, V6
+ RISBGZ $57, $60, $3, R3, R3
+ WORD $0x68034000 //ld %f0,0(%r3,%r4)
+ FMSUB F0, F3, F2
+ WORD $0xA7386FBE //lhi %r3,28606
+ WFMADB V2, V6, V0, V6
+ SUBW R1, R3, R1
+ BR L17
+L21:
+ MOVD $coshxinf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
diff --git a/platform/dbops/binaries/go/go/src/math/dim.go b/platform/dbops/binaries/go/go/src/math/dim.go
new file mode 100644
index 0000000000000000000000000000000000000000..f369f70f000fbb69823dfe987af6b6ac0191c756
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim.go
@@ -0,0 +1,100 @@
+// 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 math
+
+// Dim returns the maximum of x-y or 0.
+//
+// Special cases are:
+//
+// Dim(+Inf, +Inf) = NaN
+// Dim(-Inf, -Inf) = NaN
+// Dim(x, NaN) = Dim(NaN, x) = NaN
+func Dim(x, y float64) float64 {
+ // The special cases result in NaN after the subtraction:
+ // +Inf - +Inf = NaN
+ // -Inf - -Inf = NaN
+ // NaN - y = NaN
+ // x - NaN = NaN
+ v := x - y
+ if v <= 0 {
+ // v is negative or 0
+ return 0
+ }
+ // v is positive or NaN
+ return v
+}
+
+// Max returns the larger of x or y.
+//
+// Special cases are:
+//
+// Max(x, +Inf) = Max(+Inf, x) = +Inf
+// Max(x, NaN) = Max(NaN, x) = NaN
+// Max(+0, ±0) = Max(±0, +0) = +0
+// Max(-0, -0) = -0
+//
+// Note that this differs from the built-in function max when called
+// with NaN and +Inf.
+func Max(x, y float64) float64 {
+ if haveArchMax {
+ return archMax(x, y)
+ }
+ return max(x, y)
+}
+
+func max(x, y float64) float64 {
+ // special cases
+ switch {
+ case IsInf(x, 1) || IsInf(y, 1):
+ return Inf(1)
+ case IsNaN(x) || IsNaN(y):
+ return NaN()
+ case x == 0 && x == y:
+ if Signbit(x) {
+ return y
+ }
+ return x
+ }
+ if x > y {
+ return x
+ }
+ return y
+}
+
+// Min returns the smaller of x or y.
+//
+// Special cases are:
+//
+// Min(x, -Inf) = Min(-Inf, x) = -Inf
+// Min(x, NaN) = Min(NaN, x) = NaN
+// Min(-0, ±0) = Min(±0, -0) = -0
+//
+// Note that this differs from the built-in function min when called
+// with NaN and -Inf.
+func Min(x, y float64) float64 {
+ if haveArchMin {
+ return archMin(x, y)
+ }
+ return min(x, y)
+}
+
+func min(x, y float64) float64 {
+ // special cases
+ switch {
+ case IsInf(x, -1) || IsInf(y, -1):
+ return Inf(-1)
+ case IsNaN(x) || IsNaN(y):
+ return NaN()
+ case x == 0 && x == y:
+ if Signbit(x) {
+ return x
+ }
+ return y
+ }
+ if x < y {
+ return x
+ }
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/src/math/dim_amd64.s b/platform/dbops/binaries/go/go/src/math/dim_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..253f03b97e713314a6ffa395f7a92b69e16ee634
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_amd64.s
@@ -0,0 +1,98 @@
+// 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.
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NaN 0x7FF8000000000001
+#define NegInf 0xFFF0000000000000
+
+// func ·archMax(x, y float64) float64
+TEXT ·archMax(SB),NOSPLIT,$0
+ // +Inf special cases
+ MOVQ $PosInf, AX
+ MOVQ x+0(FP), R8
+ CMPQ AX, R8
+ JEQ isPosInf
+ MOVQ y+8(FP), R9
+ CMPQ AX, R9
+ JEQ isPosInf
+ // NaN special cases
+ MOVQ $~(1<<63), DX // bit mask
+ MOVQ $PosInf, AX
+ MOVQ R8, BX
+ ANDQ DX, BX // x = |x|
+ CMPQ AX, BX
+ JLT isMaxNaN
+ MOVQ R9, CX
+ ANDQ DX, CX // y = |y|
+ CMPQ AX, CX
+ JLT isMaxNaN
+ // ±0 special cases
+ ORQ CX, BX
+ JEQ isMaxZero
+
+ MOVQ R8, X0
+ MOVQ R9, X1
+ MAXSD X1, X0
+ MOVSD X0, ret+16(FP)
+ RET
+isMaxNaN: // return NaN
+ MOVQ $NaN, AX
+isPosInf: // return +Inf
+ MOVQ AX, ret+16(FP)
+ RET
+isMaxZero:
+ MOVQ $(1<<63), AX // -0.0
+ CMPQ AX, R8
+ JEQ +3(PC)
+ MOVQ R8, ret+16(FP) // return 0
+ RET
+ MOVQ R9, ret+16(FP) // return other 0
+ RET
+
+// func archMin(x, y float64) float64
+TEXT ·archMin(SB),NOSPLIT,$0
+ // -Inf special cases
+ MOVQ $NegInf, AX
+ MOVQ x+0(FP), R8
+ CMPQ AX, R8
+ JEQ isNegInf
+ MOVQ y+8(FP), R9
+ CMPQ AX, R9
+ JEQ isNegInf
+ // NaN special cases
+ MOVQ $~(1<<63), DX
+ MOVQ $PosInf, AX
+ MOVQ R8, BX
+ ANDQ DX, BX // x = |x|
+ CMPQ AX, BX
+ JLT isMinNaN
+ MOVQ R9, CX
+ ANDQ DX, CX // y = |y|
+ CMPQ AX, CX
+ JLT isMinNaN
+ // ±0 special cases
+ ORQ CX, BX
+ JEQ isMinZero
+
+ MOVQ R8, X0
+ MOVQ R9, X1
+ MINSD X1, X0
+ MOVSD X0, ret+16(FP)
+ RET
+isMinNaN: // return NaN
+ MOVQ $NaN, AX
+isNegInf: // return -Inf
+ MOVQ AX, ret+16(FP)
+ RET
+isMinZero:
+ MOVQ $(1<<63), AX // -0.0
+ CMPQ AX, R8
+ JEQ +3(PC)
+ MOVQ R9, ret+16(FP) // return other 0
+ RET
+ MOVQ R8, ret+16(FP) // return -0
+ RET
+
diff --git a/platform/dbops/binaries/go/go/src/math/dim_arm64.s b/platform/dbops/binaries/go/go/src/math/dim_arm64.s
new file mode 100644
index 0000000000000000000000000000000000000000..f112003dc0f615a23e1ebecbb9ef946fa953e6e1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_arm64.s
@@ -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.
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NaN 0x7FF8000000000001
+#define NegInf 0xFFF0000000000000
+
+// func ·archMax(x, y float64) float64
+TEXT ·archMax(SB),NOSPLIT,$0
+ // +Inf special cases
+ MOVD $PosInf, R0
+ MOVD x+0(FP), R1
+ CMP R0, R1
+ BEQ isPosInf
+ MOVD y+8(FP), R2
+ CMP R0, R2
+ BEQ isPosInf
+ // normal case
+ FMOVD R1, F0
+ FMOVD R2, F1
+ FMAXD F0, F1, F0
+ FMOVD F0, ret+16(FP)
+ RET
+isPosInf: // return +Inf
+ MOVD R0, ret+16(FP)
+ RET
+
+// func archMin(x, y float64) float64
+TEXT ·archMin(SB),NOSPLIT,$0
+ // -Inf special cases
+ MOVD $NegInf, R0
+ MOVD x+0(FP), R1
+ CMP R0, R1
+ BEQ isNegInf
+ MOVD y+8(FP), R2
+ CMP R0, R2
+ BEQ isNegInf
+ // normal case
+ FMOVD R1, F0
+ FMOVD R2, F1
+ FMIND F0, F1, F0
+ FMOVD F0, ret+16(FP)
+ RET
+isNegInf: // return -Inf
+ MOVD R0, ret+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/dim_asm.go b/platform/dbops/binaries/go/go/src/math/dim_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..f4adbd0ae5e11cdea85a685efbed2aea0c9ce5fe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_asm.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.
+
+//go:build amd64 || arm64 || riscv64 || s390x
+
+package math
+
+const haveArchMax = true
+
+func archMax(x, y float64) float64
+
+const haveArchMin = true
+
+func archMin(x, y float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/dim_noasm.go b/platform/dbops/binaries/go/go/src/math/dim_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..5b9e06fed33d03ad6745ed9fcd0c2601129e8d66
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_noasm.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.
+
+//go:build !amd64 && !arm64 && !riscv64 && !s390x
+
+package math
+
+const haveArchMax = false
+
+func archMax(x, y float64) float64 {
+ panic("not implemented")
+}
+
+const haveArchMin = false
+
+func archMin(x, y float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/dim_riscv64.s b/platform/dbops/binaries/go/go/src/math/dim_riscv64.s
new file mode 100644
index 0000000000000000000000000000000000000000..5b2fd3d0633f47514e570c90797d7f7039f76c2b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_riscv64.s
@@ -0,0 +1,70 @@
+// 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.
+
+#include "textflag.h"
+
+// Values returned from an FCLASS instruction.
+#define NegInf 0x001
+#define PosInf 0x080
+#define NaN 0x200
+
+// func archMax(x, y float64) float64
+TEXT ·archMax(SB),NOSPLIT,$0
+ MOVD x+0(FP), F0
+ MOVD y+8(FP), F1
+ FCLASSD F0, X5
+ FCLASSD F1, X6
+
+ // +Inf special cases
+ MOV $PosInf, X7
+ BEQ X7, X5, isMaxX
+ BEQ X7, X6, isMaxY
+
+ // NaN special cases
+ MOV $NaN, X7
+ BEQ X7, X5, isMaxX
+ BEQ X7, X6, isMaxY
+
+ // normal case
+ FMAXD F0, F1, F0
+ MOVD F0, ret+16(FP)
+ RET
+
+isMaxX: // return x
+ MOVD F0, ret+16(FP)
+ RET
+
+isMaxY: // return y
+ MOVD F1, ret+16(FP)
+ RET
+
+// func archMin(x, y float64) float64
+TEXT ·archMin(SB),NOSPLIT,$0
+ MOVD x+0(FP), F0
+ MOVD y+8(FP), F1
+ FCLASSD F0, X5
+ FCLASSD F1, X6
+
+ // -Inf special cases
+ MOV $NegInf, X7
+ BEQ X7, X5, isMinX
+ BEQ X7, X6, isMinY
+
+ // NaN special cases
+ MOV $NaN, X7
+ BEQ X7, X5, isMinX
+ BEQ X7, X6, isMinY
+
+ // normal case
+ FMIND F0, F1, F0
+ MOVD F0, ret+16(FP)
+ RET
+
+isMinX: // return x
+ MOVD F0, ret+16(FP)
+ RET
+
+isMinY: // return y
+ MOVD F1, ret+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/dim_s390x.s b/platform/dbops/binaries/go/go/src/math/dim_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..12770261f2e78d325f770f7e5af7aaa6f049a76b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/dim_s390x.s
@@ -0,0 +1,96 @@
+// 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.
+
+// Based on dim_amd64.s
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NaN 0x7FF8000000000001
+#define NegInf 0xFFF0000000000000
+
+// func ·Max(x, y float64) float64
+TEXT ·archMax(SB),NOSPLIT,$0
+ // +Inf special cases
+ MOVD $PosInf, R4
+ MOVD x+0(FP), R8
+ CMPUBEQ R4, R8, isPosInf
+ MOVD y+8(FP), R9
+ CMPUBEQ R4, R9, isPosInf
+ // NaN special cases
+ MOVD $~(1<<63), R5 // bit mask
+ MOVD $PosInf, R4
+ MOVD R8, R2
+ AND R5, R2 // x = |x|
+ CMPUBLT R4, R2, isMaxNaN
+ MOVD R9, R3
+ AND R5, R3 // y = |y|
+ CMPUBLT R4, R3, isMaxNaN
+ // ±0 special cases
+ OR R3, R2
+ BEQ isMaxZero
+
+ FMOVD x+0(FP), F1
+ FMOVD y+8(FP), F2
+ FCMPU F2, F1
+ BGT +3(PC)
+ FMOVD F1, ret+16(FP)
+ RET
+ FMOVD F2, ret+16(FP)
+ RET
+isMaxNaN: // return NaN
+ MOVD $NaN, R4
+isPosInf: // return +Inf
+ MOVD R4, ret+16(FP)
+ RET
+isMaxZero:
+ MOVD $(1<<63), R4 // -0.0
+ CMPUBEQ R4, R8, +3(PC)
+ MOVD R8, ret+16(FP) // return 0
+ RET
+ MOVD R9, ret+16(FP) // return other 0
+ RET
+
+// func archMin(x, y float64) float64
+TEXT ·archMin(SB),NOSPLIT,$0
+ // -Inf special cases
+ MOVD $NegInf, R4
+ MOVD x+0(FP), R8
+ CMPUBEQ R4, R8, isNegInf
+ MOVD y+8(FP), R9
+ CMPUBEQ R4, R9, isNegInf
+ // NaN special cases
+ MOVD $~(1<<63), R5
+ MOVD $PosInf, R4
+ MOVD R8, R2
+ AND R5, R2 // x = |x|
+ CMPUBLT R4, R2, isMinNaN
+ MOVD R9, R3
+ AND R5, R3 // y = |y|
+ CMPUBLT R4, R3, isMinNaN
+ // ±0 special cases
+ OR R3, R2
+ BEQ isMinZero
+
+ FMOVD x+0(FP), F1
+ FMOVD y+8(FP), F2
+ FCMPU F2, F1
+ BLT +3(PC)
+ FMOVD F1, ret+16(FP)
+ RET
+ FMOVD F2, ret+16(FP)
+ RET
+isMinNaN: // return NaN
+ MOVD $NaN, R4
+isNegInf: // return -Inf
+ MOVD R4, ret+16(FP)
+ RET
+isMinZero:
+ MOVD $(1<<63), R4 // -0.0
+ CMPUBEQ R4, R8, +3(PC)
+ MOVD R9, ret+16(FP) // return other 0
+ RET
+ MOVD R8, ret+16(FP) // return -0
+ RET
+
diff --git a/platform/dbops/binaries/go/go/src/math/erf.go b/platform/dbops/binaries/go/go/src/math/erf.go
new file mode 100644
index 0000000000000000000000000000000000000000..ba00c7d03edc1101c4705cc6b79649b5c094e556
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/erf.go
@@ -0,0 +1,351 @@
+// 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 math
+
+/*
+ Floating-point error function and complementary error function.
+*/
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/s_erf.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// double erf(double x)
+// double erfc(double x)
+// x
+// 2 |\
+// erf(x) = --------- | exp(-t*t)dt
+// sqrt(pi) \|
+// 0
+//
+// erfc(x) = 1-erf(x)
+// Note that
+// erf(-x) = -erf(x)
+// erfc(-x) = 2 - erfc(x)
+//
+// Method:
+// 1. For |x| in [0, 0.84375]
+// erf(x) = x + x*R(x**2)
+// erfc(x) = 1 - erf(x) if x in [-.84375,0.25]
+// = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375]
+// where R = P/Q where P is an odd poly of degree 8 and
+// Q is an odd poly of degree 10.
+// -57.90
+// | R - (erf(x)-x)/x | <= 2
+//
+//
+// Remark. The formula is derived by noting
+// erf(x) = (2/sqrt(pi))*(x - x**3/3 + x**5/10 - x**7/42 + ....)
+// and that
+// 2/sqrt(pi) = 1.128379167095512573896158903121545171688
+// is close to one. The interval is chosen because the fix
+// point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is
+// near 0.6174), and by some experiment, 0.84375 is chosen to
+// guarantee the error is less than one ulp for erf.
+//
+// 2. For |x| in [0.84375,1.25], let s = |x| - 1, and
+// c = 0.84506291151 rounded to single (24 bits)
+// erf(x) = sign(x) * (c + P1(s)/Q1(s))
+// erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0
+// 1+(c+P1(s)/Q1(s)) if x < 0
+// |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06
+// Remark: here we use the taylor series expansion at x=1.
+// erf(1+s) = erf(1) + s*Poly(s)
+// = 0.845.. + P1(s)/Q1(s)
+// That is, we use rational approximation to approximate
+// erf(1+s) - (c = (single)0.84506291151)
+// Note that |P1/Q1|< 0.078 for x in [0.84375,1.25]
+// where
+// P1(s) = degree 6 poly in s
+// Q1(s) = degree 6 poly in s
+//
+// 3. For x in [1.25,1/0.35(~2.857143)],
+// erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1)
+// erf(x) = 1 - erfc(x)
+// where
+// R1(z) = degree 7 poly in z, (z=1/x**2)
+// S1(z) = degree 8 poly in z
+//
+// 4. For x in [1/0.35,28]
+// erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0
+// = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6 x >= 28
+// erf(x) = sign(x) *(1 - tiny) (raise inexact)
+// erfc(x) = tiny*tiny (raise underflow) if x > 0
+// = 2 - tiny if x<0
+//
+// 7. Special case:
+// erf(0) = 0, erf(inf) = 1, erf(-inf) = -1,
+// erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2,
+// erfc/erf(NaN) is NaN
+
+const (
+ erx = 8.45062911510467529297e-01 // 0x3FEB0AC160000000
+ // Coefficients for approximation to erf in [0, 0.84375]
+ efx = 1.28379167095512586316e-01 // 0x3FC06EBA8214DB69
+ efx8 = 1.02703333676410069053e+00 // 0x3FF06EBA8214DB69
+ pp0 = 1.28379167095512558561e-01 // 0x3FC06EBA8214DB68
+ pp1 = -3.25042107247001499370e-01 // 0xBFD4CD7D691CB913
+ pp2 = -2.84817495755985104766e-02 // 0xBF9D2A51DBD7194F
+ pp3 = -5.77027029648944159157e-03 // 0xBF77A291236668E4
+ pp4 = -2.37630166566501626084e-05 // 0xBEF8EAD6120016AC
+ qq1 = 3.97917223959155352819e-01 // 0x3FD97779CDDADC09
+ qq2 = 6.50222499887672944485e-02 // 0x3FB0A54C5536CEBA
+ qq3 = 5.08130628187576562776e-03 // 0x3F74D022C4D36B0F
+ qq4 = 1.32494738004321644526e-04 // 0x3F215DC9221C1A10
+ qq5 = -3.96022827877536812320e-06 // 0xBED09C4342A26120
+ // Coefficients for approximation to erf in [0.84375, 1.25]
+ pa0 = -2.36211856075265944077e-03 // 0xBF6359B8BEF77538
+ pa1 = 4.14856118683748331666e-01 // 0x3FDA8D00AD92B34D
+ pa2 = -3.72207876035701323847e-01 // 0xBFD7D240FBB8C3F1
+ pa3 = 3.18346619901161753674e-01 // 0x3FD45FCA805120E4
+ pa4 = -1.10894694282396677476e-01 // 0xBFBC63983D3E28EC
+ pa5 = 3.54783043256182359371e-02 // 0x3FA22A36599795EB
+ pa6 = -2.16637559486879084300e-03 // 0xBF61BF380A96073F
+ qa1 = 1.06420880400844228286e-01 // 0x3FBB3E6618EEE323
+ qa2 = 5.40397917702171048937e-01 // 0x3FE14AF092EB6F33
+ qa3 = 7.18286544141962662868e-02 // 0x3FB2635CD99FE9A7
+ qa4 = 1.26171219808761642112e-01 // 0x3FC02660E763351F
+ qa5 = 1.36370839120290507362e-02 // 0x3F8BEDC26B51DD1C
+ qa6 = 1.19844998467991074170e-02 // 0x3F888B545735151D
+ // Coefficients for approximation to erfc in [1.25, 1/0.35]
+ ra0 = -9.86494403484714822705e-03 // 0xBF843412600D6435
+ ra1 = -6.93858572707181764372e-01 // 0xBFE63416E4BA7360
+ ra2 = -1.05586262253232909814e+01 // 0xC0251E0441B0E726
+ ra3 = -6.23753324503260060396e+01 // 0xC04F300AE4CBA38D
+ ra4 = -1.62396669462573470355e+02 // 0xC0644CB184282266
+ ra5 = -1.84605092906711035994e+02 // 0xC067135CEBCCABB2
+ ra6 = -8.12874355063065934246e+01 // 0xC054526557E4D2F2
+ ra7 = -9.81432934416914548592e+00 // 0xC023A0EFC69AC25C
+ sa1 = 1.96512716674392571292e+01 // 0x4033A6B9BD707687
+ sa2 = 1.37657754143519042600e+02 // 0x4061350C526AE721
+ sa3 = 4.34565877475229228821e+02 // 0x407B290DD58A1A71
+ sa4 = 6.45387271733267880336e+02 // 0x40842B1921EC2868
+ sa5 = 4.29008140027567833386e+02 // 0x407AD02157700314
+ sa6 = 1.08635005541779435134e+02 // 0x405B28A3EE48AE2C
+ sa7 = 6.57024977031928170135e+00 // 0x401A47EF8E484A93
+ sa8 = -6.04244152148580987438e-02 // 0xBFAEEFF2EE749A62
+ // Coefficients for approximation to erfc in [1/.35, 28]
+ rb0 = -9.86494292470009928597e-03 // 0xBF84341239E86F4A
+ rb1 = -7.99283237680523006574e-01 // 0xBFE993BA70C285DE
+ rb2 = -1.77579549177547519889e+01 // 0xC031C209555F995A
+ rb3 = -1.60636384855821916062e+02 // 0xC064145D43C5ED98
+ rb4 = -6.37566443368389627722e+02 // 0xC083EC881375F228
+ rb5 = -1.02509513161107724954e+03 // 0xC09004616A2E5992
+ rb6 = -4.83519191608651397019e+02 // 0xC07E384E9BDC383F
+ sb1 = 3.03380607434824582924e+01 // 0x403E568B261D5190
+ sb2 = 3.25792512996573918826e+02 // 0x40745CAE221B9F0A
+ sb3 = 1.53672958608443695994e+03 // 0x409802EB189D5118
+ sb4 = 3.19985821950859553908e+03 // 0x40A8FFB7688C246A
+ sb5 = 2.55305040643316442583e+03 // 0x40A3F219CEDF3BE6
+ sb6 = 4.74528541206955367215e+02 // 0x407DA874E79FE763
+ sb7 = -2.24409524465858183362e+01 // 0xC03670E242712D62
+)
+
+// Erf returns the error function of x.
+//
+// Special cases are:
+//
+// Erf(+Inf) = 1
+// Erf(-Inf) = -1
+// Erf(NaN) = NaN
+func Erf(x float64) float64 {
+ if haveArchErf {
+ return archErf(x)
+ }
+ return erf(x)
+}
+
+func erf(x float64) float64 {
+ const (
+ VeryTiny = 2.848094538889218e-306 // 0x0080000000000000
+ Small = 1.0 / (1 << 28) // 2**-28
+ )
+ // special cases
+ switch {
+ case IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return 1
+ case IsInf(x, -1):
+ return -1
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ if x < 0.84375 { // |x| < 0.84375
+ var temp float64
+ if x < Small { // |x| < 2**-28
+ if x < VeryTiny {
+ temp = 0.125 * (8.0*x + efx8*x) // avoid underflow
+ } else {
+ temp = x + efx*x
+ }
+ } else {
+ z := x * x
+ r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4)))
+ s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))))
+ y := r / s
+ temp = x + x*y
+ }
+ if sign {
+ return -temp
+ }
+ return temp
+ }
+ if x < 1.25 { // 0.84375 <= |x| < 1.25
+ s := x - 1
+ P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))))
+ Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))))
+ if sign {
+ return -erx - P/Q
+ }
+ return erx + P/Q
+ }
+ if x >= 6 { // inf > |x| >= 6
+ if sign {
+ return -1
+ }
+ return 1
+ }
+ s := 1 / (x * x)
+ var R, S float64
+ if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143
+ R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))))
+ S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))))
+ } else { // |x| >= 1 / 0.35 ~ 2.857143
+ R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))))
+ S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))))
+ }
+ z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x
+ r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S)
+ if sign {
+ return r/x - 1
+ }
+ return 1 - r/x
+}
+
+// Erfc returns the complementary error function of x.
+//
+// Special cases are:
+//
+// Erfc(+Inf) = 0
+// Erfc(-Inf) = 2
+// Erfc(NaN) = NaN
+func Erfc(x float64) float64 {
+ if haveArchErfc {
+ return archErfc(x)
+ }
+ return erfc(x)
+}
+
+func erfc(x float64) float64 {
+ const Tiny = 1.0 / (1 << 56) // 2**-56
+ // special cases
+ switch {
+ case IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return 0
+ case IsInf(x, -1):
+ return 2
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ if x < 0.84375 { // |x| < 0.84375
+ var temp float64
+ if x < Tiny { // |x| < 2**-56
+ temp = x
+ } else {
+ z := x * x
+ r := pp0 + z*(pp1+z*(pp2+z*(pp3+z*pp4)))
+ s := 1 + z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))))
+ y := r / s
+ if x < 0.25 { // |x| < 1/4
+ temp = x + x*y
+ } else {
+ temp = 0.5 + (x*y + (x - 0.5))
+ }
+ }
+ if sign {
+ return 1 + temp
+ }
+ return 1 - temp
+ }
+ if x < 1.25 { // 0.84375 <= |x| < 1.25
+ s := x - 1
+ P := pa0 + s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))))
+ Q := 1 + s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))))
+ if sign {
+ return 1 + erx + P/Q
+ }
+ return 1 - erx - P/Q
+
+ }
+ if x < 28 { // |x| < 28
+ s := 1 / (x * x)
+ var R, S float64
+ if x < 1/0.35 { // |x| < 1 / 0.35 ~ 2.857143
+ R = ra0 + s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))))
+ S = 1 + s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))))
+ } else { // |x| >= 1 / 0.35 ~ 2.857143
+ if sign && x > 6 {
+ return 2 // x < -6
+ }
+ R = rb0 + s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))))
+ S = 1 + s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))))
+ }
+ z := Float64frombits(Float64bits(x) & 0xffffffff00000000) // pseudo-single (20-bit) precision x
+ r := Exp(-z*z-0.5625) * Exp((z-x)*(z+x)+R/S)
+ if sign {
+ return 2 - r/x
+ }
+ return r / x
+ }
+ if sign {
+ return 2
+ }
+ return 0
+}
diff --git a/platform/dbops/binaries/go/go/src/math/erf_s390x.s b/platform/dbops/binaries/go/go/src/math/erf_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..99ab436e0945147eb19fe8f444abe58ddea4eecf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/erf_s390x.s
@@ -0,0 +1,293 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA ·erfrodataL13<> + 0(SB)/8, $0.243673229298474689E+01
+DATA ·erfrodataL13<> + 8(SB)/8, $-.654905018503145600E+00
+DATA ·erfrodataL13<> + 16(SB)/8, $0.404669310217538718E+01
+DATA ·erfrodataL13<> + 24(SB)/8, $-.564189219162765367E+00
+DATA ·erfrodataL13<> + 32(SB)/8, $-.200104300906596851E+01
+DATA ·erfrodataL13<> + 40(SB)/8, $0.5
+DATA ·erfrodataL13<> + 48(SB)/8, $0.144070097650207154E+00
+DATA ·erfrodataL13<> + 56(SB)/8, $-.116697735205906191E+00
+DATA ·erfrodataL13<> + 64(SB)/8, $0.256847684882319665E-01
+DATA ·erfrodataL13<> + 72(SB)/8, $-.510805169106229148E-02
+DATA ·erfrodataL13<> + 80(SB)/8, $0.885258164825590267E-03
+DATA ·erfrodataL13<> + 88(SB)/8, $-.133861989591931411E-03
+DATA ·erfrodataL13<> + 96(SB)/8, $0.178294867340272534E-04
+DATA ·erfrodataL13<> + 104(SB)/8, $-.211436095674019218E-05
+DATA ·erfrodataL13<> + 112(SB)/8, $0.225503753499344434E-06
+DATA ·erfrodataL13<> + 120(SB)/8, $-.218247939190783624E-07
+DATA ·erfrodataL13<> + 128(SB)/8, $0.193179206264594029E-08
+DATA ·erfrodataL13<> + 136(SB)/8, $-.157440643541715319E-09
+DATA ·erfrodataL13<> + 144(SB)/8, $0.118878583237342616E-10
+DATA ·erfrodataL13<> + 152(SB)/8, $0.554289288424588473E-13
+DATA ·erfrodataL13<> + 160(SB)/8, $-.277649758489502214E-14
+DATA ·erfrodataL13<> + 168(SB)/8, $-.839318416990049443E-12
+DATA ·erfrodataL13<> + 176(SB)/8, $-2.25
+DATA ·erfrodataL13<> + 184(SB)/8, $.12837916709551258632
+DATA ·erfrodataL13<> + 192(SB)/8, $1.0
+DATA ·erfrodataL13<> + 200(SB)/8, $0.500000000000004237e+00
+DATA ·erfrodataL13<> + 208(SB)/8, $1.0
+DATA ·erfrodataL13<> + 216(SB)/8, $0.416666664838056960e-01
+DATA ·erfrodataL13<> + 224(SB)/8, $0.166666666630345592e+00
+DATA ·erfrodataL13<> + 232(SB)/8, $0.138926439368309441e-02
+DATA ·erfrodataL13<> + 240(SB)/8, $0.833349307718286047e-02
+DATA ·erfrodataL13<> + 248(SB)/8, $-.693147180559945286e+00
+DATA ·erfrodataL13<> + 256(SB)/8, $-.144269504088896339e+01
+DATA ·erfrodataL13<> + 264(SB)/8, $281475245147134.9375
+DATA ·erfrodataL13<> + 272(SB)/8, $0.358256136398192529E+01
+DATA ·erfrodataL13<> + 280(SB)/8, $-.554084396500738270E+00
+DATA ·erfrodataL13<> + 288(SB)/8, $0.203630123025312046E+02
+DATA ·erfrodataL13<> + 296(SB)/8, $-.735750304705934424E+01
+DATA ·erfrodataL13<> + 304(SB)/8, $0.250491598091071797E+02
+DATA ·erfrodataL13<> + 312(SB)/8, $-.118955882760959931E+02
+DATA ·erfrodataL13<> + 320(SB)/8, $0.942903335085524187E+01
+DATA ·erfrodataL13<> + 328(SB)/8, $-.564189522219085689E+00
+DATA ·erfrodataL13<> + 336(SB)/8, $-.503767199403555540E+01
+DATA ·erfrodataL13<> + 344(SB)/8, $0xbbc79ca10c924223
+DATA ·erfrodataL13<> + 352(SB)/8, $0.004099975562609307E+01
+DATA ·erfrodataL13<> + 360(SB)/8, $-.324434353381296556E+00
+DATA ·erfrodataL13<> + 368(SB)/8, $0.945204812084476250E-01
+DATA ·erfrodataL13<> + 376(SB)/8, $-.221407443830058214E-01
+DATA ·erfrodataL13<> + 384(SB)/8, $0.426072376238804349E-02
+DATA ·erfrodataL13<> + 392(SB)/8, $-.692229229127016977E-03
+DATA ·erfrodataL13<> + 400(SB)/8, $0.971111253652087188E-04
+DATA ·erfrodataL13<> + 408(SB)/8, $-.119752226272050504E-04
+DATA ·erfrodataL13<> + 416(SB)/8, $0.131662993588532278E-05
+DATA ·erfrodataL13<> + 424(SB)/8, $0.115776482315851236E-07
+DATA ·erfrodataL13<> + 432(SB)/8, $-.780118522218151687E-09
+DATA ·erfrodataL13<> + 440(SB)/8, $-.130465975877241088E-06
+DATA ·erfrodataL13<> + 448(SB)/8, $-0.25
+GLOBL ·erfrodataL13<> + 0(SB), RODATA, $456
+
+// Table of log correction terms
+DATA ·erftab2066<> + 0(SB)/8, $0.442737824274138381e-01
+DATA ·erftab2066<> + 8(SB)/8, $0.263602189790660309e-01
+DATA ·erftab2066<> + 16(SB)/8, $0.122565642281703586e-01
+DATA ·erftab2066<> + 24(SB)/8, $0.143757052860721398e-02
+DATA ·erftab2066<> + 32(SB)/8, $-.651375034121276075e-02
+DATA ·erftab2066<> + 40(SB)/8, $-.119317678849450159e-01
+DATA ·erftab2066<> + 48(SB)/8, $-.150868749549871069e-01
+DATA ·erftab2066<> + 56(SB)/8, $-.161992609578469234e-01
+DATA ·erftab2066<> + 64(SB)/8, $-.154492360403337917e-01
+DATA ·erftab2066<> + 72(SB)/8, $-.129850717389178721e-01
+DATA ·erftab2066<> + 80(SB)/8, $-.892902649276657891e-02
+DATA ·erftab2066<> + 88(SB)/8, $-.338202636596794887e-02
+DATA ·erftab2066<> + 96(SB)/8, $0.357266307045684762e-02
+DATA ·erftab2066<> + 104(SB)/8, $0.118665304327406698e-01
+DATA ·erftab2066<> + 112(SB)/8, $0.214434994118118914e-01
+DATA ·erftab2066<> + 120(SB)/8, $0.322580645161290314e-01
+GLOBL ·erftab2066<> + 0(SB), RODATA, $128
+
+// Table of +/- 1.0
+DATA ·erftab12067<> + 0(SB)/8, $1.0
+DATA ·erftab12067<> + 8(SB)/8, $-1.0
+GLOBL ·erftab12067<> + 0(SB), RODATA, $16
+
+// Erf returns the error function of the argument.
+//
+// Special cases are:
+// Erf(+Inf) = 1
+// Erf(-Inf) = -1
+// Erf(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·erfAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·erfrodataL13<>+0(SB), R5
+ LGDR F0, R1
+ FMOVD F0, F6
+ SRAD $48, R1
+ MOVH $16383, R3
+ RISBGZ $49, $63, $0, R1, R2
+ MOVW R2, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L2
+ MOVH $12287, R1
+ MOVW R1, R7
+ CMPBLE R6, R7 ,L12
+ MOVH $16367, R1
+ MOVW R1, R7
+ CMPBGT R6, R7, L5
+ FMOVD 448(R5), F4
+ FMADD F0, F0, F4
+ FMOVD 440(R5), F3
+ WFMDB V4, V4, V2
+ FMOVD 432(R5), F0
+ FMOVD 424(R5), F1
+ WFMADB V2, V0, V3, V0
+ FMOVD 416(R5), F3
+ WFMADB V2, V1, V3, V1
+ FMOVD 408(R5), F5
+ FMOVD 400(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V1, V3, V1
+ FMOVD 392(R5), F5
+ FMOVD 384(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V1, V3, V1
+ FMOVD 376(R5), F5
+ FMOVD 368(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V1, V3, V1
+ FMOVD 360(R5), F5
+ FMOVD 352(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V1, V3, V2
+ WFMADB V4, V0, V2, V0
+ WFMADB V6, V0, V6, V0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+L2:
+ MOVH R1, R1
+ MOVH $16407, R3
+ SRW $31, R1, R1
+ MOVW R2, R6
+ MOVW R3, R7
+ CMPBLE R6, R7, L6
+ MOVW R1, R1
+ SLD $3, R1, R1
+ MOVD $·erftab12067<>+0(SB), R3
+ WORD $0x68013000 //ld %f0,0(%r1,%r3)
+ MOVH $32751, R1
+ MOVW R1, R7
+ CMPBGT R6, R7, L7
+ FMOVD 344(R5), F2
+ FMADD F2, F0, F0
+L7:
+ WFCEDBS V6, V6, V2
+ BEQ L1
+ FMOVD F6, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L6:
+ MOVW R1, R1
+ SLD $3, R1, R1
+ MOVD $·erftab12067<>+0(SB), R4
+ WFMDB V0, V0, V1
+ MOVH $0x0, R3
+ WORD $0x68014000 //ld %f0,0(%r1,%r4)
+ MOVH $16399, R1
+ MOVW R2, R6
+ MOVW R1, R7
+ CMPBGT R6, R7, L8
+ FMOVD 336(R5), F3
+ FMOVD 328(R5), F2
+ FMOVD F1, F4
+ WFMADB V1, V2, V3, V2
+ WORD $0xED405140 //adb %f4,.L30-.L13(%r5)
+ BYTE $0x00
+ BYTE $0x1A
+ FMOVD 312(R5), F3
+ WFMADB V1, V2, V3, V2
+ FMOVD 304(R5), F3
+ WFMADB V1, V4, V3, V4
+ FMOVD 296(R5), F3
+ WFMADB V1, V2, V3, V2
+ FMOVD 288(R5), F3
+ WFMADB V1, V4, V3, V4
+ FMOVD 280(R5), F3
+ WFMADB V1, V2, V3, V2
+ FMOVD 272(R5), F3
+ WFMADB V1, V4, V3, V4
+L9:
+ FMOVD 264(R5), F3
+ FMUL F4, F6
+ FMOVD 256(R5), F4
+ WFMADB V1, V4, V3, V4
+ FDIV F6, F2
+ LGDR F4, R1
+ FSUB F3, F4
+ FMOVD 248(R5), F6
+ WFMSDB V4, V6, V1, V4
+ FMOVD 240(R5), F1
+ FMOVD 232(R5), F6
+ WFMADB V4, V6, V1, V6
+ FMOVD 224(R5), F1
+ FMOVD 216(R5), F3
+ WFMADB V4, V3, V1, V3
+ WFMDB V4, V4, V1
+ FMOVD 208(R5), F5
+ WFMADB V6, V1, V3, V6
+ FMOVD 200(R5), F3
+ MOVH R1,R1
+ WFMADB V4, V3, V5, V3
+ RISBGZ $57, $60, $3, R1, R2
+ WFMADB V1, V6, V3, V6
+ RISBGN $0, $15, $48, R1, R3
+ MOVD $·erftab2066<>+0(SB), R1
+ FMOVD 192(R5), F1
+ LDGR R3, F3
+ WORD $0xED221000 //madb %f2,%f2,0(%r2,%r1)
+ BYTE $0x20
+ BYTE $0x1E
+ WFMADB V4, V6, V1, V4
+ FMUL F3, F2
+ FMADD F4, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L12:
+ FMOVD 184(R5), F0
+ WFMADB V6, V0, V6, V0
+ FMOVD F0, ret+8(FP)
+ RET
+L5:
+ FMOVD 176(R5), F1
+ FMADD F0, F0, F1
+ FMOVD 168(R5), F3
+ WFMDB V1, V1, V2
+ FMOVD 160(R5), F0
+ FMOVD 152(R5), F4
+ WFMADB V2, V0, V3, V0
+ FMOVD 144(R5), F3
+ WFMADB V2, V4, V3, V4
+ FMOVD 136(R5), F5
+ FMOVD 128(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V4
+ FMOVD 120(R5), F5
+ FMOVD 112(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V4
+ FMOVD 104(R5), F5
+ FMOVD 96(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V4
+ FMOVD 88(R5), F5
+ FMOVD 80(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V4
+ FMOVD 72(R5), F5
+ FMOVD 64(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V4
+ FMOVD 56(R5), F5
+ FMOVD 48(R5), F3
+ WFMADB V2, V0, V5, V0
+ WFMADB V2, V4, V3, V2
+ FMOVD 40(R5), F4
+ WFMADB V1, V0, V2, V0
+ FMUL F6, F0
+ FMADD F4, F6, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L8:
+ FMOVD 32(R5), F3
+ FMOVD 24(R5), F2
+ FMOVD F1, F4
+ WFMADB V1, V2, V3, V2
+ WORD $0xED405010 //adb %f4,.L68-.L13(%r5)
+ BYTE $0x00
+ BYTE $0x1A
+ FMOVD 8(R5), F3
+ WFMADB V1, V2, V3, V2
+ FMOVD ·erfrodataL13<>+0(SB), F3
+ WFMADB V1, V4, V3, V4
+ BR L9
diff --git a/platform/dbops/binaries/go/go/src/math/erfc_s390x.s b/platform/dbops/binaries/go/go/src/math/erfc_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..7e9d469cc6e0d2d81fa32186772f8a8ba7acb930
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/erfc_s390x.s
@@ -0,0 +1,527 @@
+// 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.
+
+#include "textflag.h"
+
+#define Neg2p11 0xC000E147AE147AE1
+#define Pos15 0x402E
+
+// Minimax polynomial coefficients and other constants
+DATA ·erfcrodataL38<> + 0(SB)/8, $.234875460637085087E-01
+DATA ·erfcrodataL38<> + 8(SB)/8, $.234469449299256284E-01
+DATA ·erfcrodataL38<> + 16(SB)/8, $-.606918710392844955E-04
+DATA ·erfcrodataL38<> + 24(SB)/8, $-.198827088077636213E-04
+DATA ·erfcrodataL38<> + 32(SB)/8, $.257805645845475331E-06
+DATA ·erfcrodataL38<> + 40(SB)/8, $-.184427218110620284E-09
+DATA ·erfcrodataL38<> + 48(SB)/8, $.122408098288933181E-10
+DATA ·erfcrodataL38<> + 56(SB)/8, $.484691106751495392E-07
+DATA ·erfcrodataL38<> + 64(SB)/8, $-.150147637632890281E-08
+DATA ·erfcrodataL38<> + 72(SB)/8, $23.999999999973521625
+DATA ·erfcrodataL38<> + 80(SB)/8, $27.226017111108365754
+DATA ·erfcrodataL38<> + 88(SB)/8, $-2.0
+DATA ·erfcrodataL38<> + 96(SB)/8, $0.100108802034478228E+00
+DATA ·erfcrodataL38<> + 104(SB)/8, $0.244588413746558125E+00
+DATA ·erfcrodataL38<> + 112(SB)/8, $-.669188879646637174E-01
+DATA ·erfcrodataL38<> + 120(SB)/8, $0.151311447000953551E-01
+DATA ·erfcrodataL38<> + 128(SB)/8, $-.284720833493302061E-02
+DATA ·erfcrodataL38<> + 136(SB)/8, $0.455491239358743212E-03
+DATA ·erfcrodataL38<> + 144(SB)/8, $-.631850539280720949E-04
+DATA ·erfcrodataL38<> + 152(SB)/8, $0.772532660726086679E-05
+DATA ·erfcrodataL38<> + 160(SB)/8, $-.843706007150936940E-06
+DATA ·erfcrodataL38<> + 168(SB)/8, $-.735330214904227472E-08
+DATA ·erfcrodataL38<> + 176(SB)/8, $0.753002008837084967E-09
+DATA ·erfcrodataL38<> + 184(SB)/8, $0.832482036660624637E-07
+DATA ·erfcrodataL38<> + 192(SB)/8, $-0.75
+DATA ·erfcrodataL38<> + 200(SB)/8, $.927765678007128609E-01
+DATA ·erfcrodataL38<> + 208(SB)/8, $.903621209344751506E-01
+DATA ·erfcrodataL38<> + 216(SB)/8, $-.344203375025257265E-02
+DATA ·erfcrodataL38<> + 224(SB)/8, $-.869243428221791329E-03
+DATA ·erfcrodataL38<> + 232(SB)/8, $.174699813107105603E-03
+DATA ·erfcrodataL38<> + 240(SB)/8, $.649481036316130000E-05
+DATA ·erfcrodataL38<> + 248(SB)/8, $-.895265844897118382E-05
+DATA ·erfcrodataL38<> + 256(SB)/8, $.135970046909529513E-05
+DATA ·erfcrodataL38<> + 264(SB)/8, $.277617717014748015E-06
+DATA ·erfcrodataL38<> + 272(SB)/8, $.810628018408232910E-08
+DATA ·erfcrodataL38<> + 280(SB)/8, $.210430084693497985E-07
+DATA ·erfcrodataL38<> + 288(SB)/8, $-.342138077525615091E-08
+DATA ·erfcrodataL38<> + 296(SB)/8, $-.165467946798610800E-06
+DATA ·erfcrodataL38<> + 304(SB)/8, $5.999999999988412824
+DATA ·erfcrodataL38<> + 312(SB)/8, $.468542210149072159E-01
+DATA ·erfcrodataL38<> + 320(SB)/8, $.465343528567604256E-01
+DATA ·erfcrodataL38<> + 328(SB)/8, $-.473338083650201733E-03
+DATA ·erfcrodataL38<> + 336(SB)/8, $-.147220659069079156E-03
+DATA ·erfcrodataL38<> + 344(SB)/8, $.755284723554388339E-05
+DATA ·erfcrodataL38<> + 352(SB)/8, $.116158570631428789E-05
+DATA ·erfcrodataL38<> + 360(SB)/8, $-.155445501551602389E-06
+DATA ·erfcrodataL38<> + 368(SB)/8, $-.616940119847805046E-10
+DATA ·erfcrodataL38<> + 376(SB)/8, $-.728705590727563158E-10
+DATA ·erfcrodataL38<> + 384(SB)/8, $-.983452460354586779E-08
+DATA ·erfcrodataL38<> + 392(SB)/8, $.365156164194346316E-08
+DATA ·erfcrodataL38<> + 400(SB)/8, $11.999999999996530775
+DATA ·erfcrodataL38<> + 408(SB)/8, $0.467773498104726584E-02
+DATA ·erfcrodataL38<> + 416(SB)/8, $0.206669853540920535E-01
+DATA ·erfcrodataL38<> + 424(SB)/8, $0.413339707081841473E-01
+DATA ·erfcrodataL38<> + 432(SB)/8, $0.482229658262131320E-01
+DATA ·erfcrodataL38<> + 440(SB)/8, $0.344449755901841897E-01
+DATA ·erfcrodataL38<> + 448(SB)/8, $0.130890907240765465E-01
+DATA ·erfcrodataL38<> + 456(SB)/8, $-.459266344100642687E-03
+DATA ·erfcrodataL38<> + 464(SB)/8, $-.337888800856913728E-02
+DATA ·erfcrodataL38<> + 472(SB)/8, $-.159103061687062373E-02
+DATA ·erfcrodataL38<> + 480(SB)/8, $-.501128905515922644E-04
+DATA ·erfcrodataL38<> + 488(SB)/8, $0.262775855852903132E-03
+DATA ·erfcrodataL38<> + 496(SB)/8, $0.103860982197462436E-03
+DATA ·erfcrodataL38<> + 504(SB)/8, $-.548835785414200775E-05
+DATA ·erfcrodataL38<> + 512(SB)/8, $-.157075054646618214E-04
+DATA ·erfcrodataL38<> + 520(SB)/8, $-.480056366276045110E-05
+DATA ·erfcrodataL38<> + 528(SB)/8, $0.198263013759701555E-05
+DATA ·erfcrodataL38<> + 536(SB)/8, $-.224394262958888780E-06
+DATA ·erfcrodataL38<> + 544(SB)/8, $-.321853693146683428E-06
+DATA ·erfcrodataL38<> + 552(SB)/8, $0.445073894984683537E-07
+DATA ·erfcrodataL38<> + 560(SB)/8, $0.660425940000555729E-06
+DATA ·erfcrodataL38<> + 568(SB)/8, $2.0
+DATA ·erfcrodataL38<> + 576(SB)/8, $8.63616855509444462538e-78
+DATA ·erfcrodataL38<> + 584(SB)/8, $1.00000000000000222044
+DATA ·erfcrodataL38<> + 592(SB)/8, $0.500000000000004237e+00
+DATA ·erfcrodataL38<> + 600(SB)/8, $0.416666664838056960e-01
+DATA ·erfcrodataL38<> + 608(SB)/8, $0.166666666630345592e+00
+DATA ·erfcrodataL38<> + 616(SB)/8, $0.138926439368309441e-02
+DATA ·erfcrodataL38<> + 624(SB)/8, $0.833349307718286047e-02
+DATA ·erfcrodataL38<> + 632(SB)/8, $-.693147180558298714e+00
+DATA ·erfcrodataL38<> + 640(SB)/8, $-.164659495826017651e-11
+DATA ·erfcrodataL38<> + 648(SB)/8, $.179001151181866548E+00
+DATA ·erfcrodataL38<> + 656(SB)/8, $-.144269504088896339e+01
+DATA ·erfcrodataL38<> + 664(SB)/8, $+281475245147134.9375
+DATA ·erfcrodataL38<> + 672(SB)/8, $.163116780021877404E+00
+DATA ·erfcrodataL38<> + 680(SB)/8, $-.201574395828120710E-01
+DATA ·erfcrodataL38<> + 688(SB)/8, $-.185726336009394125E-02
+DATA ·erfcrodataL38<> + 696(SB)/8, $.199349204957273749E-02
+DATA ·erfcrodataL38<> + 704(SB)/8, $-.554902415532606242E-03
+DATA ·erfcrodataL38<> + 712(SB)/8, $-.638914789660242846E-05
+DATA ·erfcrodataL38<> + 720(SB)/8, $-.424441522653742898E-04
+DATA ·erfcrodataL38<> + 728(SB)/8, $.827967511921486190E-04
+DATA ·erfcrodataL38<> + 736(SB)/8, $.913965446284062654E-05
+DATA ·erfcrodataL38<> + 744(SB)/8, $.277344791076320853E-05
+DATA ·erfcrodataL38<> + 752(SB)/8, $-.467239678927239526E-06
+DATA ·erfcrodataL38<> + 760(SB)/8, $.344814065920419986E-07
+DATA ·erfcrodataL38<> + 768(SB)/8, $-.366013491552527132E-05
+DATA ·erfcrodataL38<> + 776(SB)/8, $.181242810023783439E-05
+DATA ·erfcrodataL38<> + 784(SB)/8, $2.999999999991234567
+DATA ·erfcrodataL38<> + 792(SB)/8, $1.0
+GLOBL ·erfcrodataL38<> + 0(SB), RODATA, $800
+
+// Table of log correction terms
+DATA ·erfctab2069<> + 0(SB)/8, $0.442737824274138381e-01
+DATA ·erfctab2069<> + 8(SB)/8, $0.263602189790660309e-01
+DATA ·erfctab2069<> + 16(SB)/8, $0.122565642281703586e-01
+DATA ·erfctab2069<> + 24(SB)/8, $0.143757052860721398e-02
+DATA ·erfctab2069<> + 32(SB)/8, $-.651375034121276075e-02
+DATA ·erfctab2069<> + 40(SB)/8, $-.119317678849450159e-01
+DATA ·erfctab2069<> + 48(SB)/8, $-.150868749549871069e-01
+DATA ·erfctab2069<> + 56(SB)/8, $-.161992609578469234e-01
+DATA ·erfctab2069<> + 64(SB)/8, $-.154492360403337917e-01
+DATA ·erfctab2069<> + 72(SB)/8, $-.129850717389178721e-01
+DATA ·erfctab2069<> + 80(SB)/8, $-.892902649276657891e-02
+DATA ·erfctab2069<> + 88(SB)/8, $-.338202636596794887e-02
+DATA ·erfctab2069<> + 96(SB)/8, $0.357266307045684762e-02
+DATA ·erfctab2069<> + 104(SB)/8, $0.118665304327406698e-01
+DATA ·erfctab2069<> + 112(SB)/8, $0.214434994118118914e-01
+DATA ·erfctab2069<> + 120(SB)/8, $0.322580645161290314e-01
+GLOBL ·erfctab2069<> + 0(SB), RODATA, $128
+
+// Erfc returns the complementary error function of the argument.
+//
+// Special cases are:
+// Erfc(+Inf) = 0
+// Erfc(-Inf) = 2
+// Erfc(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+// This assembly implementation handles inputs in the range [-2.11, +15].
+// For all other inputs we call the generic Go implementation.
+
+TEXT ·erfcAsm(SB), NOSPLIT|NOFRAME, $0-16
+ MOVD x+0(FP), R1
+ MOVD $Neg2p11, R2
+ CMPUBGT R1, R2, usego
+
+ FMOVD x+0(FP), F0
+ MOVD $·erfcrodataL38<>+0(SB), R9
+ FMOVD F0, F2
+ SRAD $48, R1
+ MOVH R1, R2
+ ANDW $0x7FFF, R1
+ MOVH $Pos15, R3
+ CMPW R1, R3
+ BGT usego
+ MOVH $0x3FFF, R3
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L2
+ MOVH $0x3FEF, R3
+ MOVW R3, R7
+ CMPBGT R6, R7, L3
+ MOVH $0x2FFF, R2
+ MOVW R2, R7
+ CMPBGT R6, R7, L4
+ FMOVD 792(R9), F0
+ WFSDB V2, V0, V2
+ FMOVD F2, ret+8(FP)
+ RET
+
+L2:
+ LTDBR F0, F0
+ MOVH $0x0, R4
+ BLTU L3
+ FMOVD F0, F1
+L9:
+ MOVH $0x400F, R3
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L10
+ FMOVD 784(R9), F3
+ FSUB F1, F3
+ VLEG $0, 776(R9), V20
+ WFDDB V1, V3, V6
+ VLEG $0, 768(R9), V18
+ FMOVD 760(R9), F7
+ FMOVD 752(R9), F5
+ VLEG $0, 744(R9), V16
+ FMOVD 736(R9), F3
+ FMOVD 728(R9), F2
+ FMOVD 720(R9), F4
+ WFMDB V6, V6, V1
+ FMUL F0, F0
+ MOVH $0x0, R3
+ WFMADB V1, V7, V20, V7
+ WFMADB V1, V5, V18, V5
+ WFMADB V1, V7, V16, V7
+ WFMADB V1, V5, V3, V5
+ WFMADB V1, V7, V4, V7
+ WFMADB V1, V5, V2, V5
+ FMOVD 712(R9), F2
+ WFMADB V1, V7, V2, V7
+ FMOVD 704(R9), F2
+ WFMADB V1, V5, V2, V5
+ FMOVD 696(R9), F2
+ WFMADB V1, V7, V2, V7
+ FMOVD 688(R9), F2
+ MOVH $0x0, R1
+ WFMADB V1, V5, V2, V5
+ FMOVD 680(R9), F2
+ WFMADB V1, V7, V2, V7
+ FMOVD 672(R9), F2
+ WFMADB V1, V5, V2, V1
+ FMOVD 664(R9), F3
+ WFMADB V6, V7, V1, V7
+ FMOVD 656(R9), F5
+ FMOVD 648(R9), F2
+ WFMADB V0, V5, V3, V5
+ WFMADB V6, V7, V2, V7
+L11:
+ LGDR F5, R6
+ WFSDB V0, V0, V2
+ WORD $0xED509298 //sdb %f5,.L55-.L38(%r9)
+ BYTE $0x00
+ BYTE $0x1B
+ FMOVD 640(R9), F6
+ FMOVD 632(R9), F4
+ WFMSDB V5, V6, V2, V6
+ WFMSDB V5, V4, V0, V4
+ FMOVD 624(R9), F2
+ FADD F6, F4
+ FMOVD 616(R9), F0
+ FMOVD 608(R9), F6
+ WFMADB V4, V0, V2, V0
+ FMOVD 600(R9), F3
+ WFMDB V4, V4, V2
+ MOVH R6,R6
+ ADD R6, R3
+ WFMADB V4, V3, V6, V3
+ FMOVD 592(R9), F6
+ WFMADB V0, V2, V3, V0
+ FMOVD 584(R9), F3
+ WFMADB V4, V6, V3, V6
+ RISBGZ $57, $60, $3, R3, R12
+ WFMADB V2, V0, V6, V0
+ MOVD $·erfctab2069<>+0(SB), R5
+ WORD $0x682C5000 //ld %f2,0(%r12,%r5)
+ FMADD F2, F4, F4
+ RISBGN $0, $15, $48, R3, R4
+ WFMADB V4, V0, V2, V4
+ LDGR R4, F2
+ FMADD F4, F2, F2
+ MOVW R2, R6
+ CMPBLE R6, $0, L20
+ MOVW R1, R6
+ CMPBEQ R6, $0, L21
+ WORD $0xED709240 //mdb %f7,.L66-.L38(%r9)
+ BYTE $0x00
+ BYTE $0x1C
+L21:
+ FMUL F7, F2
+L1:
+ FMOVD F2, ret+8(FP)
+ RET
+L3:
+ LTDBR F0, F0
+ BLTU L30
+ FMOVD 568(R9), F2
+ WFSDB V0, V2, V0
+L8:
+ WFMDB V0, V0, V4
+ FMOVD 560(R9), F2
+ FMOVD 552(R9), F6
+ FMOVD 544(R9), F1
+ WFMADB V4, V6, V2, V6
+ FMOVD 536(R9), F2
+ WFMADB V4, V1, V2, V1
+ FMOVD 528(R9), F3
+ FMOVD 520(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 512(R9), F3
+ FMOVD 504(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 496(R9), F3
+ FMOVD 488(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 480(R9), F3
+ FMOVD 472(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 464(R9), F3
+ FMOVD 456(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 448(R9), F3
+ FMOVD 440(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 432(R9), F3
+ FMOVD 424(R9), F2
+ WFMADB V4, V6, V3, V6
+ WFMADB V4, V1, V2, V1
+ FMOVD 416(R9), F3
+ FMOVD 408(R9), F2
+ WFMADB V4, V6, V3, V6
+ FMADD F1, F4, F2
+ FMADD F6, F0, F2
+ MOVW R2, R6
+ CMPBGE R6, $0, L1
+ FMOVD 568(R9), F0
+ WFSDB V2, V0, V2
+ BR L1
+L10:
+ MOVH $0x401F, R3
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBLE R6, R7, L36
+ MOVH $0x402F, R3
+ MOVW R3, R7
+ CMPBGT R6, R7, L13
+ FMOVD 400(R9), F3
+ FSUB F1, F3
+ VLEG $0, 392(R9), V20
+ WFDDB V1, V3, V6
+ VLEG $0, 384(R9), V18
+ FMOVD 376(R9), F2
+ FMOVD 368(R9), F4
+ VLEG $0, 360(R9), V16
+ FMOVD 352(R9), F7
+ FMOVD 344(R9), F3
+ FMUL F0, F0
+ WFMDB V6, V6, V1
+ FMOVD 656(R9), F5
+ MOVH $0x0, R3
+ WFMADB V1, V2, V20, V2
+ WFMADB V1, V4, V18, V4
+ WFMADB V1, V2, V16, V2
+ WFMADB V1, V4, V7, V4
+ WFMADB V1, V2, V3, V2
+ FMOVD 336(R9), F3
+ WFMADB V1, V4, V3, V4
+ FMOVD 328(R9), F3
+ WFMADB V1, V2, V3, V2
+ FMOVD 320(R9), F3
+ WFMADB V1, V4, V3, V1
+ FMOVD 312(R9), F7
+ WFMADB V6, V2, V1, V2
+ MOVH $0x0, R1
+ FMOVD 664(R9), F3
+ FMADD F2, F6, F7
+ WFMADB V0, V5, V3, V5
+ BR L11
+L35:
+ WORD $0xB3130010 //lcdbr %f1,%f0
+ BR L9
+L36:
+ FMOVD 304(R9), F3
+ FSUB F1, F3
+ VLEG $0, 296(R9), V20
+ WFDDB V1, V3, V6
+ FMOVD 288(R9), F5
+ FMOVD 280(R9), F1
+ FMOVD 272(R9), F2
+ VLEG $0, 264(R9), V18
+ VLEG $0, 256(R9), V16
+ FMOVD 248(R9), F3
+ FMOVD 240(R9), F4
+ WFMDB V6, V6, V7
+ FMUL F0, F0
+ MOVH $0x0, R3
+ FMADD F5, F7, F1
+ WFMADB V7, V2, V20, V2
+ WFMADB V7, V1, V18, V1
+ WFMADB V7, V2, V16, V2
+ WFMADB V7, V1, V3, V1
+ WFMADB V7, V2, V4, V2
+ FMOVD 232(R9), F4
+ WFMADB V7, V1, V4, V1
+ FMOVD 224(R9), F4
+ WFMADB V7, V2, V4, V2
+ FMOVD 216(R9), F4
+ WFMADB V7, V1, V4, V1
+ FMOVD 208(R9), F4
+ MOVH $0x0, R1
+ WFMADB V7, V2, V4, V7
+ FMOVD 656(R9), F5
+ WFMADB V6, V1, V7, V1
+ FMOVD 664(R9), F3
+ FMOVD 200(R9), F7
+ WFMADB V0, V5, V3, V5
+ FMADD F1, F6, F7
+ BR L11
+L4:
+ FMOVD 192(R9), F1
+ FMADD F0, F0, F1
+ FMOVD 184(R9), F3
+ WFMDB V1, V1, V0
+ FMOVD 176(R9), F4
+ FMOVD 168(R9), F6
+ WFMADB V0, V4, V3, V4
+ FMOVD 160(R9), F3
+ WFMADB V0, V6, V3, V6
+ FMOVD 152(R9), F5
+ FMOVD 144(R9), F3
+ WFMADB V0, V4, V5, V4
+ WFMADB V0, V6, V3, V6
+ FMOVD 136(R9), F5
+ FMOVD 128(R9), F3
+ WFMADB V0, V4, V5, V4
+ WFMADB V0, V6, V3, V6
+ FMOVD 120(R9), F5
+ FMOVD 112(R9), F3
+ WFMADB V0, V4, V5, V4
+ WFMADB V0, V6, V3, V6
+ FMOVD 104(R9), F5
+ FMOVD 96(R9), F3
+ WFMADB V0, V4, V5, V4
+ WFMADB V0, V6, V3, V0
+ FMOVD F2, F6
+ FMADD F4, F1, F0
+ WORD $0xED609318 //sdb %f6,.L39-.L38(%r9)
+ BYTE $0x00
+ BYTE $0x1B
+ WFMSDB V2, V0, V6, V2
+ FMOVD F2, ret+8(FP)
+ RET
+L30:
+ WORD $0xED009238 //adb %f0,.L67-.L38(%r9)
+ BYTE $0x00
+ BYTE $0x1A
+ BR L8
+L20:
+ FMOVD 88(R9), F0
+ WFMADB V7, V2, V0, V2
+ WORD $0xB3130022 //lcdbr %f2,%f2
+ FMOVD F2, ret+8(FP)
+ RET
+L13:
+ MOVH $0x403A, R3
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBLE R6, R7, L4
+ WORD $0xED109050 //cdb %f1,.L128-.L38(%r9)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L37
+ BVS L37
+ FMOVD 72(R9), F6
+ FSUB F1, F6
+ MOVH $0x1000, R3
+ FDIV F1, F6
+ MOVH $0x1000, R1
+L17:
+ WFMDB V6, V6, V1
+ FMOVD 64(R9), F2
+ FMOVD 56(R9), F4
+ FMOVD 48(R9), F3
+ WFMADB V1, V3, V2, V3
+ FMOVD 40(R9), F2
+ WFMADB V1, V2, V4, V2
+ FMOVD 32(R9), F4
+ WFMADB V1, V3, V4, V3
+ FMOVD 24(R9), F4
+ WFMADB V1, V2, V4, V2
+ FMOVD 16(R9), F4
+ WFMADB V1, V3, V4, V3
+ FMOVD 8(R9), F4
+ WFMADB V1, V2, V4, V1
+ FMUL F0, F0
+ WFMADB V3, V6, V1, V3
+ FMOVD 656(R9), F5
+ FMOVD 664(R9), F4
+ FMOVD 0(R9), F7
+ WFMADB V0, V5, V4, V5
+ FMADD F6, F3, F7
+ BR L11
+L14:
+ FMOVD 72(R9), F6
+ FSUB F1, F6
+ MOVH $0x403A, R3
+ FDIV F1, F6
+ MOVW R1, R6
+ MOVW R3, R7
+ CMPBEQ R6, R7, L23
+ MOVH $0x0, R3
+ MOVH $0x0, R1
+ BR L17
+L37:
+ WFCEDBS V0, V0, V0
+ BVS L1
+ MOVW R2, R6
+ CMPBLE R6, $0, L18
+ MOVH $0x7FEF, R2
+ MOVW R1, R6
+ MOVW R2, R7
+ CMPBGT R6, R7, L24
+
+ WORD $0xA5400010 //iihh %r4,16
+ LDGR R4, F2
+ FMUL F2, F2
+ BR L1
+L23:
+ MOVH $0x1000, R3
+ MOVH $0x1000, R1
+ BR L17
+L24:
+ FMOVD $0, F2
+ BR L1
+L18:
+ MOVH $0x7FEF, R2
+ MOVW R1, R6
+ MOVW R2, R7
+ CMPBGT R6, R7, L25
+ WORD $0xA5408010 //iihh %r4,32784
+ FMOVD 568(R9), F2
+ LDGR R4, F0
+ FMADD F2, F0, F2
+ BR L1
+L25:
+ FMOVD 568(R9), F2
+ BR L1
+usego:
+ BR ·erfc(SB)
diff --git a/platform/dbops/binaries/go/go/src/math/erfinv.go b/platform/dbops/binaries/go/go/src/math/erfinv.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e630f9736810e13cd32f8701fa38efb5cac3269
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/erfinv.go
@@ -0,0 +1,129 @@
+// 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 math
+
+/*
+ Inverse of the floating-point error function.
+*/
+
+// This implementation is based on the rational approximation
+// of percentage points of normal distribution available from
+// https://www.jstor.org/stable/2347330.
+
+const (
+ // Coefficients for approximation to erf in |x| <= 0.85
+ a0 = 1.1975323115670912564578e0
+ a1 = 4.7072688112383978012285e1
+ a2 = 6.9706266534389598238465e2
+ a3 = 4.8548868893843886794648e3
+ a4 = 1.6235862515167575384252e4
+ a5 = 2.3782041382114385731252e4
+ a6 = 1.1819493347062294404278e4
+ a7 = 8.8709406962545514830200e2
+ b0 = 1.0000000000000000000e0
+ b1 = 4.2313330701600911252e1
+ b2 = 6.8718700749205790830e2
+ b3 = 5.3941960214247511077e3
+ b4 = 2.1213794301586595867e4
+ b5 = 3.9307895800092710610e4
+ b6 = 2.8729085735721942674e4
+ b7 = 5.2264952788528545610e3
+ // Coefficients for approximation to erf in 0.85 < |x| <= 1-2*exp(-25)
+ c0 = 1.42343711074968357734e0
+ c1 = 4.63033784615654529590e0
+ c2 = 5.76949722146069140550e0
+ c3 = 3.64784832476320460504e0
+ c4 = 1.27045825245236838258e0
+ c5 = 2.41780725177450611770e-1
+ c6 = 2.27238449892691845833e-2
+ c7 = 7.74545014278341407640e-4
+ d0 = 1.4142135623730950488016887e0
+ d1 = 2.9036514445419946173133295e0
+ d2 = 2.3707661626024532365971225e0
+ d3 = 9.7547832001787427186894837e-1
+ d4 = 2.0945065210512749128288442e-1
+ d5 = 2.1494160384252876777097297e-2
+ d6 = 7.7441459065157709165577218e-4
+ d7 = 1.4859850019840355905497876e-9
+ // Coefficients for approximation to erf in 1-2*exp(-25) < |x| < 1
+ e0 = 6.65790464350110377720e0
+ e1 = 5.46378491116411436990e0
+ e2 = 1.78482653991729133580e0
+ e3 = 2.96560571828504891230e-1
+ e4 = 2.65321895265761230930e-2
+ e5 = 1.24266094738807843860e-3
+ e6 = 2.71155556874348757815e-5
+ e7 = 2.01033439929228813265e-7
+ f0 = 1.414213562373095048801689e0
+ f1 = 8.482908416595164588112026e-1
+ f2 = 1.936480946950659106176712e-1
+ f3 = 2.103693768272068968719679e-2
+ f4 = 1.112800997078859844711555e-3
+ f5 = 2.611088405080593625138020e-5
+ f6 = 2.010321207683943062279931e-7
+ f7 = 2.891024605872965461538222e-15
+)
+
+// Erfinv returns the inverse error function of x.
+//
+// Special cases are:
+//
+// Erfinv(1) = +Inf
+// Erfinv(-1) = -Inf
+// Erfinv(x) = NaN if x < -1 or x > 1
+// Erfinv(NaN) = NaN
+func Erfinv(x float64) float64 {
+ // special cases
+ if IsNaN(x) || x <= -1 || x >= 1 {
+ if x == -1 || x == 1 {
+ return Inf(int(x))
+ }
+ return NaN()
+ }
+
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+
+ var ans float64
+ if x <= 0.85 { // |x| <= 0.85
+ r := 0.180625 - 0.25*x*x
+ z1 := ((((((a7*r+a6)*r+a5)*r+a4)*r+a3)*r+a2)*r+a1)*r + a0
+ z2 := ((((((b7*r+b6)*r+b5)*r+b4)*r+b3)*r+b2)*r+b1)*r + b0
+ ans = (x * z1) / z2
+ } else {
+ var z1, z2 float64
+ r := Sqrt(Ln2 - Log(1.0-x))
+ if r <= 5.0 {
+ r -= 1.6
+ z1 = ((((((c7*r+c6)*r+c5)*r+c4)*r+c3)*r+c2)*r+c1)*r + c0
+ z2 = ((((((d7*r+d6)*r+d5)*r+d4)*r+d3)*r+d2)*r+d1)*r + d0
+ } else {
+ r -= 5.0
+ z1 = ((((((e7*r+e6)*r+e5)*r+e4)*r+e3)*r+e2)*r+e1)*r + e0
+ z2 = ((((((f7*r+f6)*r+f5)*r+f4)*r+f3)*r+f2)*r+f1)*r + f0
+ }
+ ans = z1 / z2
+ }
+
+ if sign {
+ return -ans
+ }
+ return ans
+}
+
+// Erfcinv returns the inverse of [Erfc](x).
+//
+// Special cases are:
+//
+// Erfcinv(0) = +Inf
+// Erfcinv(2) = -Inf
+// Erfcinv(x) = NaN if x < 0 or x > 2
+// Erfcinv(NaN) = NaN
+func Erfcinv(x float64) float64 {
+ return Erfinv(1 - x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/example_test.go b/platform/dbops/binaries/go/go/src/math/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a26d8cbe97d8b463cbcb1ea6e57197545a253dbc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/example_test.go
@@ -0,0 +1,245 @@
+// 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 math_test
+
+import (
+ "fmt"
+ "math"
+)
+
+func ExampleAcos() {
+ fmt.Printf("%.2f", math.Acos(1))
+ // Output: 0.00
+}
+
+func ExampleAcosh() {
+ fmt.Printf("%.2f", math.Acosh(1))
+ // Output: 0.00
+}
+
+func ExampleAsin() {
+ fmt.Printf("%.2f", math.Asin(0))
+ // Output: 0.00
+}
+
+func ExampleAsinh() {
+ fmt.Printf("%.2f", math.Asinh(0))
+ // Output: 0.00
+}
+
+func ExampleAtan() {
+ fmt.Printf("%.2f", math.Atan(0))
+ // Output: 0.00
+}
+
+func ExampleAtan2() {
+ fmt.Printf("%.2f", math.Atan2(0, 0))
+ // Output: 0.00
+}
+
+func ExampleAtanh() {
+ fmt.Printf("%.2f", math.Atanh(0))
+ // Output: 0.00
+}
+
+func ExampleCopysign() {
+ fmt.Printf("%.2f", math.Copysign(3.2, -1))
+ // Output: -3.20
+}
+
+func ExampleCos() {
+ fmt.Printf("%.2f", math.Cos(math.Pi/2))
+ // Output: 0.00
+}
+
+func ExampleCosh() {
+ fmt.Printf("%.2f", math.Cosh(0))
+ // Output: 1.00
+}
+
+func ExampleSin() {
+ fmt.Printf("%.2f", math.Sin(math.Pi))
+ // Output: 0.00
+}
+
+func ExampleSincos() {
+ sin, cos := math.Sincos(0)
+ fmt.Printf("%.2f, %.2f", sin, cos)
+ // Output: 0.00, 1.00
+}
+
+func ExampleSinh() {
+ fmt.Printf("%.2f", math.Sinh(0))
+ // Output: 0.00
+}
+
+func ExampleTan() {
+ fmt.Printf("%.2f", math.Tan(0))
+ // Output: 0.00
+}
+
+func ExampleTanh() {
+ fmt.Printf("%.2f", math.Tanh(0))
+ // Output: 0.00
+}
+
+func ExampleSqrt() {
+ const (
+ a = 3
+ b = 4
+ )
+ c := math.Sqrt(a*a + b*b)
+ fmt.Printf("%.1f", c)
+ // Output: 5.0
+}
+
+func ExampleCeil() {
+ c := math.Ceil(1.49)
+ fmt.Printf("%.1f", c)
+ // Output: 2.0
+}
+
+func ExampleFloor() {
+ c := math.Floor(1.51)
+ fmt.Printf("%.1f", c)
+ // Output: 1.0
+}
+
+func ExamplePow() {
+ c := math.Pow(2, 3)
+ fmt.Printf("%.1f", c)
+ // Output: 8.0
+}
+
+func ExamplePow10() {
+ c := math.Pow10(2)
+ fmt.Printf("%.1f", c)
+ // Output: 100.0
+}
+
+func ExampleRound() {
+ p := math.Round(10.5)
+ fmt.Printf("%.1f\n", p)
+
+ n := math.Round(-10.5)
+ fmt.Printf("%.1f\n", n)
+ // Output:
+ // 11.0
+ // -11.0
+}
+
+func ExampleRoundToEven() {
+ u := math.RoundToEven(11.5)
+ fmt.Printf("%.1f\n", u)
+
+ d := math.RoundToEven(12.5)
+ fmt.Printf("%.1f\n", d)
+ // Output:
+ // 12.0
+ // 12.0
+}
+
+func ExampleLog() {
+ x := math.Log(1)
+ fmt.Printf("%.1f\n", x)
+
+ y := math.Log(2.7183)
+ fmt.Printf("%.1f\n", y)
+ // Output:
+ // 0.0
+ // 1.0
+}
+
+func ExampleLog2() {
+ fmt.Printf("%.1f", math.Log2(256))
+ // Output: 8.0
+}
+
+func ExampleLog10() {
+ fmt.Printf("%.1f", math.Log10(100))
+ // Output: 2.0
+}
+
+func ExampleRemainder() {
+ fmt.Printf("%.1f", math.Remainder(100, 30))
+ // Output: 10.0
+}
+
+func ExampleMod() {
+ c := math.Mod(7, 4)
+ fmt.Printf("%.1f", c)
+ // Output: 3.0
+}
+
+func ExampleAbs() {
+ x := math.Abs(-2)
+ fmt.Printf("%.1f\n", x)
+
+ y := math.Abs(2)
+ fmt.Printf("%.1f\n", y)
+ // Output:
+ // 2.0
+ // 2.0
+}
+func ExampleDim() {
+ fmt.Printf("%.2f\n", math.Dim(4, -2))
+ fmt.Printf("%.2f\n", math.Dim(-4, 2))
+ // Output:
+ // 6.00
+ // 0.00
+}
+
+func ExampleExp() {
+ fmt.Printf("%.2f\n", math.Exp(1))
+ fmt.Printf("%.2f\n", math.Exp(2))
+ fmt.Printf("%.2f\n", math.Exp(-1))
+ // Output:
+ // 2.72
+ // 7.39
+ // 0.37
+}
+
+func ExampleExp2() {
+ fmt.Printf("%.2f\n", math.Exp2(1))
+ fmt.Printf("%.2f\n", math.Exp2(-3))
+ // Output:
+ // 2.00
+ // 0.12
+}
+
+func ExampleExpm1() {
+ fmt.Printf("%.6f\n", math.Expm1(0.01))
+ fmt.Printf("%.6f\n", math.Expm1(-1))
+ // Output:
+ // 0.010050
+ // -0.632121
+}
+
+func ExampleTrunc() {
+ fmt.Printf("%.2f\n", math.Trunc(math.Pi))
+ fmt.Printf("%.2f\n", math.Trunc(-1.2345))
+ // Output:
+ // 3.00
+ // -1.00
+}
+
+func ExampleCbrt() {
+ fmt.Printf("%.2f\n", math.Cbrt(8))
+ fmt.Printf("%.2f\n", math.Cbrt(27))
+ // Output:
+ // 2.00
+ // 3.00
+}
+
+func ExampleModf() {
+ int, frac := math.Modf(3.14)
+ fmt.Printf("%.2f, %.2f\n", int, frac)
+
+ int, frac = math.Modf(-2.71)
+ fmt.Printf("%.2f, %.2f\n", int, frac)
+ // Output:
+ // 3.00, 0.14
+ // -2.00, -0.71
+}
diff --git a/platform/dbops/binaries/go/go/src/math/exp.go b/platform/dbops/binaries/go/go/src/math/exp.go
new file mode 100644
index 0000000000000000000000000000000000000000..050e0ee9d88239988c36d20fc043820c627a5bac
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp.go
@@ -0,0 +1,203 @@
+// 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 math
+
+// Exp returns e**x, the base-e exponential of x.
+//
+// Special cases are:
+//
+// Exp(+Inf) = +Inf
+// Exp(NaN) = NaN
+//
+// Very large values overflow to 0 or +Inf.
+// Very small values underflow to 1.
+func Exp(x float64) float64 {
+ if haveArchExp {
+ return archExp(x)
+ }
+ return exp(x)
+}
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/e_exp.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
+//
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// exp(x)
+// Returns the exponential of x.
+//
+// Method
+// 1. Argument reduction:
+// Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658.
+// Given x, find r and integer k such that
+//
+// x = k*ln2 + r, |r| <= 0.5*ln2.
+//
+// Here r will be represented as r = hi-lo for better
+// accuracy.
+//
+// 2. Approximation of exp(r) by a special rational function on
+// the interval [0,0.34658]:
+// Write
+// R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ...
+// We use a special Remez algorithm on [0,0.34658] to generate
+// a polynomial of degree 5 to approximate R. The maximum error
+// of this polynomial approximation is bounded by 2**-59. In
+// other words,
+// R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5
+// (where z=r*r, and the values of P1 to P5 are listed below)
+// and
+// | 5 | -59
+// | 2.0+P1*z+...+P5*z - R(z) | <= 2
+// | |
+// The computation of exp(r) thus becomes
+// 2*r
+// exp(r) = 1 + -------
+// R - r
+// r*R1(r)
+// = 1 + r + ----------- (for better accuracy)
+// 2 - R1(r)
+// where
+// 2 4 10
+// R1(r) = r - (P1*r + P2*r + ... + P5*r ).
+//
+// 3. Scale back to obtain exp(x):
+// From step 1, we have
+// exp(x) = 2**k * exp(r)
+//
+// Special cases:
+// exp(INF) is INF, exp(NaN) is NaN;
+// exp(-INF) is 0, and
+// for finite argument, only exp(0)=1 is exact.
+//
+// Accuracy:
+// according to an error analysis, the error is always less than
+// 1 ulp (unit in the last place).
+//
+// Misc. info.
+// For IEEE double
+// if x > 7.09782712893383973096e+02 then exp(x) overflow
+// if x < -7.45133219101941108420e+02 then exp(x) underflow
+//
+// Constants:
+// The hexadecimal values are the intended ones for the following
+// constants. The decimal values may be used, provided that the
+// compiler will convert from decimal to binary accurately enough
+// to produce the hexadecimal values shown.
+
+func exp(x float64) float64 {
+ const (
+ Ln2Hi = 6.93147180369123816490e-01
+ Ln2Lo = 1.90821492927058770002e-10
+ Log2e = 1.44269504088896338700e+00
+
+ Overflow = 7.09782712893383973096e+02
+ Underflow = -7.45133219101941108420e+02
+ NearZero = 1.0 / (1 << 28) // 2**-28
+ )
+
+ // special cases
+ switch {
+ case IsNaN(x) || IsInf(x, 1):
+ return x
+ case IsInf(x, -1):
+ return 0
+ case x > Overflow:
+ return Inf(1)
+ case x < Underflow:
+ return 0
+ case -NearZero < x && x < NearZero:
+ return 1 + x
+ }
+
+ // reduce; computed as r = hi - lo for extra precision.
+ var k int
+ switch {
+ case x < 0:
+ k = int(Log2e*x - 0.5)
+ case x > 0:
+ k = int(Log2e*x + 0.5)
+ }
+ hi := x - float64(k)*Ln2Hi
+ lo := float64(k) * Ln2Lo
+
+ // compute
+ return expmulti(hi, lo, k)
+}
+
+// Exp2 returns 2**x, the base-2 exponential of x.
+//
+// Special cases are the same as [Exp].
+func Exp2(x float64) float64 {
+ if haveArchExp2 {
+ return archExp2(x)
+ }
+ return exp2(x)
+}
+
+func exp2(x float64) float64 {
+ const (
+ Ln2Hi = 6.93147180369123816490e-01
+ Ln2Lo = 1.90821492927058770002e-10
+
+ Overflow = 1.0239999999999999e+03
+ Underflow = -1.0740e+03
+ )
+
+ // special cases
+ switch {
+ case IsNaN(x) || IsInf(x, 1):
+ return x
+ case IsInf(x, -1):
+ return 0
+ case x > Overflow:
+ return Inf(1)
+ case x < Underflow:
+ return 0
+ }
+
+ // argument reduction; x = r×lg(e) + k with |r| ≤ ln(2)/2.
+ // computed as r = hi - lo for extra precision.
+ var k int
+ switch {
+ case x > 0:
+ k = int(x + 0.5)
+ case x < 0:
+ k = int(x - 0.5)
+ }
+ t := x - float64(k)
+ hi := t * Ln2Hi
+ lo := -t * Ln2Lo
+
+ // compute
+ return expmulti(hi, lo, k)
+}
+
+// exp1 returns e**r × 2**k where r = hi - lo and |r| ≤ ln(2)/2.
+func expmulti(hi, lo float64, k int) float64 {
+ const (
+ P1 = 1.66666666666666657415e-01 /* 0x3FC55555; 0x55555555 */
+ P2 = -2.77777777770155933842e-03 /* 0xBF66C16C; 0x16BEBD93 */
+ P3 = 6.61375632143793436117e-05 /* 0x3F11566A; 0xAF25DE2C */
+ P4 = -1.65339022054652515390e-06 /* 0xBEBBBD41; 0xC5D26BF1 */
+ P5 = 4.13813679705723846039e-08 /* 0x3E663769; 0x72BEA4D0 */
+ )
+
+ r := hi - lo
+ t := r * r
+ c := r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5))))
+ y := 1 - ((lo - (r*c)/(2-c)) - hi)
+ // TODO(rsc): make sure Ldexp can handle boundary k
+ return Ldexp(y, k)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/exp2_asm.go b/platform/dbops/binaries/go/go/src/math/exp2_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..c26b2c3fab67c743e00d7539f9e0e188214ba18e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp2_asm.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.
+
+//go:build arm64
+
+package math
+
+const haveArchExp2 = true
+
+func archExp2(x float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/exp2_noasm.go b/platform/dbops/binaries/go/go/src/math/exp2_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..c2b409329f1e1f18deec411388e6a961ed4e2beb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp2_noasm.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.
+
+//go:build !arm64
+
+package math
+
+const haveArchExp2 = false
+
+func archExp2(x float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/exp_amd64.go b/platform/dbops/binaries/go/go/src/math/exp_amd64.go
new file mode 100644
index 0000000000000000000000000000000000000000..0f701b1d6d8da1fa4bf3c8e14c3c45bb348df9d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_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 amd64
+
+package math
+
+import "internal/cpu"
+
+var useFMA = cpu.X86.HasAVX && cpu.X86.HasFMA
diff --git a/platform/dbops/binaries/go/go/src/math/exp_amd64.s b/platform/dbops/binaries/go/go/src/math/exp_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..02b71c81eb636c06dc396102ac7d3024defcf246
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_amd64.s
@@ -0,0 +1,159 @@
+// 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.
+
+#include "textflag.h"
+
+// The method is based on a paper by Naoki Shibata: "Efficient evaluation
+// methods of elementary functions suitable for SIMD computation", Proc.
+// of International Supercomputing Conference 2010 (ISC'10), pp. 25 -- 32
+// (May 2010). The paper is available at
+// https://link.springer.com/article/10.1007/s00450-010-0108-2
+//
+// The original code and the constants below are from the author's
+// implementation available at http://freshmeat.net/projects/sleef.
+// The README file says, "The software is in public domain.
+// You can use the software without any obligation."
+//
+// This code is a simplified version of the original.
+
+#define LN2 0.6931471805599453094172321214581766 // log_e(2)
+#define LOG2E 1.4426950408889634073599246810018920 // 1/LN2
+#define LN2U 0.69314718055966295651160180568695068359375 // upper half LN2
+#define LN2L 0.28235290563031577122588448175013436025525412068e-12 // lower half LN2
+#define PosInf 0x7FF0000000000000
+#define NegInf 0xFFF0000000000000
+#define Overflow 7.09782712893384e+02
+
+DATA exprodata<>+0(SB)/8, $0.5
+DATA exprodata<>+8(SB)/8, $1.0
+DATA exprodata<>+16(SB)/8, $2.0
+DATA exprodata<>+24(SB)/8, $1.6666666666666666667e-1
+DATA exprodata<>+32(SB)/8, $4.1666666666666666667e-2
+DATA exprodata<>+40(SB)/8, $8.3333333333333333333e-3
+DATA exprodata<>+48(SB)/8, $1.3888888888888888889e-3
+DATA exprodata<>+56(SB)/8, $1.9841269841269841270e-4
+DATA exprodata<>+64(SB)/8, $2.4801587301587301587e-5
+GLOBL exprodata<>+0(SB), RODATA, $72
+
+// func Exp(x float64) float64
+TEXT ·archExp(SB),NOSPLIT,$0
+ // test bits for not-finite
+ MOVQ x+0(FP), BX
+ MOVQ $~(1<<63), AX // sign bit mask
+ MOVQ BX, DX
+ ANDQ AX, DX
+ MOVQ $PosInf, AX
+ CMPQ AX, DX
+ JLE notFinite
+ // check if argument will overflow
+ MOVQ BX, X0
+ MOVSD $Overflow, X1
+ COMISD X1, X0
+ JA overflow
+ MOVSD $LOG2E, X1
+ MULSD X0, X1
+ CVTSD2SL X1, BX // BX = exponent
+ CVTSL2SD BX, X1
+ CMPB ·useFMA(SB), $1
+ JE avxfma
+ MOVSD $LN2U, X2
+ MULSD X1, X2
+ SUBSD X2, X0
+ MOVSD $LN2L, X2
+ MULSD X1, X2
+ SUBSD X2, X0
+ // reduce argument
+ MULSD $0.0625, X0
+ // Taylor series evaluation
+ MOVSD exprodata<>+64(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+56(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+48(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+40(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+32(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+24(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+0(SB), X1
+ MULSD X0, X1
+ ADDSD exprodata<>+8(SB), X1
+ MULSD X1, X0
+ MOVSD exprodata<>+16(SB), X1
+ ADDSD X0, X1
+ MULSD X1, X0
+ MOVSD exprodata<>+16(SB), X1
+ ADDSD X0, X1
+ MULSD X1, X0
+ MOVSD exprodata<>+16(SB), X1
+ ADDSD X0, X1
+ MULSD X1, X0
+ MOVSD exprodata<>+16(SB), X1
+ ADDSD X0, X1
+ MULSD X1, X0
+ ADDSD exprodata<>+8(SB), X0
+ // return fr * 2**exponent
+ldexp:
+ ADDL $0x3FF, BX // add bias
+ JLE denormal
+ CMPL BX, $0x7FF
+ JGE overflow
+lastStep:
+ SHLQ $52, BX
+ MOVQ BX, X1
+ MULSD X1, X0
+ MOVSD X0, ret+8(FP)
+ RET
+notFinite:
+ // test bits for -Inf
+ MOVQ $NegInf, AX
+ CMPQ AX, BX
+ JNE notNegInf
+ // -Inf, return 0
+underflow: // return 0
+ MOVQ $0, ret+8(FP)
+ RET
+overflow: // return +Inf
+ MOVQ $PosInf, BX
+notNegInf: // NaN or +Inf, return x
+ MOVQ BX, ret+8(FP)
+ RET
+denormal:
+ CMPL BX, $-52
+ JL underflow
+ ADDL $0x3FE, BX // add bias - 1
+ SHLQ $52, BX
+ MOVQ BX, X1
+ MULSD X1, X0
+ MOVQ $1, BX
+ JMP lastStep
+
+avxfma:
+ MOVSD $LN2U, X2
+ VFNMADD231SD X2, X1, X0
+ MOVSD $LN2L, X2
+ VFNMADD231SD X2, X1, X0
+ // reduce argument
+ MULSD $0.0625, X0
+ // Taylor series evaluation
+ MOVSD exprodata<>+64(SB), X1
+ VFMADD213SD exprodata<>+56(SB), X0, X1
+ VFMADD213SD exprodata<>+48(SB), X0, X1
+ VFMADD213SD exprodata<>+40(SB), X0, X1
+ VFMADD213SD exprodata<>+32(SB), X0, X1
+ VFMADD213SD exprodata<>+24(SB), X0, X1
+ VFMADD213SD exprodata<>+0(SB), X0, X1
+ VFMADD213SD exprodata<>+8(SB), X0, X1
+ MULSD X1, X0
+ VADDSD exprodata<>+16(SB), X0, X1
+ MULSD X1, X0
+ VADDSD exprodata<>+16(SB), X0, X1
+ MULSD X1, X0
+ VADDSD exprodata<>+16(SB), X0, X1
+ MULSD X1, X0
+ VADDSD exprodata<>+16(SB), X0, X1
+ VFMADD213SD exprodata<>+8(SB), X1, X0
+ JMP ldexp
diff --git a/platform/dbops/binaries/go/go/src/math/exp_arm64.s b/platform/dbops/binaries/go/go/src/math/exp_arm64.s
new file mode 100644
index 0000000000000000000000000000000000000000..44673abefe4cce681346455a6928746b3354b33a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_arm64.s
@@ -0,0 +1,182 @@
+// 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.
+
+#define Ln2Hi 6.93147180369123816490e-01
+#define Ln2Lo 1.90821492927058770002e-10
+#define Log2e 1.44269504088896338700e+00
+#define Overflow 7.09782712893383973096e+02
+#define Underflow -7.45133219101941108420e+02
+#define Overflow2 1.0239999999999999e+03
+#define Underflow2 -1.0740e+03
+#define NearZero 0x3e30000000000000 // 2**-28
+#define PosInf 0x7ff0000000000000
+#define FracMask 0x000fffffffffffff
+#define C1 0x3cb0000000000000 // 2**-52
+#define P1 1.66666666666666657415e-01 // 0x3FC55555; 0x55555555
+#define P2 -2.77777777770155933842e-03 // 0xBF66C16C; 0x16BEBD93
+#define P3 6.61375632143793436117e-05 // 0x3F11566A; 0xAF25DE2C
+#define P4 -1.65339022054652515390e-06 // 0xBEBBBD41; 0xC5D26BF1
+#define P5 4.13813679705723846039e-08 // 0x3E663769; 0x72BEA4D0
+
+// Exp returns e**x, the base-e exponential of x.
+// This is an assembly implementation of the method used for function Exp in file exp.go.
+//
+// func Exp(x float64) float64
+TEXT ·archExp(SB),$0-16
+ FMOVD x+0(FP), F0 // F0 = x
+ FCMPD F0, F0
+ BNE isNaN // x = NaN, return NaN
+ FMOVD $Overflow, F1
+ FCMPD F1, F0
+ BGT overflow // x > Overflow, return PosInf
+ FMOVD $Underflow, F1
+ FCMPD F1, F0
+ BLT underflow // x < Underflow, return 0
+ MOVD $NearZero, R0
+ FMOVD R0, F2
+ FABSD F0, F3
+ FMOVD $1.0, F1 // F1 = 1.0
+ FCMPD F2, F3
+ BLT nearzero // fabs(x) < NearZero, return 1 + x
+ // argument reduction, x = k*ln2 + r, |r| <= 0.5*ln2
+ // computed as r = hi - lo for extra precision.
+ FMOVD $Log2e, F2
+ FMOVD $0.5, F3
+ FNMSUBD F0, F3, F2, F4 // Log2e*x - 0.5
+ FMADDD F0, F3, F2, F3 // Log2e*x + 0.5
+ FCMPD $0.0, F0
+ FCSELD LT, F4, F3, F3 // F3 = k
+ FCVTZSD F3, R1 // R1 = int(k)
+ SCVTFD R1, F3 // F3 = float64(int(k))
+ FMOVD $Ln2Hi, F4 // F4 = Ln2Hi
+ FMOVD $Ln2Lo, F5 // F5 = Ln2Lo
+ FMSUBD F3, F0, F4, F4 // F4 = hi = x - float64(int(k))*Ln2Hi
+ FMULD F3, F5 // F5 = lo = float64(int(k)) * Ln2Lo
+ FSUBD F5, F4, F6 // F6 = r = hi - lo
+ FMULD F6, F6, F7 // F7 = t = r * r
+ // compute y
+ FMOVD $P5, F8 // F8 = P5
+ FMOVD $P4, F9 // F9 = P4
+ FMADDD F7, F9, F8, F13 // P4+t*P5
+ FMOVD $P3, F10 // F10 = P3
+ FMADDD F7, F10, F13, F13 // P3+t*(P4+t*P5)
+ FMOVD $P2, F11 // F11 = P2
+ FMADDD F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5))
+ FMOVD $P1, F12 // F12 = P1
+ FMADDD F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5)))
+ FMSUBD F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5))))
+ FMOVD $2.0, F14
+ FSUBD F13, F14
+ FMULD F6, F13, F15
+ FDIVD F14, F15 // F15 = (r*c)/(2-c)
+ FSUBD F15, F5, F15 // lo-(r*c)/(2-c)
+ FSUBD F4, F15, F15 // (lo-(r*c)/(2-c))-hi
+ FSUBD F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi)
+ // inline Ldexp(y, k), benefit:
+ // 1, no parameter pass overhead.
+ // 2, skip unnecessary checks for Inf/NaN/Zero
+ FMOVD F16, R0
+ AND $FracMask, R0, R2 // fraction
+ LSR $52, R0, R5 // exponent
+ ADD R1, R5 // R1 = int(k)
+ CMP $1, R5
+ BGE normal
+ ADD $52, R5 // denormal
+ MOVD $C1, R8
+ FMOVD R8, F1 // m = 2**-52
+normal:
+ ORR R5<<52, R2, R0
+ FMOVD R0, F0
+ FMULD F1, F0 // return m * x
+ FMOVD F0, ret+8(FP)
+ RET
+nearzero:
+ FADDD F1, F0
+isNaN:
+ FMOVD F0, ret+8(FP)
+ RET
+underflow:
+ MOVD ZR, ret+8(FP)
+ RET
+overflow:
+ MOVD $PosInf, R0
+ MOVD R0, ret+8(FP)
+ RET
+
+
+// Exp2 returns 2**x, the base-2 exponential of x.
+// This is an assembly implementation of the method used for function Exp2 in file exp.go.
+//
+// func Exp2(x float64) float64
+TEXT ·archExp2(SB),$0-16
+ FMOVD x+0(FP), F0 // F0 = x
+ FCMPD F0, F0
+ BNE isNaN // x = NaN, return NaN
+ FMOVD $Overflow2, F1
+ FCMPD F1, F0
+ BGT overflow // x > Overflow, return PosInf
+ FMOVD $Underflow2, F1
+ FCMPD F1, F0
+ BLT underflow // x < Underflow, return 0
+ // argument reduction; x = r*lg(e) + k with |r| <= ln(2)/2
+ // computed as r = hi - lo for extra precision.
+ FMOVD $0.5, F2
+ FSUBD F2, F0, F3 // x + 0.5
+ FADDD F2, F0, F4 // x - 0.5
+ FCMPD $0.0, F0
+ FCSELD LT, F3, F4, F3 // F3 = k
+ FCVTZSD F3, R1 // R1 = int(k)
+ SCVTFD R1, F3 // F3 = float64(int(k))
+ FSUBD F3, F0, F3 // t = x - float64(int(k))
+ FMOVD $Ln2Hi, F4 // F4 = Ln2Hi
+ FMOVD $Ln2Lo, F5 // F5 = Ln2Lo
+ FMULD F3, F4 // F4 = hi = t * Ln2Hi
+ FNMULD F3, F5 // F5 = lo = -t * Ln2Lo
+ FSUBD F5, F4, F6 // F6 = r = hi - lo
+ FMULD F6, F6, F7 // F7 = t = r * r
+ // compute y
+ FMOVD $P5, F8 // F8 = P5
+ FMOVD $P4, F9 // F9 = P4
+ FMADDD F7, F9, F8, F13 // P4+t*P5
+ FMOVD $P3, F10 // F10 = P3
+ FMADDD F7, F10, F13, F13 // P3+t*(P4+t*P5)
+ FMOVD $P2, F11 // F11 = P2
+ FMADDD F7, F11, F13, F13 // P2+t*(P3+t*(P4+t*P5))
+ FMOVD $P1, F12 // F12 = P1
+ FMADDD F7, F12, F13, F13 // P1+t*(P2+t*(P3+t*(P4+t*P5)))
+ FMSUBD F7, F6, F13, F13 // F13 = c = r - t*(P1+t*(P2+t*(P3+t*(P4+t*P5))))
+ FMOVD $2.0, F14
+ FSUBD F13, F14
+ FMULD F6, F13, F15
+ FDIVD F14, F15 // F15 = (r*c)/(2-c)
+ FMOVD $1.0, F1 // F1 = 1.0
+ FSUBD F15, F5, F15 // lo-(r*c)/(2-c)
+ FSUBD F4, F15, F15 // (lo-(r*c)/(2-c))-hi
+ FSUBD F15, F1, F16 // F16 = y = 1-((lo-(r*c)/(2-c))-hi)
+ // inline Ldexp(y, k), benefit:
+ // 1, no parameter pass overhead.
+ // 2, skip unnecessary checks for Inf/NaN/Zero
+ FMOVD F16, R0
+ AND $FracMask, R0, R2 // fraction
+ LSR $52, R0, R5 // exponent
+ ADD R1, R5 // R1 = int(k)
+ CMP $1, R5
+ BGE normal
+ ADD $52, R5 // denormal
+ MOVD $C1, R8
+ FMOVD R8, F1 // m = 2**-52
+normal:
+ ORR R5<<52, R2, R0
+ FMOVD R0, F0
+ FMULD F1, F0 // return m * x
+isNaN:
+ FMOVD F0, ret+8(FP)
+ RET
+underflow:
+ MOVD ZR, ret+8(FP)
+ RET
+overflow:
+ MOVD $PosInf, R0
+ MOVD R0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/exp_asm.go b/platform/dbops/binaries/go/go/src/math/exp_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..424442845bb07e2645c28df400253e4de9fa4de9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_asm.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.
+
+//go:build amd64 || arm64 || s390x
+
+package math
+
+const haveArchExp = true
+
+func archExp(x float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/exp_noasm.go b/platform/dbops/binaries/go/go/src/math/exp_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..bd3f02412a28a2ab2cb98d71e88e7b11d5deaa43
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_noasm.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.
+
+//go:build !amd64 && !arm64 && !s390x
+
+package math
+
+const haveArchExp = false
+
+func archExp(x float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/exp_s390x.s b/platform/dbops/binaries/go/go/src/math/exp_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..e0ec8230738ad9a07fd8ce2073f20dc05a599e55
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/exp_s390x.s
@@ -0,0 +1,177 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial approximation and other constants
+DATA ·exprodataL22<> + 0(SB)/8, $800.0E+00
+DATA ·exprodataL22<> + 8(SB)/8, $1.0000000000000022e+00
+DATA ·exprodataL22<> + 16(SB)/8, $0.500000000000004237e+00
+DATA ·exprodataL22<> + 24(SB)/8, $0.166666666630345592e+00
+DATA ·exprodataL22<> + 32(SB)/8, $0.138926439368309441e-02
+DATA ·exprodataL22<> + 40(SB)/8, $0.833349307718286047e-02
+DATA ·exprodataL22<> + 48(SB)/8, $0.416666664838056960e-01
+DATA ·exprodataL22<> + 56(SB)/8, $-.231904681384629956E-16
+DATA ·exprodataL22<> + 64(SB)/8, $-.693147180559945286E+00
+DATA ·exprodataL22<> + 72(SB)/8, $0.144269504088896339E+01
+DATA ·exprodataL22<> + 80(SB)/8, $704.0E+00
+GLOBL ·exprodataL22<> + 0(SB), RODATA, $88
+
+DATA ·expxinf<> + 0(SB)/8, $0x7ff0000000000000
+GLOBL ·expxinf<> + 0(SB), RODATA, $8
+DATA ·expx4ff<> + 0(SB)/8, $0x4ff0000000000000
+GLOBL ·expx4ff<> + 0(SB), RODATA, $8
+DATA ·expx2ff<> + 0(SB)/8, $0x2ff0000000000000
+GLOBL ·expx2ff<> + 0(SB), RODATA, $8
+DATA ·expxaddexp<> + 0(SB)/8, $0xc2f0000100003fef
+GLOBL ·expxaddexp<> + 0(SB), RODATA, $8
+
+// Log multipliers table
+DATA ·exptexp<> + 0(SB)/8, $0.442737824274138381E-01
+DATA ·exptexp<> + 8(SB)/8, $0.263602189790660309E-01
+DATA ·exptexp<> + 16(SB)/8, $0.122565642281703586E-01
+DATA ·exptexp<> + 24(SB)/8, $0.143757052860721398E-02
+DATA ·exptexp<> + 32(SB)/8, $-.651375034121276075E-02
+DATA ·exptexp<> + 40(SB)/8, $-.119317678849450159E-01
+DATA ·exptexp<> + 48(SB)/8, $-.150868749549871069E-01
+DATA ·exptexp<> + 56(SB)/8, $-.161992609578469234E-01
+DATA ·exptexp<> + 64(SB)/8, $-.154492360403337917E-01
+DATA ·exptexp<> + 72(SB)/8, $-.129850717389178721E-01
+DATA ·exptexp<> + 80(SB)/8, $-.892902649276657891E-02
+DATA ·exptexp<> + 88(SB)/8, $-.338202636596794887E-02
+DATA ·exptexp<> + 96(SB)/8, $0.357266307045684762E-02
+DATA ·exptexp<> + 104(SB)/8, $0.118665304327406698E-01
+DATA ·exptexp<> + 112(SB)/8, $0.214434994118118914E-01
+DATA ·exptexp<> + 120(SB)/8, $0.322580645161290314E-01
+GLOBL ·exptexp<> + 0(SB), RODATA, $128
+
+// Exp returns e**x, the base-e exponential of x.
+//
+// Special cases are:
+// Exp(+Inf) = +Inf
+// Exp(NaN) = NaN
+// Very large values overflow to 0 or +Inf.
+// Very small values underflow to 1.
+// The algorithm used is minimax polynomial approximation using a table of
+// polynomial coefficients determined with a Remez exchange algorithm.
+
+TEXT ·expAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·exprodataL22<>+0(SB), R5
+ LTDBR F0, F0
+ BLTU L20
+ FMOVD F0, F2
+L2:
+ WORD $0xED205050 //cdb %f2,.L23-.L22(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L16
+ BVS L16
+ WFCEDBS V2, V2, V2
+ BVS LEXITTAGexp
+ MOVD $·expxaddexp<>+0(SB), R1
+ FMOVD 72(R5), F6
+ FMOVD 0(R1), F2
+ WFMSDB V0, V6, V2, V6
+ FMOVD 64(R5), F4
+ FADD F6, F2
+ FMOVD 56(R5), F1
+ FMADD F4, F2, F0
+ FMOVD 48(R5), F3
+ WFMADB V2, V1, V0, V2
+ FMOVD 40(R5), F1
+ FMOVD 32(R5), F4
+ FMUL F0, F0
+ WFMADB V2, V4, V1, V4
+ LGDR F6, R1
+ FMOVD 24(R5), F1
+ WFMADB V2, V3, V1, V3
+ FMOVD 16(R5), F1
+ WFMADB V0, V4, V3, V4
+ FMOVD 8(R5), F3
+ WFMADB V2, V1, V3, V1
+ RISBGZ $57, $60, $3, R1, R3
+ WFMADB V0, V4, V1, V0
+ MOVD $·exptexp<>+0(SB), R2
+ WORD $0x68432000 //ld %f4,0(%r3,%r2)
+ FMADD F4, F2, F2
+ SLD $48, R1, R2
+ WFMADB V2, V0, V4, V2
+ LDGR R2, F0
+ FMADD F0, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L16:
+ WFCEDBS V2, V2, V4
+ BVS LEXITTAGexp
+ WORD $0xED205000 //cdb %f2,.L33-.L22(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BLT L6
+ WFCEDBS V2, V0, V0
+ BVS L13
+ MOVD $·expxinf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+L20:
+ WORD $0xB3130020 //lcdbr %f2,%f0
+ BR L2
+L6:
+ MOVD $·expxaddexp<>+0(SB), R1
+ FMOVD 72(R5), F3
+ FMOVD 0(R1), F4
+ WFMSDB V0, V3, V4, V3
+ FMOVD 64(R5), F6
+ FADD F3, F4
+ FMOVD 56(R5), F5
+ WFMADB V4, V6, V0, V6
+ FMOVD 32(R5), F1
+ WFMADB V4, V5, V6, V4
+ FMOVD 40(R5), F5
+ FMUL F6, F6
+ WFMADB V4, V1, V5, V1
+ FMOVD 48(R5), F7
+ LGDR F3, R1
+ FMOVD 24(R5), F5
+ WFMADB V4, V7, V5, V7
+ FMOVD 16(R5), F5
+ WFMADB V6, V1, V7, V1
+ FMOVD 8(R5), F7
+ WFMADB V4, V5, V7, V5
+ RISBGZ $57, $60, $3, R1, R3
+ WFMADB V6, V1, V5, V6
+ MOVD $·exptexp<>+0(SB), R2
+ WFCHDBS V2, V0, V0
+ WORD $0x68132000 //ld %f1,0(%r3,%r2)
+ FMADD F1, F4, F4
+ MOVD $0x4086000000000000, R2
+ WFMADB V4, V6, V1, V4
+ BEQ L21
+ ADDW $0xF000, R1
+ RISBGN $0, $15, $48, R1, R2
+ LDGR R2, F0
+ FMADD F0, F4, F0
+ MOVD $·expx4ff<>+0(SB), R3
+ FMOVD 0(R3), F2
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L13:
+ FMOVD $0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L21:
+ ADDW $0x1000, R1
+ RISBGN $0, $15, $48, R1, R2
+ LDGR R2, F0
+ FMADD F0, F4, F0
+ MOVD $·expx2ff<>+0(SB), R3
+ FMOVD 0(R3), F2
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+LEXITTAGexp:
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/expm1.go b/platform/dbops/binaries/go/go/src/math/expm1.go
new file mode 100644
index 0000000000000000000000000000000000000000..f8e45d9becf2be550498dd58d2b3efb56cfd107d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/expm1.go
@@ -0,0 +1,244 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/s_expm1.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// expm1(x)
+// Returns exp(x)-1, the exponential of x minus 1.
+//
+// Method
+// 1. Argument reduction:
+// Given x, find r and integer k such that
+//
+// x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658
+//
+// Here a correction term c will be computed to compensate
+// the error in r when rounded to a floating-point number.
+//
+// 2. Approximating expm1(r) by a special rational function on
+// the interval [0,0.34658]:
+// Since
+// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 - r**4/360 + ...
+// we define R1(r*r) by
+// r*(exp(r)+1)/(exp(r)-1) = 2+ r**2/6 * R1(r*r)
+// That is,
+// R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r)
+// = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r))
+// = 1 - r**2/60 + r**4/2520 - r**6/100800 + ...
+// We use a special Reme algorithm on [0,0.347] to generate
+// a polynomial of degree 5 in r*r to approximate R1. The
+// maximum error of this polynomial approximation is bounded
+// by 2**-61. In other words,
+// R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5
+// where Q1 = -1.6666666666666567384E-2,
+// Q2 = 3.9682539681370365873E-4,
+// Q3 = -9.9206344733435987357E-6,
+// Q4 = 2.5051361420808517002E-7,
+// Q5 = -6.2843505682382617102E-9;
+// (where z=r*r, and the values of Q1 to Q5 are listed below)
+// with error bounded by
+// | 5 | -61
+// | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2
+// | |
+//
+// expm1(r) = exp(r)-1 is then computed by the following
+// specific way which minimize the accumulation rounding error:
+// 2 3
+// r r [ 3 - (R1 + R1*r/2) ]
+// expm1(r) = r + --- + --- * [--------------------]
+// 2 2 [ 6 - r*(3 - R1*r/2) ]
+//
+// To compensate the error in the argument reduction, we use
+// expm1(r+c) = expm1(r) + c + expm1(r)*c
+// ~ expm1(r) + c + r*c
+// Thus c+r*c will be added in as the correction terms for
+// expm1(r+c). Now rearrange the term to avoid optimization
+// screw up:
+// ( 2 2 )
+// ({ ( r [ R1 - (3 - R1*r/2) ] ) } r )
+// expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- )
+// ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 )
+// ( )
+//
+// = r - E
+// 3. Scale back to obtain expm1(x):
+// From step 1, we have
+// expm1(x) = either 2**k*[expm1(r)+1] - 1
+// = or 2**k*[expm1(r) + (1-2**-k)]
+// 4. Implementation notes:
+// (A). To save one multiplication, we scale the coefficient Qi
+// to Qi*2**i, and replace z by (x**2)/2.
+// (B). To achieve maximum accuracy, we compute expm1(x) by
+// (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf)
+// (ii) if k=0, return r-E
+// (iii) if k=-1, return 0.5*(r-E)-0.5
+// (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E)
+// else return 1.0+2.0*(r-E);
+// (v) if (k<-2||k>56) return 2**k(1-(E-r)) - 1 (or exp(x)-1)
+// (vi) if k <= 20, return 2**k((1-2**-k)-(E-r)), else
+// (vii) return 2**k(1-((E+2**-k)-r))
+//
+// Special cases:
+// expm1(INF) is INF, expm1(NaN) is NaN;
+// expm1(-INF) is -1, and
+// for finite argument, only expm1(0)=0 is exact.
+//
+// Accuracy:
+// according to an error analysis, the error is always less than
+// 1 ulp (unit in the last place).
+//
+// Misc. info.
+// For IEEE double
+// if x > 7.09782712893383973096e+02 then expm1(x) overflow
+//
+// Constants:
+// The hexadecimal values are the intended ones for the following
+// constants. The decimal values may be used, provided that the
+// compiler will convert from decimal to binary accurately enough
+// to produce the hexadecimal values shown.
+//
+
+// Expm1 returns e**x - 1, the base-e exponential of x minus 1.
+// It is more accurate than [Exp](x) - 1 when x is near zero.
+//
+// Special cases are:
+//
+// Expm1(+Inf) = +Inf
+// Expm1(-Inf) = -1
+// Expm1(NaN) = NaN
+//
+// Very large values overflow to -1 or +Inf.
+func Expm1(x float64) float64 {
+ if haveArchExpm1 {
+ return archExpm1(x)
+ }
+ return expm1(x)
+}
+
+func expm1(x float64) float64 {
+ const (
+ Othreshold = 7.09782712893383973096e+02 // 0x40862E42FEFA39EF
+ Ln2X56 = 3.88162421113569373274e+01 // 0x4043687a9f1af2b1
+ Ln2HalfX3 = 1.03972077083991796413e+00 // 0x3ff0a2b23f3bab73
+ Ln2Half = 3.46573590279972654709e-01 // 0x3fd62e42fefa39ef
+ Ln2Hi = 6.93147180369123816490e-01 // 0x3fe62e42fee00000
+ Ln2Lo = 1.90821492927058770002e-10 // 0x3dea39ef35793c76
+ InvLn2 = 1.44269504088896338700e+00 // 0x3ff71547652b82fe
+ Tiny = 1.0 / (1 << 54) // 2**-54 = 0x3c90000000000000
+ // scaled coefficients related to expm1
+ Q1 = -3.33333333333331316428e-02 // 0xBFA11111111110F4
+ Q2 = 1.58730158725481460165e-03 // 0x3F5A01A019FE5585
+ Q3 = -7.93650757867487942473e-05 // 0xBF14CE199EAADBB7
+ Q4 = 4.00821782732936239552e-06 // 0x3ED0CFCA86E65239
+ Q5 = -2.01099218183624371326e-07 // 0xBE8AFDB76E09C32D
+ )
+
+ // special cases
+ switch {
+ case IsInf(x, 1) || IsNaN(x):
+ return x
+ case IsInf(x, -1):
+ return -1
+ }
+
+ absx := x
+ sign := false
+ if x < 0 {
+ absx = -absx
+ sign = true
+ }
+
+ // filter out huge argument
+ if absx >= Ln2X56 { // if |x| >= 56 * ln2
+ if sign {
+ return -1 // x < -56*ln2, return -1
+ }
+ if absx >= Othreshold { // if |x| >= 709.78...
+ return Inf(1)
+ }
+ }
+
+ // argument reduction
+ var c float64
+ var k int
+ if absx > Ln2Half { // if |x| > 0.5 * ln2
+ var hi, lo float64
+ if absx < Ln2HalfX3 { // and |x| < 1.5 * ln2
+ if !sign {
+ hi = x - Ln2Hi
+ lo = Ln2Lo
+ k = 1
+ } else {
+ hi = x + Ln2Hi
+ lo = -Ln2Lo
+ k = -1
+ }
+ } else {
+ if !sign {
+ k = int(InvLn2*x + 0.5)
+ } else {
+ k = int(InvLn2*x - 0.5)
+ }
+ t := float64(k)
+ hi = x - t*Ln2Hi // t * Ln2Hi is exact here
+ lo = t * Ln2Lo
+ }
+ x = hi - lo
+ c = (hi - x) - lo
+ } else if absx < Tiny { // when |x| < 2**-54, return x
+ return x
+ } else {
+ k = 0
+ }
+
+ // x is now in primary range
+ hfx := 0.5 * x
+ hxs := x * hfx
+ r1 := 1 + hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5))))
+ t := 3 - r1*hfx
+ e := hxs * ((r1 - t) / (6.0 - x*t))
+ if k == 0 {
+ return x - (x*e - hxs) // c is 0
+ }
+ e = (x*(e-c) - c)
+ e -= hxs
+ switch {
+ case k == -1:
+ return 0.5*(x-e) - 0.5
+ case k == 1:
+ if x < -0.25 {
+ return -2 * (e - (x + 0.5))
+ }
+ return 1 + 2*(x-e)
+ case k <= -2 || k > 56: // suffice to return exp(x)-1
+ y := 1 - (e - x)
+ y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent
+ return y - 1
+ }
+ if k < 20 {
+ t := Float64frombits(0x3ff0000000000000 - (0x20000000000000 >> uint(k))) // t=1-2**-k
+ y := t - (e - x)
+ y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent
+ return y
+ }
+ t = Float64frombits(uint64(0x3ff-k) << 52) // 2**-k
+ y := x - (e + t)
+ y++
+ y = Float64frombits(Float64bits(y) + uint64(k)<<52) // add k to y's exponent
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/src/math/expm1_s390x.s b/platform/dbops/binaries/go/go/src/math/expm1_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..16c861bb18b605778b8716accad38d9149c3cedf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/expm1_s390x.s
@@ -0,0 +1,194 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial approximation and other constants
+DATA ·expm1rodataL22<> + 0(SB)/8, $-1.0
+DATA ·expm1rodataL22<> + 8(SB)/8, $800.0E+00
+DATA ·expm1rodataL22<> + 16(SB)/8, $1.0
+DATA ·expm1rodataL22<> + 24(SB)/8, $-.231904681384629956E-16
+DATA ·expm1rodataL22<> + 32(SB)/8, $0.50000000000000029671E+00
+DATA ·expm1rodataL22<> + 40(SB)/8, $0.16666666666666676570E+00
+DATA ·expm1rodataL22<> + 48(SB)/8, $0.83333333323590973444E-02
+DATA ·expm1rodataL22<> + 56(SB)/8, $0.13889096526400683566E-02
+DATA ·expm1rodataL22<> + 64(SB)/8, $0.41666666661701152924E-01
+DATA ·expm1rodataL22<> + 72(SB)/8, $0.19841562053987360264E-03
+DATA ·expm1rodataL22<> + 80(SB)/8, $-.693147180559945286E+00
+DATA ·expm1rodataL22<> + 88(SB)/8, $0.144269504088896339E+01
+DATA ·expm1rodataL22<> + 96(SB)/8, $704.0E+00
+GLOBL ·expm1rodataL22<> + 0(SB), RODATA, $104
+
+DATA ·expm1xmone<> + 0(SB)/8, $0xbff0000000000000
+GLOBL ·expm1xmone<> + 0(SB), RODATA, $8
+DATA ·expm1xinf<> + 0(SB)/8, $0x7ff0000000000000
+GLOBL ·expm1xinf<> + 0(SB), RODATA, $8
+DATA ·expm1x4ff<> + 0(SB)/8, $0x4ff0000000000000
+GLOBL ·expm1x4ff<> + 0(SB), RODATA, $8
+DATA ·expm1x2ff<> + 0(SB)/8, $0x2ff0000000000000
+GLOBL ·expm1x2ff<> + 0(SB), RODATA, $8
+DATA ·expm1xaddexp<> + 0(SB)/8, $0xc2f0000100003ff0
+GLOBL ·expm1xaddexp<> + 0(SB), RODATA, $8
+
+// Log multipliers table
+DATA ·expm1tab<> + 0(SB)/8, $0.0
+DATA ·expm1tab<> + 8(SB)/8, $-.171540871271399150E-01
+DATA ·expm1tab<> + 16(SB)/8, $-.306597931864376363E-01
+DATA ·expm1tab<> + 24(SB)/8, $-.410200970469965021E-01
+DATA ·expm1tab<> + 32(SB)/8, $-.486343079978231466E-01
+DATA ·expm1tab<> + 40(SB)/8, $-.538226193725835820E-01
+DATA ·expm1tab<> + 48(SB)/8, $-.568439602538111520E-01
+DATA ·expm1tab<> + 56(SB)/8, $-.579091847395528847E-01
+DATA ·expm1tab<> + 64(SB)/8, $-.571909584179366341E-01
+DATA ·expm1tab<> + 72(SB)/8, $-.548312665987204407E-01
+DATA ·expm1tab<> + 80(SB)/8, $-.509471843643441085E-01
+DATA ·expm1tab<> + 88(SB)/8, $-.456353588448863359E-01
+DATA ·expm1tab<> + 96(SB)/8, $-.389755254243262365E-01
+DATA ·expm1tab<> + 104(SB)/8, $-.310332908285244231E-01
+DATA ·expm1tab<> + 112(SB)/8, $-.218623539150173528E-01
+DATA ·expm1tab<> + 120(SB)/8, $-.115062908917949451E-01
+GLOBL ·expm1tab<> + 0(SB), RODATA, $128
+
+// Expm1 returns e**x - 1, the base-e exponential of x minus 1.
+// It is more accurate than Exp(x) - 1 when x is near zero.
+//
+// Special cases are:
+// Expm1(+Inf) = +Inf
+// Expm1(-Inf) = -1
+// Expm1(NaN) = NaN
+// Very large values overflow to -1 or +Inf.
+// The algorithm used is minimax polynomial approximation using a table of
+// polynomial coefficients determined with a Remez exchange algorithm.
+
+TEXT ·expm1Asm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·expm1rodataL22<>+0(SB), R5
+ LTDBR F0, F0
+ BLTU L20
+ FMOVD F0, F2
+L2:
+ WORD $0xED205060 //cdb %f2,.L23-.L22(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L16
+ BVS L16
+ WFCEDBS V2, V2, V2
+ BVS LEXITTAGexpm1
+ MOVD $·expm1xaddexp<>+0(SB), R1
+ FMOVD 88(R5), F1
+ FMOVD 0(R1), F2
+ WFMSDB V0, V1, V2, V1
+ FMOVD 80(R5), F6
+ WFADB V1, V2, V4
+ FMOVD 72(R5), F2
+ FMADD F6, F4, F0
+ FMOVD 64(R5), F3
+ FMOVD 56(R5), F6
+ FMOVD 48(R5), F5
+ FMADD F2, F0, F6
+ WFMADB V0, V5, V3, V5
+ WFMDB V0, V0, V2
+ LGDR F1, R1
+ WFMADB V6, V2, V5, V6
+ FMOVD 40(R5), F3
+ FMOVD 32(R5), F5
+ WFMADB V0, V3, V5, V3
+ FMOVD 24(R5), F5
+ WFMADB V2, V6, V3, V2
+ FMADD F5, F4, F0
+ FMOVD 16(R5), F6
+ WFMADB V0, V2, V6, V2
+ RISBGZ $57, $60, $3, R1, R3
+ WORD $0xB3130022 //lcdbr %f2,%f2
+ MOVD $·expm1tab<>+0(SB), R2
+ WORD $0x68432000 //ld %f4,0(%r3,%r2)
+ FMADD F4, F0, F0
+ SLD $48, R1, R2
+ WFMSDB V2, V0, V4, V0
+ LDGR R2, F4
+ WORD $0xB3130000 //lcdbr %f0,%f0
+ FSUB F4, F6
+ WFMSDB V0, V4, V6, V0
+ FMOVD F0, ret+8(FP)
+ RET
+L16:
+ WFCEDBS V2, V2, V4
+ BVS LEXITTAGexpm1
+ WORD $0xED205008 //cdb %f2,.L34-.L22(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BLT L6
+ WFCEDBS V2, V0, V0
+ BVS L7
+ MOVD $·expm1xinf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+L20:
+ WORD $0xB3130020 //lcdbr %f2,%f0
+ BR L2
+L6:
+ MOVD $·expm1xaddexp<>+0(SB), R1
+ FMOVD 88(R5), F5
+ FMOVD 0(R1), F4
+ WFMSDB V0, V5, V4, V5
+ FMOVD 80(R5), F3
+ WFADB V5, V4, V1
+ VLEG $0, 48(R5), V16
+ WFMADB V1, V3, V0, V3
+ FMOVD 56(R5), F4
+ FMOVD 64(R5), F7
+ FMOVD 72(R5), F6
+ WFMADB V3, V16, V7, V16
+ WFMADB V3, V6, V4, V6
+ WFMDB V3, V3, V4
+ MOVD $·expm1tab<>+0(SB), R2
+ WFMADB V6, V4, V16, V6
+ VLEG $0, 32(R5), V16
+ FMOVD 40(R5), F7
+ WFMADB V3, V7, V16, V7
+ VLEG $0, 24(R5), V16
+ WFMADB V4, V6, V7, V4
+ WFMADB V1, V16, V3, V1
+ FMOVD 16(R5), F6
+ FMADD F4, F1, F6
+ LGDR F5, R1
+ WORD $0xB3130066 //lcdbr %f6,%f6
+ RISBGZ $57, $60, $3, R1, R3
+ WORD $0x68432000 //ld %f4,0(%r3,%r2)
+ FMADD F4, F1, F1
+ MOVD $0x4086000000000000, R2
+ FMSUB F1, F6, F4
+ WORD $0xB3130044 //lcdbr %f4,%f4
+ WFCHDBS V2, V0, V0
+ BEQ L21
+ ADDW $0xF000, R1
+ RISBGN $0, $15, $48, R1, R2
+ LDGR R2, F0
+ FMADD F0, F4, F0
+ MOVD $·expm1x4ff<>+0(SB), R3
+ FMOVD 0(R5), F4
+ FMOVD 0(R3), F2
+ WFMADB V2, V0, V4, V0
+ FMOVD F0, ret+8(FP)
+ RET
+L7:
+ MOVD $·expm1xmone<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+L21:
+ ADDW $0x1000, R1
+ RISBGN $0, $15, $48, R1, R2
+ LDGR R2, F0
+ FMADD F0, F4, F0
+ MOVD $·expm1x2ff<>+0(SB), R3
+ FMOVD 0(R5), F4
+ FMOVD 0(R3), F2
+ WFMADB V2, V0, V4, V0
+ FMOVD F0, ret+8(FP)
+ RET
+LEXITTAGexpm1:
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/export_s390x_test.go b/platform/dbops/binaries/go/go/src/math/export_s390x_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..827bf1c8f60f3846d72836782a6a1d968e076252
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/export_s390x_test.go
@@ -0,0 +1,31 @@
+// 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 math
+
+// Export internal functions and variable for testing.
+var Log10NoVec = log10
+var CosNoVec = cos
+var CoshNoVec = cosh
+var SinNoVec = sin
+var SinhNoVec = sinh
+var TanhNoVec = tanh
+var Log1pNovec = log1p
+var AtanhNovec = atanh
+var AcosNovec = acos
+var AcoshNovec = acosh
+var AsinNovec = asin
+var AsinhNovec = asinh
+var ErfNovec = erf
+var ErfcNovec = erfc
+var AtanNovec = atan
+var Atan2Novec = atan2
+var CbrtNovec = cbrt
+var LogNovec = log
+var TanNovec = tan
+var ExpNovec = exp
+var Expm1Novec = expm1
+var PowNovec = pow
+var HypotNovec = hypot
+var HasVX = hasVX
diff --git a/platform/dbops/binaries/go/go/src/math/export_test.go b/platform/dbops/binaries/go/go/src/math/export_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..53d9205b9d1693d745e12695cb3d05fe576aef32
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/export_test.go
@@ -0,0 +1,14 @@
+// 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 math
+
+// Export internal functions for testing.
+var ExpGo = exp
+var Exp2Go = exp2
+var HypotGo = hypot
+var SqrtGo = sqrt
+var TrigReduce = trigReduce
+
+const ReduceThreshold = reduceThreshold
diff --git a/platform/dbops/binaries/go/go/src/math/floor.go b/platform/dbops/binaries/go/go/src/math/floor.go
new file mode 100644
index 0000000000000000000000000000000000000000..cb5856424b4e76a7cbbbec04a3551365d6aa9ca9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor.go
@@ -0,0 +1,151 @@
+// 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 math
+
+// Floor returns the greatest integer value less than or equal to x.
+//
+// Special cases are:
+//
+// Floor(±0) = ±0
+// Floor(±Inf) = ±Inf
+// Floor(NaN) = NaN
+func Floor(x float64) float64 {
+ if haveArchFloor {
+ return archFloor(x)
+ }
+ return floor(x)
+}
+
+func floor(x float64) float64 {
+ if x == 0 || IsNaN(x) || IsInf(x, 0) {
+ return x
+ }
+ if x < 0 {
+ d, fract := Modf(-x)
+ if fract != 0.0 {
+ d = d + 1
+ }
+ return -d
+ }
+ d, _ := Modf(x)
+ return d
+}
+
+// Ceil returns the least integer value greater than or equal to x.
+//
+// Special cases are:
+//
+// Ceil(±0) = ±0
+// Ceil(±Inf) = ±Inf
+// Ceil(NaN) = NaN
+func Ceil(x float64) float64 {
+ if haveArchCeil {
+ return archCeil(x)
+ }
+ return ceil(x)
+}
+
+func ceil(x float64) float64 {
+ return -Floor(-x)
+}
+
+// Trunc returns the integer value of x.
+//
+// Special cases are:
+//
+// Trunc(±0) = ±0
+// Trunc(±Inf) = ±Inf
+// Trunc(NaN) = NaN
+func Trunc(x float64) float64 {
+ if haveArchTrunc {
+ return archTrunc(x)
+ }
+ return trunc(x)
+}
+
+func trunc(x float64) float64 {
+ if x == 0 || IsNaN(x) || IsInf(x, 0) {
+ return x
+ }
+ d, _ := Modf(x)
+ return d
+}
+
+// Round returns the nearest integer, rounding half away from zero.
+//
+// Special cases are:
+//
+// Round(±0) = ±0
+// Round(±Inf) = ±Inf
+// Round(NaN) = NaN
+func Round(x float64) float64 {
+ // Round is a faster implementation of:
+ //
+ // func Round(x float64) float64 {
+ // t := Trunc(x)
+ // if Abs(x-t) >= 0.5 {
+ // return t + Copysign(1, x)
+ // }
+ // return t
+ // }
+ bits := Float64bits(x)
+ e := uint(bits>>shift) & mask
+ if e < bias {
+ // Round abs(x) < 1 including denormals.
+ bits &= signMask // +-0
+ if e == bias-1 {
+ bits |= uvone // +-1
+ }
+ } else if e < bias+shift {
+ // Round any abs(x) >= 1 containing a fractional component [0,1).
+ //
+ // Numbers with larger exponents are returned unchanged since they
+ // must be either an integer, infinity, or NaN.
+ const half = 1 << (shift - 1)
+ e -= bias
+ bits += half >> e
+ bits &^= fracMask >> e
+ }
+ return Float64frombits(bits)
+}
+
+// RoundToEven returns the nearest integer, rounding ties to even.
+//
+// Special cases are:
+//
+// RoundToEven(±0) = ±0
+// RoundToEven(±Inf) = ±Inf
+// RoundToEven(NaN) = NaN
+func RoundToEven(x float64) float64 {
+ // RoundToEven is a faster implementation of:
+ //
+ // func RoundToEven(x float64) float64 {
+ // t := math.Trunc(x)
+ // odd := math.Remainder(t, 2) != 0
+ // if d := math.Abs(x - t); d > 0.5 || (d == 0.5 && odd) {
+ // return t + math.Copysign(1, x)
+ // }
+ // return t
+ // }
+ bits := Float64bits(x)
+ e := uint(bits>>shift) & mask
+ if e >= bias {
+ // Round abs(x) >= 1.
+ // - Large numbers without fractional components, infinity, and NaN are unchanged.
+ // - Add 0.499.. or 0.5 before truncating depending on whether the truncated
+ // number is even or odd (respectively).
+ const halfMinusULP = (1 << (shift - 1)) - 1
+ e -= bias
+ bits += (halfMinusULP + (bits>>(shift-e))&1) >> e
+ bits &^= fracMask >> e
+ } else if e == bias-1 && bits&fracMask != 0 {
+ // Round 0.5 < abs(x) < 1.
+ bits = bits&signMask | uvone // +-1
+ } else {
+ // Round abs(x) <= 0.5 including denormals.
+ bits &= signMask // +-0
+ }
+ return Float64frombits(bits)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/floor_386.s b/platform/dbops/binaries/go/go/src/math/floor_386.s
new file mode 100644
index 0000000000000000000000000000000000000000..1990cb0c8c00d56c2dffa7e9eab5613afd95f2b4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_386.s
@@ -0,0 +1,46 @@
+// 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.
+
+#include "textflag.h"
+
+// func archCeil(x float64) float64
+TEXT ·archCeil(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0 // F0=x
+ FSTCW -2(SP) // save old Control Word
+ MOVW -2(SP), AX
+ ANDW $0xf3ff, AX
+ ORW $0x0800, AX // Rounding Control set to +Inf
+ MOVW AX, -4(SP) // store new Control Word
+ FLDCW -4(SP) // load new Control Word
+ FRNDINT // F0=Ceil(x)
+ FLDCW -2(SP) // load old Control Word
+ FMOVDP F0, ret+8(FP)
+ RET
+
+// func archFloor(x float64) float64
+TEXT ·archFloor(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0 // F0=x
+ FSTCW -2(SP) // save old Control Word
+ MOVW -2(SP), AX
+ ANDW $0xf3ff, AX
+ ORW $0x0400, AX // Rounding Control set to -Inf
+ MOVW AX, -4(SP) // store new Control Word
+ FLDCW -4(SP) // load new Control Word
+ FRNDINT // F0=Floor(x)
+ FLDCW -2(SP) // load old Control Word
+ FMOVDP F0, ret+8(FP)
+ RET
+
+// func archTrunc(x float64) float64
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0 // F0=x
+ FSTCW -2(SP) // save old Control Word
+ MOVW -2(SP), AX
+ ORW $0x0c00, AX // Rounding Control set to truncate
+ MOVW AX, -4(SP) // store new Control Word
+ FLDCW -4(SP) // load new Control Word
+ FRNDINT // F0=Trunc(x)
+ FLDCW -2(SP) // load old Control Word
+ FMOVDP F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/floor_amd64.s b/platform/dbops/binaries/go/go/src/math/floor_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..088049958ab4c7bf392bc119bcb710c48f7b0422
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_amd64.s
@@ -0,0 +1,76 @@
+// 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.
+
+#include "textflag.h"
+
+#define Big 0x4330000000000000 // 2**52
+
+// func archFloor(x float64) float64
+TEXT ·archFloor(SB),NOSPLIT,$0
+ MOVQ x+0(FP), AX
+ MOVQ $~(1<<63), DX // sign bit mask
+ ANDQ AX,DX // DX = |x|
+ SUBQ $1,DX
+ MOVQ $(Big - 1), CX // if |x| >= 2**52-1 or IsNaN(x) or |x| == 0, return x
+ CMPQ DX,CX
+ JAE isBig_floor
+ MOVQ AX, X0 // X0 = x
+ CVTTSD2SQ X0, AX
+ CVTSQ2SD AX, X1 // X1 = float(int(x))
+ CMPSD X1, X0, 1 // compare LT; X0 = 0xffffffffffffffff or 0
+ MOVSD $(-1.0), X2
+ ANDPD X2, X0 // if x < float(int(x)) {X0 = -1} else {X0 = 0}
+ ADDSD X1, X0
+ MOVSD X0, ret+8(FP)
+ RET
+isBig_floor:
+ MOVQ AX, ret+8(FP) // return x
+ RET
+
+// func archCeil(x float64) float64
+TEXT ·archCeil(SB),NOSPLIT,$0
+ MOVQ x+0(FP), AX
+ MOVQ $~(1<<63), DX // sign bit mask
+ MOVQ AX, BX // BX = copy of x
+ ANDQ DX, BX // BX = |x|
+ MOVQ $Big, CX // if |x| >= 2**52 or IsNaN(x), return x
+ CMPQ BX, CX
+ JAE isBig_ceil
+ MOVQ AX, X0 // X0 = x
+ MOVQ DX, X2 // X2 = sign bit mask
+ CVTTSD2SQ X0, AX
+ ANDNPD X0, X2 // X2 = sign
+ CVTSQ2SD AX, X1 // X1 = float(int(x))
+ CMPSD X1, X0, 2 // compare LE; X0 = 0xffffffffffffffff or 0
+ ORPD X2, X1 // if X1 = 0.0, incorporate sign
+ MOVSD $1.0, X3
+ ANDNPD X3, X0
+ ORPD X2, X0 // if float(int(x)) <= x {X0 = 1} else {X0 = -0}
+ ADDSD X1, X0
+ MOVSD X0, ret+8(FP)
+ RET
+isBig_ceil:
+ MOVQ AX, ret+8(FP)
+ RET
+
+// func archTrunc(x float64) float64
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ MOVQ x+0(FP), AX
+ MOVQ $~(1<<63), DX // sign bit mask
+ MOVQ AX, BX // BX = copy of x
+ ANDQ DX, BX // BX = |x|
+ MOVQ $Big, CX // if |x| >= 2**52 or IsNaN(x), return x
+ CMPQ BX, CX
+ JAE isBig_trunc
+ MOVQ AX, X0
+ MOVQ DX, X2 // X2 = sign bit mask
+ CVTTSD2SQ X0, AX
+ ANDNPD X0, X2 // X2 = sign
+ CVTSQ2SD AX, X0 // X0 = float(int(x))
+ ORPD X2, X0 // if X0 = 0.0, incorporate sign
+ MOVSD X0, ret+8(FP)
+ RET
+isBig_trunc:
+ MOVQ AX, ret+8(FP) // return x
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/floor_arm64.s b/platform/dbops/binaries/go/go/src/math/floor_arm64.s
new file mode 100644
index 0000000000000000000000000000000000000000..d9c5df7b2472dbff1566042612a18e5181871718
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_arm64.s
@@ -0,0 +1,26 @@
+// 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.
+
+#include "textflag.h"
+
+// func archFloor(x float64) float64
+TEXT ·archFloor(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRINTMD F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+// func archCeil(x float64) float64
+TEXT ·archCeil(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRINTPD F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+// func archTrunc(x float64) float64
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRINTZD F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/floor_asm.go b/platform/dbops/binaries/go/go/src/math/floor_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..fb419d6da2f6bfc98fcf8d12a82b39dc987f86d0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_asm.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.
+
+//go:build 386 || amd64 || arm64 || ppc64 || ppc64le || s390x || wasm
+
+package math
+
+const haveArchFloor = true
+
+func archFloor(x float64) float64
+
+const haveArchCeil = true
+
+func archCeil(x float64) float64
+
+const haveArchTrunc = true
+
+func archTrunc(x float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/floor_noasm.go b/platform/dbops/binaries/go/go/src/math/floor_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..5641c7ea0a49caf563cf496e2be234612dd0d2c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_noasm.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.
+
+//go:build !386 && !amd64 && !arm64 && !ppc64 && !ppc64le && !s390x && !wasm
+
+package math
+
+const haveArchFloor = false
+
+func archFloor(x float64) float64 {
+ panic("not implemented")
+}
+
+const haveArchCeil = false
+
+func archCeil(x float64) float64 {
+ panic("not implemented")
+}
+
+const haveArchTrunc = false
+
+func archTrunc(x float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/floor_ppc64x.s b/platform/dbops/binaries/go/go/src/math/floor_ppc64x.s
new file mode 100644
index 0000000000000000000000000000000000000000..e9c5d49f4a5aaf6dfd2a438ad2ec98acc8e5cfc9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_ppc64x.s
@@ -0,0 +1,25 @@
+// 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 ppc64 || ppc64le
+
+#include "textflag.h"
+
+TEXT ·archFloor(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRIM F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+TEXT ·archCeil(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRIP F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FRIZ F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/floor_s390x.s b/platform/dbops/binaries/go/go/src/math/floor_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..b5dd462e526926bfb6d61911a898c37907f05c25
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_s390x.s
@@ -0,0 +1,26 @@
+// 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.
+
+#include "textflag.h"
+
+// func archFloor(x float64) float64
+TEXT ·archFloor(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FIDBR $7, F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+// func archCeil(x float64) float64
+TEXT ·archCeil(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FIDBR $6, F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+// func archTrunc(x float64) float64
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ FMOVD x+0(FP), F0
+ FIDBR $5, F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/floor_wasm.s b/platform/dbops/binaries/go/go/src/math/floor_wasm.s
new file mode 100644
index 0000000000000000000000000000000000000000..3751471574610c5c2c85793b7c8a01f77ef89ffc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/floor_wasm.s
@@ -0,0 +1,26 @@
+// Copyright 2018 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "textflag.h"
+
+TEXT ·archFloor(SB),NOSPLIT,$0
+ Get SP
+ F64Load x+0(FP)
+ F64Floor
+ F64Store ret+8(FP)
+ RET
+
+TEXT ·archCeil(SB),NOSPLIT,$0
+ Get SP
+ F64Load x+0(FP)
+ F64Ceil
+ F64Store ret+8(FP)
+ RET
+
+TEXT ·archTrunc(SB),NOSPLIT,$0
+ Get SP
+ F64Load x+0(FP)
+ F64Trunc
+ F64Store ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/fma.go b/platform/dbops/binaries/go/go/src/math/fma.go
new file mode 100644
index 0000000000000000000000000000000000000000..ba03fbe8a93b27a2834b3248cc1c1fbb0804177a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/fma.go
@@ -0,0 +1,175 @@
+// 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 math
+
+import "math/bits"
+
+func zero(x uint64) uint64 {
+ if x == 0 {
+ return 1
+ }
+ return 0
+ // branchless:
+ // return ((x>>1 | x&1) - 1) >> 63
+}
+
+func nonzero(x uint64) uint64 {
+ if x != 0 {
+ return 1
+ }
+ return 0
+ // branchless:
+ // return 1 - ((x>>1|x&1)-1)>>63
+}
+
+func shl(u1, u2 uint64, n uint) (r1, r2 uint64) {
+ r1 = u1<>(64-n) | u2<<(n-64)
+ r2 = u2 << n
+ return
+}
+
+func shr(u1, u2 uint64, n uint) (r1, r2 uint64) {
+ r2 = u2>>n | u1<<(64-n) | u1>>(n-64)
+ r1 = u1 >> n
+ return
+}
+
+// shrcompress compresses the bottom n+1 bits of the two-word
+// value into a single bit. the result is equal to the value
+// shifted to the right by n, except the result's 0th bit is
+// set to the bitwise OR of the bottom n+1 bits.
+func shrcompress(u1, u2 uint64, n uint) (r1, r2 uint64) {
+ // TODO: Performance here is really sensitive to the
+ // order/placement of these branches. n == 0 is common
+ // enough to be in the fast path. Perhaps more measurement
+ // needs to be done to find the optimal order/placement?
+ switch {
+ case n == 0:
+ return u1, u2
+ case n == 64:
+ return 0, u1 | nonzero(u2)
+ case n >= 128:
+ return 0, nonzero(u1 | u2)
+ case n < 64:
+ r1, r2 = shr(u1, u2, n)
+ r2 |= nonzero(u2 & (1<> 63)
+ exp = int32(b>>52) & mask
+ mantissa = b & fracMask
+
+ if exp == 0 {
+ // Normalize value if subnormal.
+ shift := uint(bits.LeadingZeros64(mantissa) - 11)
+ mantissa <<= shift
+ exp = 1 - int32(shift)
+ } else {
+ // Add implicit 1 bit
+ mantissa |= 1 << 52
+ }
+ return
+}
+
+// FMA returns x * y + z, computed with only one rounding.
+// (That is, FMA returns the fused multiply-add of x, y, and z.)
+func FMA(x, y, z float64) float64 {
+ bx, by, bz := Float64bits(x), Float64bits(y), Float64bits(z)
+
+ // Inf or NaN or zero involved. At most one rounding will occur.
+ if x == 0.0 || y == 0.0 || z == 0.0 || bx&uvinf == uvinf || by&uvinf == uvinf {
+ return x*y + z
+ }
+ // Handle non-finite z separately. Evaluating x*y+z where
+ // x and y are finite, but z is infinite, should always result in z.
+ if bz&uvinf == uvinf {
+ return z
+ }
+
+ // Inputs are (sub)normal.
+ // Split x, y, z into sign, exponent, mantissa.
+ xs, xe, xm := split(bx)
+ ys, ye, ym := split(by)
+ zs, ze, zm := split(bz)
+
+ // Compute product p = x*y as sign, exponent, two-word mantissa.
+ // Start with exponent. "is normal" bit isn't subtracted yet.
+ pe := xe + ye - bias + 1
+
+ // pm1:pm2 is the double-word mantissa for the product p.
+ // Shift left to leave top bit in product. Effectively
+ // shifts the 106-bit product to the left by 21.
+ pm1, pm2 := bits.Mul64(xm<<10, ym<<11)
+ zm1, zm2 := zm<<10, uint64(0)
+ ps := xs ^ ys // product sign
+
+ // normalize to 62nd bit
+ is62zero := uint((^pm1 >> 62) & 1)
+ pm1, pm2 = shl(pm1, pm2, is62zero)
+ pe -= int32(is62zero)
+
+ // Swap addition operands so |p| >= |z|
+ if pe < ze || pe == ze && pm1 < zm1 {
+ ps, pe, pm1, pm2, zs, ze, zm1, zm2 = zs, ze, zm1, zm2, ps, pe, pm1, pm2
+ }
+
+ // Special case: if p == -z the result is always +0 since neither operand is zero.
+ if ps != zs && pe == ze && pm1 == zm1 && pm2 == zm2 {
+ return 0
+ }
+
+ // Align significands
+ zm1, zm2 = shrcompress(zm1, zm2, uint(pe-ze))
+
+ // Compute resulting significands, normalizing if necessary.
+ var m, c uint64
+ if ps == zs {
+ // Adding (pm1:pm2) + (zm1:zm2)
+ pm2, c = bits.Add64(pm2, zm2, 0)
+ pm1, _ = bits.Add64(pm1, zm1, c)
+ pe -= int32(^pm1 >> 63)
+ pm1, m = shrcompress(pm1, pm2, uint(64+pm1>>63))
+ } else {
+ // Subtracting (pm1:pm2) - (zm1:zm2)
+ // TODO: should we special-case cancellation?
+ pm2, c = bits.Sub64(pm2, zm2, 0)
+ pm1, _ = bits.Sub64(pm1, zm1, c)
+ nz := lz(pm1, pm2)
+ pe -= nz
+ m, pm2 = shl(pm1, pm2, uint(nz-1))
+ m |= nonzero(pm2)
+ }
+
+ // Round and break ties to even
+ if pe > 1022+bias || pe == 1022+bias && (m+1<<9)>>63 == 1 {
+ // rounded value overflows exponent range
+ return Float64frombits(uint64(ps)<<63 | uvinf)
+ }
+ if pe < 0 {
+ n := uint(-pe)
+ m = m>>n | nonzero(m&(1<> 10) & ^zero((m&(1<<10-1))^1<<9)
+ pe &= -int32(nonzero(m))
+ return Float64frombits(uint64(ps)<<63 + uint64(pe)<<52 + m)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/frexp.go b/platform/dbops/binaries/go/go/src/math/frexp.go
new file mode 100644
index 0000000000000000000000000000000000000000..e194947e646af437a251de11271f5635dbebcde7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/frexp.go
@@ -0,0 +1,39 @@
+// 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 math
+
+// Frexp breaks f into a normalized fraction
+// and an integral power of two.
+// It returns frac and exp satisfying f == frac × 2**exp,
+// with the absolute value of frac in the interval [½, 1).
+//
+// Special cases are:
+//
+// Frexp(±0) = ±0, 0
+// Frexp(±Inf) = ±Inf, 0
+// Frexp(NaN) = NaN, 0
+func Frexp(f float64) (frac float64, exp int) {
+ if haveArchFrexp {
+ return archFrexp(f)
+ }
+ return frexp(f)
+}
+
+func frexp(f float64) (frac float64, exp int) {
+ // special cases
+ switch {
+ case f == 0:
+ return f, 0 // correctly return -0
+ case IsInf(f, 0) || IsNaN(f):
+ return f, 0
+ }
+ f, exp = normalize(f)
+ x := Float64bits(f)
+ exp += int((x>>shift)&mask) - bias + 1
+ x &^= mask << shift
+ x |= (-1 + bias) << shift
+ frac = Float64frombits(x)
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/gamma.go b/platform/dbops/binaries/go/go/src/math/gamma.go
new file mode 100644
index 0000000000000000000000000000000000000000..86c67232580154070c44634d7bdbc6021d66db7f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/gamma.go
@@ -0,0 +1,222 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below are from http://netlib.sandia.gov/cephes/cprob/gamma.c.
+// The go code is a simplified version of the original C.
+//
+// tgamma.c
+//
+// Gamma function
+//
+// SYNOPSIS:
+//
+// double x, y, tgamma();
+// extern int signgam;
+//
+// y = tgamma( x );
+//
+// DESCRIPTION:
+//
+// Returns gamma function of the argument. The result is
+// correctly signed, and the sign (+1 or -1) is also
+// returned in a global (extern) variable named signgam.
+// This variable is also filled in by the logarithmic gamma
+// function lgamma().
+//
+// Arguments |x| <= 34 are reduced by recurrence and the function
+// approximated by a rational function of degree 6/7 in the
+// interval (2,3). Large arguments are handled by Stirling's
+// formula. Large negative arguments are made positive using
+// a reflection formula.
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC -34, 34 10000 1.3e-16 2.5e-17
+// IEEE -170,-33 20000 2.3e-15 3.3e-16
+// IEEE -33, 33 20000 9.4e-16 2.2e-16
+// IEEE 33, 171.6 20000 2.3e-15 3.2e-16
+//
+// Error for arguments outside the test range will be larger
+// owing to error amplification by the exponential function.
+//
+// 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
+
+var _gamP = [...]float64{
+ 1.60119522476751861407e-04,
+ 1.19135147006586384913e-03,
+ 1.04213797561761569935e-02,
+ 4.76367800457137231464e-02,
+ 2.07448227648435975150e-01,
+ 4.94214826801497100753e-01,
+ 9.99999999999999996796e-01,
+}
+var _gamQ = [...]float64{
+ -2.31581873324120129819e-05,
+ 5.39605580493303397842e-04,
+ -4.45641913851797240494e-03,
+ 1.18139785222060435552e-02,
+ 3.58236398605498653373e-02,
+ -2.34591795718243348568e-01,
+ 7.14304917030273074085e-02,
+ 1.00000000000000000320e+00,
+}
+var _gamS = [...]float64{
+ 7.87311395793093628397e-04,
+ -2.29549961613378126380e-04,
+ -2.68132617805781232825e-03,
+ 3.47222221605458667310e-03,
+ 8.33333333333482257126e-02,
+}
+
+// Gamma function computed by Stirling's formula.
+// The pair of results must be multiplied together to get the actual answer.
+// The multiplication is left to the caller so that, if careful, the caller can avoid
+// infinity for 172 <= x <= 180.
+// The polynomial is valid for 33 <= x <= 172; larger values are only used
+// in reciprocal and produce denormalized floats. The lower precision there
+// masks any imprecision in the polynomial.
+func stirling(x float64) (float64, float64) {
+ if x > 200 {
+ return Inf(1), 1
+ }
+ const (
+ SqrtTwoPi = 2.506628274631000502417
+ MaxStirling = 143.01608
+ )
+ w := 1 / x
+ w = 1 + w*((((_gamS[0]*w+_gamS[1])*w+_gamS[2])*w+_gamS[3])*w+_gamS[4])
+ y1 := Exp(x)
+ y2 := 1.0
+ if x > MaxStirling { // avoid Pow() overflow
+ v := Pow(x, 0.5*x-0.25)
+ y1, y2 = v, v/y1
+ } else {
+ y1 = Pow(x, x-0.5) / y1
+ }
+ return y1, SqrtTwoPi * w * y2
+}
+
+// Gamma returns the Gamma function of x.
+//
+// Special cases are:
+//
+// Gamma(+Inf) = +Inf
+// Gamma(+0) = +Inf
+// Gamma(-0) = -Inf
+// Gamma(x) = NaN for integer x < 0
+// Gamma(-Inf) = NaN
+// Gamma(NaN) = NaN
+func Gamma(x float64) float64 {
+ const Euler = 0.57721566490153286060651209008240243104215933593992 // A001620
+ // special cases
+ switch {
+ case isNegInt(x) || IsInf(x, -1) || IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return Inf(1)
+ case x == 0:
+ if Signbit(x) {
+ return Inf(-1)
+ }
+ return Inf(1)
+ }
+ q := Abs(x)
+ p := Floor(q)
+ if q > 33 {
+ if x >= 0 {
+ y1, y2 := stirling(x)
+ return y1 * y2
+ }
+ // Note: x is negative but (checked above) not a negative integer,
+ // so x must be small enough to be in range for conversion to int64.
+ // If |x| were >= 2⁶³ it would have to be an integer.
+ signgam := 1
+ if ip := int64(p); ip&1 == 0 {
+ signgam = -1
+ }
+ z := q - p
+ if z > 0.5 {
+ p = p + 1
+ z = q - p
+ }
+ z = q * Sin(Pi*z)
+ if z == 0 {
+ return Inf(signgam)
+ }
+ sq1, sq2 := stirling(q)
+ absz := Abs(z)
+ d := absz * sq1 * sq2
+ if IsInf(d, 0) {
+ z = Pi / absz / sq1 / sq2
+ } else {
+ z = Pi / d
+ }
+ return float64(signgam) * z
+ }
+
+ // Reduce argument
+ z := 1.0
+ for x >= 3 {
+ x = x - 1
+ z = z * x
+ }
+ for x < 0 {
+ if x > -1e-09 {
+ goto small
+ }
+ z = z / x
+ x = x + 1
+ }
+ for x < 2 {
+ if x < 1e-09 {
+ goto small
+ }
+ z = z / x
+ x = x + 1
+ }
+
+ if x == 2 {
+ return z
+ }
+
+ x = x - 2
+ p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6]
+ q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7]
+ return z * p / q
+
+small:
+ if x == 0 {
+ return Inf(1)
+ }
+ return z / ((1 + Euler*x) * x)
+}
+
+func isNegInt(x float64) bool {
+ if x < 0 {
+ _, xf := Modf(x)
+ return xf == 0
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/math/huge_test.go b/platform/dbops/binaries/go/go/src/math/huge_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2eadb7f89a8a8cbe3fd2ded3ccb1abc6624fa5db
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/huge_test.go
@@ -0,0 +1,126 @@
+// 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 math_test
+
+import (
+ . "math"
+ "testing"
+)
+
+// Inputs to test trig_reduce
+var trigHuge = []float64{
+ 1 << 28,
+ 1 << 29,
+ 1 << 30,
+ 1 << 35,
+ 1 << 120,
+ 1 << 240,
+ 1 << 480,
+ 1234567891234567 << 180,
+ 1234567891234567 << 300,
+ MaxFloat64,
+}
+
+// Results for trigHuge[i] calculated with https://github.com/robpike/ivy
+// using 4096 bits of working precision. Values requiring less than
+// 102 decimal digits (1 << 120, 1 << 240, 1 << 480, 1234567891234567 << 180)
+// were confirmed via https://keisan.casio.com/
+var cosHuge = []float64{
+ -0.16556897949057876,
+ -0.94517382606089662,
+ 0.78670712294118812,
+ -0.76466301249635305,
+ -0.92587902285483787,
+ 0.93601042593353793,
+ -0.28282777640193788,
+ -0.14616431394103619,
+ -0.79456058210671406,
+ -0.99998768942655994,
+}
+
+var sinHuge = []float64{
+ -0.98619821183697566,
+ 0.32656766301856334,
+ -0.61732641504604217,
+ -0.64443035102329113,
+ 0.37782010936075202,
+ -0.35197227524865778,
+ 0.95917070894368716,
+ 0.98926032637023618,
+ -0.60718488235646949,
+ 0.00496195478918406,
+}
+
+var tanHuge = []float64{
+ 5.95641897939639421,
+ -0.34551069233430392,
+ -0.78469661331920043,
+ 0.84276385870875983,
+ -0.40806638884180424,
+ -0.37603456702698076,
+ -3.39135965054779932,
+ -6.76813854009065030,
+ 0.76417695016604922,
+ -0.00496201587444489,
+}
+
+// Check that trig values of huge angles return accurate results.
+// This confirms that argument reduction works for very large values
+// up to MaxFloat64.
+func TestHugeCos(t *testing.T) {
+ for i := 0; i < len(trigHuge); i++ {
+ f1 := cosHuge[i]
+ f2 := Cos(trigHuge[i])
+ if !close(f1, f2) {
+ t.Errorf("Cos(%g) = %g, want %g", trigHuge[i], f2, f1)
+ }
+ f3 := Cos(-trigHuge[i])
+ if !close(f1, f3) {
+ t.Errorf("Cos(%g) = %g, want %g", -trigHuge[i], f3, f1)
+ }
+ }
+}
+
+func TestHugeSin(t *testing.T) {
+ for i := 0; i < len(trigHuge); i++ {
+ f1 := sinHuge[i]
+ f2 := Sin(trigHuge[i])
+ if !close(f1, f2) {
+ t.Errorf("Sin(%g) = %g, want %g", trigHuge[i], f2, f1)
+ }
+ f3 := Sin(-trigHuge[i])
+ if !close(-f1, f3) {
+ t.Errorf("Sin(%g) = %g, want %g", -trigHuge[i], f3, -f1)
+ }
+ }
+}
+
+func TestHugeSinCos(t *testing.T) {
+ for i := 0; i < len(trigHuge); i++ {
+ f1, g1 := sinHuge[i], cosHuge[i]
+ f2, g2 := Sincos(trigHuge[i])
+ if !close(f1, f2) || !close(g1, g2) {
+ t.Errorf("Sincos(%g) = %g, %g, want %g, %g", trigHuge[i], f2, g2, f1, g1)
+ }
+ f3, g3 := Sincos(-trigHuge[i])
+ if !close(-f1, f3) || !close(g1, g3) {
+ t.Errorf("Sincos(%g) = %g, %g, want %g, %g", -trigHuge[i], f3, g3, -f1, g1)
+ }
+ }
+}
+
+func TestHugeTan(t *testing.T) {
+ for i := 0; i < len(trigHuge); i++ {
+ f1 := tanHuge[i]
+ f2 := Tan(trigHuge[i])
+ if !close(f1, f2) {
+ t.Errorf("Tan(%g) = %g, want %g", trigHuge[i], f2, f1)
+ }
+ f3 := Tan(-trigHuge[i])
+ if !close(-f1, f3) {
+ t.Errorf("Tan(%g) = %g, want %g", -trigHuge[i], f3, -f1)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/math/hypot.go b/platform/dbops/binaries/go/go/src/math/hypot.go
new file mode 100644
index 0000000000000000000000000000000000000000..03c3602acfe2851ff068ab08ec247116dab0e756
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/hypot.go
@@ -0,0 +1,44 @@
+// 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 math
+
+/*
+ Hypot -- sqrt(p*p + q*q), but overflows only if the result does.
+*/
+
+// Hypot returns [Sqrt](p*p + q*q), taking care to avoid
+// unnecessary overflow and underflow.
+//
+// Special cases are:
+//
+// Hypot(±Inf, q) = +Inf
+// Hypot(p, ±Inf) = +Inf
+// Hypot(NaN, q) = NaN
+// Hypot(p, NaN) = NaN
+func Hypot(p, q float64) float64 {
+ if haveArchHypot {
+ return archHypot(p, q)
+ }
+ return hypot(p, q)
+}
+
+func hypot(p, q float64) float64 {
+ p, q = Abs(p), Abs(q)
+ // special cases
+ switch {
+ case IsInf(p, 1) || IsInf(q, 1):
+ return Inf(1)
+ case IsNaN(p) || IsNaN(q):
+ return NaN()
+ }
+ if p < q {
+ p, q = q, p
+ }
+ if p == 0 {
+ return 0
+ }
+ q = q / p
+ return p * Sqrt(1+q*q)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/hypot_386.s b/platform/dbops/binaries/go/go/src/math/hypot_386.s
new file mode 100644
index 0000000000000000000000000000000000000000..80a8fd3fd02a01ae4b15337e0f6e89ae9b730545
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/hypot_386.s
@@ -0,0 +1,59 @@
+// 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.
+
+#include "textflag.h"
+
+// func archHypot(p, q float64) float64
+TEXT ·archHypot(SB),NOSPLIT,$0
+// test bits for not-finite
+ MOVL p_hi+4(FP), AX // high word p
+ ANDL $0x7ff00000, AX
+ CMPL AX, $0x7ff00000
+ JEQ not_finite
+ MOVL q_hi+12(FP), AX // high word q
+ ANDL $0x7ff00000, AX
+ CMPL AX, $0x7ff00000
+ JEQ not_finite
+ FMOVD p+0(FP), F0 // F0=p
+ FABS // F0=|p|
+ FMOVD q+8(FP), F0 // F0=q, F1=|p|
+ FABS // F0=|q|, F1=|p|
+ FUCOMI F0, F1 // compare F0 to F1
+ JCC 2(PC) // jump if F0 >= F1
+ FXCHD F0, F1 // F0=|p| (larger), F1=|q| (smaller)
+ FTST // compare F0 to 0
+ FSTSW AX
+ ANDW $0x4000, AX
+ JNE 10(PC) // jump if F0 = 0
+ FXCHD F0, F1 // F0=q (smaller), F1=p (larger)
+ FDIVD F1, F0 // F0=q(=q/p), F1=p
+ FMULD F0, F0 // F0=q*q, F1=p
+ FLD1 // F0=1, F1=q*q, F2=p
+ FADDDP F0, F1 // F0=1+q*q, F1=p
+ FSQRT // F0=sqrt(1+q*q), F1=p
+ FMULDP F0, F1 // F0=p*sqrt(1+q*q)
+ FMOVDP F0, ret+16(FP)
+ RET
+ FMOVDP F0, F1 // F0=0
+ FMOVDP F0, ret+16(FP)
+ RET
+not_finite:
+// test bits for -Inf or +Inf
+ MOVL p_hi+4(FP), AX // high word p
+ ORL p_lo+0(FP), AX // low word p
+ ANDL $0x7fffffff, AX
+ CMPL AX, $0x7ff00000
+ JEQ is_inf
+ MOVL q_hi+12(FP), AX // high word q
+ ORL q_lo+8(FP), AX // low word q
+ ANDL $0x7fffffff, AX
+ CMPL AX, $0x7ff00000
+ JEQ is_inf
+ MOVL $0x7ff80000, ret_hi+20(FP) // return NaN = 0x7FF8000000000001
+ MOVL $0x00000001, ret_lo+16(FP)
+ RET
+is_inf:
+ MOVL AX, ret_hi+20(FP) // return +Inf = 0x7FF0000000000000
+ MOVL $0x00000000, ret_lo+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/hypot_amd64.s b/platform/dbops/binaries/go/go/src/math/hypot_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..fe326c928173f51cdacdff63c55c534645b995f9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/hypot_amd64.s
@@ -0,0 +1,52 @@
+// 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.
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NaN 0x7FF8000000000001
+
+// func archHypot(p, q float64) float64
+TEXT ·archHypot(SB),NOSPLIT,$0
+ // test bits for special cases
+ MOVQ p+0(FP), BX
+ MOVQ $~(1<<63), AX
+ ANDQ AX, BX // p = |p|
+ MOVQ q+8(FP), CX
+ ANDQ AX, CX // q = |q|
+ MOVQ $PosInf, AX
+ CMPQ AX, BX
+ JLE isInfOrNaN
+ CMPQ AX, CX
+ JLE isInfOrNaN
+ // hypot = max * sqrt(1 + (min/max)**2)
+ MOVQ BX, X0
+ MOVQ CX, X1
+ ORQ CX, BX
+ JEQ isZero
+ MOVAPD X0, X2
+ MAXSD X1, X0
+ MINSD X2, X1
+ DIVSD X0, X1
+ MULSD X1, X1
+ ADDSD $1.0, X1
+ SQRTSD X1, X1
+ MULSD X1, X0
+ MOVSD X0, ret+16(FP)
+ RET
+isInfOrNaN:
+ CMPQ AX, BX
+ JEQ isInf
+ CMPQ AX, CX
+ JEQ isInf
+ MOVQ $NaN, AX
+ MOVQ AX, ret+16(FP) // return NaN
+ RET
+isInf:
+ MOVQ AX, ret+16(FP) // return +Inf
+ RET
+isZero:
+ MOVQ $0, AX
+ MOVQ AX, ret+16(FP) // return 0
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/hypot_asm.go b/platform/dbops/binaries/go/go/src/math/hypot_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..852691037f6f4bc4a8e848d17bebc682181073eb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/hypot_asm.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.
+
+//go:build 386 || amd64
+
+package math
+
+const haveArchHypot = true
+
+func archHypot(p, q float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/hypot_noasm.go b/platform/dbops/binaries/go/go/src/math/hypot_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..8b64812a1c197e048839bf23858ff4bafbd3aaa7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/hypot_noasm.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.
+
+//go:build !386 && !amd64
+
+package math
+
+const haveArchHypot = false
+
+func archHypot(p, q float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/j0.go b/platform/dbops/binaries/go/go/src/math/j0.go
new file mode 100644
index 0000000000000000000000000000000000000000..a311e18d62d4d3c60127159719bb0df1187745a6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/j0.go
@@ -0,0 +1,429 @@
+// 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 math
+
+/*
+ Bessel function of the first and second kinds of order zero.
+*/
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/e_j0.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_j0(x), __ieee754_y0(x)
+// Bessel function of the first and second kinds of order zero.
+// Method -- j0(x):
+// 1. For tiny x, we use j0(x) = 1 - x**2/4 + x**4/64 - ...
+// 2. Reduce x to |x| since j0(x)=j0(-x), and
+// for x in (0,2)
+// j0(x) = 1-z/4+ z**2*R0/S0, where z = x*x;
+// (precision: |j0-1+z/4-z**2R0/S0 |<2**-63.67 )
+// for x in (2,inf)
+// j0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)-q0(x)*sin(x0))
+// where x0 = x-pi/4. It is better to compute sin(x0),cos(x0)
+// as follow:
+// cos(x0) = cos(x)cos(pi/4)+sin(x)sin(pi/4)
+// = 1/sqrt(2) * (cos(x) + sin(x))
+// sin(x0) = sin(x)cos(pi/4)-cos(x)sin(pi/4)
+// = 1/sqrt(2) * (sin(x) - cos(x))
+// (To avoid cancellation, use
+// sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x))
+// to compute the worse one.)
+//
+// 3 Special cases
+// j0(nan)= nan
+// j0(0) = 1
+// j0(inf) = 0
+//
+// Method -- y0(x):
+// 1. For x<2.
+// Since
+// y0(x) = 2/pi*(j0(x)*(ln(x/2)+Euler) + x**2/4 - ...)
+// therefore y0(x)-2/pi*j0(x)*ln(x) is an even function.
+// We use the following function to approximate y0,
+// y0(x) = U(z)/V(z) + (2/pi)*(j0(x)*ln(x)), z= x**2
+// where
+// U(z) = u00 + u01*z + ... + u06*z**6
+// V(z) = 1 + v01*z + ... + v04*z**4
+// with absolute approximation error bounded by 2**-72.
+// Note: For tiny x, U/V = u0 and j0(x)~1, hence
+// y0(tiny) = u0 + (2/pi)*ln(tiny), (choose tiny<2**-27)
+// 2. For x>=2.
+// y0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)+q0(x)*sin(x0))
+// where x0 = x-pi/4. It is better to compute sin(x0),cos(x0)
+// by the method mentioned above.
+// 3. Special cases: y0(0)=-inf, y0(x<0)=NaN, y0(inf)=0.
+//
+
+// J0 returns the order-zero Bessel function of the first kind.
+//
+// Special cases are:
+//
+// J0(±Inf) = 0
+// J0(0) = 1
+// J0(NaN) = NaN
+func J0(x float64) float64 {
+ const (
+ Huge = 1e300
+ TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000
+ TwoM13 = 1.0 / (1 << 13) // 2**-13 0x3f20000000000000
+ Two129 = 1 << 129 // 2**129 0x4800000000000000
+ // R0/S0 on [0, 2]
+ R02 = 1.56249999999999947958e-02 // 0x3F8FFFFFFFFFFFFD
+ R03 = -1.89979294238854721751e-04 // 0xBF28E6A5B61AC6E9
+ R04 = 1.82954049532700665670e-06 // 0x3EBEB1D10C503919
+ R05 = -4.61832688532103189199e-09 // 0xBE33D5E773D63FCE
+ S01 = 1.56191029464890010492e-02 // 0x3F8FFCE882C8C2A4
+ S02 = 1.16926784663337450260e-04 // 0x3F1EA6D2DD57DBF4
+ S03 = 5.13546550207318111446e-07 // 0x3EA13B54CE84D5A9
+ S04 = 1.16614003333790000205e-09 // 0x3E1408BCF4745D8F
+ )
+ // special cases
+ switch {
+ case IsNaN(x):
+ return x
+ case IsInf(x, 0):
+ return 0
+ case x == 0:
+ return 1
+ }
+
+ x = Abs(x)
+ if x >= 2 {
+ s, c := Sincos(x)
+ ss := s - c
+ cc := s + c
+
+ // make sure x+x does not overflow
+ if x < MaxFloat64/2 {
+ z := -Cos(x + x)
+ if s*c < 0 {
+ cc = z / ss
+ } else {
+ ss = z / cc
+ }
+ }
+
+ // j0(x) = 1/sqrt(pi) * (P(0,x)*cc - Q(0,x)*ss) / sqrt(x)
+ // y0(x) = 1/sqrt(pi) * (P(0,x)*ss + Q(0,x)*cc) / sqrt(x)
+
+ var z float64
+ if x > Two129 { // |x| > ~6.8056e+38
+ z = (1 / SqrtPi) * cc / Sqrt(x)
+ } else {
+ u := pzero(x)
+ v := qzero(x)
+ z = (1 / SqrtPi) * (u*cc - v*ss) / Sqrt(x)
+ }
+ return z // |x| >= 2.0
+ }
+ if x < TwoM13 { // |x| < ~1.2207e-4
+ if x < TwoM27 {
+ return 1 // |x| < ~7.4506e-9
+ }
+ return 1 - 0.25*x*x // ~7.4506e-9 < |x| < ~1.2207e-4
+ }
+ z := x * x
+ r := z * (R02 + z*(R03+z*(R04+z*R05)))
+ s := 1 + z*(S01+z*(S02+z*(S03+z*S04)))
+ if x < 1 {
+ return 1 + z*(-0.25+(r/s)) // |x| < 1.00
+ }
+ u := 0.5 * x
+ return (1+u)*(1-u) + z*(r/s) // 1.0 < |x| < 2.0
+}
+
+// Y0 returns the order-zero Bessel function of the second kind.
+//
+// Special cases are:
+//
+// Y0(+Inf) = 0
+// Y0(0) = -Inf
+// Y0(x < 0) = NaN
+// Y0(NaN) = NaN
+func Y0(x float64) float64 {
+ const (
+ TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000
+ Two129 = 1 << 129 // 2**129 0x4800000000000000
+ U00 = -7.38042951086872317523e-02 // 0xBFB2E4D699CBD01F
+ U01 = 1.76666452509181115538e-01 // 0x3FC69D019DE9E3FC
+ U02 = -1.38185671945596898896e-02 // 0xBF8C4CE8B16CFA97
+ U03 = 3.47453432093683650238e-04 // 0x3F36C54D20B29B6B
+ U04 = -3.81407053724364161125e-06 // 0xBECFFEA773D25CAD
+ U05 = 1.95590137035022920206e-08 // 0x3E5500573B4EABD4
+ U06 = -3.98205194132103398453e-11 // 0xBDC5E43D693FB3C8
+ V01 = 1.27304834834123699328e-02 // 0x3F8A127091C9C71A
+ V02 = 7.60068627350353253702e-05 // 0x3F13ECBBF578C6C1
+ V03 = 2.59150851840457805467e-07 // 0x3E91642D7FF202FD
+ V04 = 4.41110311332675467403e-10 // 0x3DFE50183BD6D9EF
+ )
+ // special cases
+ switch {
+ case x < 0 || IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return 0
+ case x == 0:
+ return Inf(-1)
+ }
+
+ if x >= 2 { // |x| >= 2.0
+
+ // y0(x) = sqrt(2/(pi*x))*(p0(x)*sin(x0)+q0(x)*cos(x0))
+ // where x0 = x-pi/4
+ // Better formula:
+ // cos(x0) = cos(x)cos(pi/4)+sin(x)sin(pi/4)
+ // = 1/sqrt(2) * (sin(x) + cos(x))
+ // sin(x0) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4)
+ // = 1/sqrt(2) * (sin(x) - cos(x))
+ // To avoid cancellation, use
+ // sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x))
+ // to compute the worse one.
+
+ s, c := Sincos(x)
+ ss := s - c
+ cc := s + c
+
+ // j0(x) = 1/sqrt(pi) * (P(0,x)*cc - Q(0,x)*ss) / sqrt(x)
+ // y0(x) = 1/sqrt(pi) * (P(0,x)*ss + Q(0,x)*cc) / sqrt(x)
+
+ // make sure x+x does not overflow
+ if x < MaxFloat64/2 {
+ z := -Cos(x + x)
+ if s*c < 0 {
+ cc = z / ss
+ } else {
+ ss = z / cc
+ }
+ }
+ var z float64
+ if x > Two129 { // |x| > ~6.8056e+38
+ z = (1 / SqrtPi) * ss / Sqrt(x)
+ } else {
+ u := pzero(x)
+ v := qzero(x)
+ z = (1 / SqrtPi) * (u*ss + v*cc) / Sqrt(x)
+ }
+ return z // |x| >= 2.0
+ }
+ if x <= TwoM27 {
+ return U00 + (2/Pi)*Log(x) // |x| < ~7.4506e-9
+ }
+ z := x * x
+ u := U00 + z*(U01+z*(U02+z*(U03+z*(U04+z*(U05+z*U06)))))
+ v := 1 + z*(V01+z*(V02+z*(V03+z*V04)))
+ return u/v + (2/Pi)*J0(x)*Log(x) // ~7.4506e-9 < |x| < 2.0
+}
+
+// The asymptotic expansions of pzero is
+// 1 - 9/128 s**2 + 11025/98304 s**4 - ..., where s = 1/x.
+// For x >= 2, We approximate pzero by
+// pzero(x) = 1 + (R/S)
+// where R = pR0 + pR1*s**2 + pR2*s**4 + ... + pR5*s**10
+// S = 1 + pS0*s**2 + ... + pS4*s**10
+// and
+// | pzero(x)-1-R/S | <= 2 ** ( -60.26)
+
+// for x in [inf, 8]=1/[0,0.125]
+var p0R8 = [6]float64{
+ 0.00000000000000000000e+00, // 0x0000000000000000
+ -7.03124999999900357484e-02, // 0xBFB1FFFFFFFFFD32
+ -8.08167041275349795626e+00, // 0xC02029D0B44FA779
+ -2.57063105679704847262e+02, // 0xC07011027B19E863
+ -2.48521641009428822144e+03, // 0xC0A36A6ECD4DCAFC
+ -5.25304380490729545272e+03, // 0xC0B4850B36CC643D
+}
+var p0S8 = [5]float64{
+ 1.16534364619668181717e+02, // 0x405D223307A96751
+ 3.83374475364121826715e+03, // 0x40ADF37D50596938
+ 4.05978572648472545552e+04, // 0x40E3D2BB6EB6B05F
+ 1.16752972564375915681e+05, // 0x40FC810F8F9FA9BD
+ 4.76277284146730962675e+04, // 0x40E741774F2C49DC
+}
+
+// for x in [8,4.5454]=1/[0.125,0.22001]
+var p0R5 = [6]float64{
+ -1.14125464691894502584e-11, // 0xBDA918B147E495CC
+ -7.03124940873599280078e-02, // 0xBFB1FFFFE69AFBC6
+ -4.15961064470587782438e+00, // 0xC010A370F90C6BBF
+ -6.76747652265167261021e+01, // 0xC050EB2F5A7D1783
+ -3.31231299649172967747e+02, // 0xC074B3B36742CC63
+ -3.46433388365604912451e+02, // 0xC075A6EF28A38BD7
+}
+var p0S5 = [5]float64{
+ 6.07539382692300335975e+01, // 0x404E60810C98C5DE
+ 1.05125230595704579173e+03, // 0x40906D025C7E2864
+ 5.97897094333855784498e+03, // 0x40B75AF88FBE1D60
+ 9.62544514357774460223e+03, // 0x40C2CCB8FA76FA38
+ 2.40605815922939109441e+03, // 0x40A2CC1DC70BE864
+}
+
+// for x in [4.547,2.8571]=1/[0.2199,0.35001]
+var p0R3 = [6]float64{
+ -2.54704601771951915620e-09, // 0xBE25E1036FE1AA86
+ -7.03119616381481654654e-02, // 0xBFB1FFF6F7C0E24B
+ -2.40903221549529611423e+00, // 0xC00345B2AEA48074
+ -2.19659774734883086467e+01, // 0xC035F74A4CB94E14
+ -5.80791704701737572236e+01, // 0xC04D0A22420A1A45
+ -3.14479470594888503854e+01, // 0xC03F72ACA892D80F
+}
+var p0S3 = [5]float64{
+ 3.58560338055209726349e+01, // 0x4041ED9284077DD3
+ 3.61513983050303863820e+02, // 0x40769839464A7C0E
+ 1.19360783792111533330e+03, // 0x4092A66E6D1061D6
+ 1.12799679856907414432e+03, // 0x40919FFCB8C39B7E
+ 1.73580930813335754692e+02, // 0x4065B296FC379081
+}
+
+// for x in [2.8570,2]=1/[0.3499,0.5]
+var p0R2 = [6]float64{
+ -8.87534333032526411254e-08, // 0xBE77D316E927026D
+ -7.03030995483624743247e-02, // 0xBFB1FF62495E1E42
+ -1.45073846780952986357e+00, // 0xBFF736398A24A843
+ -7.63569613823527770791e+00, // 0xC01E8AF3EDAFA7F3
+ -1.11931668860356747786e+01, // 0xC02662E6C5246303
+ -3.23364579351335335033e+00, // 0xC009DE81AF8FE70F
+}
+var p0S2 = [5]float64{
+ 2.22202997532088808441e+01, // 0x40363865908B5959
+ 1.36206794218215208048e+02, // 0x4061069E0EE8878F
+ 2.70470278658083486789e+02, // 0x4070E78642EA079B
+ 1.53875394208320329881e+02, // 0x40633C033AB6FAFF
+ 1.46576176948256193810e+01, // 0x402D50B344391809
+}
+
+func pzero(x float64) float64 {
+ var p *[6]float64
+ var q *[5]float64
+ if x >= 8 {
+ p = &p0R8
+ q = &p0S8
+ } else if x >= 4.5454 {
+ p = &p0R5
+ q = &p0S5
+ } else if x >= 2.8571 {
+ p = &p0R3
+ q = &p0S3
+ } else if x >= 2 {
+ p = &p0R2
+ q = &p0S2
+ }
+ z := 1 / (x * x)
+ r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5]))))
+ s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*q[4]))))
+ return 1 + r/s
+}
+
+// For x >= 8, the asymptotic expansions of qzero is
+// -1/8 s + 75/1024 s**3 - ..., where s = 1/x.
+// We approximate pzero by
+// qzero(x) = s*(-1.25 + (R/S))
+// where R = qR0 + qR1*s**2 + qR2*s**4 + ... + qR5*s**10
+// S = 1 + qS0*s**2 + ... + qS5*s**12
+// and
+// | qzero(x)/s +1.25-R/S | <= 2**(-61.22)
+
+// for x in [inf, 8]=1/[0,0.125]
+var q0R8 = [6]float64{
+ 0.00000000000000000000e+00, // 0x0000000000000000
+ 7.32421874999935051953e-02, // 0x3FB2BFFFFFFFFE2C
+ 1.17682064682252693899e+01, // 0x402789525BB334D6
+ 5.57673380256401856059e+02, // 0x40816D6315301825
+ 8.85919720756468632317e+03, // 0x40C14D993E18F46D
+ 3.70146267776887834771e+04, // 0x40E212D40E901566
+}
+var q0S8 = [6]float64{
+ 1.63776026895689824414e+02, // 0x406478D5365B39BC
+ 8.09834494656449805916e+03, // 0x40BFA2584E6B0563
+ 1.42538291419120476348e+05, // 0x4101665254D38C3F
+ 8.03309257119514397345e+05, // 0x412883DA83A52B43
+ 8.40501579819060512818e+05, // 0x4129A66B28DE0B3D
+ -3.43899293537866615225e+05, // 0xC114FD6D2C9530C5
+}
+
+// for x in [8,4.5454]=1/[0.125,0.22001]
+var q0R5 = [6]float64{
+ 1.84085963594515531381e-11, // 0x3DB43D8F29CC8CD9
+ 7.32421766612684765896e-02, // 0x3FB2BFFFD172B04C
+ 5.83563508962056953777e+00, // 0x401757B0B9953DD3
+ 1.35111577286449829671e+02, // 0x4060E3920A8788E9
+ 1.02724376596164097464e+03, // 0x40900CF99DC8C481
+ 1.98997785864605384631e+03, // 0x409F17E953C6E3A6
+}
+var q0S5 = [6]float64{
+ 8.27766102236537761883e+01, // 0x4054B1B3FB5E1543
+ 2.07781416421392987104e+03, // 0x40A03BA0DA21C0CE
+ 1.88472887785718085070e+04, // 0x40D267D27B591E6D
+ 5.67511122894947329769e+04, // 0x40EBB5E397E02372
+ 3.59767538425114471465e+04, // 0x40E191181F7A54A0
+ -5.35434275601944773371e+03, // 0xC0B4EA57BEDBC609
+}
+
+// for x in [4.547,2.8571]=1/[0.2199,0.35001]
+var q0R3 = [6]float64{
+ 4.37741014089738620906e-09, // 0x3E32CD036ADECB82
+ 7.32411180042911447163e-02, // 0x3FB2BFEE0E8D0842
+ 3.34423137516170720929e+00, // 0x400AC0FC61149CF5
+ 4.26218440745412650017e+01, // 0x40454F98962DAEDD
+ 1.70808091340565596283e+02, // 0x406559DBE25EFD1F
+ 1.66733948696651168575e+02, // 0x4064D77C81FA21E0
+}
+var q0S3 = [6]float64{
+ 4.87588729724587182091e+01, // 0x40486122BFE343A6
+ 7.09689221056606015736e+02, // 0x40862D8386544EB3
+ 3.70414822620111362994e+03, // 0x40ACF04BE44DFC63
+ 6.46042516752568917582e+03, // 0x40B93C6CD7C76A28
+ 2.51633368920368957333e+03, // 0x40A3A8AAD94FB1C0
+ -1.49247451836156386662e+02, // 0xC062A7EB201CF40F
+}
+
+// for x in [2.8570,2]=1/[0.3499,0.5]
+var q0R2 = [6]float64{
+ 1.50444444886983272379e-07, // 0x3E84313B54F76BDB
+ 7.32234265963079278272e-02, // 0x3FB2BEC53E883E34
+ 1.99819174093815998816e+00, // 0x3FFFF897E727779C
+ 1.44956029347885735348e+01, // 0x402CFDBFAAF96FE5
+ 3.16662317504781540833e+01, // 0x403FAA8E29FBDC4A
+ 1.62527075710929267416e+01, // 0x403040B171814BB4
+}
+var q0S2 = [6]float64{
+ 3.03655848355219184498e+01, // 0x403E5D96F7C07AED
+ 2.69348118608049844624e+02, // 0x4070D591E4D14B40
+ 8.44783757595320139444e+02, // 0x408A664522B3BF22
+ 8.82935845112488550512e+02, // 0x408B977C9C5CC214
+ 2.12666388511798828631e+02, // 0x406A95530E001365
+ -5.31095493882666946917e+00, // 0xC0153E6AF8B32931
+}
+
+func qzero(x float64) float64 {
+ var p, q *[6]float64
+ if x >= 8 {
+ p = &q0R8
+ q = &q0S8
+ } else if x >= 4.5454 {
+ p = &q0R5
+ q = &q0S5
+ } else if x >= 2.8571 {
+ p = &q0R3
+ q = &q0S3
+ } else if x >= 2 {
+ p = &q0R2
+ q = &q0S2
+ }
+ z := 1 / (x * x)
+ r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5]))))
+ s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*(q[4]+z*q[5])))))
+ return (-0.125 + r/s) / x
+}
diff --git a/platform/dbops/binaries/go/go/src/math/j1.go b/platform/dbops/binaries/go/go/src/math/j1.go
new file mode 100644
index 0000000000000000000000000000000000000000..cc19e75b95002a6ce3de86d17bb1e73639de8d9b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/j1.go
@@ -0,0 +1,424 @@
+// 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 math
+
+/*
+ Bessel function of the first and second kinds of order one.
+*/
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/e_j1.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_j1(x), __ieee754_y1(x)
+// Bessel function of the first and second kinds of order one.
+// Method -- j1(x):
+// 1. For tiny x, we use j1(x) = x/2 - x**3/16 + x**5/384 - ...
+// 2. Reduce x to |x| since j1(x)=-j1(-x), and
+// for x in (0,2)
+// j1(x) = x/2 + x*z*R0/S0, where z = x*x;
+// (precision: |j1/x - 1/2 - R0/S0 |<2**-61.51 )
+// for x in (2,inf)
+// j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1))
+// y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1))
+// where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1)
+// as follow:
+// cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4)
+// = 1/sqrt(2) * (sin(x) - cos(x))
+// sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4)
+// = -1/sqrt(2) * (sin(x) + cos(x))
+// (To avoid cancellation, use
+// sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x))
+// to compute the worse one.)
+//
+// 3 Special cases
+// j1(nan)= nan
+// j1(0) = 0
+// j1(inf) = 0
+//
+// Method -- y1(x):
+// 1. screen out x<=0 cases: y1(0)=-inf, y1(x<0)=NaN
+// 2. For x<2.
+// Since
+// y1(x) = 2/pi*(j1(x)*(ln(x/2)+Euler)-1/x-x/2+5/64*x**3-...)
+// therefore y1(x)-2/pi*j1(x)*ln(x)-1/x is an odd function.
+// We use the following function to approximate y1,
+// y1(x) = x*U(z)/V(z) + (2/pi)*(j1(x)*ln(x)-1/x), z= x**2
+// where for x in [0,2] (abs err less than 2**-65.89)
+// U(z) = U0[0] + U0[1]*z + ... + U0[4]*z**4
+// V(z) = 1 + v0[0]*z + ... + v0[4]*z**5
+// Note: For tiny x, 1/x dominate y1 and hence
+// y1(tiny) = -2/pi/tiny, (choose tiny<2**-54)
+// 3. For x>=2.
+// y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1))
+// where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1)
+// by method mentioned above.
+
+// J1 returns the order-one Bessel function of the first kind.
+//
+// Special cases are:
+//
+// J1(±Inf) = 0
+// J1(NaN) = NaN
+func J1(x float64) float64 {
+ const (
+ TwoM27 = 1.0 / (1 << 27) // 2**-27 0x3e40000000000000
+ Two129 = 1 << 129 // 2**129 0x4800000000000000
+ // R0/S0 on [0, 2]
+ R00 = -6.25000000000000000000e-02 // 0xBFB0000000000000
+ R01 = 1.40705666955189706048e-03 // 0x3F570D9F98472C61
+ R02 = -1.59955631084035597520e-05 // 0xBEF0C5C6BA169668
+ R03 = 4.96727999609584448412e-08 // 0x3E6AAAFA46CA0BD9
+ S01 = 1.91537599538363460805e-02 // 0x3F939D0B12637E53
+ S02 = 1.85946785588630915560e-04 // 0x3F285F56B9CDF664
+ S03 = 1.17718464042623683263e-06 // 0x3EB3BFF8333F8498
+ S04 = 5.04636257076217042715e-09 // 0x3E35AC88C97DFF2C
+ S05 = 1.23542274426137913908e-11 // 0x3DAB2ACFCFB97ED8
+ )
+ // special cases
+ switch {
+ case IsNaN(x):
+ return x
+ case IsInf(x, 0) || x == 0:
+ return 0
+ }
+
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ if x >= 2 {
+ s, c := Sincos(x)
+ ss := -s - c
+ cc := s - c
+
+ // make sure x+x does not overflow
+ if x < MaxFloat64/2 {
+ z := Cos(x + x)
+ if s*c > 0 {
+ cc = z / ss
+ } else {
+ ss = z / cc
+ }
+ }
+
+ // j1(x) = 1/sqrt(pi) * (P(1,x)*cc - Q(1,x)*ss) / sqrt(x)
+ // y1(x) = 1/sqrt(pi) * (P(1,x)*ss + Q(1,x)*cc) / sqrt(x)
+
+ var z float64
+ if x > Two129 {
+ z = (1 / SqrtPi) * cc / Sqrt(x)
+ } else {
+ u := pone(x)
+ v := qone(x)
+ z = (1 / SqrtPi) * (u*cc - v*ss) / Sqrt(x)
+ }
+ if sign {
+ return -z
+ }
+ return z
+ }
+ if x < TwoM27 { // |x|<2**-27
+ return 0.5 * x // inexact if x!=0 necessary
+ }
+ z := x * x
+ r := z * (R00 + z*(R01+z*(R02+z*R03)))
+ s := 1.0 + z*(S01+z*(S02+z*(S03+z*(S04+z*S05))))
+ r *= x
+ z = 0.5*x + r/s
+ if sign {
+ return -z
+ }
+ return z
+}
+
+// Y1 returns the order-one Bessel function of the second kind.
+//
+// Special cases are:
+//
+// Y1(+Inf) = 0
+// Y1(0) = -Inf
+// Y1(x < 0) = NaN
+// Y1(NaN) = NaN
+func Y1(x float64) float64 {
+ const (
+ TwoM54 = 1.0 / (1 << 54) // 2**-54 0x3c90000000000000
+ Two129 = 1 << 129 // 2**129 0x4800000000000000
+ U00 = -1.96057090646238940668e-01 // 0xBFC91866143CBC8A
+ U01 = 5.04438716639811282616e-02 // 0x3FA9D3C776292CD1
+ U02 = -1.91256895875763547298e-03 // 0xBF5F55E54844F50F
+ U03 = 2.35252600561610495928e-05 // 0x3EF8AB038FA6B88E
+ U04 = -9.19099158039878874504e-08 // 0xBE78AC00569105B8
+ V00 = 1.99167318236649903973e-02 // 0x3F94650D3F4DA9F0
+ V01 = 2.02552581025135171496e-04 // 0x3F2A8C896C257764
+ V02 = 1.35608801097516229404e-06 // 0x3EB6C05A894E8CA6
+ V03 = 6.22741452364621501295e-09 // 0x3E3ABF1D5BA69A86
+ V04 = 1.66559246207992079114e-11 // 0x3DB25039DACA772A
+ )
+ // special cases
+ switch {
+ case x < 0 || IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return 0
+ case x == 0:
+ return Inf(-1)
+ }
+
+ if x >= 2 {
+ s, c := Sincos(x)
+ ss := -s - c
+ cc := s - c
+
+ // make sure x+x does not overflow
+ if x < MaxFloat64/2 {
+ z := Cos(x + x)
+ if s*c > 0 {
+ cc = z / ss
+ } else {
+ ss = z / cc
+ }
+ }
+ // y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x0)+q1(x)*cos(x0))
+ // where x0 = x-3pi/4
+ // Better formula:
+ // cos(x0) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4)
+ // = 1/sqrt(2) * (sin(x) - cos(x))
+ // sin(x0) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4)
+ // = -1/sqrt(2) * (cos(x) + sin(x))
+ // To avoid cancellation, use
+ // sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x))
+ // to compute the worse one.
+
+ var z float64
+ if x > Two129 {
+ z = (1 / SqrtPi) * ss / Sqrt(x)
+ } else {
+ u := pone(x)
+ v := qone(x)
+ z = (1 / SqrtPi) * (u*ss + v*cc) / Sqrt(x)
+ }
+ return z
+ }
+ if x <= TwoM54 { // x < 2**-54
+ return -(2 / Pi) / x
+ }
+ z := x * x
+ u := U00 + z*(U01+z*(U02+z*(U03+z*U04)))
+ v := 1 + z*(V00+z*(V01+z*(V02+z*(V03+z*V04))))
+ return x*(u/v) + (2/Pi)*(J1(x)*Log(x)-1/x)
+}
+
+// For x >= 8, the asymptotic expansions of pone is
+// 1 + 15/128 s**2 - 4725/2**15 s**4 - ..., where s = 1/x.
+// We approximate pone by
+// pone(x) = 1 + (R/S)
+// where R = pr0 + pr1*s**2 + pr2*s**4 + ... + pr5*s**10
+// S = 1 + ps0*s**2 + ... + ps4*s**10
+// and
+// | pone(x)-1-R/S | <= 2**(-60.06)
+
+// for x in [inf, 8]=1/[0,0.125]
+var p1R8 = [6]float64{
+ 0.00000000000000000000e+00, // 0x0000000000000000
+ 1.17187499999988647970e-01, // 0x3FBDFFFFFFFFFCCE
+ 1.32394806593073575129e+01, // 0x402A7A9D357F7FCE
+ 4.12051854307378562225e+02, // 0x4079C0D4652EA590
+ 3.87474538913960532227e+03, // 0x40AE457DA3A532CC
+ 7.91447954031891731574e+03, // 0x40BEEA7AC32782DD
+}
+var p1S8 = [5]float64{
+ 1.14207370375678408436e+02, // 0x405C8D458E656CAC
+ 3.65093083420853463394e+03, // 0x40AC85DC964D274F
+ 3.69562060269033463555e+04, // 0x40E20B8697C5BB7F
+ 9.76027935934950801311e+04, // 0x40F7D42CB28F17BB
+ 3.08042720627888811578e+04, // 0x40DE1511697A0B2D
+}
+
+// for x in [8,4.5454] = 1/[0.125,0.22001]
+var p1R5 = [6]float64{
+ 1.31990519556243522749e-11, // 0x3DAD0667DAE1CA7D
+ 1.17187493190614097638e-01, // 0x3FBDFFFFE2C10043
+ 6.80275127868432871736e+00, // 0x401B36046E6315E3
+ 1.08308182990189109773e+02, // 0x405B13B9452602ED
+ 5.17636139533199752805e+02, // 0x40802D16D052D649
+ 5.28715201363337541807e+02, // 0x408085B8BB7E0CB7
+}
+var p1S5 = [5]float64{
+ 5.92805987221131331921e+01, // 0x404DA3EAA8AF633D
+ 9.91401418733614377743e+02, // 0x408EFB361B066701
+ 5.35326695291487976647e+03, // 0x40B4E9445706B6FB
+ 7.84469031749551231769e+03, // 0x40BEA4B0B8A5BB15
+ 1.50404688810361062679e+03, // 0x40978030036F5E51
+}
+
+// for x in[4.5453,2.8571] = 1/[0.2199,0.35001]
+var p1R3 = [6]float64{
+ 3.02503916137373618024e-09, // 0x3E29FC21A7AD9EDD
+ 1.17186865567253592491e-01, // 0x3FBDFFF55B21D17B
+ 3.93297750033315640650e+00, // 0x400F76BCE85EAD8A
+ 3.51194035591636932736e+01, // 0x40418F489DA6D129
+ 9.10550110750781271918e+01, // 0x4056C3854D2C1837
+ 4.85590685197364919645e+01, // 0x4048478F8EA83EE5
+}
+var p1S3 = [5]float64{
+ 3.47913095001251519989e+01, // 0x40416549A134069C
+ 3.36762458747825746741e+02, // 0x40750C3307F1A75F
+ 1.04687139975775130551e+03, // 0x40905B7C5037D523
+ 8.90811346398256432622e+02, // 0x408BD67DA32E31E9
+ 1.03787932439639277504e+02, // 0x4059F26D7C2EED53
+}
+
+// for x in [2.8570,2] = 1/[0.3499,0.5]
+var p1R2 = [6]float64{
+ 1.07710830106873743082e-07, // 0x3E7CE9D4F65544F4
+ 1.17176219462683348094e-01, // 0x3FBDFF42BE760D83
+ 2.36851496667608785174e+00, // 0x4002F2B7F98FAEC0
+ 1.22426109148261232917e+01, // 0x40287C377F71A964
+ 1.76939711271687727390e+01, // 0x4031B1A8177F8EE2
+ 5.07352312588818499250e+00, // 0x40144B49A574C1FE
+}
+var p1S2 = [5]float64{
+ 2.14364859363821409488e+01, // 0x40356FBD8AD5ECDC
+ 1.25290227168402751090e+02, // 0x405F529314F92CD5
+ 2.32276469057162813669e+02, // 0x406D08D8D5A2DBD9
+ 1.17679373287147100768e+02, // 0x405D6B7ADA1884A9
+ 8.36463893371618283368e+00, // 0x4020BAB1F44E5192
+}
+
+func pone(x float64) float64 {
+ var p *[6]float64
+ var q *[5]float64
+ if x >= 8 {
+ p = &p1R8
+ q = &p1S8
+ } else if x >= 4.5454 {
+ p = &p1R5
+ q = &p1S5
+ } else if x >= 2.8571 {
+ p = &p1R3
+ q = &p1S3
+ } else if x >= 2 {
+ p = &p1R2
+ q = &p1S2
+ }
+ z := 1 / (x * x)
+ r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5]))))
+ s := 1.0 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*q[4]))))
+ return 1 + r/s
+}
+
+// For x >= 8, the asymptotic expansions of qone is
+// 3/8 s - 105/1024 s**3 - ..., where s = 1/x.
+// We approximate qone by
+// qone(x) = s*(0.375 + (R/S))
+// where R = qr1*s**2 + qr2*s**4 + ... + qr5*s**10
+// S = 1 + qs1*s**2 + ... + qs6*s**12
+// and
+// | qone(x)/s -0.375-R/S | <= 2**(-61.13)
+
+// for x in [inf, 8] = 1/[0,0.125]
+var q1R8 = [6]float64{
+ 0.00000000000000000000e+00, // 0x0000000000000000
+ -1.02539062499992714161e-01, // 0xBFBA3FFFFFFFFDF3
+ -1.62717534544589987888e+01, // 0xC0304591A26779F7
+ -7.59601722513950107896e+02, // 0xC087BCD053E4B576
+ -1.18498066702429587167e+04, // 0xC0C724E740F87415
+ -4.84385124285750353010e+04, // 0xC0E7A6D065D09C6A
+}
+var q1S8 = [6]float64{
+ 1.61395369700722909556e+02, // 0x40642CA6DE5BCDE5
+ 7.82538599923348465381e+03, // 0x40BE9162D0D88419
+ 1.33875336287249578163e+05, // 0x4100579AB0B75E98
+ 7.19657723683240939863e+05, // 0x4125F65372869C19
+ 6.66601232617776375264e+05, // 0x412457D27719AD5C
+ -2.94490264303834643215e+05, // 0xC111F9690EA5AA18
+}
+
+// for x in [8,4.5454] = 1/[0.125,0.22001]
+var q1R5 = [6]float64{
+ -2.08979931141764104297e-11, // 0xBDB6FA431AA1A098
+ -1.02539050241375426231e-01, // 0xBFBA3FFFCB597FEF
+ -8.05644828123936029840e+00, // 0xC0201CE6CA03AD4B
+ -1.83669607474888380239e+02, // 0xC066F56D6CA7B9B0
+ -1.37319376065508163265e+03, // 0xC09574C66931734F
+ -2.61244440453215656817e+03, // 0xC0A468E388FDA79D
+}
+var q1S5 = [6]float64{
+ 8.12765501384335777857e+01, // 0x405451B2FF5A11B2
+ 1.99179873460485964642e+03, // 0x409F1F31E77BF839
+ 1.74684851924908907677e+04, // 0x40D10F1F0D64CE29
+ 4.98514270910352279316e+04, // 0x40E8576DAABAD197
+ 2.79480751638918118260e+04, // 0x40DB4B04CF7C364B
+ -4.71918354795128470869e+03, // 0xC0B26F2EFCFFA004
+}
+
+// for x in [4.5454,2.8571] = 1/[0.2199,0.35001] ???
+var q1R3 = [6]float64{
+ -5.07831226461766561369e-09, // 0xBE35CFA9D38FC84F
+ -1.02537829820837089745e-01, // 0xBFBA3FEB51AEED54
+ -4.61011581139473403113e+00, // 0xC01270C23302D9FF
+ -5.78472216562783643212e+01, // 0xC04CEC71C25D16DA
+ -2.28244540737631695038e+02, // 0xC06C87D34718D55F
+ -2.19210128478909325622e+02, // 0xC06B66B95F5C1BF6
+}
+var q1S3 = [6]float64{
+ 4.76651550323729509273e+01, // 0x4047D523CCD367E4
+ 6.73865112676699709482e+02, // 0x40850EEBC031EE3E
+ 3.38015286679526343505e+03, // 0x40AA684E448E7C9A
+ 5.54772909720722782367e+03, // 0x40B5ABBAA61D54A6
+ 1.90311919338810798763e+03, // 0x409DBC7A0DD4DF4B
+ -1.35201191444307340817e+02, // 0xC060E670290A311F
+}
+
+// for x in [2.8570,2] = 1/[0.3499,0.5]
+var q1R2 = [6]float64{
+ -1.78381727510958865572e-07, // 0xBE87F12644C626D2
+ -1.02517042607985553460e-01, // 0xBFBA3E8E9148B010
+ -2.75220568278187460720e+00, // 0xC006048469BB4EDA
+ -1.96636162643703720221e+01, // 0xC033A9E2C168907F
+ -4.23253133372830490089e+01, // 0xC04529A3DE104AAA
+ -2.13719211703704061733e+01, // 0xC0355F3639CF6E52
+}
+var q1S2 = [6]float64{
+ 2.95333629060523854548e+01, // 0x403D888A78AE64FF
+ 2.52981549982190529136e+02, // 0x406F9F68DB821CBA
+ 7.57502834868645436472e+02, // 0x4087AC05CE49A0F7
+ 7.39393205320467245656e+02, // 0x40871B2548D4C029
+ 1.55949003336666123687e+02, // 0x40637E5E3C3ED8D4
+ -4.95949898822628210127e+00, // 0xC013D686E71BE86B
+}
+
+func qone(x float64) float64 {
+ var p, q *[6]float64
+ if x >= 8 {
+ p = &q1R8
+ q = &q1S8
+ } else if x >= 4.5454 {
+ p = &q1R5
+ q = &q1S5
+ } else if x >= 2.8571 {
+ p = &q1R3
+ q = &q1S3
+ } else if x >= 2 {
+ p = &q1R2
+ q = &q1S2
+ }
+ z := 1 / (x * x)
+ r := p[0] + z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5]))))
+ s := 1 + z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*(q[4]+z*q[5])))))
+ return (0.375 + r/s) / x
+}
diff --git a/platform/dbops/binaries/go/go/src/math/jn.go b/platform/dbops/binaries/go/go/src/math/jn.go
new file mode 100644
index 0000000000000000000000000000000000000000..3491692a96ca7f3e570a2545d1cca7353ad6524a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/jn.go
@@ -0,0 +1,306 @@
+// 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 math
+
+/*
+ Bessel function of the first and second kinds of order n.
+*/
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/e_jn.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_jn(n, x), __ieee754_yn(n, x)
+// floating point Bessel's function of the 1st and 2nd kind
+// of order n
+//
+// Special cases:
+// y0(0)=y1(0)=yn(n,0) = -inf with division by zero signal;
+// y0(-ve)=y1(-ve)=yn(n,-ve) are NaN with invalid signal.
+// Note 2. About jn(n,x), yn(n,x)
+// For n=0, j0(x) is called,
+// for n=1, j1(x) is called,
+// for nx, a continued fraction approximation to
+// j(n,x)/j(n-1,x) is evaluated and then backward
+// recursion is used starting from a supposed value
+// for j(n,x). The resulting value of j(0,x) is
+// compared with the actual value to correct the
+// supposed value of j(n,x).
+//
+// yn(n,x) is similar in all respects, except
+// that forward recursion is used for all
+// values of n>1.
+
+// Jn returns the order-n Bessel function of the first kind.
+//
+// Special cases are:
+//
+// Jn(n, ±Inf) = 0
+// Jn(n, NaN) = NaN
+func Jn(n int, x float64) float64 {
+ const (
+ TwoM29 = 1.0 / (1 << 29) // 2**-29 0x3e10000000000000
+ Two302 = 1 << 302 // 2**302 0x52D0000000000000
+ )
+ // special cases
+ switch {
+ case IsNaN(x):
+ return x
+ case IsInf(x, 0):
+ return 0
+ }
+ // J(-n, x) = (-1)**n * J(n, x), J(n, -x) = (-1)**n * J(n, x)
+ // Thus, J(-n, x) = J(n, -x)
+
+ if n == 0 {
+ return J0(x)
+ }
+ if x == 0 {
+ return 0
+ }
+ if n < 0 {
+ n, x = -n, -x
+ }
+ if n == 1 {
+ return J1(x)
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ if n&1 == 1 {
+ sign = true // odd n and negative x
+ }
+ }
+ var b float64
+ if float64(n) <= x {
+ // Safe to use J(n+1,x)=2n/x *J(n,x)-J(n-1,x)
+ if x >= Two302 { // x > 2**302
+
+ // (x >> n**2)
+ // Jn(x) = cos(x-(2n+1)*pi/4)*sqrt(2/x*pi)
+ // Yn(x) = sin(x-(2n+1)*pi/4)*sqrt(2/x*pi)
+ // Let s=sin(x), c=cos(x),
+ // xn=x-(2n+1)*pi/4, sqt2 = sqrt(2),then
+ //
+ // n sin(xn)*sqt2 cos(xn)*sqt2
+ // ----------------------------------
+ // 0 s-c c+s
+ // 1 -s-c -c+s
+ // 2 -s+c -c-s
+ // 3 s+c c-s
+
+ var temp float64
+ switch s, c := Sincos(x); n & 3 {
+ case 0:
+ temp = c + s
+ case 1:
+ temp = -c + s
+ case 2:
+ temp = -c - s
+ case 3:
+ temp = c - s
+ }
+ b = (1 / SqrtPi) * temp / Sqrt(x)
+ } else {
+ b = J1(x)
+ for i, a := 1, J0(x); i < n; i++ {
+ a, b = b, b*(float64(i+i)/x)-a // avoid underflow
+ }
+ }
+ } else {
+ if x < TwoM29 { // x < 2**-29
+ // x is tiny, return the first Taylor expansion of J(n,x)
+ // J(n,x) = 1/n!*(x/2)**n - ...
+
+ if n > 33 { // underflow
+ b = 0
+ } else {
+ temp := x * 0.5
+ b = temp
+ a := 1.0
+ for i := 2; i <= n; i++ {
+ a *= float64(i) // a = n!
+ b *= temp // b = (x/2)**n
+ }
+ b /= a
+ }
+ } else {
+ // use backward recurrence
+ // x x**2 x**2
+ // J(n,x)/J(n-1,x) = ---- ------ ------ .....
+ // 2n - 2(n+1) - 2(n+2)
+ //
+ // 1 1 1
+ // (for large x) = ---- ------ ------ .....
+ // 2n 2(n+1) 2(n+2)
+ // -- - ------ - ------ -
+ // x x x
+ //
+ // Let w = 2n/x and h=2/x, then the above quotient
+ // is equal to the continued fraction:
+ // 1
+ // = -----------------------
+ // 1
+ // w - -----------------
+ // 1
+ // w+h - ---------
+ // w+2h - ...
+ //
+ // To determine how many terms needed, let
+ // Q(0) = w, Q(1) = w(w+h) - 1,
+ // Q(k) = (w+k*h)*Q(k-1) - Q(k-2),
+ // When Q(k) > 1e4 good for single
+ // When Q(k) > 1e9 good for double
+ // When Q(k) > 1e17 good for quadruple
+
+ // determine k
+ w := float64(n+n) / x
+ h := 2 / x
+ q0 := w
+ z := w + h
+ q1 := w*z - 1
+ k := 1
+ for q1 < 1e9 {
+ k++
+ z += h
+ q0, q1 = q1, z*q1-q0
+ }
+ m := n + n
+ t := 0.0
+ for i := 2 * (n + k); i >= m; i -= 2 {
+ t = 1 / (float64(i)/x - t)
+ }
+ a := t
+ b = 1
+ // estimate log((2/x)**n*n!) = n*log(2/x)+n*ln(n)
+ // Hence, if n*(log(2n/x)) > ...
+ // single 8.8722839355e+01
+ // double 7.09782712893383973096e+02
+ // long double 1.1356523406294143949491931077970765006170e+04
+ // then recurrent value may overflow and the result is
+ // likely underflow to zero
+
+ tmp := float64(n)
+ v := 2 / x
+ tmp = tmp * Log(Abs(v*tmp))
+ if tmp < 7.09782712893383973096e+02 {
+ for i := n - 1; i > 0; i-- {
+ di := float64(i + i)
+ a, b = b, b*di/x-a
+ }
+ } else {
+ for i := n - 1; i > 0; i-- {
+ di := float64(i + i)
+ a, b = b, b*di/x-a
+ // scale b to avoid spurious overflow
+ if b > 1e100 {
+ a /= b
+ t /= b
+ b = 1
+ }
+ }
+ }
+ b = t * J0(x) / b
+ }
+ }
+ if sign {
+ return -b
+ }
+ return b
+}
+
+// Yn returns the order-n Bessel function of the second kind.
+//
+// Special cases are:
+//
+// Yn(n, +Inf) = 0
+// Yn(n ≥ 0, 0) = -Inf
+// Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
+// Yn(n, x < 0) = NaN
+// Yn(n, NaN) = NaN
+func Yn(n int, x float64) float64 {
+ const Two302 = 1 << 302 // 2**302 0x52D0000000000000
+ // special cases
+ switch {
+ case x < 0 || IsNaN(x):
+ return NaN()
+ case IsInf(x, 1):
+ return 0
+ }
+
+ if n == 0 {
+ return Y0(x)
+ }
+ if x == 0 {
+ if n < 0 && n&1 == 1 {
+ return Inf(1)
+ }
+ return Inf(-1)
+ }
+ sign := false
+ if n < 0 {
+ n = -n
+ if n&1 == 1 {
+ sign = true // sign true if n < 0 && |n| odd
+ }
+ }
+ if n == 1 {
+ if sign {
+ return -Y1(x)
+ }
+ return Y1(x)
+ }
+ var b float64
+ if x >= Two302 { // x > 2**302
+ // (x >> n**2)
+ // Jn(x) = cos(x-(2n+1)*pi/4)*sqrt(2/x*pi)
+ // Yn(x) = sin(x-(2n+1)*pi/4)*sqrt(2/x*pi)
+ // Let s=sin(x), c=cos(x),
+ // xn=x-(2n+1)*pi/4, sqt2 = sqrt(2),then
+ //
+ // n sin(xn)*sqt2 cos(xn)*sqt2
+ // ----------------------------------
+ // 0 s-c c+s
+ // 1 -s-c -c+s
+ // 2 -s+c -c-s
+ // 3 s+c c-s
+
+ var temp float64
+ switch s, c := Sincos(x); n & 3 {
+ case 0:
+ temp = s - c
+ case 1:
+ temp = -s - c
+ case 2:
+ temp = -s + c
+ case 3:
+ temp = s + c
+ }
+ b = (1 / SqrtPi) * temp / Sqrt(x)
+ } else {
+ a := Y0(x)
+ b = Y1(x)
+ // quit if b is -inf
+ for i := 1; i < n && !IsInf(b, -1); i++ {
+ a, b = b, (float64(i+i)/x)*b-a
+ }
+ }
+ if sign {
+ return -b
+ }
+ return b
+}
diff --git a/platform/dbops/binaries/go/go/src/math/ldexp.go b/platform/dbops/binaries/go/go/src/math/ldexp.go
new file mode 100644
index 0000000000000000000000000000000000000000..fad099dfa26e6f18aad278766f159d2130384b5c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/ldexp.go
@@ -0,0 +1,51 @@
+// 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 math
+
+// Ldexp is the inverse of [Frexp].
+// It returns frac × 2**exp.
+//
+// Special cases are:
+//
+// Ldexp(±0, exp) = ±0
+// Ldexp(±Inf, exp) = ±Inf
+// Ldexp(NaN, exp) = NaN
+func Ldexp(frac float64, exp int) float64 {
+ if haveArchLdexp {
+ return archLdexp(frac, exp)
+ }
+ return ldexp(frac, exp)
+}
+
+func ldexp(frac float64, exp int) float64 {
+ // special cases
+ switch {
+ case frac == 0:
+ return frac // correctly return -0
+ case IsInf(frac, 0) || IsNaN(frac):
+ return frac
+ }
+ frac, e := normalize(frac)
+ exp += e
+ x := Float64bits(frac)
+ exp += int(x>>shift)&mask - bias
+ if exp < -1075 {
+ return Copysign(0, frac) // underflow
+ }
+ if exp > 1023 { // overflow
+ if frac < 0 {
+ return Inf(-1)
+ }
+ return Inf(1)
+ }
+ var m float64 = 1
+ if exp < -1022 { // denormal
+ exp += 53
+ m = 1.0 / (1 << 53) // 2**-53
+ }
+ x &^= mask << shift
+ x |= uint64(exp+bias) << shift
+ return m * Float64frombits(x)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/lgamma.go b/platform/dbops/binaries/go/go/src/math/lgamma.go
new file mode 100644
index 0000000000000000000000000000000000000000..5a7ea2a58c7cf0a918b78938369090b2d518591f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/lgamma.go
@@ -0,0 +1,366 @@
+// 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 math
+
+/*
+ Floating-point logarithm of the Gamma function.
+*/
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/e_lgamma_r.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_lgamma_r(x, signgamp)
+// Reentrant version of the logarithm of the Gamma function
+// with user provided pointer for the sign of Gamma(x).
+//
+// Method:
+// 1. Argument Reduction for 0 < x <= 8
+// Since gamma(1+s)=s*gamma(s), for x in [0,8], we may
+// reduce x to a number in [1.5,2.5] by
+// lgamma(1+s) = log(s) + lgamma(s)
+// for example,
+// lgamma(7.3) = log(6.3) + lgamma(6.3)
+// = log(6.3*5.3) + lgamma(5.3)
+// = log(6.3*5.3*4.3*3.3*2.3) + lgamma(2.3)
+// 2. Polynomial approximation of lgamma around its
+// minimum (ymin=1.461632144968362245) to maintain monotonicity.
+// On [ymin-0.23, ymin+0.27] (i.e., [1.23164,1.73163]), use
+// Let z = x-ymin;
+// lgamma(x) = -1.214862905358496078218 + z**2*poly(z)
+// poly(z) is a 14 degree polynomial.
+// 2. Rational approximation in the primary interval [2,3]
+// We use the following approximation:
+// s = x-2.0;
+// lgamma(x) = 0.5*s + s*P(s)/Q(s)
+// with accuracy
+// |P/Q - (lgamma(x)-0.5s)| < 2**-61.71
+// Our algorithms are based on the following observation
+//
+// zeta(2)-1 2 zeta(3)-1 3
+// lgamma(2+s) = s*(1-Euler) + --------- * s - --------- * s + ...
+// 2 3
+//
+// where Euler = 0.5772156649... is the Euler constant, which
+// is very close to 0.5.
+//
+// 3. For x>=8, we have
+// lgamma(x)~(x-0.5)log(x)-x+0.5*log(2pi)+1/(12x)-1/(360x**3)+....
+// (better formula:
+// lgamma(x)~(x-0.5)*(log(x)-1)-.5*(log(2pi)-1) + ...)
+// Let z = 1/x, then we approximation
+// f(z) = lgamma(x) - (x-0.5)(log(x)-1)
+// by
+// 3 5 11
+// w = w0 + w1*z + w2*z + w3*z + ... + w6*z
+// where
+// |w - f(z)| < 2**-58.74
+//
+// 4. For negative x, since (G is gamma function)
+// -x*G(-x)*G(x) = pi/sin(pi*x),
+// we have
+// G(x) = pi/(sin(pi*x)*(-x)*G(-x))
+// since G(-x) is positive, sign(G(x)) = sign(sin(pi*x)) for x<0
+// Hence, for x<0, signgam = sign(sin(pi*x)) and
+// lgamma(x) = log(|Gamma(x)|)
+// = log(pi/(|x*sin(pi*x)|)) - lgamma(-x);
+// Note: one should avoid computing pi*(-x) directly in the
+// computation of sin(pi*(-x)).
+//
+// 5. Special Cases
+// lgamma(2+s) ~ s*(1-Euler) for tiny s
+// lgamma(1)=lgamma(2)=0
+// lgamma(x) ~ -log(x) for tiny x
+// lgamma(0) = lgamma(inf) = inf
+// lgamma(-integer) = +-inf
+//
+//
+
+var _lgamA = [...]float64{
+ 7.72156649015328655494e-02, // 0x3FB3C467E37DB0C8
+ 3.22467033424113591611e-01, // 0x3FD4A34CC4A60FAD
+ 6.73523010531292681824e-02, // 0x3FB13E001A5562A7
+ 2.05808084325167332806e-02, // 0x3F951322AC92547B
+ 7.38555086081402883957e-03, // 0x3F7E404FB68FEFE8
+ 2.89051383673415629091e-03, // 0x3F67ADD8CCB7926B
+ 1.19270763183362067845e-03, // 0x3F538A94116F3F5D
+ 5.10069792153511336608e-04, // 0x3F40B6C689B99C00
+ 2.20862790713908385557e-04, // 0x3F2CF2ECED10E54D
+ 1.08011567247583939954e-04, // 0x3F1C5088987DFB07
+ 2.52144565451257326939e-05, // 0x3EFA7074428CFA52
+ 4.48640949618915160150e-05, // 0x3F07858E90A45837
+}
+var _lgamR = [...]float64{
+ 1.0, // placeholder
+ 1.39200533467621045958e+00, // 0x3FF645A762C4AB74
+ 7.21935547567138069525e-01, // 0x3FE71A1893D3DCDC
+ 1.71933865632803078993e-01, // 0x3FC601EDCCFBDF27
+ 1.86459191715652901344e-02, // 0x3F9317EA742ED475
+ 7.77942496381893596434e-04, // 0x3F497DDACA41A95B
+ 7.32668430744625636189e-06, // 0x3EDEBAF7A5B38140
+}
+var _lgamS = [...]float64{
+ -7.72156649015328655494e-02, // 0xBFB3C467E37DB0C8
+ 2.14982415960608852501e-01, // 0x3FCB848B36E20878
+ 3.25778796408930981787e-01, // 0x3FD4D98F4F139F59
+ 1.46350472652464452805e-01, // 0x3FC2BB9CBEE5F2F7
+ 2.66422703033638609560e-02, // 0x3F9B481C7E939961
+ 1.84028451407337715652e-03, // 0x3F5E26B67368F239
+ 3.19475326584100867617e-05, // 0x3F00BFECDD17E945
+}
+var _lgamT = [...]float64{
+ 4.83836122723810047042e-01, // 0x3FDEF72BC8EE38A2
+ -1.47587722994593911752e-01, // 0xBFC2E4278DC6C509
+ 6.46249402391333854778e-02, // 0x3FB08B4294D5419B
+ -3.27885410759859649565e-02, // 0xBFA0C9A8DF35B713
+ 1.79706750811820387126e-02, // 0x3F9266E7970AF9EC
+ -1.03142241298341437450e-02, // 0xBF851F9FBA91EC6A
+ 6.10053870246291332635e-03, // 0x3F78FCE0E370E344
+ -3.68452016781138256760e-03, // 0xBF6E2EFFB3E914D7
+ 2.25964780900612472250e-03, // 0x3F6282D32E15C915
+ -1.40346469989232843813e-03, // 0xBF56FE8EBF2D1AF1
+ 8.81081882437654011382e-04, // 0x3F4CDF0CEF61A8E9
+ -5.38595305356740546715e-04, // 0xBF41A6109C73E0EC
+ 3.15632070903625950361e-04, // 0x3F34AF6D6C0EBBF7
+ -3.12754168375120860518e-04, // 0xBF347F24ECC38C38
+ 3.35529192635519073543e-04, // 0x3F35FD3EE8C2D3F4
+}
+var _lgamU = [...]float64{
+ -7.72156649015328655494e-02, // 0xBFB3C467E37DB0C8
+ 6.32827064025093366517e-01, // 0x3FE4401E8B005DFF
+ 1.45492250137234768737e+00, // 0x3FF7475CD119BD6F
+ 9.77717527963372745603e-01, // 0x3FEF497644EA8450
+ 2.28963728064692451092e-01, // 0x3FCD4EAEF6010924
+ 1.33810918536787660377e-02, // 0x3F8B678BBF2BAB09
+}
+var _lgamV = [...]float64{
+ 1.0,
+ 2.45597793713041134822e+00, // 0x4003A5D7C2BD619C
+ 2.12848976379893395361e+00, // 0x40010725A42B18F5
+ 7.69285150456672783825e-01, // 0x3FE89DFBE45050AF
+ 1.04222645593369134254e-01, // 0x3FBAAE55D6537C88
+ 3.21709242282423911810e-03, // 0x3F6A5ABB57D0CF61
+}
+var _lgamW = [...]float64{
+ 4.18938533204672725052e-01, // 0x3FDACFE390C97D69
+ 8.33333333333329678849e-02, // 0x3FB555555555553B
+ -2.77777777728775536470e-03, // 0xBF66C16C16B02E5C
+ 7.93650558643019558500e-04, // 0x3F4A019F98CF38B6
+ -5.95187557450339963135e-04, // 0xBF4380CB8C0FE741
+ 8.36339918996282139126e-04, // 0x3F4B67BA4CDAD5D1
+ -1.63092934096575273989e-03, // 0xBF5AB89D0B9E43E4
+}
+
+// Lgamma returns the natural logarithm and sign (-1 or +1) of [Gamma](x).
+//
+// Special cases are:
+//
+// Lgamma(+Inf) = +Inf
+// Lgamma(0) = +Inf
+// Lgamma(-integer) = +Inf
+// Lgamma(-Inf) = -Inf
+// Lgamma(NaN) = NaN
+func Lgamma(x float64) (lgamma float64, sign int) {
+ const (
+ Ymin = 1.461632144968362245
+ Two52 = 1 << 52 // 0x4330000000000000 ~4.5036e+15
+ Two53 = 1 << 53 // 0x4340000000000000 ~9.0072e+15
+ Two58 = 1 << 58 // 0x4390000000000000 ~2.8823e+17
+ Tiny = 1.0 / (1 << 70) // 0x3b90000000000000 ~8.47033e-22
+ Tc = 1.46163214496836224576e+00 // 0x3FF762D86356BE3F
+ Tf = -1.21486290535849611461e-01 // 0xBFBF19B9BCC38A42
+ // Tt = -(tail of Tf)
+ Tt = -3.63867699703950536541e-18 // 0xBC50C7CAA48A971F
+ )
+ // special cases
+ sign = 1
+ switch {
+ case IsNaN(x):
+ lgamma = x
+ return
+ case IsInf(x, 0):
+ lgamma = x
+ return
+ case x == 0:
+ lgamma = Inf(1)
+ return
+ }
+
+ neg := false
+ if x < 0 {
+ x = -x
+ neg = true
+ }
+
+ if x < Tiny { // if |x| < 2**-70, return -log(|x|)
+ if neg {
+ sign = -1
+ }
+ lgamma = -Log(x)
+ return
+ }
+ var nadj float64
+ if neg {
+ if x >= Two52 { // |x| >= 2**52, must be -integer
+ lgamma = Inf(1)
+ return
+ }
+ t := sinPi(x)
+ if t == 0 {
+ lgamma = Inf(1) // -integer
+ return
+ }
+ nadj = Log(Pi / Abs(t*x))
+ if t < 0 {
+ sign = -1
+ }
+ }
+
+ switch {
+ case x == 1 || x == 2: // purge off 1 and 2
+ lgamma = 0
+ return
+ case x < 2: // use lgamma(x) = lgamma(x+1) - log(x)
+ var y float64
+ var i int
+ if x <= 0.9 {
+ lgamma = -Log(x)
+ switch {
+ case x >= (Ymin - 1 + 0.27): // 0.7316 <= x <= 0.9
+ y = 1 - x
+ i = 0
+ case x >= (Ymin - 1 - 0.27): // 0.2316 <= x < 0.7316
+ y = x - (Tc - 1)
+ i = 1
+ default: // 0 < x < 0.2316
+ y = x
+ i = 2
+ }
+ } else {
+ lgamma = 0
+ switch {
+ case x >= (Ymin + 0.27): // 1.7316 <= x < 2
+ y = 2 - x
+ i = 0
+ case x >= (Ymin - 0.27): // 1.2316 <= x < 1.7316
+ y = x - Tc
+ i = 1
+ default: // 0.9 < x < 1.2316
+ y = x - 1
+ i = 2
+ }
+ }
+ switch i {
+ case 0:
+ z := y * y
+ p1 := _lgamA[0] + z*(_lgamA[2]+z*(_lgamA[4]+z*(_lgamA[6]+z*(_lgamA[8]+z*_lgamA[10]))))
+ p2 := z * (_lgamA[1] + z*(+_lgamA[3]+z*(_lgamA[5]+z*(_lgamA[7]+z*(_lgamA[9]+z*_lgamA[11])))))
+ p := y*p1 + p2
+ lgamma += (p - 0.5*y)
+ case 1:
+ z := y * y
+ w := z * y
+ p1 := _lgamT[0] + w*(_lgamT[3]+w*(_lgamT[6]+w*(_lgamT[9]+w*_lgamT[12]))) // parallel comp
+ p2 := _lgamT[1] + w*(_lgamT[4]+w*(_lgamT[7]+w*(_lgamT[10]+w*_lgamT[13])))
+ p3 := _lgamT[2] + w*(_lgamT[5]+w*(_lgamT[8]+w*(_lgamT[11]+w*_lgamT[14])))
+ p := z*p1 - (Tt - w*(p2+y*p3))
+ lgamma += (Tf + p)
+ case 2:
+ p1 := y * (_lgamU[0] + y*(_lgamU[1]+y*(_lgamU[2]+y*(_lgamU[3]+y*(_lgamU[4]+y*_lgamU[5])))))
+ p2 := 1 + y*(_lgamV[1]+y*(_lgamV[2]+y*(_lgamV[3]+y*(_lgamV[4]+y*_lgamV[5]))))
+ lgamma += (-0.5*y + p1/p2)
+ }
+ case x < 8: // 2 <= x < 8
+ i := int(x)
+ y := x - float64(i)
+ p := y * (_lgamS[0] + y*(_lgamS[1]+y*(_lgamS[2]+y*(_lgamS[3]+y*(_lgamS[4]+y*(_lgamS[5]+y*_lgamS[6]))))))
+ q := 1 + y*(_lgamR[1]+y*(_lgamR[2]+y*(_lgamR[3]+y*(_lgamR[4]+y*(_lgamR[5]+y*_lgamR[6])))))
+ lgamma = 0.5*y + p/q
+ z := 1.0 // Lgamma(1+s) = Log(s) + Lgamma(s)
+ switch i {
+ case 7:
+ z *= (y + 6)
+ fallthrough
+ case 6:
+ z *= (y + 5)
+ fallthrough
+ case 5:
+ z *= (y + 4)
+ fallthrough
+ case 4:
+ z *= (y + 3)
+ fallthrough
+ case 3:
+ z *= (y + 2)
+ lgamma += Log(z)
+ }
+ case x < Two58: // 8 <= x < 2**58
+ t := Log(x)
+ z := 1 / x
+ y := z * z
+ w := _lgamW[0] + z*(_lgamW[1]+y*(_lgamW[2]+y*(_lgamW[3]+y*(_lgamW[4]+y*(_lgamW[5]+y*_lgamW[6])))))
+ lgamma = (x-0.5)*(t-1) + w
+ default: // 2**58 <= x <= Inf
+ lgamma = x * (Log(x) - 1)
+ }
+ if neg {
+ lgamma = nadj - lgamma
+ }
+ return
+}
+
+// sinPi(x) is a helper function for negative x
+func sinPi(x float64) float64 {
+ const (
+ Two52 = 1 << 52 // 0x4330000000000000 ~4.5036e+15
+ Two53 = 1 << 53 // 0x4340000000000000 ~9.0072e+15
+ )
+ if x < 0.25 {
+ return -Sin(Pi * x)
+ }
+
+ // argument reduction
+ z := Floor(x)
+ var n int
+ if z != x { // inexact
+ x = Mod(x, 2)
+ n = int(x * 4)
+ } else {
+ if x >= Two53 { // x must be even
+ x = 0
+ n = 0
+ } else {
+ if x < Two52 {
+ z = x + Two52 // exact
+ }
+ n = int(1 & Float64bits(z))
+ x = float64(n)
+ n <<= 2
+ }
+ }
+ switch n {
+ case 0:
+ x = Sin(Pi * x)
+ case 1, 2:
+ x = Cos(Pi * (0.5 - x))
+ case 3, 4:
+ x = Sin(Pi * (1 - x))
+ case 5, 6:
+ x = -Cos(Pi * (x - 1.5))
+ default:
+ x = Sin(Pi * (x - 2))
+ }
+ return -x
+}
diff --git a/platform/dbops/binaries/go/go/src/math/log.go b/platform/dbops/binaries/go/go/src/math/log.go
new file mode 100644
index 0000000000000000000000000000000000000000..695a545e7f00ec23ccf024e91c6172a454613fe4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log.go
@@ -0,0 +1,129 @@
+// 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 math
+
+/*
+ Floating-point logarithm.
+*/
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/e_log.c
+// and came with this notice. The go code is a simpler
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_log(x)
+// Return the logarithm of x
+//
+// Method :
+// 1. Argument Reduction: find k and f such that
+// x = 2**k * (1+f),
+// where sqrt(2)/2 < 1+f < sqrt(2) .
+//
+// 2. Approximation of log(1+f).
+// Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)
+// = 2s + 2/3 s**3 + 2/5 s**5 + .....,
+// = 2s + s*R
+// We use a special Reme algorithm on [0,0.1716] to generate
+// a polynomial of degree 14 to approximate R. The maximum error
+// of this polynomial approximation is bounded by 2**-58.45. In
+// other words,
+// 2 4 6 8 10 12 14
+// R(z) ~ L1*s +L2*s +L3*s +L4*s +L5*s +L6*s +L7*s
+// (the values of L1 to L7 are listed in the program) and
+// | 2 14 | -58.45
+// | L1*s +...+L7*s - R(z) | <= 2
+// | |
+// Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.
+// In order to guarantee error in log below 1ulp, we compute log by
+// log(1+f) = f - s*(f - R) (if f is not too large)
+// log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy)
+//
+// 3. Finally, log(x) = k*Ln2 + log(1+f).
+// = k*Ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*Ln2_lo)))
+// Here Ln2 is split into two floating point number:
+// Ln2_hi + Ln2_lo,
+// where n*Ln2_hi is always exact for |n| < 2000.
+//
+// Special cases:
+// log(x) is NaN with signal if x < 0 (including -INF) ;
+// log(+INF) is +INF; log(0) is -INF with signal;
+// log(NaN) is that NaN with no signal.
+//
+// Accuracy:
+// according to an error analysis, the error is always less than
+// 1 ulp (unit in the last place).
+//
+// Constants:
+// The hexadecimal values are the intended ones for the following
+// constants. The decimal values may be used, provided that the
+// compiler will convert from decimal to binary accurately enough
+// to produce the hexadecimal values shown.
+
+// Log returns the natural logarithm of x.
+//
+// Special cases are:
+//
+// Log(+Inf) = +Inf
+// Log(0) = -Inf
+// Log(x < 0) = NaN
+// Log(NaN) = NaN
+func Log(x float64) float64 {
+ if haveArchLog {
+ return archLog(x)
+ }
+ return log(x)
+}
+
+func log(x float64) float64 {
+ const (
+ Ln2Hi = 6.93147180369123816490e-01 /* 3fe62e42 fee00000 */
+ Ln2Lo = 1.90821492927058770002e-10 /* 3dea39ef 35793c76 */
+ L1 = 6.666666666666735130e-01 /* 3FE55555 55555593 */
+ L2 = 3.999999999940941908e-01 /* 3FD99999 9997FA04 */
+ L3 = 2.857142874366239149e-01 /* 3FD24924 94229359 */
+ L4 = 2.222219843214978396e-01 /* 3FCC71C5 1D8E78AF */
+ L5 = 1.818357216161805012e-01 /* 3FC74664 96CB03DE */
+ L6 = 1.531383769920937332e-01 /* 3FC39A09 D078C69F */
+ L7 = 1.479819860511658591e-01 /* 3FC2F112 DF3E5244 */
+ )
+
+ // special cases
+ switch {
+ case IsNaN(x) || IsInf(x, 1):
+ return x
+ case x < 0:
+ return NaN()
+ case x == 0:
+ return Inf(-1)
+ }
+
+ // reduce
+ f1, ki := Frexp(x)
+ if f1 < Sqrt2/2 {
+ f1 *= 2
+ ki--
+ }
+ f := f1 - 1
+ k := float64(ki)
+
+ // compute
+ s := f / (2 + f)
+ s2 := s * s
+ s4 := s2 * s2
+ t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7)))
+ t2 := s4 * (L2 + s4*(L4+s4*L6))
+ R := t1 + t2
+ hfsq := 0.5 * f * f
+ return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/log10.go b/platform/dbops/binaries/go/go/src/math/log10.go
new file mode 100644
index 0000000000000000000000000000000000000000..02c3a757c012be60ff3654fe063364390b8b947a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log10.go
@@ -0,0 +1,37 @@
+// 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 math
+
+// Log10 returns the decimal logarithm of x.
+// The special cases are the same as for [Log].
+func Log10(x float64) float64 {
+ if haveArchLog10 {
+ return archLog10(x)
+ }
+ return log10(x)
+}
+
+func log10(x float64) float64 {
+ return Log(x) * (1 / Ln10)
+}
+
+// Log2 returns the binary logarithm of x.
+// The special cases are the same as for [Log].
+func Log2(x float64) float64 {
+ if haveArchLog2 {
+ return archLog2(x)
+ }
+ return log2(x)
+}
+
+func log2(x float64) float64 {
+ frac, exp := Frexp(x)
+ // Make sure exact powers of two give an exact answer.
+ // Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1.
+ if frac == 0.5 {
+ return float64(exp - 1)
+ }
+ return Log(frac)*(1/Ln2) + float64(exp)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/log10_s390x.s b/platform/dbops/binaries/go/go/src/math/log10_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..3638afe700df47ad95aa2bc16c9e07ed5ee04b23
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log10_s390x.s
@@ -0,0 +1,156 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial coefficients and other constants
+DATA log10rodataL19<>+0(SB)/8, $0.000000000000000000E+00
+DATA log10rodataL19<>+8(SB)/8, $-1.0
+DATA log10rodataL19<>+16(SB)/8, $0x7FF8000000000000 //+NanN
+DATA log10rodataL19<>+24(SB)/8, $.15375570329280596749
+DATA log10rodataL19<>+32(SB)/8, $.60171950900703668594E+04
+DATA log10rodataL19<>+40(SB)/8, $-1.9578460454940795898
+DATA log10rodataL19<>+48(SB)/8, $0.78962633073318517310E-01
+DATA log10rodataL19<>+56(SB)/8, $-.71784211884836937993E-02
+DATA log10rodataL19<>+64(SB)/8, $0.87011165920689940661E-03
+DATA log10rodataL19<>+72(SB)/8, $-.11865158981621437541E-03
+DATA log10rodataL19<>+80(SB)/8, $0.17258413403018680410E-04
+DATA log10rodataL19<>+88(SB)/8, $0.40752932047883484315E-06
+DATA log10rodataL19<>+96(SB)/8, $-.26149194688832680410E-05
+DATA log10rodataL19<>+104(SB)/8, $0.92453396963875026759E-08
+DATA log10rodataL19<>+112(SB)/8, $-.64572084905921579630E-07
+DATA log10rodataL19<>+120(SB)/8, $-5.5
+DATA log10rodataL19<>+128(SB)/8, $18446744073709551616.
+GLOBL log10rodataL19<>+0(SB), RODATA, $136
+
+// Table of log10 correction terms
+DATA log10tab2074<>+0(SB)/8, $0.254164497922885069E-01
+DATA log10tab2074<>+8(SB)/8, $0.179018857989381839E-01
+DATA log10tab2074<>+16(SB)/8, $0.118926768029048674E-01
+DATA log10tab2074<>+24(SB)/8, $0.722595568238080033E-02
+DATA log10tab2074<>+32(SB)/8, $0.376393570022739135E-02
+DATA log10tab2074<>+40(SB)/8, $0.138901135928814326E-02
+DATA log10tab2074<>+48(SB)/8, $0
+DATA log10tab2074<>+56(SB)/8, $-0.490780466387818203E-03
+DATA log10tab2074<>+64(SB)/8, $-0.159811431402137571E-03
+DATA log10tab2074<>+72(SB)/8, $0.925796337165100494E-03
+DATA log10tab2074<>+80(SB)/8, $0.270683176738357035E-02
+DATA log10tab2074<>+88(SB)/8, $0.513079030821304758E-02
+DATA log10tab2074<>+96(SB)/8, $0.815089785397996303E-02
+DATA log10tab2074<>+104(SB)/8, $0.117253060262419215E-01
+DATA log10tab2074<>+112(SB)/8, $0.158164239345343963E-01
+DATA log10tab2074<>+120(SB)/8, $0.203903595489229786E-01
+GLOBL log10tab2074<>+0(SB), RODATA, $128
+
+// Log10 returns the decimal logarithm of the argument.
+//
+// Special cases are:
+// Log(+Inf) = +Inf
+// Log(0) = -Inf
+// Log(x < 0) = NaN
+// Log(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·log10Asm(SB),NOSPLIT,$8-16
+ FMOVD x+0(FP), F0
+ MOVD $log10rodataL19<>+0(SB), R9
+ FMOVD F0, x-8(SP)
+ WORD $0xC0298006 //iilf %r2,2147909631
+ BYTE $0x7F
+ BYTE $0xFF
+ WORD $0x5840F008 //l %r4, 8(%r15)
+ SUBW R4, R2, R3
+ RISBGZ $32, $47, $0, R3, R5
+ MOVH $0x0, R1
+ RISBGN $0, $31, $32, R5, R1
+ WORD $0xC0590016 //iilf %r5,1507327
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R4, R10
+ MOVW R5, R11
+ CMPBLE R10, R11, L2
+ WORD $0xC0297FEF //iilf %r2,2146435071
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R4, R10
+ MOVW R2, R11
+ CMPBLE R10, R11, L16
+L3:
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+
+L2:
+ LTDBR F0, F0
+ BLEU L13
+ WORD $0xED009080 //mdb %f0,.L20-.L19(%r9)
+ BYTE $0x00
+ BYTE $0x1C
+ FMOVD F0, x-8(SP)
+ WORD $0x5B20F008 //s %r2, 8(%r15)
+ RISBGZ $57, $60, $51, R2, R3
+ ANDW $0xFFFF0000, R2
+ RISBGN $0, $31, $32, R2, R1
+ ADDW $0x4000000, R2
+ BLEU L17
+L8:
+ SRW $8, R2, R2
+ ORW $0x45000000, R2
+L4:
+ FMOVD log10rodataL19<>+120(SB), F2
+ LDGR R1, F4
+ WFMADB V4, V0, V2, V0
+ FMOVD log10rodataL19<>+112(SB), F4
+ FMOVD log10rodataL19<>+104(SB), F6
+ WFMADB V0, V6, V4, V6
+ FMOVD log10rodataL19<>+96(SB), F4
+ FMOVD log10rodataL19<>+88(SB), F1
+ WFMADB V0, V1, V4, V1
+ WFMDB V0, V0, V4
+ FMOVD log10rodataL19<>+80(SB), F2
+ WFMADB V6, V4, V1, V6
+ FMOVD log10rodataL19<>+72(SB), F1
+ WFMADB V0, V2, V1, V2
+ FMOVD log10rodataL19<>+64(SB), F1
+ RISBGZ $57, $60, $0, R3, R3
+ WFMADB V4, V6, V2, V6
+ FMOVD log10rodataL19<>+56(SB), F2
+ WFMADB V0, V1, V2, V1
+ VLVGF $0, R2, V2
+ WFMADB V4, V6, V1, V4
+ LDEBR F2, F2
+ FMOVD log10rodataL19<>+48(SB), F6
+ WFMADB V0, V4, V6, V4
+ FMOVD log10rodataL19<>+40(SB), F1
+ FMOVD log10rodataL19<>+32(SB), F6
+ MOVD $log10tab2074<>+0(SB), R1
+ WFMADB V2, V1, V6, V2
+ WORD $0x68331000 //ld %f3,0(%r3,%r1)
+ WFMADB V0, V4, V3, V0
+ FMOVD log10rodataL19<>+24(SB), F4
+ FMADD F4, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L16:
+ RISBGZ $40, $55, $56, R3, R2
+ RISBGZ $57, $60, $51, R3, R3
+ ORW $0x45000000, R2
+ BR L4
+L13:
+ BGE L18 //jnl .L18
+ BVS L18
+ FMOVD log10rodataL19<>+16(SB), F0
+ BR L1
+L17:
+ SRAW $1, R2, R2
+ SUBW $0x40000000, R2
+ BR L8
+L18:
+ FMOVD log10rodataL19<>+8(SB), F0
+ WORD $0xED009000 //ddb %f0,.L36-.L19(%r9)
+ BYTE $0x00
+ BYTE $0x1D
+ BR L1
diff --git a/platform/dbops/binaries/go/go/src/math/log1p.go b/platform/dbops/binaries/go/go/src/math/log1p.go
new file mode 100644
index 0000000000000000000000000000000000000000..bfcb813be8ceeccd197e374fdfb2595cc41346fe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log1p.go
@@ -0,0 +1,203 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below are from FreeBSD's /usr/src/lib/msun/src/s_log1p.c
+// and came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+//
+// double log1p(double x)
+//
+// Method :
+// 1. Argument Reduction: find k and f such that
+// 1+x = 2**k * (1+f),
+// where sqrt(2)/2 < 1+f < sqrt(2) .
+//
+// Note. If k=0, then f=x is exact. However, if k!=0, then f
+// may not be representable exactly. In that case, a correction
+// term is need. Let u=1+x rounded. Let c = (1+x)-u, then
+// log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u),
+// and add back the correction term c/u.
+// (Note: when x > 2**53, one can simply return log(x))
+//
+// 2. Approximation of log1p(f).
+// Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)
+// = 2s + 2/3 s**3 + 2/5 s**5 + .....,
+// = 2s + s*R
+// We use a special Reme algorithm on [0,0.1716] to generate
+// a polynomial of degree 14 to approximate R The maximum error
+// of this polynomial approximation is bounded by 2**-58.45. In
+// other words,
+// 2 4 6 8 10 12 14
+// R(z) ~ Lp1*s +Lp2*s +Lp3*s +Lp4*s +Lp5*s +Lp6*s +Lp7*s
+// (the values of Lp1 to Lp7 are listed in the program)
+// and
+// | 2 14 | -58.45
+// | Lp1*s +...+Lp7*s - R(z) | <= 2
+// | |
+// Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.
+// In order to guarantee error in log below 1ulp, we compute log
+// by
+// log1p(f) = f - (hfsq - s*(hfsq+R)).
+//
+// 3. Finally, log1p(x) = k*ln2 + log1p(f).
+// = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo)))
+// Here ln2 is split into two floating point number:
+// ln2_hi + ln2_lo,
+// where n*ln2_hi is always exact for |n| < 2000.
+//
+// Special cases:
+// log1p(x) is NaN with signal if x < -1 (including -INF) ;
+// log1p(+INF) is +INF; log1p(-1) is -INF with signal;
+// log1p(NaN) is that NaN with no signal.
+//
+// Accuracy:
+// according to an error analysis, the error is always less than
+// 1 ulp (unit in the last place).
+//
+// Constants:
+// The hexadecimal values are the intended ones for the following
+// constants. The decimal values may be used, provided that the
+// compiler will convert from decimal to binary accurately enough
+// to produce the hexadecimal values shown.
+//
+// Note: Assuming log() return accurate answer, the following
+// algorithm can be used to compute log1p(x) to within a few ULP:
+//
+// u = 1+x;
+// if(u==1.0) return x ; else
+// return log(u)*(x/(u-1.0));
+//
+// See HP-15C Advanced Functions Handbook, p.193.
+
+// Log1p returns the natural logarithm of 1 plus its argument x.
+// It is more accurate than [Log](1 + x) when x is near zero.
+//
+// Special cases are:
+//
+// Log1p(+Inf) = +Inf
+// Log1p(±0) = ±0
+// Log1p(-1) = -Inf
+// Log1p(x < -1) = NaN
+// Log1p(NaN) = NaN
+func Log1p(x float64) float64 {
+ if haveArchLog1p {
+ return archLog1p(x)
+ }
+ return log1p(x)
+}
+
+func log1p(x float64) float64 {
+ const (
+ Sqrt2M1 = 4.142135623730950488017e-01 // Sqrt(2)-1 = 0x3fda827999fcef34
+ Sqrt2HalfM1 = -2.928932188134524755992e-01 // Sqrt(2)/2-1 = 0xbfd2bec333018866
+ Small = 1.0 / (1 << 29) // 2**-29 = 0x3e20000000000000
+ Tiny = 1.0 / (1 << 54) // 2**-54
+ Two53 = 1 << 53 // 2**53
+ Ln2Hi = 6.93147180369123816490e-01 // 3fe62e42fee00000
+ Ln2Lo = 1.90821492927058770002e-10 // 3dea39ef35793c76
+ Lp1 = 6.666666666666735130e-01 // 3FE5555555555593
+ Lp2 = 3.999999999940941908e-01 // 3FD999999997FA04
+ Lp3 = 2.857142874366239149e-01 // 3FD2492494229359
+ Lp4 = 2.222219843214978396e-01 // 3FCC71C51D8E78AF
+ Lp5 = 1.818357216161805012e-01 // 3FC7466496CB03DE
+ Lp6 = 1.531383769920937332e-01 // 3FC39A09D078C69F
+ Lp7 = 1.479819860511658591e-01 // 3FC2F112DF3E5244
+ )
+
+ // special cases
+ switch {
+ case x < -1 || IsNaN(x): // includes -Inf
+ return NaN()
+ case x == -1:
+ return Inf(-1)
+ case IsInf(x, 1):
+ return Inf(1)
+ }
+
+ absx := Abs(x)
+
+ var f float64
+ var iu uint64
+ k := 1
+ if absx < Sqrt2M1 { // |x| < Sqrt(2)-1
+ if absx < Small { // |x| < 2**-29
+ if absx < Tiny { // |x| < 2**-54
+ return x
+ }
+ return x - x*x*0.5
+ }
+ if x > Sqrt2HalfM1 { // Sqrt(2)/2-1 < x
+ // (Sqrt(2)/2-1) < x < (Sqrt(2)-1)
+ k = 0
+ f = x
+ iu = 1
+ }
+ }
+ var c float64
+ if k != 0 {
+ var u float64
+ if absx < Two53 { // 1<<53
+ u = 1.0 + x
+ iu = Float64bits(u)
+ k = int((iu >> 52) - 1023)
+ // correction term
+ if k > 0 {
+ c = 1.0 - (u - x)
+ } else {
+ c = x - (u - 1.0)
+ }
+ c /= u
+ } else {
+ u = x
+ iu = Float64bits(u)
+ k = int((iu >> 52) - 1023)
+ c = 0
+ }
+ iu &= 0x000fffffffffffff
+ if iu < 0x0006a09e667f3bcd { // mantissa of Sqrt(2)
+ u = Float64frombits(iu | 0x3ff0000000000000) // normalize u
+ } else {
+ k++
+ u = Float64frombits(iu | 0x3fe0000000000000) // normalize u/2
+ iu = (0x0010000000000000 - iu) >> 2
+ }
+ f = u - 1.0 // Sqrt(2)/2 < u < Sqrt(2)
+ }
+ hfsq := 0.5 * f * f
+ var s, R, z float64
+ if iu == 0 { // |f| < 2**-20
+ if f == 0 {
+ if k == 0 {
+ return 0
+ }
+ c += float64(k) * Ln2Lo
+ return float64(k)*Ln2Hi + c
+ }
+ R = hfsq * (1.0 - 0.66666666666666666*f) // avoid division
+ if k == 0 {
+ return f - R
+ }
+ return float64(k)*Ln2Hi - ((R - (float64(k)*Ln2Lo + c)) - f)
+ }
+ s = f / (2.0 + f)
+ z = s * s
+ R = z * (Lp1 + z*(Lp2+z*(Lp3+z*(Lp4+z*(Lp5+z*(Lp6+z*Lp7))))))
+ if k == 0 {
+ return f - (hfsq - s*(hfsq+R))
+ }
+ return float64(k)*Ln2Hi - ((hfsq - (s*(hfsq+R) + (float64(k)*Ln2Lo + c))) - f)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/log1p_s390x.s b/platform/dbops/binaries/go/go/src/math/log1p_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..00eb374996391fb6ce5078a31fadf795daf89022
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log1p_s390x.s
@@ -0,0 +1,180 @@
+// 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.
+
+#include "textflag.h"
+
+// Constants
+DATA ·log1pxlim<> + 0(SB)/4, $0xfff00000
+GLOBL ·log1pxlim<> + 0(SB), RODATA, $4
+DATA ·log1pxzero<> + 0(SB)/8, $0.0
+GLOBL ·log1pxzero<> + 0(SB), RODATA, $8
+DATA ·log1pxminf<> + 0(SB)/8, $0xfff0000000000000
+GLOBL ·log1pxminf<> + 0(SB), RODATA, $8
+DATA ·log1pxnan<> + 0(SB)/8, $0x7ff8000000000000
+GLOBL ·log1pxnan<> + 0(SB), RODATA, $8
+DATA ·log1pyout<> + 0(SB)/8, $0x40fce621e71da000
+GLOBL ·log1pyout<> + 0(SB), RODATA, $8
+DATA ·log1pxout<> + 0(SB)/8, $0x40f1000000000000
+GLOBL ·log1pxout<> + 0(SB), RODATA, $8
+DATA ·log1pxl2<> + 0(SB)/8, $0xbfda7aecbeba4e46
+GLOBL ·log1pxl2<> + 0(SB), RODATA, $8
+DATA ·log1pxl1<> + 0(SB)/8, $0x3ffacde700000000
+GLOBL ·log1pxl1<> + 0(SB), RODATA, $8
+DATA ·log1pxa<> + 0(SB)/8, $5.5
+GLOBL ·log1pxa<> + 0(SB), RODATA, $8
+DATA ·log1pxmone<> + 0(SB)/8, $-1.0
+GLOBL ·log1pxmone<> + 0(SB), RODATA, $8
+
+// Minimax polynomial approximations
+DATA ·log1pc8<> + 0(SB)/8, $0.212881813645679599E-07
+GLOBL ·log1pc8<> + 0(SB), RODATA, $8
+DATA ·log1pc7<> + 0(SB)/8, $-.148682720127920854E-06
+GLOBL ·log1pc7<> + 0(SB), RODATA, $8
+DATA ·log1pc6<> + 0(SB)/8, $0.938370938292558173E-06
+GLOBL ·log1pc6<> + 0(SB), RODATA, $8
+DATA ·log1pc5<> + 0(SB)/8, $-.602107458843052029E-05
+GLOBL ·log1pc5<> + 0(SB), RODATA, $8
+DATA ·log1pc4<> + 0(SB)/8, $0.397389654305194527E-04
+GLOBL ·log1pc4<> + 0(SB), RODATA, $8
+DATA ·log1pc3<> + 0(SB)/8, $-.273205381970859341E-03
+GLOBL ·log1pc3<> + 0(SB), RODATA, $8
+DATA ·log1pc2<> + 0(SB)/8, $0.200350613573012186E-02
+GLOBL ·log1pc2<> + 0(SB), RODATA, $8
+DATA ·log1pc1<> + 0(SB)/8, $-.165289256198351540E-01
+GLOBL ·log1pc1<> + 0(SB), RODATA, $8
+DATA ·log1pc0<> + 0(SB)/8, $0.181818181818181826E+00
+GLOBL ·log1pc0<> + 0(SB), RODATA, $8
+
+
+// Table of log10 correction terms
+DATA ·log1ptab<> + 0(SB)/8, $0.585235384085551248E-01
+DATA ·log1ptab<> + 8(SB)/8, $0.412206153771168640E-01
+DATA ·log1ptab<> + 16(SB)/8, $0.273839003221648339E-01
+DATA ·log1ptab<> + 24(SB)/8, $0.166383778368856480E-01
+DATA ·log1ptab<> + 32(SB)/8, $0.866678223433169637E-02
+DATA ·log1ptab<> + 40(SB)/8, $0.319831684989627514E-02
+DATA ·log1ptab<> + 48(SB)/8, $-.000000000000000000E+00
+DATA ·log1ptab<> + 56(SB)/8, $-.113006378583725549E-02
+DATA ·log1ptab<> + 64(SB)/8, $-.367979419636602491E-03
+DATA ·log1ptab<> + 72(SB)/8, $0.213172484510484979E-02
+DATA ·log1ptab<> + 80(SB)/8, $0.623271047682013536E-02
+DATA ·log1ptab<> + 88(SB)/8, $0.118140812789696885E-01
+DATA ·log1ptab<> + 96(SB)/8, $0.187681358930914206E-01
+DATA ·log1ptab<> + 104(SB)/8, $0.269985148668178992E-01
+DATA ·log1ptab<> + 112(SB)/8, $0.364186619761331328E-01
+DATA ·log1ptab<> + 120(SB)/8, $0.469505379381388441E-01
+GLOBL ·log1ptab<> + 0(SB), RODATA, $128
+
+// Log1p returns the natural logarithm of 1 plus its argument x.
+// It is more accurate than Log(1 + x) when x is near zero.
+//
+// Special cases are:
+// Log1p(+Inf) = +Inf
+// Log1p(±0) = ±0
+// Log1p(-1) = -Inf
+// Log1p(x < -1) = NaN
+// Log1p(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·log1pAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·log1pxmone<>+0(SB), R1
+ MOVD ·log1pxout<>+0(SB), R2
+ FMOVD 0(R1), F3
+ MOVD $·log1pxa<>+0(SB), R1
+ MOVWZ ·log1pxlim<>+0(SB), R0
+ FMOVD 0(R1), F1
+ MOVD $·log1pc8<>+0(SB), R1
+ FMOVD 0(R1), F5
+ MOVD $·log1pc7<>+0(SB), R1
+ VLEG $0, 0(R1), V20
+ MOVD $·log1pc6<>+0(SB), R1
+ WFSDB V0, V3, V4
+ VLEG $0, 0(R1), V18
+ MOVD $·log1pc5<>+0(SB), R1
+ VLEG $0, 0(R1), V16
+ MOVD R2, R5
+ LGDR F4, R3
+ WORD $0xC0190006 //iilf %r1,425983
+ BYTE $0x7F
+ BYTE $0xFF
+ SRAD $32, R3, R3
+ SUBW R3, R1
+ SRW $16, R1, R1
+ BYTE $0x18 //lr %r4,%r1
+ BYTE $0x41
+ RISBGN $0, $15, $48, R4, R2
+ RISBGN $16, $31, $32, R4, R5
+ MOVW R0, R6
+ MOVW R3, R7
+ CMPBGT R6, R7, L8
+ WFCEDBS V4, V4, V6
+ MOVD $·log1pxzero<>+0(SB), R1
+ FMOVD 0(R1), F2
+ BVS LEXITTAGlog1p
+ WORD $0xB3130044 // lcdbr %f4,%f4
+ WFCEDBS V2, V4, V6
+ BEQ L9
+ WFCHDBS V4, V2, V2
+ BEQ LEXITTAGlog1p
+ MOVD $·log1pxnan<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L8:
+ LDGR R2, F2
+ FSUB F4, F3
+ FMADD F2, F4, F1
+ MOVD $·log1pc4<>+0(SB), R2
+ WORD $0xB3130041 // lcdbr %f4,%f1
+ FMOVD 0(R2), F7
+ FSUB F3, F0
+ MOVD $·log1pc3<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $·log1pc2<>+0(SB), R2
+ WFMDB V1, V1, V6
+ FMADD F7, F4, F3
+ WFMSDB V0, V2, V1, V0
+ FMOVD 0(R2), F7
+ WFMADB V4, V5, V20, V5
+ MOVD $·log1pc1<>+0(SB), R2
+ FMOVD 0(R2), F2
+ FMADD F7, F4, F2
+ WFMADB V4, V18, V16, V4
+ FMADD F3, F6, F2
+ WFMADB V5, V6, V4, V5
+ FMUL F6, F6
+ MOVD $·log1pc0<>+0(SB), R2
+ WFMADB V6, V5, V2, V6
+ FMOVD 0(R2), F4
+ WFMADB V0, V6, V4, V6
+ RISBGZ $57, $60, $3, R1, R1
+ MOVD $·log1ptab<>+0(SB), R2
+ MOVD $·log1pxl1<>+0(SB), R3
+ WORD $0x68112000 //ld %f1,0(%r1,%r2)
+ FMOVD 0(R3), F2
+ WFMADB V0, V6, V1, V0
+ MOVD $·log1pyout<>+0(SB), R1
+ LDGR R5, F6
+ FMOVD 0(R1), F4
+ WFMSDB V2, V6, V4, V2
+ MOVD $·log1pxl2<>+0(SB), R1
+ FMOVD 0(R1), F4
+ FMADD F4, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L9:
+ MOVD $·log1pxminf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+
+LEXITTAGlog1p:
+ FMOVD F0, ret+8(FP)
+ RET
+
diff --git a/platform/dbops/binaries/go/go/src/math/log_amd64.s b/platform/dbops/binaries/go/go/src/math/log_amd64.s
new file mode 100644
index 0000000000000000000000000000000000000000..508df68a9bddce0ced5e6017934679b581704620
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log_amd64.s
@@ -0,0 +1,112 @@
+// 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.
+
+#include "textflag.h"
+
+#define HSqrt2 7.07106781186547524401e-01 // sqrt(2)/2
+#define Ln2Hi 6.93147180369123816490e-01 // 0x3fe62e42fee00000
+#define Ln2Lo 1.90821492927058770002e-10 // 0x3dea39ef35793c76
+#define L1 6.666666666666735130e-01 // 0x3FE5555555555593
+#define L2 3.999999999940941908e-01 // 0x3FD999999997FA04
+#define L3 2.857142874366239149e-01 // 0x3FD2492494229359
+#define L4 2.222219843214978396e-01 // 0x3FCC71C51D8E78AF
+#define L5 1.818357216161805012e-01 // 0x3FC7466496CB03DE
+#define L6 1.531383769920937332e-01 // 0x3FC39A09D078C69F
+#define L7 1.479819860511658591e-01 // 0x3FC2F112DF3E5244
+#define NaN 0x7FF8000000000001
+#define NegInf 0xFFF0000000000000
+#define PosInf 0x7FF0000000000000
+
+// func Log(x float64) float64
+TEXT ·archLog(SB),NOSPLIT,$0
+ // test bits for special cases
+ MOVQ x+0(FP), BX
+ MOVQ $~(1<<63), AX // sign bit mask
+ ANDQ BX, AX
+ JEQ isZero
+ MOVQ $0, AX
+ CMPQ AX, BX
+ JGT isNegative
+ MOVQ $PosInf, AX
+ CMPQ AX, BX
+ JLE isInfOrNaN
+ // f1, ki := math.Frexp(x); k := float64(ki)
+ MOVQ BX, X0
+ MOVQ $0x000FFFFFFFFFFFFF, AX
+ MOVQ AX, X2
+ ANDPD X0, X2
+ MOVSD $0.5, X0 // 0x3FE0000000000000
+ ORPD X0, X2 // X2= f1
+ SHRQ $52, BX
+ ANDL $0x7FF, BX
+ SUBL $0x3FE, BX
+ XORPS X1, X1 // break dependency for CVTSL2SD
+ CVTSL2SD BX, X1 // x1= k, x2= f1
+ // if f1 < math.Sqrt2/2 { k -= 1; f1 *= 2 }
+ MOVSD $HSqrt2, X0 // x0= 0.7071, x1= k, x2= f1
+ CMPSD X2, X0, 5 // cmpnlt; x0= 0 or ^0, x1= k, x2 = f1
+ MOVSD $1.0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 1
+ ANDPD X0, X3 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1
+ SUBSD X3, X1 // x0= 0 or ^0, x1= k, x2 = f1, x3= 0 or 1
+ MOVSD $1.0, X0 // x0= 1, x1= k, x2= f1, x3= 0 or 1
+ ADDSD X0, X3 // x0= 1, x1= k, x2= f1, x3= 1 or 2
+ MULSD X3, X2 // x0= 1, x1= k, x2= f1
+ // f := f1 - 1
+ SUBSD X0, X2 // x1= k, x2= f
+ // s := f / (2 + f)
+ MOVSD $2.0, X0
+ ADDSD X2, X0
+ MOVAPD X2, X3
+ DIVSD X0, X3 // x1=k, x2= f, x3= s
+ // s2 := s * s
+ MOVAPD X3, X4 // x1= k, x2= f, x3= s
+ MULSD X4, X4 // x1= k, x2= f, x3= s, x4= s2
+ // s4 := s2 * s2
+ MOVAPD X4, X5 // x1= k, x2= f, x3= s, x4= s2
+ MULSD X5, X5 // x1= k, x2= f, x3= s, x4= s2, x5= s4
+ // t1 := s2 * (L1 + s4*(L3+s4*(L5+s4*L7)))
+ MOVSD $L7, X6
+ MULSD X5, X6
+ ADDSD $L5, X6
+ MULSD X5, X6
+ ADDSD $L3, X6
+ MULSD X5, X6
+ ADDSD $L1, X6
+ MULSD X6, X4 // x1= k, x2= f, x3= s, x4= t1, x5= s4
+ // t2 := s4 * (L2 + s4*(L4+s4*L6))
+ MOVSD $L6, X6
+ MULSD X5, X6
+ ADDSD $L4, X6
+ MULSD X5, X6
+ ADDSD $L2, X6
+ MULSD X6, X5 // x1= k, x2= f, x3= s, x4= t1, x5= t2
+ // R := t1 + t2
+ ADDSD X5, X4 // x1= k, x2= f, x3= s, x4= R
+ // hfsq := 0.5 * f * f
+ MOVSD $0.5, X0
+ MULSD X2, X0
+ MULSD X2, X0 // x0= hfsq, x1= k, x2= f, x3= s, x4= R
+ // return k*Ln2Hi - ((hfsq - (s*(hfsq+R) + k*Ln2Lo)) - f)
+ ADDSD X0, X4 // x0= hfsq, x1= k, x2= f, x3= s, x4= hfsq+R
+ MULSD X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R)
+ MOVSD $Ln2Lo, X4
+ MULSD X1, X4 // x4= k*Ln2Lo
+ ADDSD X4, X3 // x0= hfsq, x1= k, x2= f, x3= s*(hfsq+R)+k*Ln2Lo
+ SUBSD X3, X0 // x0= hfsq-(s*(hfsq+R)+k*Ln2Lo), x1= k, x2= f
+ SUBSD X2, X0 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k
+ MULSD $Ln2Hi, X1 // x0= (hfsq-(s*(hfsq+R)+k*Ln2Lo))-f, x1= k*Ln2Hi
+ SUBSD X0, X1 // x1= k*Ln2Hi-((hfsq-(s*(hfsq+R)+k*Ln2Lo))-f)
+ MOVSD X1, ret+8(FP)
+ RET
+isInfOrNaN:
+ MOVQ BX, ret+8(FP) // +Inf or NaN, return x
+ RET
+isNegative:
+ MOVQ $NaN, AX
+ MOVQ AX, ret+8(FP) // return NaN
+ RET
+isZero:
+ MOVQ $NegInf, AX
+ MOVQ AX, ret+8(FP) // return -Inf
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/log_asm.go b/platform/dbops/binaries/go/go/src/math/log_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..848cce13b289b52e37c8f08e9c3d6d0c149831d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log_asm.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.
+
+//go:build amd64 || s390x
+
+package math
+
+const haveArchLog = true
+
+func archLog(x float64) float64
diff --git a/platform/dbops/binaries/go/go/src/math/log_s390x.s b/platform/dbops/binaries/go/go/src/math/log_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..4b514f3dd42eb11fa4ca0a3673ad6a36bd93adcf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log_s390x.s
@@ -0,0 +1,168 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial approximations
+DATA ·logrodataL21<> + 0(SB)/8, $-.499999999999999778E+00
+DATA ·logrodataL21<> + 8(SB)/8, $0.333333333333343751E+00
+DATA ·logrodataL21<> + 16(SB)/8, $-.250000000001606881E+00
+DATA ·logrodataL21<> + 24(SB)/8, $0.199999999971603032E+00
+DATA ·logrodataL21<> + 32(SB)/8, $-.166666663114122038E+00
+DATA ·logrodataL21<> + 40(SB)/8, $-.125002923782692399E+00
+DATA ·logrodataL21<> + 48(SB)/8, $0.111142014580396256E+00
+DATA ·logrodataL21<> + 56(SB)/8, $0.759438932618934220E-01
+DATA ·logrodataL21<> + 64(SB)/8, $0.142857144267212549E+00
+DATA ·logrodataL21<> + 72(SB)/8, $-.993038938793590759E-01
+DATA ·logrodataL21<> + 80(SB)/8, $-1.0
+GLOBL ·logrodataL21<> + 0(SB), RODATA, $88
+
+// Constants
+DATA ·logxminf<> + 0(SB)/8, $0xfff0000000000000
+GLOBL ·logxminf<> + 0(SB), RODATA, $8
+DATA ·logxnan<> + 0(SB)/8, $0x7ff8000000000000
+GLOBL ·logxnan<> + 0(SB), RODATA, $8
+DATA ·logx43f<> + 0(SB)/8, $0x43f0000000000000
+GLOBL ·logx43f<> + 0(SB), RODATA, $8
+DATA ·logxl2<> + 0(SB)/8, $0x3fda7aecbeba4e46
+GLOBL ·logxl2<> + 0(SB), RODATA, $8
+DATA ·logxl1<> + 0(SB)/8, $0x3ffacde700000000
+GLOBL ·logxl1<> + 0(SB), RODATA, $8
+
+/* Input transform scale and add constants */
+DATA ·logxm<> + 0(SB)/8, $0x3fc77604e63c84b1
+DATA ·logxm<> + 8(SB)/8, $0x40fb39456ab53250
+DATA ·logxm<> + 16(SB)/8, $0x3fc9ee358b945f3f
+DATA ·logxm<> + 24(SB)/8, $0x40fb39418bf3b137
+DATA ·logxm<> + 32(SB)/8, $0x3fccfb2e1304f4b6
+DATA ·logxm<> + 40(SB)/8, $0x40fb393d3eda3022
+DATA ·logxm<> + 48(SB)/8, $0x3fd0000000000000
+DATA ·logxm<> + 56(SB)/8, $0x40fb393969e70000
+DATA ·logxm<> + 64(SB)/8, $0x3fd11117aafbfe04
+DATA ·logxm<> + 72(SB)/8, $0x40fb3936eaefafcf
+DATA ·logxm<> + 80(SB)/8, $0x3fd2492af5e658b2
+DATA ·logxm<> + 88(SB)/8, $0x40fb39343ff01715
+DATA ·logxm<> + 96(SB)/8, $0x3fd3b50c622a43dd
+DATA ·logxm<> + 104(SB)/8, $0x40fb39315adae2f3
+DATA ·logxm<> + 112(SB)/8, $0x3fd56bbeea918777
+DATA ·logxm<> + 120(SB)/8, $0x40fb392e21698552
+GLOBL ·logxm<> + 0(SB), RODATA, $128
+
+// Log returns the natural logarithm of the argument.
+//
+// Special cases are:
+// Log(+Inf) = +Inf
+// Log(0) = -Inf
+// Log(x < 0) = NaN
+// Log(NaN) = NaN
+// The algorithm used is minimax polynomial approximation using a table of
+// polynomial coefficients determined with a Remez exchange algorithm.
+
+TEXT ·logAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ MOVD $·logrodataL21<>+0(SB), R9
+ MOVH $0x8006, R4
+ LGDR F0, R1
+ MOVD $0x3FF0000000000000, R6
+ SRAD $48, R1, R1
+ MOVD $0x40F03E8000000000, R8
+ SUBW R1, R4
+ RISBGZ $32, $59, $0, R4, R2
+ RISBGN $0, $15, $48, R2, R6
+ RISBGN $16, $31, $32, R2, R8
+ MOVW R1, R7
+ CMPBGT R7, $22, L17
+ LTDBR F0, F0
+ MOVD $·logx43f<>+0(SB), R1
+ FMOVD 0(R1), F2
+ BLEU L3
+ MOVH $0x8005, R12
+ MOVH $0x8405, R0
+ BR L15
+L7:
+ LTDBR F0, F0
+ BLEU L3
+L15:
+ FMUL F2, F0
+ LGDR F0, R1
+ SRAD $48, R1, R1
+ SUBW R1, R0, R2
+ SUBW R1, R12, R3
+ BYTE $0x18 //lr %r4,%r2
+ BYTE $0x42
+ ANDW $0xFFFFFFF0, R3
+ ANDW $0xFFFFFFF0, R2
+ BYTE $0x18 //lr %r5,%r1
+ BYTE $0x51
+ MOVW R1, R7
+ CMPBLE R7, $22, L7
+ RISBGN $0, $15, $48, R3, R6
+ RISBGN $16, $31, $32, R2, R8
+L2:
+ MOVH R5, R5
+ MOVH $0x7FEF, R1
+ CMPW R5, R1
+ BGT L1
+ LDGR R6, F2
+ FMUL F2, F0
+ RISBGZ $57, $59, $3, R4, R4
+ FMOVD 80(R9), F2
+ MOVD $·logxm<>+0(SB), R7
+ ADD R7, R4
+ FMOVD 72(R9), F4
+ WORD $0xED004000 //madb %f2,%f0,0(%r4)
+ BYTE $0x20
+ BYTE $0x1E
+ FMOVD 64(R9), F1
+ FMOVD F2, F0
+ FMOVD 56(R9), F2
+ WFMADB V0, V2, V4, V2
+ WFMDB V0, V0, V6
+ FMOVD 48(R9), F4
+ WFMADB V0, V2, V4, V2
+ FMOVD 40(R9), F4
+ WFMADB V2, V6, V1, V2
+ FMOVD 32(R9), F1
+ WFMADB V6, V4, V1, V4
+ FMOVD 24(R9), F1
+ WFMADB V6, V2, V1, V2
+ FMOVD 16(R9), F1
+ WFMADB V6, V4, V1, V4
+ MOVD $·logxl1<>+0(SB), R1
+ FMOVD 8(R9), F1
+ WFMADB V6, V2, V1, V2
+ FMOVD 0(R9), F1
+ WFMADB V6, V4, V1, V4
+ FMOVD 8(R4), F1
+ WFMADB V0, V2, V4, V2
+ LDGR R8, F4
+ WFMADB V6, V2, V0, V2
+ WORD $0xED401000 //msdb %f1,%f4,0(%r1)
+ BYTE $0x10
+ BYTE $0x1F
+ MOVD ·logxl2<>+0(SB), R1
+ WORD $0xB3130001 //lcdbr %f0,%f1
+ LDGR R1, F4
+ WFMADB V0, V4, V2, V0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+L3:
+ LTDBR F0, F0
+ BEQ L20
+ BGE L1
+ BVS L1
+
+ MOVD $·logxnan<>+0(SB), R1
+ FMOVD 0(R1), F0
+ BR L1
+L20:
+ MOVD $·logxminf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+L17:
+ BYTE $0x18 //lr %r5,%r1
+ BYTE $0x51
+ BR L2
diff --git a/platform/dbops/binaries/go/go/src/math/log_stub.go b/platform/dbops/binaries/go/go/src/math/log_stub.go
new file mode 100644
index 0000000000000000000000000000000000000000..d35992bf37ab69227a4afe49a21cef7e37d0fc30
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/log_stub.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.
+
+//go:build !amd64 && !s390x
+
+package math
+
+const haveArchLog = false
+
+func archLog(x float64) float64 {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/logb.go b/platform/dbops/binaries/go/go/src/math/logb.go
new file mode 100644
index 0000000000000000000000000000000000000000..1a46464127cc886aa78ad825c075fda4eab05614
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/logb.go
@@ -0,0 +1,52 @@
+// 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 math
+
+// Logb returns the binary exponent of x.
+//
+// Special cases are:
+//
+// Logb(±Inf) = +Inf
+// Logb(0) = -Inf
+// Logb(NaN) = NaN
+func Logb(x float64) float64 {
+ // special cases
+ switch {
+ case x == 0:
+ return Inf(-1)
+ case IsInf(x, 0):
+ return Inf(1)
+ case IsNaN(x):
+ return x
+ }
+ return float64(ilogb(x))
+}
+
+// Ilogb returns the binary exponent of x as an integer.
+//
+// Special cases are:
+//
+// Ilogb(±Inf) = MaxInt32
+// Ilogb(0) = MinInt32
+// Ilogb(NaN) = MaxInt32
+func Ilogb(x float64) int {
+ // special cases
+ switch {
+ case x == 0:
+ return MinInt32
+ case IsNaN(x):
+ return MaxInt32
+ case IsInf(x, 0):
+ return MaxInt32
+ }
+ return ilogb(x)
+}
+
+// ilogb returns the binary exponent of x. It assumes x is finite and
+// non-zero.
+func ilogb(x float64) int {
+ x, exp := normalize(x)
+ return int((Float64bits(x)>>shift)&mask) - bias + exp
+}
diff --git a/platform/dbops/binaries/go/go/src/math/mod.go b/platform/dbops/binaries/go/go/src/math/mod.go
new file mode 100644
index 0000000000000000000000000000000000000000..6f24250cfb461265fa51362c7ccc140c559abfc7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/mod.go
@@ -0,0 +1,52 @@
+// Copyright 2009-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 math
+
+/*
+ Floating-point mod function.
+*/
+
+// Mod returns the floating-point remainder of x/y.
+// The magnitude of the result is less than y and its
+// sign agrees with that of x.
+//
+// Special cases are:
+//
+// Mod(±Inf, y) = NaN
+// Mod(NaN, y) = NaN
+// Mod(x, 0) = NaN
+// Mod(x, ±Inf) = x
+// Mod(x, NaN) = NaN
+func Mod(x, y float64) float64 {
+ if haveArchMod {
+ return archMod(x, y)
+ }
+ return mod(x, y)
+}
+
+func mod(x, y float64) float64 {
+ if y == 0 || IsInf(x, 0) || IsNaN(x) || IsNaN(y) {
+ return NaN()
+ }
+ y = Abs(y)
+
+ yfr, yexp := Frexp(y)
+ r := x
+ if x < 0 {
+ r = -x
+ }
+
+ for r >= y {
+ rfr, rexp := Frexp(r)
+ if rfr < yfr {
+ rexp = rexp - 1
+ }
+ r = r - Ldexp(y, rexp-yexp)
+ }
+ if x < 0 {
+ r = -r
+ }
+ return r
+}
diff --git a/platform/dbops/binaries/go/go/src/math/modf.go b/platform/dbops/binaries/go/go/src/math/modf.go
new file mode 100644
index 0000000000000000000000000000000000000000..613a75fc9a6864d47902a57ed5663c78a8e5c5c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/modf.go
@@ -0,0 +1,43 @@
+// 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 math
+
+// Modf returns integer and fractional floating-point numbers
+// that sum to f. Both values have the same sign as f.
+//
+// Special cases are:
+//
+// Modf(±Inf) = ±Inf, NaN
+// Modf(NaN) = NaN, NaN
+func Modf(f float64) (int float64, frac float64) {
+ if haveArchModf {
+ return archModf(f)
+ }
+ return modf(f)
+}
+
+func modf(f float64) (int float64, frac float64) {
+ if f < 1 {
+ switch {
+ case f < 0:
+ int, frac = Modf(-f)
+ return -int, -frac
+ case f == 0:
+ return f, f // Return -0, -0 when f == -0
+ }
+ return 0, f
+ }
+
+ x := Float64bits(f)
+ e := uint(x>>shift)&mask - bias
+
+ // Keep the top 12+e bits, the integer part; clear the rest.
+ if e < 64-12 {
+ x &^= 1<<(64-12-e) - 1
+ }
+ int = Float64frombits(x)
+ frac = f - int
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/modf_arm64.s b/platform/dbops/binaries/go/go/src/math/modf_arm64.s
new file mode 100644
index 0000000000000000000000000000000000000000..1e4a329a4be78e93efeb382e3987e008c2e850cf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/modf_arm64.s
@@ -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.
+
+#include "textflag.h"
+
+// func archModf(f float64) (int float64, frac float64)
+TEXT ·archModf(SB),NOSPLIT,$0
+ MOVD f+0(FP), R0
+ FMOVD R0, F0
+ FRINTZD F0, F1
+ FMOVD F1, int+8(FP)
+ FSUBD F1, F0
+ FMOVD F0, R1
+ AND $(1<<63), R0
+ ORR R0, R1 // must have same sign
+ MOVD R1, frac+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/modf_asm.go b/platform/dbops/binaries/go/go/src/math/modf_asm.go
new file mode 100644
index 0000000000000000000000000000000000000000..c63be6cf361a5f4c6adfbfcbfdd9ee9a74f81965
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/modf_asm.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.
+
+//go:build arm64 || ppc64 || ppc64le
+
+package math
+
+const haveArchModf = true
+
+func archModf(f float64) (int float64, frac float64)
diff --git a/platform/dbops/binaries/go/go/src/math/modf_noasm.go b/platform/dbops/binaries/go/go/src/math/modf_noasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..55c6a7f6e20693d98502bbe70df51748806f586d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/modf_noasm.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.
+
+//go:build !arm64 && !ppc64 && !ppc64le
+
+package math
+
+const haveArchModf = false
+
+func archModf(f float64) (int float64, frac float64) {
+ panic("not implemented")
+}
diff --git a/platform/dbops/binaries/go/go/src/math/modf_ppc64x.s b/platform/dbops/binaries/go/go/src/math/modf_ppc64x.s
new file mode 100644
index 0000000000000000000000000000000000000000..410b523c0e815ca96aaf159f77969b288de89886
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/modf_ppc64x.s
@@ -0,0 +1,17 @@
+// 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 ppc64 || ppc64le
+
+#include "textflag.h"
+
+// func archModf(f float64) (int float64, frac float64)
+TEXT ·archModf(SB),NOSPLIT,$0
+ FMOVD f+0(FP), F0
+ FRIZ F0, F1
+ FMOVD F1, int+8(FP)
+ FSUB F1, F0, F2
+ FCPSGN F2, F0, F2
+ FMOVD F2, frac+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/nextafter.go b/platform/dbops/binaries/go/go/src/math/nextafter.go
new file mode 100644
index 0000000000000000000000000000000000000000..ec18d542d9c0371d0b69831971faa415ab0f216c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/nextafter.go
@@ -0,0 +1,51 @@
+// 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 math
+
+// Nextafter32 returns the next representable float32 value after x towards y.
+//
+// Special cases are:
+//
+// Nextafter32(x, x) = x
+// Nextafter32(NaN, y) = NaN
+// Nextafter32(x, NaN) = NaN
+func Nextafter32(x, y float32) (r float32) {
+ switch {
+ case IsNaN(float64(x)) || IsNaN(float64(y)): // special case
+ r = float32(NaN())
+ case x == y:
+ r = x
+ case x == 0:
+ r = float32(Copysign(float64(Float32frombits(1)), float64(y)))
+ case (y > x) == (x > 0):
+ r = Float32frombits(Float32bits(x) + 1)
+ default:
+ r = Float32frombits(Float32bits(x) - 1)
+ }
+ return
+}
+
+// Nextafter returns the next representable float64 value after x towards y.
+//
+// Special cases are:
+//
+// Nextafter(x, x) = x
+// Nextafter(NaN, y) = NaN
+// Nextafter(x, NaN) = NaN
+func Nextafter(x, y float64) (r float64) {
+ switch {
+ case IsNaN(x) || IsNaN(y): // special case
+ r = NaN()
+ case x == y:
+ r = x
+ case x == 0:
+ r = Copysign(Float64frombits(1), y)
+ case (y > x) == (x > 0):
+ r = Float64frombits(Float64bits(x) + 1)
+ default:
+ r = Float64frombits(Float64bits(x) - 1)
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/pow.go b/platform/dbops/binaries/go/go/src/math/pow.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f42945376d3fac2888d27cfe848ffecdf3abfdc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/pow.go
@@ -0,0 +1,166 @@
+// 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 math
+
+func isOddInt(x float64) bool {
+ if Abs(x) >= (1 << 53) {
+ // 1 << 53 is the largest exact integer in the float64 format.
+ // Any number outside this range will be truncated before the decimal point and therefore will always be
+ // an even integer.
+ // Without this check and if x overflows int64 the int64(xi) conversion below may produce incorrect results
+ // on some architectures (and does so on arm64). See issue #57465.
+ return false
+ }
+
+ xi, xf := Modf(x)
+ return xf == 0 && int64(xi)&1 == 1
+}
+
+// Special cases taken from FreeBSD's /usr/src/lib/msun/src/e_pow.c
+// updated by IEEE Std. 754-2008 "Section 9.2.1 Special values".
+
+// Pow returns x**y, the base-x exponential of y.
+//
+// Special cases are (in order):
+//
+// Pow(x, ±0) = 1 for any x
+// Pow(1, y) = 1 for any y
+// Pow(x, 1) = x for any x
+// Pow(NaN, y) = NaN
+// Pow(x, NaN) = NaN
+// Pow(±0, y) = ±Inf for y an odd integer < 0
+// Pow(±0, -Inf) = +Inf
+// Pow(±0, +Inf) = +0
+// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
+// Pow(±0, y) = ±0 for y an odd integer > 0
+// Pow(±0, y) = +0 for finite y > 0 and not an odd integer
+// Pow(-1, ±Inf) = 1
+// Pow(x, +Inf) = +Inf for |x| > 1
+// Pow(x, -Inf) = +0 for |x| > 1
+// Pow(x, +Inf) = +0 for |x| < 1
+// Pow(x, -Inf) = +Inf for |x| < 1
+// Pow(+Inf, y) = +Inf for y > 0
+// Pow(+Inf, y) = +0 for y < 0
+// Pow(-Inf, y) = Pow(-0, -y)
+// Pow(x, y) = NaN for finite x < 0 and finite non-integer y
+func Pow(x, y float64) float64 {
+ if haveArchPow {
+ return archPow(x, y)
+ }
+ return pow(x, y)
+}
+
+func pow(x, y float64) float64 {
+ switch {
+ case y == 0 || x == 1:
+ return 1
+ case y == 1:
+ return x
+ case IsNaN(x) || IsNaN(y):
+ return NaN()
+ case x == 0:
+ switch {
+ case y < 0:
+ if Signbit(x) && isOddInt(y) {
+ return Inf(-1)
+ }
+ return Inf(1)
+ case y > 0:
+ if Signbit(x) && isOddInt(y) {
+ return x
+ }
+ return 0
+ }
+ case IsInf(y, 0):
+ switch {
+ case x == -1:
+ return 1
+ case (Abs(x) < 1) == IsInf(y, 1):
+ return 0
+ default:
+ return Inf(1)
+ }
+ case IsInf(x, 0):
+ if IsInf(x, -1) {
+ return Pow(1/x, -y) // Pow(-0, -y)
+ }
+ switch {
+ case y < 0:
+ return 0
+ case y > 0:
+ return Inf(1)
+ }
+ case y == 0.5:
+ return Sqrt(x)
+ case y == -0.5:
+ return 1 / Sqrt(x)
+ }
+
+ yi, yf := Modf(Abs(y))
+ if yf != 0 && x < 0 {
+ return NaN()
+ }
+ if yi >= 1<<63 {
+ // yi is a large even int that will lead to overflow (or underflow to 0)
+ // for all x except -1 (x == 1 was handled earlier)
+ switch {
+ case x == -1:
+ return 1
+ case (Abs(x) < 1) == (y > 0):
+ return 0
+ default:
+ return Inf(1)
+ }
+ }
+
+ // ans = a1 * 2**ae (= 1 for now).
+ a1 := 1.0
+ ae := 0
+
+ // ans *= x**yf
+ if yf != 0 {
+ if yf > 0.5 {
+ yf--
+ yi++
+ }
+ a1 = Exp(yf * Log(x))
+ }
+
+ // ans *= x**yi
+ // by multiplying in successive squarings
+ // of x according to bits of yi.
+ // accumulate powers of two into exp.
+ x1, xe := Frexp(x)
+ for i := int64(yi); i != 0; i >>= 1 {
+ if xe < -1<<12 || 1<<12 < xe {
+ // catch xe before it overflows the left shift below
+ // Since i !=0 it has at least one bit still set, so ae will accumulate xe
+ // on at least one more iteration, ae += xe is a lower bound on ae
+ // the lower bound on ae exceeds the size of a float64 exp
+ // so the final call to Ldexp will produce under/overflow (0/Inf)
+ ae += xe
+ break
+ }
+ if i&1 == 1 {
+ a1 *= x1
+ ae += xe
+ }
+ x1 *= x1
+ xe <<= 1
+ if x1 < .5 {
+ x1 += x1
+ xe--
+ }
+ }
+
+ // ans = a1*2**ae
+ // if y < 0 { ans = 1 / ans }
+ // but in the opposite order
+ if y < 0 {
+ a1 = 1 / a1
+ ae = -ae
+ }
+ return Ldexp(a1, ae)
+}
diff --git a/platform/dbops/binaries/go/go/src/math/pow10.go b/platform/dbops/binaries/go/go/src/math/pow10.go
new file mode 100644
index 0000000000000000000000000000000000000000..c31ad8dbc778fe5dbd2a676645019b7ac0e91974
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/pow10.go
@@ -0,0 +1,47 @@
+// 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 math
+
+// pow10tab stores the pre-computed values 10**i for i < 32.
+var pow10tab = [...]float64{
+ 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09,
+ 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
+ 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29,
+ 1e30, 1e31,
+}
+
+// pow10postab32 stores the pre-computed value for 10**(i*32) at index i.
+var pow10postab32 = [...]float64{
+ 1e00, 1e32, 1e64, 1e96, 1e128, 1e160, 1e192, 1e224, 1e256, 1e288,
+}
+
+// pow10negtab32 stores the pre-computed value for 10**(-i*32) at index i.
+var pow10negtab32 = [...]float64{
+ 1e-00, 1e-32, 1e-64, 1e-96, 1e-128, 1e-160, 1e-192, 1e-224, 1e-256, 1e-288, 1e-320,
+}
+
+// Pow10 returns 10**n, the base-10 exponential of n.
+//
+// Special cases are:
+//
+// Pow10(n) = 0 for n < -323
+// Pow10(n) = +Inf for n > 308
+func Pow10(n int) float64 {
+ if 0 <= n && n <= 308 {
+ return pow10postab32[uint(n)/32] * pow10tab[uint(n)%32]
+ }
+
+ if -323 <= n && n <= 0 {
+ return pow10negtab32[uint(-n)/32] / pow10tab[uint(-n)%32]
+ }
+
+ // n < -323 || 308 < n
+ if n > 0 {
+ return Inf(1)
+ }
+
+ // n < -323
+ return 0
+}
diff --git a/platform/dbops/binaries/go/go/src/math/pow_s390x.s b/platform/dbops/binaries/go/go/src/math/pow_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..c8758fc5f8598f78ca21f558a912eb003dd5e704
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/pow_s390x.s
@@ -0,0 +1,634 @@
+// 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.
+
+#include "textflag.h"
+
+#define PosInf 0x7FF0000000000000
+#define NaN 0x7FF8000000000001
+#define NegInf 0xFFF0000000000000
+#define PosOne 0x3FF0000000000000
+#define NegOne 0xBFF0000000000000
+#define NegZero 0x8000000000000000
+
+// Minimax polynomial approximation
+DATA ·powrodataL51<> + 0(SB)/8, $-1.0
+DATA ·powrodataL51<> + 8(SB)/8, $1.0
+DATA ·powrodataL51<> + 16(SB)/8, $0.24022650695910110361E+00
+DATA ·powrodataL51<> + 24(SB)/8, $0.69314718055994686185E+00
+DATA ·powrodataL51<> + 32(SB)/8, $0.96181291057109484809E-02
+DATA ·powrodataL51<> + 40(SB)/8, $0.15403814778342868389E-03
+DATA ·powrodataL51<> + 48(SB)/8, $0.55504108652095235601E-01
+DATA ·powrodataL51<> + 56(SB)/8, $0.13333818813168698658E-02
+DATA ·powrodataL51<> + 64(SB)/8, $0.68205322933914439200E-12
+DATA ·powrodataL51<> + 72(SB)/8, $-.18466496523378731640E-01
+DATA ·powrodataL51<> + 80(SB)/8, $0.19697596291603973706E-02
+DATA ·powrodataL51<> + 88(SB)/8, $0.23083120654155209200E+00
+DATA ·powrodataL51<> + 96(SB)/8, $0.55324356012093416771E-06
+DATA ·powrodataL51<> + 104(SB)/8, $-.40340677224649339048E-05
+DATA ·powrodataL51<> + 112(SB)/8, $0.30255507904062541562E-04
+DATA ·powrodataL51<> + 120(SB)/8, $-.77453979912413008787E-07
+DATA ·powrodataL51<> + 128(SB)/8, $-.23637115549923464737E-03
+DATA ·powrodataL51<> + 136(SB)/8, $0.11016119077267717198E-07
+DATA ·powrodataL51<> + 144(SB)/8, $0.22608272174486123035E-09
+DATA ·powrodataL51<> + 152(SB)/8, $-.15895808101370190382E-08
+DATA ·powrodataL51<> + 160(SB)/8, $0x4540190000000000
+GLOBL ·powrodataL51<> + 0(SB), RODATA, $168
+
+// Constants
+DATA ·pow_x001a<> + 0(SB)/8, $0x1a000000000000
+GLOBL ·pow_x001a<> + 0(SB), RODATA, $8
+DATA ·pow_xinf<> + 0(SB)/8, $0x7ff0000000000000 //+Inf
+GLOBL ·pow_xinf<> + 0(SB), RODATA, $8
+DATA ·pow_xnan<> + 0(SB)/8, $0x7ff8000000000000 //NaN
+GLOBL ·pow_xnan<> + 0(SB), RODATA, $8
+DATA ·pow_x434<> + 0(SB)/8, $0x4340000000000000
+GLOBL ·pow_x434<> + 0(SB), RODATA, $8
+DATA ·pow_x433<> + 0(SB)/8, $0x4330000000000000
+GLOBL ·pow_x433<> + 0(SB), RODATA, $8
+DATA ·pow_x43f<> + 0(SB)/8, $0x43f0000000000000
+GLOBL ·pow_x43f<> + 0(SB), RODATA, $8
+DATA ·pow_xadd<> + 0(SB)/8, $0xc2f0000100003fef
+GLOBL ·pow_xadd<> + 0(SB), RODATA, $8
+DATA ·pow_xa<> + 0(SB)/8, $0x4019000000000000
+GLOBL ·pow_xa<> + 0(SB), RODATA, $8
+
+// Scale correction tables
+DATA powiadd<> + 0(SB)/8, $0xf000000000000000
+DATA powiadd<> + 8(SB)/8, $0x1000000000000000
+GLOBL powiadd<> + 0(SB), RODATA, $16
+DATA powxscale<> + 0(SB)/8, $0x4ff0000000000000
+DATA powxscale<> + 8(SB)/8, $0x2ff0000000000000
+GLOBL powxscale<> + 0(SB), RODATA, $16
+
+// Fractional powers of 2 table
+DATA ·powtexp<> + 0(SB)/8, $0.442737824274138381E-01
+DATA ·powtexp<> + 8(SB)/8, $0.263602189790660309E-01
+DATA ·powtexp<> + 16(SB)/8, $0.122565642281703586E-01
+DATA ·powtexp<> + 24(SB)/8, $0.143757052860721398E-02
+DATA ·powtexp<> + 32(SB)/8, $-.651375034121276075E-02
+DATA ·powtexp<> + 40(SB)/8, $-.119317678849450159E-01
+DATA ·powtexp<> + 48(SB)/8, $-.150868749549871069E-01
+DATA ·powtexp<> + 56(SB)/8, $-.161992609578469234E-01
+DATA ·powtexp<> + 64(SB)/8, $-.154492360403337917E-01
+DATA ·powtexp<> + 72(SB)/8, $-.129850717389178721E-01
+DATA ·powtexp<> + 80(SB)/8, $-.892902649276657891E-02
+DATA ·powtexp<> + 88(SB)/8, $-.338202636596794887E-02
+DATA ·powtexp<> + 96(SB)/8, $0.357266307045684762E-02
+DATA ·powtexp<> + 104(SB)/8, $0.118665304327406698E-01
+DATA ·powtexp<> + 112(SB)/8, $0.214434994118118914E-01
+DATA ·powtexp<> + 120(SB)/8, $0.322580645161290314E-01
+GLOBL ·powtexp<> + 0(SB), RODATA, $128
+
+// Log multiplier tables
+DATA ·powtl<> + 0(SB)/8, $0xbdf9723a80db6a05
+DATA ·powtl<> + 8(SB)/8, $0x3e0cfe4a0babe862
+DATA ·powtl<> + 16(SB)/8, $0xbe163b42dd33dada
+DATA ·powtl<> + 24(SB)/8, $0xbe0cdf9de2a8429c
+DATA ·powtl<> + 32(SB)/8, $0xbde9723a80db6a05
+DATA ·powtl<> + 40(SB)/8, $0xbdb37fcae081745e
+DATA ·powtl<> + 48(SB)/8, $0xbdd8b2f901ac662c
+DATA ·powtl<> + 56(SB)/8, $0xbde867dc68c36cc9
+DATA ·powtl<> + 64(SB)/8, $0xbdd23e36b47256b7
+DATA ·powtl<> + 72(SB)/8, $0xbde4c9b89fcc7933
+DATA ·powtl<> + 80(SB)/8, $0xbdd16905cad7cf66
+DATA ·powtl<> + 88(SB)/8, $0x3ddb417414aa5529
+DATA ·powtl<> + 96(SB)/8, $0xbdce046f2889983c
+DATA ·powtl<> + 104(SB)/8, $0x3dc2c3865d072897
+DATA ·powtl<> + 112(SB)/8, $0x8000000000000000
+DATA ·powtl<> + 120(SB)/8, $0x3dc1ca48817f8afe
+DATA ·powtl<> + 128(SB)/8, $0xbdd703518a88bfb7
+DATA ·powtl<> + 136(SB)/8, $0x3dc64afcc46942ce
+DATA ·powtl<> + 144(SB)/8, $0xbd9d79191389891a
+DATA ·powtl<> + 152(SB)/8, $0x3ddd563044da4fa0
+DATA ·powtl<> + 160(SB)/8, $0x3e0f42b5e5f8f4b6
+DATA ·powtl<> + 168(SB)/8, $0x3e0dfa2c2cbf6ead
+DATA ·powtl<> + 176(SB)/8, $0x3e14e25e91661293
+DATA ·powtl<> + 184(SB)/8, $0x3e0aac461509e20c
+GLOBL ·powtl<> + 0(SB), RODATA, $192
+
+DATA ·powtm<> + 0(SB)/8, $0x3da69e13
+DATA ·powtm<> + 8(SB)/8, $0x100003d66fcb6
+DATA ·powtm<> + 16(SB)/8, $0x200003d1538df
+DATA ·powtm<> + 24(SB)/8, $0x300003cab729e
+DATA ·powtm<> + 32(SB)/8, $0x400003c1a784c
+DATA ·powtm<> + 40(SB)/8, $0x500003ac9b074
+DATA ·powtm<> + 48(SB)/8, $0x60000bb498d22
+DATA ·powtm<> + 56(SB)/8, $0x68000bb8b29a2
+DATA ·powtm<> + 64(SB)/8, $0x70000bb9a32d4
+DATA ·powtm<> + 72(SB)/8, $0x74000bb9946bb
+DATA ·powtm<> + 80(SB)/8, $0x78000bb92e34b
+DATA ·powtm<> + 88(SB)/8, $0x80000bb6c57dc
+DATA ·powtm<> + 96(SB)/8, $0x84000bb4020f7
+DATA ·powtm<> + 104(SB)/8, $0x8c000ba93832d
+DATA ·powtm<> + 112(SB)/8, $0x9000080000000
+DATA ·powtm<> + 120(SB)/8, $0x940003aa66c4c
+DATA ·powtm<> + 128(SB)/8, $0x980003b2fb12a
+DATA ·powtm<> + 136(SB)/8, $0xa00003bc1def6
+DATA ·powtm<> + 144(SB)/8, $0xa80003c1eb0eb
+DATA ·powtm<> + 152(SB)/8, $0xb00003c64dcec
+DATA ·powtm<> + 160(SB)/8, $0xc00003cc49e4e
+DATA ·powtm<> + 168(SB)/8, $0xd00003d12f1de
+DATA ·powtm<> + 176(SB)/8, $0xe00003d4a9c6f
+DATA ·powtm<> + 184(SB)/8, $0xf00003d846c66
+GLOBL ·powtm<> + 0(SB), RODATA, $192
+
+// Table of indices into multiplier tables
+// Adjusted from asm to remove offset and convert
+DATA ·powtabi<> + 0(SB)/8, $0x1010101
+DATA ·powtabi<> + 8(SB)/8, $0x101020202020203
+DATA ·powtabi<> + 16(SB)/8, $0x303030404040405
+DATA ·powtabi<> + 24(SB)/8, $0x505050606060708
+DATA ·powtabi<> + 32(SB)/8, $0x90a0b0c0d0e0f10
+DATA ·powtabi<> + 40(SB)/8, $0x1011111212121313
+DATA ·powtabi<> + 48(SB)/8, $0x1314141414151515
+DATA ·powtabi<> + 56(SB)/8, $0x1516161617171717
+GLOBL ·powtabi<> + 0(SB), RODATA, $64
+
+// Pow returns x**y, the base-x exponential of y.
+//
+// Special cases are (in order):
+// Pow(x, ±0) = 1 for any x
+// Pow(1, y) = 1 for any y
+// Pow(x, 1) = x for any x
+// Pow(NaN, y) = NaN
+// Pow(x, NaN) = NaN
+// Pow(±0, y) = ±Inf for y an odd integer < 0
+// Pow(±0, -Inf) = +Inf
+// Pow(±0, +Inf) = +0
+// Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
+// Pow(±0, y) = ±0 for y an odd integer > 0
+// Pow(±0, y) = +0 for finite y > 0 and not an odd integer
+// Pow(-1, ±Inf) = 1
+// Pow(x, +Inf) = +Inf for |x| > 1
+// Pow(x, -Inf) = +0 for |x| > 1
+// Pow(x, +Inf) = +0 for |x| < 1
+// Pow(x, -Inf) = +Inf for |x| < 1
+// Pow(+Inf, y) = +Inf for y > 0
+// Pow(+Inf, y) = +0 for y < 0
+// Pow(-Inf, y) = Pow(-0, -y)
+// Pow(x, y) = NaN for finite x < 0 and finite non-integer y
+
+TEXT ·powAsm(SB), NOSPLIT, $0-24
+ // special case
+ MOVD x+0(FP), R1
+ MOVD y+8(FP), R2
+
+ // special case Pow(1, y) = 1 for any y
+ MOVD $PosOne, R3
+ CMPUBEQ R1, R3, xIsOne
+
+ // special case Pow(x, 1) = x for any x
+ MOVD $PosOne, R4
+ CMPUBEQ R2, R4, yIsOne
+
+ // special case Pow(x, NaN) = NaN for any x
+ MOVD $~(1<<63), R5
+ AND R2, R5 // y = |y|
+ MOVD $PosInf, R4
+ CMPUBLT R4, R5, yIsNan
+
+ MOVD $NegInf, R3
+ CMPUBEQ R1, R3, xIsNegInf
+
+ MOVD $NegOne, R3
+ CMPUBEQ R1, R3, xIsNegOne
+
+ MOVD $PosInf, R3
+ CMPUBEQ R1, R3, xIsPosInf
+
+ MOVD $NegZero, R3
+ CMPUBEQ R1, R3, xIsNegZero
+
+ MOVD $PosInf, R4
+ CMPUBEQ R2, R4, yIsPosInf
+
+ MOVD $0x0, R3
+ CMPUBEQ R1, R3, xIsPosZero
+ CMPBLT R1, R3, xLtZero
+ BR Normal
+xIsPosInf:
+ // special case Pow(+Inf, y) = +Inf for y > 0
+ MOVD $0x0, R4
+ CMPBGT R2, R4, posInfGeZero
+ BR Normal
+xIsNegInf:
+ //Pow(-Inf, y) = Pow(-0, -y)
+ FMOVD y+8(FP), F2
+ FNEG F2, F2 // y = -y
+ BR negZeroNegY // call Pow(-0, -y)
+xIsNegOne:
+ // special case Pow(-1, ±Inf) = 1
+ MOVD $PosInf, R4
+ CMPUBEQ R2, R4, negOnePosInf
+ MOVD $NegInf, R4
+ CMPUBEQ R2, R4, negOneNegInf
+ BR Normal
+xIsPosZero:
+ // special case Pow(+0, -Inf) = +Inf
+ MOVD $NegInf, R4
+ CMPUBEQ R2, R4, zeroNegInf
+
+ // special case Pow(+0, y < 0) = +Inf
+ FMOVD y+8(FP), F2
+ FMOVD $(0.0), F4
+ FCMPU F2, F4
+ BLT posZeroLtZero //y < 0.0
+ BR Normal
+xIsNegZero:
+ // special case Pow(-0, -Inf) = +Inf
+ MOVD $NegInf, R4
+ CMPUBEQ R2, R4, zeroNegInf
+ FMOVD y+8(FP), F2
+negZeroNegY:
+ // special case Pow(x, ±0) = 1 for any x
+ FMOVD $(0.0), F4
+ FCMPU F4, F2
+ BLT negZeroGtZero // y > 0.0
+ BEQ yIsZero // y = 0.0
+
+ FMOVD $(-0.0), F4
+ FCMPU F4, F2
+ BLT negZeroGtZero // y > -0.0
+ BEQ yIsZero // y = -0.0
+
+ // special case Pow(-0, y) = -Inf for y an odd integer < 0
+ // special case Pow(-0, y) = +Inf for finite y < 0 and not an odd integer
+ FIDBR $5, F2, F4 //F2 translate to integer F4
+ FCMPU F2, F4
+ BNE zeroNotOdd // y is not an (odd) integer and y < 0
+ FMOVD $(2.0), F4
+ FDIV F4, F2 // F2 = F2 / 2.0
+ FIDBR $5, F2, F4 //F2 translate to integer F4
+ FCMPU F2, F4
+ BNE negZeroOddInt // y is an odd integer and y < 0
+ BR zeroNotOdd // y is not an (odd) integer and y < 0
+
+negZeroGtZero:
+ // special case Pow(-0, y) = -0 for y an odd integer > 0
+ // special case Pow(±0, y) = +0 for finite y > 0 and not an odd integer
+ FIDBR $5, F2, F4 //F2 translate to integer F4
+ FCMPU F2, F4
+ BNE zeroNotOddGtZero // y is not an (odd) integer and y > 0
+ FMOVD $(2.0), F4
+ FDIV F4, F2 // F2 = F2 / 2.0
+ FIDBR $5, F2, F4 //F2 translate to integer F4
+ FCMPU F2, F4
+ BNE negZeroOddIntGtZero // y is an odd integer and y > 0
+ BR zeroNotOddGtZero // y is not an (odd) integer
+
+xLtZero:
+ // special case Pow(x, y) = NaN for finite x < 0 and finite non-integer y
+ FMOVD y+8(FP), F2
+ FIDBR $5, F2, F4
+ FCMPU F2, F4
+ BNE ltZeroInt
+ BR Normal
+yIsPosInf:
+ // special case Pow(x, +Inf) = +Inf for |x| > 1
+ FMOVD x+0(FP), F1
+ FMOVD $(1.0), F3
+ FCMPU F1, F3
+ BGT gtOnePosInf
+ FMOVD $(-1.0), F3
+ FCMPU F1, F3
+ BLT ltNegOnePosInf
+Normal:
+ FMOVD x+0(FP), F0
+ FMOVD y+8(FP), F2
+ MOVD $·powrodataL51<>+0(SB), R9
+ LGDR F0, R3
+ WORD $0xC0298009 //iilf %r2,2148095317
+ BYTE $0x55
+ BYTE $0x55
+ RISBGNZ $32, $63, $32, R3, R1
+ SUBW R1, R2
+ RISBGNZ $58, $63, $50, R2, R3
+ BYTE $0x18 //lr %r5,%r1
+ BYTE $0x51
+ MOVD $·powtabi<>+0(SB), R12
+ WORD $0xE303C000 //llgc %r0,0(%r3,%r12)
+ BYTE $0x00
+ BYTE $0x90
+ SUBW $0x1A0000, R5
+ SLD $3, R0, R3
+ MOVD $·powtm<>+0(SB), R4
+ MOVH $0x0, R8
+ ANDW $0x7FF00000, R2
+ ORW R5, R1
+ WORD $0x5A234000 //a %r2,0(%r3,%r4)
+ MOVD $0x3FF0000000000000, R5
+ RISBGZ $40, $63, $56, R2, R3
+ RISBGN $0, $31, $32, R2, R8
+ ORW $0x45000000, R3
+ MOVW R1, R6
+ CMPBLT R6, $0, L42
+ FMOVD F0, F4
+L2:
+ VLVGF $0, R3, V1
+ MOVD $·pow_xa<>+0(SB), R2
+ WORD $0xED3090A0 //lde %f3,.L52-.L51(%r9)
+ BYTE $0x00
+ BYTE $0x24
+ FMOVD 0(R2), F6
+ FSUBS F1, F3
+ LDGR R8, F1
+ WFMSDB V4, V1, V6, V4
+ FMOVD 152(R9), F6
+ WFMDB V4, V4, V7
+ FMOVD 144(R9), F1
+ FMOVD 136(R9), F5
+ WFMADB V4, V1, V6, V1
+ VLEG $0, 128(R9), V16
+ FMOVD 120(R9), F6
+ WFMADB V4, V5, V6, V5
+ FMOVD 112(R9), F6
+ WFMADB V1, V7, V5, V1
+ WFMADB V4, V6, V16, V16
+ SLD $3, R0, R2
+ FMOVD 104(R9), F5
+ WORD $0xED824004 //ldeb %f8,4(%r2,%r4)
+ BYTE $0x00
+ BYTE $0x04
+ LDEBR F3, F3
+ FMOVD 96(R9), F6
+ WFMADB V4, V6, V5, V6
+ FADD F8, F3
+ WFMADB V7, V6, V16, V6
+ FMUL F7, F7
+ FMOVD 88(R9), F5
+ FMADD F7, F1, F6
+ WFMADB V4, V5, V3, V16
+ FMOVD 80(R9), F1
+ WFSDB V16, V3, V3
+ MOVD $·powtl<>+0(SB), R3
+ WFMADB V4, V6, V1, V6
+ FMADD F5, F4, F3
+ FMOVD 72(R9), F1
+ WFMADB V4, V6, V1, V6
+ WORD $0xED323000 //adb %f3,0(%r2,%r3)
+ BYTE $0x00
+ BYTE $0x1A
+ FMOVD 64(R9), F1
+ WFMADB V4, V6, V1, V6
+ MOVD $·pow_xadd<>+0(SB), R2
+ WFMADB V4, V6, V3, V4
+ FMOVD 0(R2), F5
+ WFADB V4, V16, V3
+ VLEG $0, 56(R9), V20
+ WFMSDB V2, V3, V5, V3
+ VLEG $0, 48(R9), V18
+ WFADB V3, V5, V6
+ LGDR F3, R2
+ WFMSDB V2, V16, V6, V16
+ FMOVD 40(R9), F1
+ WFMADB V2, V4, V16, V4
+ FMOVD 32(R9), F7
+ WFMDB V4, V4, V3
+ WFMADB V4, V1, V20, V1
+ WFMADB V4, V7, V18, V7
+ VLEG $0, 24(R9), V16
+ WFMADB V1, V3, V7, V1
+ FMOVD 16(R9), F5
+ WFMADB V4, V5, V16, V5
+ RISBGZ $57, $60, $3, R2, R4
+ WFMADB V3, V1, V5, V1
+ MOVD $·powtexp<>+0(SB), R3
+ WORD $0x68343000 //ld %f3,0(%r4,%r3)
+ FMADD F3, F4, F4
+ RISBGN $0, $15, $48, R2, R5
+ WFMADB V4, V1, V3, V4
+ LGDR F6, R2
+ LDGR R5, F1
+ SRAD $48, R2, R2
+ FMADD F1, F4, F1
+ RLL $16, R2, R2
+ ANDW $0x7FFF0000, R2
+ WORD $0xC22B3F71 //alfi %r2,1064370176
+ BYTE $0x00
+ BYTE $0x00
+ ORW R2, R1, R3
+ MOVW R3, R6
+ CMPBLT R6, $0, L43
+L1:
+ FMOVD F1, ret+16(FP)
+ RET
+L43:
+ LTDBR F0, F0
+ BLTU L44
+ FMOVD F0, F3
+L7:
+ MOVD $·pow_xinf<>+0(SB), R3
+ FMOVD 0(R3), F5
+ WFCEDBS V3, V5, V7
+ BVS L8
+ WFMDB V3, V2, V6
+L8:
+ WFCEDBS V2, V2, V3
+ BVS L9
+ LTDBR F2, F2
+ BEQ L26
+ MOVW R1, R6
+ CMPBLT R6, $0, L45
+L11:
+ WORD $0xC0190003 //iilf %r1,262143
+ BYTE $0xFF
+ BYTE $0xFF
+ MOVW R2, R7
+ MOVW R1, R6
+ CMPBLE R7, R6, L34
+ RISBGNZ $32, $63, $32, R5, R1
+ LGDR F6, R2
+ MOVD $powiadd<>+0(SB), R3
+ RISBGZ $60, $60, $4, R2, R2
+ WORD $0x5A123000 //a %r1,0(%r2,%r3)
+ RISBGN $0, $31, $32, R1, R5
+ LDGR R5, F1
+ FMADD F1, F4, F1
+ MOVD $powxscale<>+0(SB), R1
+ WORD $0xED121000 //mdb %f1,0(%r2,%r1)
+ BYTE $0x00
+ BYTE $0x1C
+ BR L1
+L42:
+ LTDBR F0, F0
+ BLTU L46
+ FMOVD F0, F4
+L3:
+ MOVD $·pow_x001a<>+0(SB), R2
+ WORD $0xED402000 //cdb %f4,0(%r2)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L2
+ BVS L2
+ MOVD $·pow_x43f<>+0(SB), R2
+ WORD $0xED402000 //mdb %f4,0(%r2)
+ BYTE $0x00
+ BYTE $0x1C
+ WORD $0xC0298009 //iilf %r2,2148095317
+ BYTE $0x55
+ BYTE $0x55
+ LGDR F4, R3
+ RISBGNZ $32, $63, $32, R3, R3
+ SUBW R3, R2, R3
+ RISBGZ $33, $43, $0, R3, R2
+ RISBGNZ $58, $63, $50, R3, R3
+ WORD $0xE303C000 //llgc %r0,0(%r3,%r12)
+ BYTE $0x00
+ BYTE $0x90
+ SLD $3, R0, R3
+ WORD $0x5A234000 //a %r2,0(%r3,%r4)
+ BYTE $0x18 //lr %r3,%r2
+ BYTE $0x32
+ RISBGN $0, $31, $32, R3, R8
+ ADDW $0x4000000, R3
+ BLEU L5
+ RISBGZ $40, $63, $56, R3, R3
+ ORW $0x45000000, R3
+ BR L2
+L9:
+ WFCEDBS V0, V0, V4
+ BVS L35
+ FMOVD F2, F1
+ BR L1
+L46:
+ WORD $0xB3130040 //lcdbr %f4,%f0
+ BR L3
+L44:
+ WORD $0xB3130030 //lcdbr %f3,%f0
+ BR L7
+L35:
+ FMOVD F0, F1
+ BR L1
+L26:
+ FMOVD 8(R9), F1
+ BR L1
+L34:
+ FMOVD 8(R9), F4
+L19:
+ LTDBR F6, F6
+ BLEU L47
+L18:
+ WFMDB V4, V5, V1
+ BR L1
+L5:
+ RISBGZ $33, $50, $63, R3, R3
+ WORD $0xC23B4000 //alfi %r3,1073741824
+ BYTE $0x00
+ BYTE $0x00
+ RLL $24, R3, R3
+ ORW $0x45000000, R3
+ BR L2
+L45:
+ WFCEDBS V0, V0, V4
+ BVS L35
+ LTDBR F0, F0
+ BLEU L48
+ FMOVD 8(R9), F4
+L12:
+ MOVW R2, R6
+ CMPBLT R6, $0, L19
+ FMUL F4, F1
+ BR L1
+L47:
+ BLT L40
+ WFCEDBS V0, V0, V2
+ BVS L49
+L16:
+ MOVD ·pow_xnan<>+0(SB), R1
+ LDGR R1, F0
+ WFMDB V4, V0, V1
+ BR L1
+L48:
+ LGDR F0, R3
+ RISBGNZ $32, $63, $32, R3, R1
+ MOVW R1, R6
+ CMPBEQ R6, $0, L29
+ LTDBR F2, F2
+ BLTU L50
+ FMOVD F2, F4
+L14:
+ MOVD $·pow_x433<>+0(SB), R1
+ FMOVD 0(R1), F7
+ WFCHDBS V4, V7, V3
+ BEQ L15
+ WFADB V7, V4, V3
+ FSUB F7, F3
+ WFCEDBS V4, V3, V3
+ BEQ L15
+ LTDBR F0, F0
+ FMOVD 8(R9), F4
+ BNE L16
+L13:
+ LTDBR F2, F2
+ BLT L18
+L40:
+ FMOVD $0, F0
+ WFMDB V4, V0, V1
+ BR L1
+L49:
+ WFMDB V0, V4, V1
+ BR L1
+L29:
+ FMOVD 8(R9), F4
+ BR L13
+L15:
+ MOVD $·pow_x434<>+0(SB), R1
+ FMOVD 0(R1), F7
+ WFCHDBS V4, V7, V3
+ BEQ L32
+ WFADB V7, V4, V3
+ FSUB F7, F3
+ WFCEDBS V4, V3, V4
+ BEQ L32
+ FMOVD 0(R9), F4
+L17:
+ LTDBR F0, F0
+ BNE L12
+ BR L13
+L32:
+ FMOVD 8(R9), F4
+ BR L17
+L50:
+ WORD $0xB3130042 //lcdbr %f4,%f2
+ BR L14
+xIsOne: // Pow(1, y) = 1 for any y
+yIsOne: // Pow(x, 1) = x for any x
+posInfGeZero: // Pow(+Inf, y) = +Inf for y > 0
+ MOVD R1, ret+16(FP)
+ RET
+yIsNan: // Pow(NaN, y) = NaN
+ltZeroInt: // Pow(x, y) = NaN for finite x < 0 and finite non-integer y
+ MOVD $NaN, R2
+ MOVD R2, ret+16(FP)
+ RET
+negOnePosInf: // Pow(-1, ±Inf) = 1
+negOneNegInf:
+ MOVD $PosOne, R3
+ MOVD R3, ret+16(FP)
+ RET
+negZeroOddInt:
+ MOVD $NegInf, R3
+ MOVD R3, ret+16(FP)
+ RET
+zeroNotOdd: // Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
+posZeroLtZero: // special case Pow(+0, y < 0) = +Inf
+zeroNegInf: // Pow(±0, -Inf) = +Inf
+ MOVD $PosInf, R3
+ MOVD R3, ret+16(FP)
+ RET
+gtOnePosInf: //Pow(x, +Inf) = +Inf for |x| > 1
+ltNegOnePosInf:
+ MOVD R2, ret+16(FP)
+ RET
+yIsZero: //Pow(x, ±0) = 1 for any x
+ MOVD $PosOne, R4
+ MOVD R4, ret+16(FP)
+ RET
+negZeroOddIntGtZero: // Pow(-0, y) = -0 for y an odd integer > 0
+ MOVD $NegZero, R3
+ MOVD R3, ret+16(FP)
+ RET
+zeroNotOddGtZero: // Pow(±0, y) = +0 for finite y > 0 and not an odd integer
+ MOVD $0, ret+16(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/remainder.go b/platform/dbops/binaries/go/go/src/math/remainder.go
new file mode 100644
index 0000000000000000000000000000000000000000..8e99345c59b79733440ae789b1a3dc265fca6c25
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/remainder.go
@@ -0,0 +1,95 @@
+// 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 math
+
+// The original C code and the comment below are from
+// FreeBSD's /usr/src/lib/msun/src/e_remainder.c and came
+// with this notice. The go code is a simplified version of
+// the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_remainder(x,y)
+// Return :
+// returns x REM y = x - [x/y]*y as if in infinite
+// precision arithmetic, where [x/y] is the (infinite bit)
+// integer nearest x/y (in half way cases, choose the even one).
+// Method :
+// Based on Mod() returning x - [x/y]chopped * y exactly.
+
+// Remainder returns the IEEE 754 floating-point remainder of x/y.
+//
+// Special cases are:
+//
+// Remainder(±Inf, y) = NaN
+// Remainder(NaN, y) = NaN
+// Remainder(x, 0) = NaN
+// Remainder(x, ±Inf) = x
+// Remainder(x, NaN) = NaN
+func Remainder(x, y float64) float64 {
+ if haveArchRemainder {
+ return archRemainder(x, y)
+ }
+ return remainder(x, y)
+}
+
+func remainder(x, y float64) float64 {
+ const (
+ Tiny = 4.45014771701440276618e-308 // 0x0020000000000000
+ HalfMax = MaxFloat64 / 2
+ )
+ // special cases
+ switch {
+ case IsNaN(x) || IsNaN(y) || IsInf(x, 0) || y == 0:
+ return NaN()
+ case IsInf(y, 0):
+ return x
+ }
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ if y < 0 {
+ y = -y
+ }
+ if x == y {
+ if sign {
+ zero := 0.0
+ return -zero
+ }
+ return 0
+ }
+ if y <= HalfMax {
+ x = Mod(x, y+y) // now x < 2y
+ }
+ if y < Tiny {
+ if x+x > y {
+ x -= y
+ if x+x >= y {
+ x -= y
+ }
+ }
+ } else {
+ yHalf := 0.5 * y
+ if x > yHalf {
+ x -= y
+ if x >= yHalf {
+ x -= y
+ }
+ }
+ }
+ if sign {
+ x = -x
+ }
+ return x
+}
diff --git a/platform/dbops/binaries/go/go/src/math/signbit.go b/platform/dbops/binaries/go/go/src/math/signbit.go
new file mode 100644
index 0000000000000000000000000000000000000000..f6e61d660e27d9d8376ecb13c3fe8b535d0acc71
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/signbit.go
@@ -0,0 +1,10 @@
+// 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 math
+
+// Signbit reports whether x is negative or negative zero.
+func Signbit(x float64) bool {
+ return Float64bits(x)&(1<<63) != 0
+}
diff --git a/platform/dbops/binaries/go/go/src/math/sin.go b/platform/dbops/binaries/go/go/src/math/sin.go
new file mode 100644
index 0000000000000000000000000000000000000000..4793d7e7cd63da1f7eb9634aa6c76ba3328bca1d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sin.go
@@ -0,0 +1,244 @@
+// 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 math
+
+/*
+ Floating-point sine and cosine.
+*/
+
+// The original C code, the long comment, and the constants
+// below were from http://netlib.sandia.gov/cephes/cmath/sin.c,
+// available from http://www.netlib.org/cephes/cmath.tgz.
+// The go code is a simplified version of the original C.
+//
+// sin.c
+//
+// Circular sine
+//
+// SYNOPSIS:
+//
+// double x, y, sin();
+// y = sin( x );
+//
+// DESCRIPTION:
+//
+// Range reduction is into intervals of pi/4. The reduction error is nearly
+// eliminated by contriving an extended precision modular arithmetic.
+//
+// Two polynomial approximating functions are employed.
+// Between 0 and pi/4 the sine is approximated by
+// x + x**3 P(x**2).
+// Between pi/4 and pi/2 the cosine is represented as
+// 1 - x**2 Q(x**2).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// DEC 0, 10 150000 3.0e-17 7.8e-18
+// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17
+//
+// Partial loss of accuracy begins to occur at x = 2**30 = 1.074e9. The loss
+// is not gradual, but jumps suddenly to about 1 part in 10e7. Results may
+// be meaningless for x > 2**49 = 5.6e14.
+//
+// cos.c
+//
+// Circular cosine
+//
+// SYNOPSIS:
+//
+// double x, y, cos();
+// y = cos( x );
+//
+// DESCRIPTION:
+//
+// Range reduction is into intervals of pi/4. The reduction error is nearly
+// eliminated by contriving an extended precision modular arithmetic.
+//
+// Two polynomial approximating functions are employed.
+// Between 0 and pi/4 the cosine is approximated by
+// 1 - x**2 Q(x**2).
+// Between pi/4 and pi/2 the sine is represented as
+// x + x**3 P(x**2).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -1.07e9,+1.07e9 130000 2.1e-16 5.4e-17
+// DEC 0,+1.07e9 17000 3.0e-17 7.2e-18
+//
+// 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
+
+// sin coefficients
+var _sin = [...]float64{
+ 1.58962301576546568060e-10, // 0x3de5d8fd1fd19ccd
+ -2.50507477628578072866e-8, // 0xbe5ae5e5a9291f5d
+ 2.75573136213857245213e-6, // 0x3ec71de3567d48a1
+ -1.98412698295895385996e-4, // 0xbf2a01a019bfdf03
+ 8.33333333332211858878e-3, // 0x3f8111111110f7d0
+ -1.66666666666666307295e-1, // 0xbfc5555555555548
+}
+
+// cos coefficients
+var _cos = [...]float64{
+ -1.13585365213876817300e-11, // 0xbda8fa49a0861a9b
+ 2.08757008419747316778e-9, // 0x3e21ee9d7b4e3f05
+ -2.75573141792967388112e-7, // 0xbe927e4f7eac4bc6
+ 2.48015872888517045348e-5, // 0x3efa01a019c844f5
+ -1.38888888888730564116e-3, // 0xbf56c16c16c14f91
+ 4.16666666666665929218e-2, // 0x3fa555555555554b
+}
+
+// Cos returns the cosine of the radian argument x.
+//
+// Special cases are:
+//
+// Cos(±Inf) = NaN
+// Cos(NaN) = NaN
+func Cos(x float64) float64 {
+ if haveArchCos {
+ return archCos(x)
+ }
+ return cos(x)
+}
+
+func cos(x float64) float64 {
+ const (
+ PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts
+ PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000,
+ PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170,
+ )
+ // special cases
+ switch {
+ case IsNaN(x) || IsInf(x, 0):
+ return NaN()
+ }
+
+ // make argument positive
+ sign := false
+ x = Abs(x)
+
+ var j uint64
+ var y, z float64
+ if x >= reduceThreshold {
+ j, z = trigReduce(x)
+ } else {
+ j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle
+ y = float64(j) // integer part of x/(Pi/4), as float
+
+ // map zeros to origin
+ if j&1 == 1 {
+ j++
+ y++
+ }
+ j &= 7 // octant modulo 2Pi radians (360 degrees)
+ z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic
+ }
+
+ if j > 3 {
+ j -= 4
+ sign = !sign
+ }
+ if j > 1 {
+ sign = !sign
+ }
+
+ zz := z * z
+ if j == 1 || j == 2 {
+ y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5])
+ } else {
+ y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5])
+ }
+ if sign {
+ y = -y
+ }
+ return y
+}
+
+// Sin returns the sine of the radian argument x.
+//
+// Special cases are:
+//
+// Sin(±0) = ±0
+// Sin(±Inf) = NaN
+// Sin(NaN) = NaN
+func Sin(x float64) float64 {
+ if haveArchSin {
+ return archSin(x)
+ }
+ return sin(x)
+}
+
+func sin(x float64) float64 {
+ const (
+ PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts
+ PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000,
+ PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170,
+ )
+ // special cases
+ switch {
+ case x == 0 || IsNaN(x):
+ return x // return ±0 || NaN()
+ case IsInf(x, 0):
+ return NaN()
+ }
+
+ // make argument positive but save the sign
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+
+ var j uint64
+ var y, z float64
+ if x >= reduceThreshold {
+ j, z = trigReduce(x)
+ } else {
+ j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle
+ y = float64(j) // integer part of x/(Pi/4), as float
+
+ // map zeros to origin
+ if j&1 == 1 {
+ j++
+ y++
+ }
+ j &= 7 // octant modulo 2Pi radians (360 degrees)
+ z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic
+ }
+ // reflect in x axis
+ if j > 3 {
+ sign = !sign
+ j -= 4
+ }
+ zz := z * z
+ if j == 1 || j == 2 {
+ y = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5])
+ } else {
+ y = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5])
+ }
+ if sign {
+ y = -y
+ }
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/src/math/sin_s390x.s b/platform/dbops/binaries/go/go/src/math/sin_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..79d564b938ec2881296957e159c823f187a12f7b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sin_s390x.s
@@ -0,0 +1,369 @@
+// 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.
+
+#include "textflag.h"
+
+// Various constants
+DATA sincosxnan<>+0(SB)/8, $0x7ff8000000000000
+GLOBL sincosxnan<>+0(SB), RODATA, $8
+DATA sincosxlim<>+0(SB)/8, $0x432921fb54442d19
+GLOBL sincosxlim<>+0(SB), RODATA, $8
+DATA sincosxadd<>+0(SB)/8, $0xc338000000000000
+GLOBL sincosxadd<>+0(SB), RODATA, $8
+DATA sincosxpi2l<>+0(SB)/8, $0.108285667392191389e-31
+GLOBL sincosxpi2l<>+0(SB), RODATA, $8
+DATA sincosxpi2m<>+0(SB)/8, $0.612323399573676480e-16
+GLOBL sincosxpi2m<>+0(SB), RODATA, $8
+DATA sincosxpi2h<>+0(SB)/8, $0.157079632679489656e+01
+GLOBL sincosxpi2h<>+0(SB), RODATA, $8
+DATA sincosrpi2<>+0(SB)/8, $0.636619772367581341e+00
+GLOBL sincosrpi2<>+0(SB), RODATA, $8
+
+// Minimax polynomial approximations
+DATA sincosc0<>+0(SB)/8, $0.100000000000000000E+01
+GLOBL sincosc0<>+0(SB), RODATA, $8
+DATA sincosc1<>+0(SB)/8, $-.499999999999999833E+00
+GLOBL sincosc1<>+0(SB), RODATA, $8
+DATA sincosc2<>+0(SB)/8, $0.416666666666625843E-01
+GLOBL sincosc2<>+0(SB), RODATA, $8
+DATA sincosc3<>+0(SB)/8, $-.138888888885498984E-02
+GLOBL sincosc3<>+0(SB), RODATA, $8
+DATA sincosc4<>+0(SB)/8, $0.248015871681607202E-04
+GLOBL sincosc4<>+0(SB), RODATA, $8
+DATA sincosc5<>+0(SB)/8, $-.275572911309937875E-06
+GLOBL sincosc5<>+0(SB), RODATA, $8
+DATA sincosc6<>+0(SB)/8, $0.208735047247632818E-08
+GLOBL sincosc6<>+0(SB), RODATA, $8
+DATA sincosc7<>+0(SB)/8, $-.112753632738365317E-10
+GLOBL sincosc7<>+0(SB), RODATA, $8
+DATA sincoss0<>+0(SB)/8, $0.100000000000000000E+01
+GLOBL sincoss0<>+0(SB), RODATA, $8
+DATA sincoss1<>+0(SB)/8, $-.166666666666666657E+00
+GLOBL sincoss1<>+0(SB), RODATA, $8
+DATA sincoss2<>+0(SB)/8, $0.833333333333309209E-02
+GLOBL sincoss2<>+0(SB), RODATA, $8
+DATA sincoss3<>+0(SB)/8, $-.198412698410701448E-03
+GLOBL sincoss3<>+0(SB), RODATA, $8
+DATA sincoss4<>+0(SB)/8, $0.275573191453906794E-05
+GLOBL sincoss4<>+0(SB), RODATA, $8
+DATA sincoss5<>+0(SB)/8, $-.250520918387633290E-07
+GLOBL sincoss5<>+0(SB), RODATA, $8
+DATA sincoss6<>+0(SB)/8, $0.160571285514715856E-09
+GLOBL sincoss6<>+0(SB), RODATA, $8
+DATA sincoss7<>+0(SB)/8, $-.753213484933210972E-12
+GLOBL sincoss7<>+0(SB), RODATA, $8
+
+// Sin returns the sine of the radian argument x.
+//
+// Special cases are:
+// Sin(±0) = ±0
+// Sin(±Inf) = NaN
+// Sin(NaN) = NaN
+// The algorithm used is minimax polynomial approximation.
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·sinAsm(SB),NOSPLIT,$0-16
+ FMOVD x+0(FP), F0
+ //special case Sin(±0) = ±0
+ FMOVD $(0.0), F1
+ FCMPU F0, F1
+ BEQ sinIsZero
+ LTDBR F0, F0
+ BLTU L17
+ FMOVD F0, F5
+L2:
+ MOVD $sincosxlim<>+0(SB), R1
+ FMOVD 0(R1), F1
+ FCMPU F5, F1
+ BGT L16
+ MOVD $sincoss7<>+0(SB), R1
+ FMOVD 0(R1), F4
+ MOVD $sincoss6<>+0(SB), R1
+ FMOVD 0(R1), F1
+ MOVD $sincoss5<>+0(SB), R1
+ VLEG $0, 0(R1), V18
+ MOVD $sincoss4<>+0(SB), R1
+ FMOVD 0(R1), F6
+ MOVD $sincoss2<>+0(SB), R1
+ VLEG $0, 0(R1), V16
+ MOVD $sincoss3<>+0(SB), R1
+ FMOVD 0(R1), F7
+ MOVD $sincoss1<>+0(SB), R1
+ FMOVD 0(R1), F3
+ MOVD $sincoss0<>+0(SB), R1
+ FMOVD 0(R1), F2
+ WFCHDBS V2, V5, V2
+ BEQ L18
+ MOVD $sincosrpi2<>+0(SB), R1
+ FMOVD 0(R1), F3
+ MOVD $sincosxadd<>+0(SB), R1
+ FMOVD 0(R1), F2
+ WFMSDB V0, V3, V2, V3
+ FMOVD 0(R1), F6
+ FADD F3, F6
+ MOVD $sincosxpi2h<>+0(SB), R1
+ FMOVD 0(R1), F2
+ FMSUB F2, F6, F0
+ MOVD $sincosxpi2m<>+0(SB), R1
+ FMOVD 0(R1), F4
+ FMADD F4, F6, F0
+ MOVD $sincosxpi2l<>+0(SB), R1
+ WFMDB V0, V0, V1
+ FMOVD 0(R1), F7
+ WFMDB V1, V1, V2
+ LGDR F3, R1
+ MOVD $sincosxlim<>+0(SB), R2
+ TMLL R1, $1
+ BEQ L6
+ FMOVD 0(R2), F0
+ WFCHDBS V0, V5, V0
+ BNE L14
+ MOVD $sincosc7<>+0(SB), R2
+ FMOVD 0(R2), F0
+ MOVD $sincosc6<>+0(SB), R2
+ FMOVD 0(R2), F4
+ MOVD $sincosc5<>+0(SB), R2
+ WFMADB V1, V0, V4, V0
+ FMOVD 0(R2), F6
+ MOVD $sincosc4<>+0(SB), R2
+ WFMADB V1, V0, V6, V0
+ FMOVD 0(R2), F4
+ MOVD $sincosc2<>+0(SB), R2
+ FMOVD 0(R2), F6
+ WFMADB V2, V4, V6, V4
+ MOVD $sincosc3<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $sincosc1<>+0(SB), R2
+ WFMADB V2, V0, V3, V0
+ FMOVD 0(R2), F6
+ WFMADB V1, V4, V6, V4
+ TMLL R1, $2
+ WFMADB V2, V0, V4, V0
+ MOVD $sincosc0<>+0(SB), R1
+ FMOVD 0(R1), F2
+ WFMADB V1, V0, V2, V0
+ BNE L15
+ FMOVD F0, ret+8(FP)
+ RET
+
+L6:
+ FMOVD 0(R2), F4
+ WFCHDBS V4, V5, V4
+ BNE L14
+ MOVD $sincoss7<>+0(SB), R2
+ FMOVD 0(R2), F4
+ MOVD $sincoss6<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $sincoss5<>+0(SB), R2
+ WFMADB V1, V4, V3, V4
+ WFMADB V6, V7, V0, V6
+ FMOVD 0(R2), F0
+ MOVD $sincoss4<>+0(SB), R2
+ FMADD F4, F1, F0
+ FMOVD 0(R2), F3
+ MOVD $sincoss2<>+0(SB), R2
+ FMOVD 0(R2), F4
+ MOVD $sincoss3<>+0(SB), R2
+ WFMADB V2, V3, V4, V3
+ FMOVD 0(R2), F4
+ MOVD $sincoss1<>+0(SB), R2
+ WFMADB V2, V0, V4, V0
+ FMOVD 0(R2), F4
+ WFMADB V1, V3, V4, V3
+ FNEG F6, F4
+ WFMADB V2, V0, V3, V2
+ WFMDB V4, V1, V0
+ TMLL R1, $2
+ WFMSDB V0, V2, V6, V0
+ BNE L15
+ FMOVD F0, ret+8(FP)
+ RET
+
+L14:
+ MOVD $sincosxnan<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L18:
+ WFMDB V0, V0, V2
+ WFMADB V2, V4, V1, V4
+ WFMDB V2, V2, V1
+ WFMADB V2, V4, V18, V4
+ WFMADB V1, V6, V16, V6
+ WFMADB V1, V4, V7, V4
+ WFMADB V2, V6, V3, V6
+ FMUL F0, F2
+ WFMADB V1, V4, V6, V4
+ FMADD F4, F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L17:
+ FNEG F0, F5
+ BR L2
+L15:
+ FNEG F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+
+L16:
+ BR ·sin(SB) //tail call
+sinIsZero:
+ FMOVD F0, ret+8(FP)
+ RET
+
+// Cos returns the cosine of the radian argument.
+//
+// Special cases are:
+// Cos(±Inf) = NaN
+// Cos(NaN) = NaN
+// The algorithm used is minimax polynomial approximation.
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·cosAsm(SB),NOSPLIT,$0-16
+ FMOVD x+0(FP), F0
+ LTDBR F0, F0
+ BLTU L35
+ FMOVD F0, F1
+L21:
+ MOVD $sincosxlim<>+0(SB), R1
+ FMOVD 0(R1), F2
+ FCMPU F1, F2
+ BGT L30
+ MOVD $sincosc7<>+0(SB), R1
+ FMOVD 0(R1), F4
+ MOVD $sincosc6<>+0(SB), R1
+ VLEG $0, 0(R1), V20
+ MOVD $sincosc5<>+0(SB), R1
+ VLEG $0, 0(R1), V18
+ MOVD $sincosc4<>+0(SB), R1
+ FMOVD 0(R1), F6
+ MOVD $sincosc2<>+0(SB), R1
+ VLEG $0, 0(R1), V16
+ MOVD $sincosc3<>+0(SB), R1
+ FMOVD 0(R1), F7
+ MOVD $sincosc1<>+0(SB), R1
+ FMOVD 0(R1), F5
+ MOVD $sincosrpi2<>+0(SB), R1
+ FMOVD 0(R1), F2
+ MOVD $sincosxadd<>+0(SB), R1
+ FMOVD 0(R1), F3
+ MOVD $sincoss0<>+0(SB), R1
+ WFMSDB V0, V2, V3, V2
+ FMOVD 0(R1), F3
+ WFCHDBS V3, V1, V3
+ LGDR F2, R1
+ BEQ L36
+ MOVD $sincosxadd<>+0(SB), R2
+ FMOVD 0(R2), F4
+ FADD F2, F4
+ MOVD $sincosxpi2h<>+0(SB), R2
+ FMOVD 0(R2), F2
+ WFMSDB V4, V2, V0, V2
+ MOVD $sincosxpi2m<>+0(SB), R2
+ FMOVD 0(R2), F0
+ WFMADB V4, V0, V2, V0
+ MOVD $sincosxpi2l<>+0(SB), R2
+ WFMDB V0, V0, V2
+ FMOVD 0(R2), F5
+ WFMDB V2, V2, V6
+ MOVD $sincosxlim<>+0(SB), R2
+ TMLL R1, $1
+ BNE L25
+ FMOVD 0(R2), F0
+ WFCHDBS V0, V1, V0
+ BNE L33
+ MOVD $sincosc7<>+0(SB), R2
+ FMOVD 0(R2), F0
+ MOVD $sincosc6<>+0(SB), R2
+ FMOVD 0(R2), F4
+ MOVD $sincosc5<>+0(SB), R2
+ WFMADB V2, V0, V4, V0
+ FMOVD 0(R2), F1
+ MOVD $sincosc4<>+0(SB), R2
+ WFMADB V2, V0, V1, V0
+ FMOVD 0(R2), F4
+ MOVD $sincosc2<>+0(SB), R2
+ FMOVD 0(R2), F1
+ WFMADB V6, V4, V1, V4
+ MOVD $sincosc3<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $sincosc1<>+0(SB), R2
+ WFMADB V6, V0, V3, V0
+ FMOVD 0(R2), F1
+ WFMADB V2, V4, V1, V4
+ TMLL R1, $2
+ WFMADB V6, V0, V4, V0
+ MOVD $sincosc0<>+0(SB), R1
+ FMOVD 0(R1), F4
+ WFMADB V2, V0, V4, V0
+ BNE L34
+ FMOVD F0, ret+8(FP)
+ RET
+
+L25:
+ FMOVD 0(R2), F3
+ WFCHDBS V3, V1, V1
+ BNE L33
+ MOVD $sincoss7<>+0(SB), R2
+ FMOVD 0(R2), F1
+ MOVD $sincoss6<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $sincoss5<>+0(SB), R2
+ WFMADB V2, V1, V3, V1
+ FMOVD 0(R2), F3
+ MOVD $sincoss4<>+0(SB), R2
+ WFMADB V2, V1, V3, V1
+ FMOVD 0(R2), F3
+ MOVD $sincoss2<>+0(SB), R2
+ FMOVD 0(R2), F7
+ WFMADB V6, V3, V7, V3
+ MOVD $sincoss3<>+0(SB), R2
+ FMADD F5, F4, F0
+ FMOVD 0(R2), F4
+ MOVD $sincoss1<>+0(SB), R2
+ FMADD F1, F6, F4
+ FMOVD 0(R2), F1
+ FMADD F3, F2, F1
+ FMUL F0, F2
+ WFMADB V6, V4, V1, V6
+ TMLL R1, $2
+ FMADD F6, F2, F0
+ BNE L34
+ FMOVD F0, ret+8(FP)
+ RET
+
+L33:
+ MOVD $sincosxnan<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L36:
+ FMUL F0, F0
+ MOVD $sincosc0<>+0(SB), R1
+ WFMDB V0, V0, V1
+ WFMADB V0, V4, V20, V4
+ WFMADB V1, V6, V16, V6
+ WFMADB V0, V4, V18, V4
+ WFMADB V0, V6, V5, V6
+ WFMADB V1, V4, V7, V4
+ FMOVD 0(R1), F2
+ WFMADB V1, V4, V6, V4
+ WFMADB V0, V4, V2, V0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L35:
+ FNEG F0, F1
+ BR L21
+L34:
+ FNEG F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L30:
+ BR ·cos(SB) //tail call
diff --git a/platform/dbops/binaries/go/go/src/math/sincos.go b/platform/dbops/binaries/go/go/src/math/sincos.go
new file mode 100644
index 0000000000000000000000000000000000000000..e3fb96094fa75f33727cd676bb937b17233707d9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sincos.go
@@ -0,0 +1,73 @@
+// 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 math
+
+// Coefficients _sin[] and _cos[] are found in pkg/math/sin.go.
+
+// Sincos returns Sin(x), Cos(x).
+//
+// Special cases are:
+//
+// Sincos(±0) = ±0, 1
+// Sincos(±Inf) = NaN, NaN
+// Sincos(NaN) = NaN, NaN
+func Sincos(x float64) (sin, cos float64) {
+ const (
+ PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts
+ PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000,
+ PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170,
+ )
+ // special cases
+ switch {
+ case x == 0:
+ return x, 1 // return ±0.0, 1.0
+ case IsNaN(x) || IsInf(x, 0):
+ return NaN(), NaN()
+ }
+
+ // make argument positive
+ sinSign, cosSign := false, false
+ if x < 0 {
+ x = -x
+ sinSign = true
+ }
+
+ var j uint64
+ var y, z float64
+ if x >= reduceThreshold {
+ j, z = trigReduce(x)
+ } else {
+ j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle
+ y = float64(j) // integer part of x/(Pi/4), as float
+
+ if j&1 == 1 { // map zeros to origin
+ j++
+ y++
+ }
+ j &= 7 // octant modulo 2Pi radians (360 degrees)
+ z = ((x - y*PI4A) - y*PI4B) - y*PI4C // Extended precision modular arithmetic
+ }
+ if j > 3 { // reflect in x axis
+ j -= 4
+ sinSign, cosSign = !sinSign, !cosSign
+ }
+ if j > 1 {
+ cosSign = !cosSign
+ }
+
+ zz := z * z
+ cos = 1.0 - 0.5*zz + zz*zz*((((((_cos[0]*zz)+_cos[1])*zz+_cos[2])*zz+_cos[3])*zz+_cos[4])*zz+_cos[5])
+ sin = z + z*zz*((((((_sin[0]*zz)+_sin[1])*zz+_sin[2])*zz+_sin[3])*zz+_sin[4])*zz+_sin[5])
+ if j == 1 || j == 2 {
+ sin, cos = cos, sin
+ }
+ if cosSign {
+ cos = -cos
+ }
+ if sinSign {
+ sin = -sin
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/math/sinh.go b/platform/dbops/binaries/go/go/src/math/sinh.go
new file mode 100644
index 0000000000000000000000000000000000000000..78b3c299d668931fb0289328a99b0ab5ce29f723
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sinh.go
@@ -0,0 +1,93 @@
+// 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 math
+
+/*
+ Floating-point hyperbolic sine and cosine.
+
+ The exponential func is called for arguments
+ greater in magnitude than 0.5.
+
+ A series is used for arguments smaller in magnitude than 0.5.
+
+ Cosh(x) is computed from the exponential func for
+ all arguments.
+*/
+
+// Sinh returns the hyperbolic sine of x.
+//
+// Special cases are:
+//
+// Sinh(±0) = ±0
+// Sinh(±Inf) = ±Inf
+// Sinh(NaN) = NaN
+func Sinh(x float64) float64 {
+ if haveArchSinh {
+ return archSinh(x)
+ }
+ return sinh(x)
+}
+
+func sinh(x float64) float64 {
+ // The coefficients are #2029 from Hart & Cheney. (20.36D)
+ const (
+ P0 = -0.6307673640497716991184787251e+6
+ P1 = -0.8991272022039509355398013511e+5
+ P2 = -0.2894211355989563807284660366e+4
+ P3 = -0.2630563213397497062819489e+2
+ Q0 = -0.6307673640497716991212077277e+6
+ Q1 = 0.1521517378790019070696485176e+5
+ Q2 = -0.173678953558233699533450911e+3
+ )
+
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+
+ var temp float64
+ switch {
+ case x > 21:
+ temp = Exp(x) * 0.5
+
+ case x > 0.5:
+ ex := Exp(x)
+ temp = (ex - 1/ex) * 0.5
+
+ default:
+ sq := x * x
+ temp = (((P3*sq+P2)*sq+P1)*sq + P0) * x
+ temp = temp / (((sq+Q2)*sq+Q1)*sq + Q0)
+ }
+
+ if sign {
+ temp = -temp
+ }
+ return temp
+}
+
+// Cosh returns the hyperbolic cosine of x.
+//
+// Special cases are:
+//
+// Cosh(±0) = 1
+// Cosh(±Inf) = +Inf
+// Cosh(NaN) = NaN
+func Cosh(x float64) float64 {
+ if haveArchCosh {
+ return archCosh(x)
+ }
+ return cosh(x)
+}
+
+func cosh(x float64) float64 {
+ x = Abs(x)
+ if x > 21 {
+ return Exp(x) * 0.5
+ }
+ ex := Exp(x)
+ return (ex + 1/ex) * 0.5
+}
diff --git a/platform/dbops/binaries/go/go/src/math/sinh_s390x.s b/platform/dbops/binaries/go/go/src/math/sinh_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..d684968a3a87e684c80d166369fc3dc229a1186c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sinh_s390x.s
@@ -0,0 +1,251 @@
+// 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.
+
+
+#include "textflag.h"
+
+// Constants
+DATA sinhrodataL21<>+0(SB)/8, $0.231904681384629956E-16
+DATA sinhrodataL21<>+8(SB)/8, $0.693147180559945286E+00
+DATA sinhrodataL21<>+16(SB)/8, $704.E0
+GLOBL sinhrodataL21<>+0(SB), RODATA, $24
+DATA sinhrlog2<>+0(SB)/8, $0x3ff7154760000000
+GLOBL sinhrlog2<>+0(SB), RODATA, $8
+DATA sinhxinf<>+0(SB)/8, $0x7ff0000000000000
+GLOBL sinhxinf<>+0(SB), RODATA, $8
+DATA sinhxinit<>+0(SB)/8, $0x3ffb504f333f9de6
+GLOBL sinhxinit<>+0(SB), RODATA, $8
+DATA sinhxlim1<>+0(SB)/8, $800.E0
+GLOBL sinhxlim1<>+0(SB), RODATA, $8
+DATA sinhxadd<>+0(SB)/8, $0xc3200001610007fb
+GLOBL sinhxadd<>+0(SB), RODATA, $8
+DATA sinhx4ff<>+0(SB)/8, $0x4ff0000000000000
+GLOBL sinhx4ff<>+0(SB), RODATA, $8
+
+// Minimax polynomial approximations
+DATA sinhe0<>+0(SB)/8, $0.11715728752538099300E+01
+GLOBL sinhe0<>+0(SB), RODATA, $8
+DATA sinhe1<>+0(SB)/8, $0.11715728752538099300E+01
+GLOBL sinhe1<>+0(SB), RODATA, $8
+DATA sinhe2<>+0(SB)/8, $0.58578643762688526692E+00
+GLOBL sinhe2<>+0(SB), RODATA, $8
+DATA sinhe3<>+0(SB)/8, $0.19526214587563004497E+00
+GLOBL sinhe3<>+0(SB), RODATA, $8
+DATA sinhe4<>+0(SB)/8, $0.48815536475176217404E-01
+GLOBL sinhe4<>+0(SB), RODATA, $8
+DATA sinhe5<>+0(SB)/8, $0.97631072948627397816E-02
+GLOBL sinhe5<>+0(SB), RODATA, $8
+DATA sinhe6<>+0(SB)/8, $0.16271839297756073153E-02
+GLOBL sinhe6<>+0(SB), RODATA, $8
+DATA sinhe7<>+0(SB)/8, $0.23245485387271142509E-03
+GLOBL sinhe7<>+0(SB), RODATA, $8
+DATA sinhe8<>+0(SB)/8, $0.29080955860869629131E-04
+GLOBL sinhe8<>+0(SB), RODATA, $8
+DATA sinhe9<>+0(SB)/8, $0.32311267157667725278E-05
+GLOBL sinhe9<>+0(SB), RODATA, $8
+
+// Sinh returns the hyperbolic sine of the argument.
+//
+// Special cases are:
+// Sinh(±0) = ±0
+// Sinh(±Inf) = ±Inf
+// Sinh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation
+// with coefficients determined with a Remez exchange algorithm.
+
+TEXT ·sinhAsm(SB),NOSPLIT,$0-16
+ FMOVD x+0(FP), F0
+ //special case Sinh(±0) = ±0
+ FMOVD $(0.0), F1
+ FCMPU F0, F1
+ BEQ sinhIsZero
+ //special case Sinh(±Inf) = ±Inf
+ FMOVD $1.797693134862315708145274237317043567981e+308, F1
+ FCMPU F1, F0
+ BLEU sinhIsInf
+ FMOVD $-1.797693134862315708145274237317043567981e+308, F1
+ FCMPU F1, F0
+ BGT sinhIsInf
+
+ MOVD $sinhrodataL21<>+0(SB), R5
+ LTDBR F0, F0
+ MOVD sinhxinit<>+0(SB), R1
+ FMOVD F0, F4
+ MOVD R1, R3
+ BLTU L19
+ FMOVD F0, F2
+L2:
+ WORD $0xED205010 //cdb %f2,.L22-.L21(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ BGE L15 //jnl .L15
+ BVS L15
+ WFCEDBS V2, V2, V0
+ BEQ L20
+L12:
+ FMOVD F4, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L15:
+ WFCEDBS V2, V2, V0
+ BVS L12
+ MOVD $sinhxlim1<>+0(SB), R2
+ FMOVD 0(R2), F0
+ WFCHDBS V0, V2, V0
+ BEQ L6
+ WFCHEDBS V4, V2, V6
+ MOVD $sinhxinf<>+0(SB), R1
+ FMOVD 0(R1), F0
+ BNE LEXITTAGsinh
+ WFCHDBS V2, V4, V2
+ BNE L16
+ FNEG F0, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L19:
+ FNEG F0, F2
+ BR L2
+L6:
+ MOVD $sinhxadd<>+0(SB), R2
+ FMOVD 0(R2), F0
+ MOVD sinhrlog2<>+0(SB), R2
+ LDGR R2, F6
+ WFMSDB V4, V6, V0, V16
+ FMOVD sinhrodataL21<>+8(SB), F6
+ WFADB V0, V16, V0
+ FMOVD sinhrodataL21<>+0(SB), F3
+ WFMSDB V0, V6, V4, V6
+ MOVD $sinhe9<>+0(SB), R2
+ WFMADB V0, V3, V6, V0
+ FMOVD 0(R2), F1
+ MOVD $sinhe7<>+0(SB), R2
+ WFMDB V0, V0, V6
+ FMOVD 0(R2), F5
+ MOVD $sinhe8<>+0(SB), R2
+ FMOVD 0(R2), F3
+ MOVD $sinhe6<>+0(SB), R2
+ WFMADB V6, V1, V5, V1
+ FMOVD 0(R2), F5
+ MOVD $sinhe5<>+0(SB), R2
+ FMOVD 0(R2), F7
+ MOVD $sinhe3<>+0(SB), R2
+ WFMADB V6, V3, V5, V3
+ FMOVD 0(R2), F5
+ MOVD $sinhe4<>+0(SB), R2
+ WFMADB V6, V7, V5, V7
+ FMOVD 0(R2), F5
+ MOVD $sinhe2<>+0(SB), R2
+ VLEG $0, 0(R2), V20
+ WFMDB V6, V6, V18
+ WFMADB V6, V5, V20, V5
+ WFMADB V1, V18, V7, V1
+ FNEG F0, F0
+ WFMADB V3, V18, V5, V3
+ MOVD $sinhe1<>+0(SB), R3
+ WFCEDBS V2, V4, V2
+ FMOVD 0(R3), F5
+ MOVD $sinhe0<>+0(SB), R3
+ WFMADB V6, V1, V5, V1
+ FMOVD 0(R3), F5
+ VLGVG $0, V16, R2
+ WFMADB V6, V3, V5, V6
+ RLL $3, R2, R2
+ RISBGN $0, $15, $48, R2, R1
+ BEQ L9
+ WFMSDB V0, V1, V6, V0
+ MOVD $sinhx4ff<>+0(SB), R3
+ FNEG F0, F0
+ FMOVD 0(R3), F2
+ FMUL F2, F0
+ ANDW $0xFFFF, R2
+ WORD $0xA53FEFB6 //llill %r3,61366
+ SUBW R2, R3, R2
+ RISBGN $0, $15, $48, R2, R1
+ LDGR R1, F2
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L20:
+ MOVD $sinhxadd<>+0(SB), R2
+ FMOVD 0(R2), F2
+ MOVD sinhrlog2<>+0(SB), R2
+ LDGR R2, F0
+ WFMSDB V4, V0, V2, V6
+ FMOVD sinhrodataL21<>+8(SB), F0
+ FADD F6, F2
+ MOVD $sinhe9<>+0(SB), R2
+ FMSUB F0, F2, F4
+ FMOVD 0(R2), F1
+ FMOVD sinhrodataL21<>+0(SB), F3
+ MOVD $sinhe7<>+0(SB), R2
+ FMADD F3, F2, F4
+ FMOVD 0(R2), F0
+ MOVD $sinhe8<>+0(SB), R2
+ WFMDB V4, V4, V2
+ FMOVD 0(R2), F3
+ MOVD $sinhe6<>+0(SB), R2
+ FMOVD 0(R2), F5
+ LGDR F6, R2
+ RLL $3, R2, R2
+ RISBGN $0, $15, $48, R2, R1
+ WFMADB V2, V1, V0, V1
+ LDGR R1, F0
+ MOVD $sinhe5<>+0(SB), R1
+ WFMADB V2, V3, V5, V3
+ FMOVD 0(R1), F5
+ MOVD $sinhe3<>+0(SB), R1
+ FMOVD 0(R1), F6
+ WFMDB V2, V2, V7
+ WFMADB V2, V5, V6, V5
+ WORD $0xA7487FB6 //lhi %r4,32694
+ FNEG F4, F4
+ ANDW $0xFFFF, R2
+ SUBW R2, R4, R2
+ RISBGN $0, $15, $48, R2, R3
+ LDGR R3, F6
+ WFADB V0, V6, V16
+ MOVD $sinhe4<>+0(SB), R1
+ WFMADB V1, V7, V5, V1
+ WFMDB V4, V16, V4
+ FMOVD 0(R1), F5
+ MOVD $sinhe2<>+0(SB), R1
+ VLEG $0, 0(R1), V16
+ MOVD $sinhe1<>+0(SB), R1
+ WFMADB V2, V5, V16, V5
+ VLEG $0, 0(R1), V16
+ WFMADB V3, V7, V5, V3
+ WFMADB V2, V1, V16, V1
+ FSUB F6, F0
+ FMUL F1, F4
+ MOVD $sinhe0<>+0(SB), R1
+ FMOVD 0(R1), F6
+ WFMADB V2, V3, V6, V2
+ WFMADB V0, V2, V4, V0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L9:
+ WFMADB V0, V1, V6, V0
+ MOVD $sinhx4ff<>+0(SB), R3
+ FMOVD 0(R3), F2
+ FMUL F2, F0
+ WORD $0xA72AF000 //ahi %r2,-4096
+ RISBGN $0, $15, $48, R2, R1
+ LDGR R1, F2
+ FMUL F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L16:
+ FMOVD F0, ret+8(FP)
+ RET
+
+LEXITTAGsinh:
+sinhIsInf:
+sinhIsZero:
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/sqrt.go b/platform/dbops/binaries/go/go/src/math/sqrt.go
new file mode 100644
index 0000000000000000000000000000000000000000..54929ebcaf74c30fdf6462d521e5aab5fc28942e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/sqrt.go
@@ -0,0 +1,145 @@
+// 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 math
+
+// The original C code and the long comment below are
+// from FreeBSD's /usr/src/lib/msun/src/e_sqrt.c and
+// came with this notice. The go code is a simplified
+// version of the original C.
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunPro, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+//
+// __ieee754_sqrt(x)
+// Return correctly rounded sqrt.
+// -----------------------------------------
+// | Use the hardware sqrt if you have one |
+// -----------------------------------------
+// Method:
+// Bit by bit method using integer arithmetic. (Slow, but portable)
+// 1. Normalization
+// Scale x to y in [1,4) with even powers of 2:
+// find an integer k such that 1 <= (y=x*2**(2k)) < 4, then
+// sqrt(x) = 2**k * sqrt(y)
+// 2. Bit by bit computation
+// Let q = sqrt(y) truncated to i bit after binary point (q = 1),
+// i 0
+// i+1 2
+// s = 2*q , and y = 2 * ( y - q ). (1)
+// i i i i
+//
+// To compute q from q , one checks whether
+// i+1 i
+//
+// -(i+1) 2
+// (q + 2 ) <= y. (2)
+// i
+// -(i+1)
+// If (2) is false, then q = q ; otherwise q = q + 2 .
+// i+1 i i+1 i
+//
+// With some algebraic manipulation, it is not difficult to see
+// that (2) is equivalent to
+// -(i+1)
+// s + 2 <= y (3)
+// i i
+//
+// The advantage of (3) is that s and y can be computed by
+// i i
+// the following recurrence formula:
+// if (3) is false
+//
+// s = s , y = y ; (4)
+// i+1 i i+1 i
+//
+// otherwise,
+// -i -(i+1)
+// s = s + 2 , y = y - s - 2 (5)
+// i+1 i i+1 i i
+//
+// One may easily use induction to prove (4) and (5).
+// Note. Since the left hand side of (3) contain only i+2 bits,
+// it is not necessary to do a full (53-bit) comparison
+// in (3).
+// 3. Final rounding
+// After generating the 53 bits result, we compute one more bit.
+// Together with the remainder, we can decide whether the
+// result is exact, bigger than 1/2ulp, or less than 1/2ulp
+// (it will never equal to 1/2ulp).
+// The rounding mode can be detected by checking whether
+// huge + tiny is equal to huge, and whether huge - tiny is
+// equal to huge for some floating point number "huge" and "tiny".
+//
+//
+// Notes: Rounding mode detection omitted. The constants "mask", "shift",
+// and "bias" are found in src/math/bits.go
+
+// Sqrt returns the square root of x.
+//
+// Special cases are:
+//
+// Sqrt(+Inf) = +Inf
+// Sqrt(±0) = ±0
+// Sqrt(x < 0) = NaN
+// Sqrt(NaN) = NaN
+func Sqrt(x float64) float64 {
+ return sqrt(x)
+}
+
+// Note: On systems where Sqrt is a single instruction, the compiler
+// may turn a direct call into a direct use of that instruction instead.
+
+func sqrt(x float64) float64 {
+ // special cases
+ switch {
+ case x == 0 || IsNaN(x) || IsInf(x, 1):
+ return x
+ case x < 0:
+ return NaN()
+ }
+ ix := Float64bits(x)
+ // normalize x
+ exp := int((ix >> shift) & mask)
+ if exp == 0 { // subnormal x
+ for ix&(1<>= 1 // exp = exp/2, exponent of square root
+ // generate sqrt(x) bit by bit
+ ix <<= 1
+ var q, s uint64 // q = sqrt(x)
+ r := uint64(1 << (shift + 1)) // r = moving bit from MSB to LSB
+ for r != 0 {
+ t := s + r
+ if t <= ix {
+ s = t + r
+ ix -= t
+ q += r
+ }
+ ix <<= 1
+ r >>= 1
+ }
+ // final rounding
+ if ix != 0 { // remainder, result not exact
+ q += q & 1 // round according to extra bit
+ }
+ ix = q>>1 + uint64(exp-1+bias)< 2**49 = 5.6e14.
+// [Accuracy loss statement from sin.go comments.]
+//
+// 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
+
+// tan coefficients
+var _tanP = [...]float64{
+ -1.30936939181383777646e4, // 0xc0c992d8d24f3f38
+ 1.15351664838587416140e6, // 0x413199eca5fc9ddd
+ -1.79565251976484877988e7, // 0xc1711fead3299176
+}
+var _tanQ = [...]float64{
+ 1.00000000000000000000e0,
+ 1.36812963470692954678e4, // 0x40cab8a5eeb36572
+ -1.32089234440210967447e6, // 0xc13427bc582abc96
+ 2.50083801823357915839e7, // 0x4177d98fc2ead8ef
+ -5.38695755929454629881e7, // 0xc189afe03cbe5a31
+}
+
+// Tan returns the tangent of the radian argument x.
+//
+// Special cases are:
+//
+// Tan(±0) = ±0
+// Tan(±Inf) = NaN
+// Tan(NaN) = NaN
+func Tan(x float64) float64 {
+ if haveArchTan {
+ return archTan(x)
+ }
+ return tan(x)
+}
+
+func tan(x float64) float64 {
+ const (
+ PI4A = 7.85398125648498535156e-1 // 0x3fe921fb40000000, Pi/4 split into three parts
+ PI4B = 3.77489470793079817668e-8 // 0x3e64442d00000000,
+ PI4C = 2.69515142907905952645e-15 // 0x3ce8469898cc5170,
+ )
+ // special cases
+ switch {
+ case x == 0 || IsNaN(x):
+ return x // return ±0 || NaN()
+ case IsInf(x, 0):
+ return NaN()
+ }
+
+ // make argument positive but save the sign
+ sign := false
+ if x < 0 {
+ x = -x
+ sign = true
+ }
+ var j uint64
+ var y, z float64
+ if x >= reduceThreshold {
+ j, z = trigReduce(x)
+ } else {
+ j = uint64(x * (4 / Pi)) // integer part of x/(Pi/4), as integer for tests on the phase angle
+ y = float64(j) // integer part of x/(Pi/4), as float
+
+ /* map zeros and singularities to origin */
+ if j&1 == 1 {
+ j++
+ y++
+ }
+
+ z = ((x - y*PI4A) - y*PI4B) - y*PI4C
+ }
+ zz := z * z
+
+ if zz > 1e-14 {
+ y = z + z*(zz*(((_tanP[0]*zz)+_tanP[1])*zz+_tanP[2])/((((zz+_tanQ[1])*zz+_tanQ[2])*zz+_tanQ[3])*zz+_tanQ[4]))
+ } else {
+ y = z
+ }
+ if j&2 == 2 {
+ y = -1 / y
+ }
+ if sign {
+ y = -y
+ }
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/src/math/tan_s390x.s b/platform/dbops/binaries/go/go/src/math/tan_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..6a4c449b0dfcb60c45f59fa8d0712c9d53c259ec
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/tan_s390x.s
@@ -0,0 +1,111 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial approximations
+DATA ·tanrodataL13<> + 0(SB)/8, $0.181017336383229927e-07
+DATA ·tanrodataL13<> + 8(SB)/8, $-.256590857271311164e-03
+DATA ·tanrodataL13<> + 16(SB)/8, $-.464359274328689195e+00
+DATA ·tanrodataL13<> + 24(SB)/8, $1.0
+DATA ·tanrodataL13<> + 32(SB)/8, $-.333333333333333464e+00
+DATA ·tanrodataL13<> + 40(SB)/8, $0.245751217306830032e-01
+DATA ·tanrodataL13<> + 48(SB)/8, $-.245391301343844510e-03
+DATA ·tanrodataL13<> + 56(SB)/8, $0.214530914428992319e-01
+DATA ·tanrodataL13<> + 64(SB)/8, $0.108285667160535624e-31
+DATA ·tanrodataL13<> + 72(SB)/8, $0.612323399573676480e-16
+DATA ·tanrodataL13<> + 80(SB)/8, $0.157079632679489656e+01
+DATA ·tanrodataL13<> + 88(SB)/8, $0.636619772367581341e+00
+GLOBL ·tanrodataL13<> + 0(SB), RODATA, $96
+
+// Constants
+DATA ·tanxnan<> + 0(SB)/8, $0x7ff8000000000000
+GLOBL ·tanxnan<> + 0(SB), RODATA, $8
+DATA ·tanxlim<> + 0(SB)/8, $0x432921fb54442d19
+GLOBL ·tanxlim<> + 0(SB), RODATA, $8
+DATA ·tanxadd<> + 0(SB)/8, $0xc338000000000000
+GLOBL ·tanxadd<> + 0(SB), RODATA, $8
+
+// Tan returns the tangent of the radian argument.
+//
+// Special cases are:
+// Tan(±0) = ±0
+// Tan(±Inf) = NaN
+// Tan(NaN) = NaN
+// The algorithm used is minimax polynomial approximation using a table of
+// polynomial coefficients determined with a Remez exchange algorithm.
+
+TEXT ·tanAsm(SB), NOSPLIT, $0-16
+ FMOVD x+0(FP), F0
+ //special case Tan(±0) = ±0
+ FMOVD $(0.0), F1
+ FCMPU F0, F1
+ BEQ atanIsZero
+
+ MOVD $·tanrodataL13<>+0(SB), R5
+ LTDBR F0, F0
+ BLTU L10
+ FMOVD F0, F2
+L2:
+ MOVD $·tanxlim<>+0(SB), R1
+ FMOVD 0(R1), F1
+ FCMPU F2, F1
+ BGT L9
+ BVS L11
+ MOVD $·tanxadd<>+0(SB), R1
+ FMOVD 88(R5), F6
+ FMOVD 0(R1), F4
+ WFMSDB V0, V6, V4, V6
+ FMOVD 80(R5), F1
+ FADD F6, F4
+ FMOVD 72(R5), F2
+ FMSUB F1, F4, F0
+ FMOVD 64(R5), F3
+ WFMADB V4, V2, V0, V2
+ FMOVD 56(R5), F1
+ WFMADB V4, V3, V2, V4
+ FMUL F2, F2
+ VLEG $0, 48(R5), V18
+ LGDR F6, R1
+ FMOVD 40(R5), F5
+ FMOVD 32(R5), F3
+ FMADD F1, F2, F3
+ FMOVD 24(R5), F1
+ FMOVD 16(R5), F7
+ FMOVD 8(R5), F0
+ WFMADB V2, V7, V1, V7
+ WFMADB V2, V0, V5, V0
+ WFMDB V2, V2, V1
+ FMOVD 0(R5), F5
+ WFLCDB V4, V16
+ WFMADB V2, V5, V18, V5
+ WFMADB V1, V0, V7, V0
+ TMLL R1, $1
+ WFMADB V1, V5, V3, V1
+ BNE L12
+ WFDDB V0, V1, V0
+ WFMDB V2, V16, V2
+ WFMADB V2, V0, V4, V0
+ WORD $0xB3130000 //lcdbr %f0,%f0
+ FMOVD F0, ret+8(FP)
+ RET
+L12:
+ WFMSDB V2, V1, V0, V2
+ WFMDB V16, V2, V2
+ FDIV F2, F0
+ FMOVD F0, ret+8(FP)
+ RET
+L11:
+ MOVD $·tanxnan<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+L10:
+ WORD $0xB3130020 //lcdbr %f2,%f0
+ BR L2
+L9:
+ BR ·tan(SB)
+atanIsZero:
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/tanh.go b/platform/dbops/binaries/go/go/src/math/tanh.go
new file mode 100644
index 0000000000000000000000000000000000000000..94ebc3b6515d52cb8eccdc62f341518913c2ec7a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/tanh.go
@@ -0,0 +1,105 @@
+// 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 math
+
+// The original C code, the long comment, and the constants
+// below were from http://netlib.sandia.gov/cephes/cmath/sin.c,
+// available from http://www.netlib.org/cephes/cmath.tgz.
+// The go code is a simplified version of the original C.
+// tanh.c
+//
+// Hyperbolic tangent
+//
+// SYNOPSIS:
+//
+// double x, y, tanh();
+//
+// y = tanh( x );
+//
+// DESCRIPTION:
+//
+// Returns hyperbolic tangent of argument in the range MINLOG to MAXLOG.
+// MAXLOG = 8.8029691931113054295988e+01 = log(2**127)
+// MINLOG = -8.872283911167299960540e+01 = log(2**-128)
+//
+// A rational function is used for |x| < 0.625. The form
+// x + x**3 P(x)/Q(x) of Cody & Waite is employed.
+// Otherwise,
+// tanh(x) = sinh(x)/cosh(x) = 1 - 2/(exp(2x) + 1).
+//
+// ACCURACY:
+//
+// Relative error:
+// arithmetic domain # trials peak rms
+// IEEE -2,2 30000 2.5e-16 5.8e-17
+//
+// 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
+//
+
+var tanhP = [...]float64{
+ -9.64399179425052238628e-1,
+ -9.92877231001918586564e1,
+ -1.61468768441708447952e3,
+}
+var tanhQ = [...]float64{
+ 1.12811678491632931402e2,
+ 2.23548839060100448583e3,
+ 4.84406305325125486048e3,
+}
+
+// Tanh returns the hyperbolic tangent of x.
+//
+// Special cases are:
+//
+// Tanh(±0) = ±0
+// Tanh(±Inf) = ±1
+// Tanh(NaN) = NaN
+func Tanh(x float64) float64 {
+ if haveArchTanh {
+ return archTanh(x)
+ }
+ return tanh(x)
+}
+
+func tanh(x float64) float64 {
+ const MAXLOG = 8.8029691931113054295988e+01 // log(2**127)
+ z := Abs(x)
+ switch {
+ case z > 0.5*MAXLOG:
+ if x < 0 {
+ return -1
+ }
+ return 1
+ case z >= 0.625:
+ s := Exp(2 * z)
+ z = 1 - 2/(s+1)
+ if x < 0 {
+ z = -z
+ }
+ default:
+ if x == 0 {
+ return x
+ }
+ s := x * x
+ z = x + x*s*((tanhP[0]*s+tanhP[1])*s+tanhP[2])/(((s+tanhQ[0])*s+tanhQ[1])*s+tanhQ[2])
+ }
+ return z
+}
diff --git a/platform/dbops/binaries/go/go/src/math/tanh_s390x.s b/platform/dbops/binaries/go/go/src/math/tanh_s390x.s
new file mode 100644
index 0000000000000000000000000000000000000000..7e2d4dd7972935c305848a407ee6f6c91bdd1b4c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/tanh_s390x.s
@@ -0,0 +1,169 @@
+// 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.
+
+#include "textflag.h"
+
+// Minimax polynomial approximations
+DATA tanhrodataL18<>+0(SB)/8, $-1.0
+DATA tanhrodataL18<>+8(SB)/8, $-2.0
+DATA tanhrodataL18<>+16(SB)/8, $1.0
+DATA tanhrodataL18<>+24(SB)/8, $2.0
+DATA tanhrodataL18<>+32(SB)/8, $0.20000000000000011868E+01
+DATA tanhrodataL18<>+40(SB)/8, $0.13333333333333341256E+01
+DATA tanhrodataL18<>+48(SB)/8, $0.26666666663549111502E+00
+DATA tanhrodataL18<>+56(SB)/8, $0.66666666658721844678E+00
+DATA tanhrodataL18<>+64(SB)/8, $0.88890217768964374821E-01
+DATA tanhrodataL18<>+72(SB)/8, $0.25397199429103821138E-01
+DATA tanhrodataL18<>+80(SB)/8, $-.346573590279972643E+00
+DATA tanhrodataL18<>+88(SB)/8, $20.E0
+GLOBL tanhrodataL18<>+0(SB), RODATA, $96
+
+// Constants
+DATA tanhrlog2<>+0(SB)/8, $0x4007154760000000
+GLOBL tanhrlog2<>+0(SB), RODATA, $8
+DATA tanhxadd<>+0(SB)/8, $0xc2f0000100003ff0
+GLOBL tanhxadd<>+0(SB), RODATA, $8
+DATA tanhxmone<>+0(SB)/8, $-1.0
+GLOBL tanhxmone<>+0(SB), RODATA, $8
+DATA tanhxzero<>+0(SB)/8, $0
+GLOBL tanhxzero<>+0(SB), RODATA, $8
+
+// Polynomial coefficients
+DATA tanhtab<>+0(SB)/8, $0.000000000000000000E+00
+DATA tanhtab<>+8(SB)/8, $-.171540871271399150E-01
+DATA tanhtab<>+16(SB)/8, $-.306597931864376363E-01
+DATA tanhtab<>+24(SB)/8, $-.410200970469965021E-01
+DATA tanhtab<>+32(SB)/8, $-.486343079978231466E-01
+DATA tanhtab<>+40(SB)/8, $-.538226193725835820E-01
+DATA tanhtab<>+48(SB)/8, $-.568439602538111520E-01
+DATA tanhtab<>+56(SB)/8, $-.579091847395528847E-01
+DATA tanhtab<>+64(SB)/8, $-.571909584179366341E-01
+DATA tanhtab<>+72(SB)/8, $-.548312665987204407E-01
+DATA tanhtab<>+80(SB)/8, $-.509471843643441085E-01
+DATA tanhtab<>+88(SB)/8, $-.456353588448863359E-01
+DATA tanhtab<>+96(SB)/8, $-.389755254243262365E-01
+DATA tanhtab<>+104(SB)/8, $-.310332908285244231E-01
+DATA tanhtab<>+112(SB)/8, $-.218623539150173528E-01
+DATA tanhtab<>+120(SB)/8, $-.115062908917949451E-01
+GLOBL tanhtab<>+0(SB), RODATA, $128
+
+// Tanh returns the hyperbolic tangent of the argument.
+//
+// Special cases are:
+// Tanh(±0) = ±0
+// Tanh(±Inf) = ±1
+// Tanh(NaN) = NaN
+// The algorithm used is minimax polynomial approximation using a table of
+// polynomial coefficients determined with a Remez exchange algorithm.
+
+TEXT ·tanhAsm(SB),NOSPLIT,$0-16
+ FMOVD x+0(FP), F0
+ // special case Tanh(±0) = ±0
+ FMOVD $(0.0), F1
+ FCMPU F0, F1
+ BEQ tanhIsZero
+ MOVD $tanhrodataL18<>+0(SB), R5
+ LTDBR F0, F0
+ MOVD $0x4034000000000000, R1
+ BLTU L15
+ FMOVD F0, F1
+L2:
+ MOVD $tanhxadd<>+0(SB), R2
+ FMOVD 0(R2), F2
+ MOVD tanhrlog2<>+0(SB), R2
+ LDGR R2, F4
+ WFMSDB V0, V4, V2, V4
+ MOVD $tanhtab<>+0(SB), R3
+ LGDR F4, R2
+ RISBGZ $57, $60, $3, R2, R4
+ WORD $0xED105058 //cdb %f1,.L19-.L18(%r5)
+ BYTE $0x00
+ BYTE $0x19
+ RISBGN $0, $15, $48, R2, R1
+ WORD $0x68543000 //ld %f5,0(%r4,%r3)
+ LDGR R1, F6
+ BLT L3
+ MOVD $tanhxzero<>+0(SB), R1
+ FMOVD 0(R1), F2
+ WFCHDBS V0, V2, V4
+ BEQ L9
+ WFCHDBS V2, V0, V2
+ BNE L1
+ MOVD $tanhxmone<>+0(SB), R1
+ FMOVD 0(R1), F0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L3:
+ FADD F4, F2
+ FMOVD tanhrodataL18<>+80(SB), F4
+ FMADD F4, F2, F0
+ FMOVD tanhrodataL18<>+72(SB), F1
+ WFMDB V0, V0, V3
+ FMOVD tanhrodataL18<>+64(SB), F2
+ WFMADB V0, V1, V2, V1
+ FMOVD tanhrodataL18<>+56(SB), F4
+ FMOVD tanhrodataL18<>+48(SB), F2
+ WFMADB V1, V3, V4, V1
+ FMOVD tanhrodataL18<>+40(SB), F4
+ WFMADB V3, V2, V4, V2
+ FMOVD tanhrodataL18<>+32(SB), F4
+ WORD $0xB9270022 //lhr %r2,%r2
+ WFMADB V3, V1, V4, V1
+ FMOVD tanhrodataL18<>+24(SB), F4
+ WFMADB V3, V2, V4, V3
+ WFMADB V0, V5, V0, V2
+ WFMADB V0, V1, V3, V0
+ WORD $0xA7183ECF //lhi %r1,16079
+ WFMADB V0, V2, V5, V2
+ FMUL F6, F2
+ MOVW R2, R10
+ MOVW R1, R11
+ CMPBLE R10, R11, L16
+ FMOVD F6, F0
+ WORD $0xED005010 //adb %f0,.L28-.L18(%r5)
+ BYTE $0x00
+ BYTE $0x1A
+ WORD $0xA7184330 //lhi %r1,17200
+ FADD F2, F0
+ MOVW R2, R10
+ MOVW R1, R11
+ CMPBGT R10, R11, L17
+ WORD $0xED605010 //sdb %f6,.L28-.L18(%r5)
+ BYTE $0x00
+ BYTE $0x1B
+ FADD F6, F2
+ WFDDB V0, V2, V0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L9:
+ FMOVD tanhrodataL18<>+16(SB), F0
+L1:
+ FMOVD F0, ret+8(FP)
+ RET
+
+L15:
+ FNEG F0, F1
+ BR L2
+L16:
+ FADD F6, F2
+ FMOVD tanhrodataL18<>+8(SB), F0
+ FMADD F4, F2, F0
+ FMOVD tanhrodataL18<>+0(SB), F4
+ FNEG F0, F0
+ WFMADB V0, V2, V4, V0
+ FMOVD F0, ret+8(FP)
+ RET
+
+L17:
+ WFDDB V0, V4, V0
+ FMOVD tanhrodataL18<>+16(SB), F2
+ WFSDB V0, V2, V0
+ FMOVD F0, ret+8(FP)
+ RET
+
+tanhIsZero: //return ±0
+ FMOVD F0, ret+8(FP)
+ RET
diff --git a/platform/dbops/binaries/go/go/src/math/trig_reduce.go b/platform/dbops/binaries/go/go/src/math/trig_reduce.go
new file mode 100644
index 0000000000000000000000000000000000000000..5ecdd8375e3295b5aa3f9bc60f0ab40b06db9f54
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/trig_reduce.go
@@ -0,0 +1,102 @@
+// 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 math
+
+import (
+ "math/bits"
+)
+
+// reduceThreshold is the maximum value of x where the reduction using Pi/4
+// in 3 float64 parts still gives accurate results. This threshold
+// is set by y*C being representable as a float64 without error
+// where y is given by y = floor(x * (4 / Pi)) and C is the leading partial
+// terms of 4/Pi. Since the leading terms (PI4A and PI4B in sin.go) have 30
+// and 32 trailing zero bits, y should have less than 30 significant bits.
+//
+// y < 1<<30 -> floor(x*4/Pi) < 1<<30 -> x < (1<<30 - 1) * Pi/4
+//
+// So, conservatively we can take x < 1<<29.
+// Above this threshold Payne-Hanek range reduction must be used.
+const reduceThreshold = 1 << 29
+
+// trigReduce implements Payne-Hanek range reduction by Pi/4
+// for x > 0. It returns the integer part mod 8 (j) and
+// the fractional part (z) of x / (Pi/4).
+// The implementation is based on:
+// "ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit"
+// K. C. Ng et al, March 24, 1992
+// The simulated multi-precision calculation of x*B uses 64-bit integer arithmetic.
+func trigReduce(x float64) (j uint64, z float64) {
+ const PI4 = Pi / 4
+ if x < PI4 {
+ return 0, x
+ }
+ // Extract out the integer and exponent such that,
+ // x = ix * 2 ** exp.
+ ix := Float64bits(x)
+ exp := int(ix>>shift&mask) - bias - shift
+ ix &^= mask << shift
+ ix |= 1 << shift
+ // Use the exponent to extract the 3 appropriate uint64 digits from mPi4,
+ // B ~ (z0, z1, z2), such that the product leading digit has the exponent -61.
+ // Note, exp >= -53 since x >= PI4 and exp < 971 for maximum float64.
+ digit, bitshift := uint(exp+61)/64, uint(exp+61)%64
+ z0 := (mPi4[digit] << bitshift) | (mPi4[digit+1] >> (64 - bitshift))
+ z1 := (mPi4[digit+1] << bitshift) | (mPi4[digit+2] >> (64 - bitshift))
+ z2 := (mPi4[digit+2] << bitshift) | (mPi4[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)
+ // The top 3 bits are j.
+ j = hi >> 61
+ // Extract the fraction and find its magnitude.
+ hi = hi<<3 | lo>>61
+ 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
+ z = Float64frombits(hi)
+ // Map zeros to origin.
+ if j&1 == 1 {
+ j++
+ j &= 7
+ z--
+ }
+ // Multiply the fractional part by pi/4.
+ return j, z * PI4
+}
+
+// mPi4 is the binary digits of 4/pi as a uint64 array,
+// that is, 4/pi = Sum mPi4[i]*2^(-64*i)
+// 19 64-bit digits and the leading one bit give 1217 bits
+// of precision to handle the largest possible float64 exponent.
+var mPi4 = [...]uint64{
+ 0x0000000000000001,
+ 0x45f306dc9c882a53,
+ 0xf84eafa3ea69bb81,
+ 0xb6c52b3278872083,
+ 0xfca2c757bd778ac3,
+ 0x6e48dc74849ba5c0,
+ 0x0c925dd413a32439,
+ 0xfc3bd63962534e7d,
+ 0xd1046bea5d768909,
+ 0xd338e04d68befc82,
+ 0x7323ac7306a673e9,
+ 0x3908bf177bf25076,
+ 0x3ff12fffbc0b301f,
+ 0xde5e2316b414da3e,
+ 0xda6cfd9e4f96136e,
+ 0x9e8c7ecd3cbfd45a,
+ 0xea4f758fd7cbe2f6,
+ 0x7a0e73ef14a525d4,
+ 0xd7f6bf623f1aba10,
+ 0xac06608df8f6d757,
+}
diff --git a/platform/dbops/binaries/go/go/src/math/unsafe.go b/platform/dbops/binaries/go/go/src/math/unsafe.go
new file mode 100644
index 0000000000000000000000000000000000000000..e59f50ca62e5cc4ecdcc334b319093c5ef6a905d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/math/unsafe.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.
+
+package math
+
+import "unsafe"
+
+// Float32bits returns the IEEE 754 binary representation of f,
+// with the sign bit of f and the result in the same bit position.
+// Float32bits(Float32frombits(x)) == x.
+func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) }
+
+// Float32frombits returns the floating-point number corresponding
+// to the IEEE 754 binary representation b, with the sign bit of b
+// and the result in the same bit position.
+// Float32frombits(Float32bits(x)) == x.
+func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) }
+
+// Float64bits returns the IEEE 754 binary representation of f,
+// with the sign bit of f and the result in the same bit position,
+// and Float64bits(Float64frombits(x)) == x.
+func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) }
+
+// Float64frombits returns the floating-point number corresponding
+// to the IEEE 754 binary representation b, with the sign bit of b
+// and the result in the same bit position.
+// Float64frombits(Float64bits(x)) == x.
+func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) }
diff --git a/platform/dbops/binaries/go/go/src/mime/encodedword.go b/platform/dbops/binaries/go/go/src/mime/encodedword.go
new file mode 100644
index 0000000000000000000000000000000000000000..e6b470b1fb0ef83548656fc06f13d8e14cc6be02
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/encodedword.go
@@ -0,0 +1,414 @@
+// 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 mime
+
+import (
+ "bytes"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// A WordEncoder is an RFC 2047 encoded-word encoder.
+type WordEncoder byte
+
+const (
+ // BEncoding represents Base64 encoding scheme as defined by RFC 2045.
+ BEncoding = WordEncoder('b')
+ // QEncoding represents the Q-encoding scheme as defined by RFC 2047.
+ QEncoding = WordEncoder('q')
+)
+
+var (
+ errInvalidWord = errors.New("mime: invalid RFC 2047 encoded-word")
+)
+
+// Encode returns the encoded-word form of s. If s is ASCII without special
+// characters, it is returned unchanged. The provided charset is the IANA
+// charset name of s. It is case insensitive.
+func (e WordEncoder) Encode(charset, s string) string {
+ if !needsEncoding(s) {
+ return s
+ }
+ return e.encodeWord(charset, s)
+}
+
+func needsEncoding(s string) bool {
+ for _, b := range s {
+ if (b < ' ' || b > '~') && b != '\t' {
+ return true
+ }
+ }
+ return false
+}
+
+// encodeWord encodes a string into an encoded-word.
+func (e WordEncoder) encodeWord(charset, s string) string {
+ var buf strings.Builder
+ // Could use a hint like len(s)*3, but that's not enough for cases
+ // with word splits and too much for simpler inputs.
+ // 48 is close to maxEncodedWordLen/2, but adjusted to allocator size class.
+ buf.Grow(48)
+
+ e.openWord(&buf, charset)
+ if e == BEncoding {
+ e.bEncode(&buf, charset, s)
+ } else {
+ e.qEncode(&buf, charset, s)
+ }
+ closeWord(&buf)
+
+ return buf.String()
+}
+
+const (
+ // The maximum length of an encoded-word is 75 characters.
+ // See RFC 2047, section 2.
+ maxEncodedWordLen = 75
+ // maxContentLen is how much content can be encoded, ignoring the header and
+ // 2-byte footer.
+ maxContentLen = maxEncodedWordLen - len("=?UTF-8?q?") - len("?=")
+)
+
+var maxBase64Len = base64.StdEncoding.DecodedLen(maxContentLen)
+
+// bEncode encodes s using base64 encoding and writes it to buf.
+func (e WordEncoder) bEncode(buf *strings.Builder, charset, s string) {
+ w := base64.NewEncoder(base64.StdEncoding, buf)
+ // If the charset is not UTF-8 or if the content is short, do not bother
+ // splitting the encoded-word.
+ if !isUTF8(charset) || base64.StdEncoding.EncodedLen(len(s)) <= maxContentLen {
+ io.WriteString(w, s)
+ w.Close()
+ return
+ }
+
+ var currentLen, last, runeLen int
+ for i := 0; i < len(s); i += runeLen {
+ // Multi-byte characters must not be split across encoded-words.
+ // See RFC 2047, section 5.3.
+ _, runeLen = utf8.DecodeRuneInString(s[i:])
+
+ if currentLen+runeLen <= maxBase64Len {
+ currentLen += runeLen
+ } else {
+ io.WriteString(w, s[last:i])
+ w.Close()
+ e.splitWord(buf, charset)
+ last = i
+ currentLen = runeLen
+ }
+ }
+ io.WriteString(w, s[last:])
+ w.Close()
+}
+
+// qEncode encodes s using Q encoding and writes it to buf. It splits the
+// encoded-words when necessary.
+func (e WordEncoder) qEncode(buf *strings.Builder, charset, s string) {
+ // We only split encoded-words when the charset is UTF-8.
+ if !isUTF8(charset) {
+ writeQString(buf, s)
+ return
+ }
+
+ var currentLen, runeLen int
+ for i := 0; i < len(s); i += runeLen {
+ b := s[i]
+ // Multi-byte characters must not be split across encoded-words.
+ // See RFC 2047, section 5.3.
+ var encLen int
+ if b >= ' ' && b <= '~' && b != '=' && b != '?' && b != '_' {
+ runeLen, encLen = 1, 1
+ } else {
+ _, runeLen = utf8.DecodeRuneInString(s[i:])
+ encLen = 3 * runeLen
+ }
+
+ if currentLen+encLen > maxContentLen {
+ e.splitWord(buf, charset)
+ currentLen = 0
+ }
+ writeQString(buf, s[i:i+runeLen])
+ currentLen += encLen
+ }
+}
+
+// writeQString encodes s using Q encoding and writes it to buf.
+func writeQString(buf *strings.Builder, s string) {
+ for i := 0; i < len(s); i++ {
+ switch b := s[i]; {
+ case b == ' ':
+ buf.WriteByte('_')
+ case b >= '!' && b <= '~' && b != '=' && b != '?' && b != '_':
+ buf.WriteByte(b)
+ default:
+ buf.WriteByte('=')
+ buf.WriteByte(upperhex[b>>4])
+ buf.WriteByte(upperhex[b&0x0f])
+ }
+ }
+}
+
+// openWord writes the beginning of an encoded-word into buf.
+func (e WordEncoder) openWord(buf *strings.Builder, charset string) {
+ buf.WriteString("=?")
+ buf.WriteString(charset)
+ buf.WriteByte('?')
+ buf.WriteByte(byte(e))
+ buf.WriteByte('?')
+}
+
+// closeWord writes the end of an encoded-word into buf.
+func closeWord(buf *strings.Builder) {
+ buf.WriteString("?=")
+}
+
+// splitWord closes the current encoded-word and opens a new one.
+func (e WordEncoder) splitWord(buf *strings.Builder, charset string) {
+ closeWord(buf)
+ buf.WriteByte(' ')
+ e.openWord(buf, charset)
+}
+
+func isUTF8(charset string) bool {
+ return strings.EqualFold(charset, "UTF-8")
+}
+
+const upperhex = "0123456789ABCDEF"
+
+// A WordDecoder decodes MIME headers containing RFC 2047 encoded-words.
+type WordDecoder struct {
+ // CharsetReader, if non-nil, defines a function to generate
+ // charset-conversion readers, converting from the provided
+ // charset into UTF-8.
+ // Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets
+ // are handled by default.
+ // One of the CharsetReader's result values must be non-nil.
+ CharsetReader func(charset string, input io.Reader) (io.Reader, error)
+}
+
+// Decode decodes an RFC 2047 encoded-word.
+func (d *WordDecoder) Decode(word string) (string, error) {
+ // See https://tools.ietf.org/html/rfc2047#section-2 for details.
+ // Our decoder is permissive, we accept empty encoded-text.
+ if len(word) < 8 || !strings.HasPrefix(word, "=?") || !strings.HasSuffix(word, "?=") || strings.Count(word, "?") != 4 {
+ return "", errInvalidWord
+ }
+ word = word[2 : len(word)-2]
+
+ // split word "UTF-8?q?text" into "UTF-8", 'q', and "text"
+ charset, text, _ := strings.Cut(word, "?")
+ if charset == "" {
+ return "", errInvalidWord
+ }
+ encoding, text, _ := strings.Cut(text, "?")
+ if len(encoding) != 1 {
+ return "", errInvalidWord
+ }
+
+ content, err := decode(encoding[0], text)
+ if err != nil {
+ return "", err
+ }
+
+ var buf strings.Builder
+ if err := d.convert(&buf, charset, content); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+// DecodeHeader decodes all encoded-words of the given string. It returns an
+// error if and only if CharsetReader of d returns an error.
+func (d *WordDecoder) DecodeHeader(header string) (string, error) {
+ // If there is no encoded-word, returns before creating a buffer.
+ i := strings.Index(header, "=?")
+ if i == -1 {
+ return header, nil
+ }
+
+ var buf strings.Builder
+
+ buf.WriteString(header[:i])
+ header = header[i:]
+
+ betweenWords := false
+ for {
+ start := strings.Index(header, "=?")
+ if start == -1 {
+ break
+ }
+ cur := start + len("=?")
+
+ i := strings.Index(header[cur:], "?")
+ if i == -1 {
+ break
+ }
+ charset := header[cur : cur+i]
+ cur += i + len("?")
+
+ if len(header) < cur+len("Q??=") {
+ break
+ }
+ encoding := header[cur]
+ cur++
+
+ if header[cur] != '?' {
+ break
+ }
+ cur++
+
+ j := strings.Index(header[cur:], "?=")
+ if j == -1 {
+ break
+ }
+ text := header[cur : cur+j]
+ end := cur + j + len("?=")
+
+ content, err := decode(encoding, text)
+ if err != nil {
+ betweenWords = false
+ buf.WriteString(header[:start+2])
+ header = header[start+2:]
+ continue
+ }
+
+ // Write characters before the encoded-word. White-space and newline
+ // characters separating two encoded-words must be deleted.
+ if start > 0 && (!betweenWords || hasNonWhitespace(header[:start])) {
+ buf.WriteString(header[:start])
+ }
+
+ if err := d.convert(&buf, charset, content); err != nil {
+ return "", err
+ }
+
+ header = header[end:]
+ betweenWords = true
+ }
+
+ if len(header) > 0 {
+ buf.WriteString(header)
+ }
+
+ return buf.String(), nil
+}
+
+func decode(encoding byte, text string) ([]byte, error) {
+ switch encoding {
+ case 'B', 'b':
+ return base64.StdEncoding.DecodeString(text)
+ case 'Q', 'q':
+ return qDecode(text)
+ default:
+ return nil, errInvalidWord
+ }
+}
+
+func (d *WordDecoder) convert(buf *strings.Builder, charset string, content []byte) error {
+ switch {
+ case strings.EqualFold("utf-8", charset):
+ buf.Write(content)
+ case strings.EqualFold("iso-8859-1", charset):
+ for _, c := range content {
+ buf.WriteRune(rune(c))
+ }
+ case strings.EqualFold("us-ascii", charset):
+ for _, c := range content {
+ if c >= utf8.RuneSelf {
+ buf.WriteRune(unicode.ReplacementChar)
+ } else {
+ buf.WriteByte(c)
+ }
+ }
+ default:
+ if d.CharsetReader == nil {
+ return fmt.Errorf("mime: unhandled charset %q", charset)
+ }
+ r, err := d.CharsetReader(strings.ToLower(charset), bytes.NewReader(content))
+ if err != nil {
+ return err
+ }
+ if _, err = io.Copy(buf, r); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// hasNonWhitespace reports whether s (assumed to be ASCII) contains at least
+// one byte of non-whitespace.
+func hasNonWhitespace(s string) bool {
+ for _, b := range s {
+ switch b {
+ // Encoded-words can only be separated by linear white spaces which does
+ // not include vertical tabs (\v).
+ case ' ', '\t', '\n', '\r':
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// qDecode decodes a Q encoded string.
+func qDecode(s string) ([]byte, error) {
+ dec := make([]byte, len(s))
+ n := 0
+ for i := 0; i < len(s); i++ {
+ switch c := s[i]; {
+ case c == '_':
+ dec[n] = ' '
+ case c == '=':
+ if i+2 >= len(s) {
+ return nil, errInvalidWord
+ }
+ b, err := readHexByte(s[i+1], s[i+2])
+ if err != nil {
+ return nil, err
+ }
+ dec[n] = b
+ i += 2
+ case (c <= '~' && c >= ' ') || c == '\n' || c == '\r' || c == '\t':
+ dec[n] = c
+ default:
+ return nil, errInvalidWord
+ }
+ n++
+ }
+
+ return dec[:n], nil
+}
+
+// readHexByte returns the byte from its quoted-printable representation.
+func readHexByte(a, b byte) (byte, error) {
+ var hb, lb byte
+ var err error
+ if hb, err = fromHex(a); err != nil {
+ return 0, err
+ }
+ if lb, err = fromHex(b); err != nil {
+ return 0, err
+ }
+ return hb<<4 | lb, nil
+}
+
+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("mime: invalid hex byte %#02x", b)
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/encodedword_test.go b/platform/dbops/binaries/go/go/src/mime/encodedword_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a98794380fb029bb61b51d59a9de8eb67d81cf6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/encodedword_test.go
@@ -0,0 +1,239 @@
+// 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 mime
+
+import (
+ "errors"
+ "io"
+ "strings"
+ "testing"
+)
+
+func TestEncodeWord(t *testing.T) {
+ utf8, iso88591 := "utf-8", "iso-8859-1"
+ tests := []struct {
+ enc WordEncoder
+ charset string
+ src, exp string
+ }{
+ {QEncoding, utf8, "François-Jérôme", "=?utf-8?q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?="},
+ {BEncoding, utf8, "Café", "=?utf-8?b?Q2Fmw6k=?="},
+ {QEncoding, iso88591, "La Seleção", "=?iso-8859-1?q?La_Sele=C3=A7=C3=A3o?="},
+ {QEncoding, utf8, "", ""},
+ {QEncoding, utf8, "A", "A"},
+ {QEncoding, iso88591, "a", "a"},
+ {QEncoding, utf8, "123 456", "123 456"},
+ {QEncoding, utf8, "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~", "\t !\"#$%&'()*+,-./ :;<>?@[\\]^_`{|}~"},
+ {QEncoding, utf8, strings.Repeat("é", 10), "=?utf-8?q?" + strings.Repeat("=C3=A9", 10) + "?="},
+ {QEncoding, utf8, strings.Repeat("é", 11), "=?utf-8?q?" + strings.Repeat("=C3=A9", 10) + "?= =?utf-8?q?=C3=A9?="},
+ {QEncoding, iso88591, strings.Repeat("\xe9", 22), "=?iso-8859-1?q?" + strings.Repeat("=E9", 22) + "?="},
+ {QEncoding, utf8, strings.Repeat("\x80", 22), "=?utf-8?q?" + strings.Repeat("=80", 21) + "?= =?utf-8?q?=80?="},
+ {BEncoding, iso88591, strings.Repeat("\xe9", 45), "=?iso-8859-1?b?" + strings.Repeat("6enp", 15) + "?="},
+ {BEncoding, utf8, strings.Repeat("\x80", 48), "=?utf-8?b?" + strings.Repeat("gICA", 15) + "?= =?utf-8?b?gICA?="},
+ }
+
+ for _, test := range tests {
+ if s := test.enc.Encode(test.charset, test.src); s != test.exp {
+ t.Errorf("Encode(%q) = %q, want %q", test.src, s, test.exp)
+ }
+ }
+}
+
+func TestEncodedWordLength(t *testing.T) {
+ tests := []struct {
+ enc WordEncoder
+ src string
+ }{
+ {QEncoding, strings.Repeat("à", 30)},
+ {QEncoding, strings.Repeat("é", 60)},
+ {BEncoding, strings.Repeat("ï", 25)},
+ {BEncoding, strings.Repeat("ô", 37)},
+ {BEncoding, strings.Repeat("\x80", 50)},
+ {QEncoding, "{$firstname} Bienvendio a Apostolica, aquà inicia el camino de tu"},
+ }
+
+ for _, test := range tests {
+ s := test.enc.Encode("utf-8", test.src)
+ wordLen := 0
+ for i := 0; i < len(s); i++ {
+ if s[i] == ' ' {
+ wordLen = 0
+ continue
+ }
+
+ wordLen++
+ if wordLen > maxEncodedWordLen {
+ t.Errorf("Encode(%q) has more than %d characters: %q",
+ test.src, maxEncodedWordLen, s)
+ }
+ }
+ }
+}
+
+func TestDecodeWord(t *testing.T) {
+ tests := []struct {
+ src, exp string
+ hasErr bool
+ }{
+ {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!", false},
+ {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme", false},
+ {"=?UTF-8?q?ascii?=", "ascii", false},
+ {"=?utf-8?B?QW5kcsOp?=", "André", false},
+ {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont", false},
+ {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" `, false},
+ {"=?UTF-8?A?Test?=", "", true},
+ {"=?UTF-8?Q?A=B?=", "", true},
+ {"=?UTF-8?Q?=A?=", "", true},
+ {"=?UTF-8?A?A?=", "", true},
+ {"=????=", "", true},
+ {"=?UTF-8???=", "", true},
+ {"=?UTF-8?Q??=", "", false},
+ }
+
+ for _, test := range tests {
+ dec := new(WordDecoder)
+ s, err := dec.Decode(test.src)
+ if test.hasErr && err == nil {
+ t.Errorf("Decode(%q) should return an error", test.src)
+ continue
+ }
+ if !test.hasErr && err != nil {
+ t.Errorf("Decode(%q): %v", test.src, err)
+ continue
+ }
+ if s != test.exp {
+ t.Errorf("Decode(%q) = %q, want %q", test.src, s, test.exp)
+ }
+ }
+}
+
+func TestDecodeHeader(t *testing.T) {
+ tests := []struct {
+ src, exp string
+ }{
+ {"=?UTF-8?Q?=C2=A1Hola,_se=C3=B1or!?=", "¡Hola, señor!"},
+ {"=?UTF-8?Q?Fran=C3=A7ois-J=C3=A9r=C3=B4me?=", "François-Jérôme"},
+ {"=?UTF-8?q?ascii?=", "ascii"},
+ {"=?utf-8?B?QW5kcsOp?=", "André"},
+ {"=?ISO-8859-1?Q?Rapha=EBl_Dupont?=", "Raphaël Dupont"},
+ {"Jean", "Jean"},
+ {"=?utf-8?b?IkFudG9uaW8gSm9zw6kiIDxqb3NlQGV4YW1wbGUub3JnPg==?=", `"Antonio José" `},
+ {"=?UTF-8?A?Test?=", "=?UTF-8?A?Test?="},
+ {"=?UTF-8?Q?A=B?=", "=?UTF-8?Q?A=B?="},
+ {"=?UTF-8?Q?=A?=", "=?UTF-8?Q?=A?="},
+ {"=?UTF-8?A?A?=", "=?UTF-8?A?A?="},
+ // Incomplete words
+ {"=?", "=?"},
+ {"=?UTF-8?", "=?UTF-8?"},
+ {"=?UTF-8?=", "=?UTF-8?="},
+ {"=?UTF-8?Q", "=?UTF-8?Q"},
+ {"=?UTF-8?Q?", "=?UTF-8?Q?"},
+ {"=?UTF-8?Q?=", "=?UTF-8?Q?="},
+ {"=?UTF-8?Q?A", "=?UTF-8?Q?A"},
+ {"=?UTF-8?Q?A?", "=?UTF-8?Q?A?"},
+ // Tests from RFC 2047
+ {"=?ISO-8859-1?Q?a?=", "a"},
+ {"=?ISO-8859-1?Q?a?= b", "a b"},
+ {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"},
+ {"=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=", "ab"},
+ {"=?ISO-8859-1?Q?a?= \r\n\t =?ISO-8859-1?Q?b?=", "ab"},
+ {"=?ISO-8859-1?Q?a_b?=", "a b"},
+ }
+
+ for _, test := range tests {
+ dec := new(WordDecoder)
+ s, err := dec.DecodeHeader(test.src)
+ if err != nil {
+ t.Errorf("DecodeHeader(%q): %v", test.src, err)
+ }
+ if s != test.exp {
+ t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, s, test.exp)
+ }
+ }
+}
+
+func TestCharsetDecoder(t *testing.T) {
+ tests := []struct {
+ src string
+ want string
+ charsets []string
+ content []string
+ }{
+ {"=?utf-8?b?Q2Fmw6k=?=", "Café", nil, nil},
+ {"=?ISO-8859-1?Q?caf=E9?=", "café", nil, nil},
+ {"=?US-ASCII?Q?foo_bar?=", "foo bar", nil, nil},
+ {"=?utf-8?Q?=?=", "=?utf-8?Q?=?=", nil, nil},
+ {"=?utf-8?Q?=A?=", "=?utf-8?Q?=A?=", nil, nil},
+ {
+ "=?ISO-8859-15?Q?f=F5=F6?= =?windows-1252?Q?b=E0r?=",
+ "f\xf5\xf6b\xe0r",
+ []string{"iso-8859-15", "windows-1252"},
+ []string{"f\xf5\xf6", "b\xe0r"},
+ },
+ }
+
+ for _, test := range tests {
+ i := 0
+ dec := &WordDecoder{
+ CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
+ if charset != test.charsets[i] {
+ t.Errorf("DecodeHeader(%q), got charset %q, want %q", test.src, charset, test.charsets[i])
+ }
+ content, err := io.ReadAll(input)
+ if err != nil {
+ t.Errorf("DecodeHeader(%q), error in reader: %v", test.src, err)
+ }
+ got := string(content)
+ if got != test.content[i] {
+ t.Errorf("DecodeHeader(%q), got content %q, want %q", test.src, got, test.content[i])
+ }
+ i++
+
+ return strings.NewReader(got), nil
+ },
+ }
+ got, err := dec.DecodeHeader(test.src)
+ if err != nil {
+ t.Errorf("DecodeHeader(%q): %v", test.src, err)
+ }
+ if got != test.want {
+ t.Errorf("DecodeHeader(%q) = %q, want %q", test.src, got, test.want)
+ }
+ }
+}
+
+func TestCharsetDecoderError(t *testing.T) {
+ dec := &WordDecoder{
+ CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
+ return nil, errors.New("Test error")
+ },
+ }
+
+ if _, err := dec.DecodeHeader("=?charset?Q?foo?="); err == nil {
+ t.Error("DecodeHeader should return an error")
+ }
+}
+
+func BenchmarkQEncodeWord(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ QEncoding.Encode("UTF-8", "¡Hola, señor!")
+ }
+}
+
+func BenchmarkQDecodeWord(b *testing.B) {
+ dec := new(WordDecoder)
+
+ for i := 0; i < b.N; i++ {
+ dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
+ }
+}
+
+func BenchmarkQDecodeHeader(b *testing.B) {
+ dec := new(WordDecoder)
+
+ for i := 0; i < b.N; i++ {
+ dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/example_test.go b/platform/dbops/binaries/go/go/src/mime/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a96873e5dc6b77d34f69563e8fea4f9e40b6743
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/example_test.go
@@ -0,0 +1,123 @@
+// 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 mime_test
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "mime"
+)
+
+func ExampleWordEncoder_Encode() {
+ fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!"))
+ fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!"))
+ fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!"))
+ fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9"))
+ // Output:
+ // =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=
+ // Hello!
+ // =?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?=
+ // =?ISO-8859-1?q?Caf=E9?=
+}
+
+func ExampleWordDecoder_Decode() {
+ dec := new(mime.WordDecoder)
+ header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(header)
+
+ dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
+ switch charset {
+ case "x-case":
+ // Fake character set for example.
+ // Real use would integrate with packages such
+ // as code.google.com/p/go-charset
+ content, err := io.ReadAll(input)
+ if err != nil {
+ return nil, err
+ }
+ return bytes.NewReader(bytes.ToUpper(content)), nil
+ default:
+ return nil, fmt.Errorf("unhandled charset %q", charset)
+ }
+ }
+ header, err = dec.Decode("=?x-case?q?hello!?=")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(header)
+ // Output:
+ // ¡Hola, señor!
+ // HELLO!
+}
+
+func ExampleWordDecoder_DecodeHeader() {
+ dec := new(mime.WordDecoder)
+ header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= , =?utf-8?q?Ana=C3=AFs?= ")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(header)
+
+ header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(header)
+
+ dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
+ switch charset {
+ case "x-case":
+ // Fake character set for example.
+ // Real use would integrate with packages such
+ // as code.google.com/p/go-charset
+ content, err := io.ReadAll(input)
+ if err != nil {
+ return nil, err
+ }
+ return bytes.NewReader(bytes.ToUpper(content)), nil
+ default:
+ return nil, fmt.Errorf("unhandled charset %q", charset)
+ }
+ }
+ header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(header)
+ // Output:
+ // Éric , Anaïs
+ // ¡Hola, señor!
+ // HELLO WORLD!
+}
+
+func ExampleFormatMediaType() {
+ mediatype := "text/html"
+ params := map[string]string{
+ "charset": "utf-8",
+ }
+
+ result := mime.FormatMediaType(mediatype, params)
+
+ fmt.Println("result:", result)
+ // Output:
+ // result: text/html; charset=utf-8
+}
+
+func ExampleParseMediaType() {
+ mediatype, params, err := mime.ParseMediaType("text/html; charset=utf-8")
+ if err != nil {
+ panic(err)
+ }
+
+ fmt.Println("type:", mediatype)
+ fmt.Println("charset:", params["charset"])
+ // Output:
+ // type: text/html
+ // charset: utf-8
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/grammar.go b/platform/dbops/binaries/go/go/src/mime/grammar.go
new file mode 100644
index 0000000000000000000000000000000000000000..6a6f71dbd40ed8ad20e36dc5cc1761cb017ed344
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/grammar.go
@@ -0,0 +1,32 @@
+// 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 mime
+
+import (
+ "strings"
+)
+
+// isTSpecial reports whether rune is in 'tspecials' as defined by RFC
+// 1521 and RFC 2045.
+func isTSpecial(r rune) bool {
+ return strings.ContainsRune(`()<>@,;:\"/[]?=`, r)
+}
+
+// isTokenChar reports whether rune is in 'token' as defined by RFC
+// 1521 and RFC 2045.
+func isTokenChar(r rune) bool {
+ // token := 1*
+ return r > 0x20 && r < 0x7f && !isTSpecial(r)
+}
+
+// isToken reports whether s is a 'token' as defined by RFC 1521
+// and RFC 2045.
+func isToken(s string) bool {
+ if s == "" {
+ return false
+ }
+ return strings.IndexFunc(s, isNotTokenChar) < 0
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/mediatype.go b/platform/dbops/binaries/go/go/src/mime/mediatype.go
new file mode 100644
index 0000000000000000000000000000000000000000..bc8d417e62893e9aa28709ca88f6c056ad5caef0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/mediatype.go
@@ -0,0 +1,410 @@
+// 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 mime
+
+import (
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "unicode"
+)
+
+// FormatMediaType serializes mediatype t and the parameters
+// param as a media type conforming to RFC 2045 and RFC 2616.
+// The type and parameter names are written in lower-case.
+// When any of the arguments result in a standard violation then
+// FormatMediaType returns the empty string.
+func FormatMediaType(t string, param map[string]string) string {
+ var b strings.Builder
+ if major, sub, ok := strings.Cut(t, "/"); !ok {
+ if !isToken(t) {
+ return ""
+ }
+ b.WriteString(strings.ToLower(t))
+ } else {
+ if !isToken(major) || !isToken(sub) {
+ return ""
+ }
+ b.WriteString(strings.ToLower(major))
+ b.WriteByte('/')
+ b.WriteString(strings.ToLower(sub))
+ }
+
+ attrs := make([]string, 0, len(param))
+ for a := range param {
+ attrs = append(attrs, a)
+ }
+ sort.Strings(attrs)
+
+ for _, attribute := range attrs {
+ value := param[attribute]
+ b.WriteByte(';')
+ b.WriteByte(' ')
+ if !isToken(attribute) {
+ return ""
+ }
+ b.WriteString(strings.ToLower(attribute))
+
+ needEnc := needsEncoding(value)
+ if needEnc {
+ // RFC 2231 section 4
+ b.WriteByte('*')
+ }
+ b.WriteByte('=')
+
+ if needEnc {
+ b.WriteString("utf-8''")
+
+ offset := 0
+ for index := 0; index < len(value); index++ {
+ ch := value[index]
+ // {RFC 2231 section 7}
+ // attribute-char :=
+ if ch <= ' ' || ch >= 0x7F ||
+ ch == '*' || ch == '\'' || ch == '%' ||
+ isTSpecial(rune(ch)) {
+
+ b.WriteString(value[offset:index])
+ offset = index + 1
+
+ b.WriteByte('%')
+ b.WriteByte(upperhex[ch>>4])
+ b.WriteByte(upperhex[ch&0x0F])
+ }
+ }
+ b.WriteString(value[offset:])
+ continue
+ }
+
+ if isToken(value) {
+ b.WriteString(value)
+ continue
+ }
+
+ b.WriteByte('"')
+ offset := 0
+ for index := 0; index < len(value); index++ {
+ character := value[index]
+ if character == '"' || character == '\\' {
+ b.WriteString(value[offset:index])
+ offset = index
+ b.WriteByte('\\')
+ }
+ }
+ b.WriteString(value[offset:])
+ b.WriteByte('"')
+ }
+ return b.String()
+}
+
+func checkMediaTypeDisposition(s string) error {
+ typ, rest := consumeToken(s)
+ if typ == "" {
+ return errors.New("mime: no media type")
+ }
+ if rest == "" {
+ return nil
+ }
+ if !strings.HasPrefix(rest, "/") {
+ return errors.New("mime: expected slash after first token")
+ }
+ subtype, rest := consumeToken(rest[1:])
+ if subtype == "" {
+ return errors.New("mime: expected token after slash")
+ }
+ if rest != "" {
+ return errors.New("mime: unexpected content after media subtype")
+ }
+ return nil
+}
+
+// ErrInvalidMediaParameter is returned by ParseMediaType if
+// the media type value was found but there was an error parsing
+// the optional parameters
+var ErrInvalidMediaParameter = errors.New("mime: invalid media parameter")
+
+// ParseMediaType parses a media type value and any optional
+// parameters, per RFC 1521. Media types are the values in
+// Content-Type and Content-Disposition headers (RFC 2183).
+// On success, ParseMediaType returns the media type converted
+// to lowercase and trimmed of white space and a non-nil map.
+// If there is an error parsing the optional parameter,
+// the media type will be returned along with the error
+// ErrInvalidMediaParameter.
+// The returned map, params, maps from the lowercase
+// attribute to the attribute value with its case preserved.
+func ParseMediaType(v string) (mediatype string, params map[string]string, err error) {
+ base, _, _ := strings.Cut(v, ";")
+ mediatype = strings.TrimSpace(strings.ToLower(base))
+
+ err = checkMediaTypeDisposition(mediatype)
+ if err != nil {
+ return "", nil, err
+ }
+
+ params = make(map[string]string)
+
+ // Map of base parameter name -> parameter name -> value
+ // for parameters containing a '*' character.
+ // Lazily initialized.
+ var continuation map[string]map[string]string
+
+ v = v[len(base):]
+ for len(v) > 0 {
+ v = strings.TrimLeftFunc(v, unicode.IsSpace)
+ if len(v) == 0 {
+ break
+ }
+ key, value, rest := consumeMediaParam(v)
+ if key == "" {
+ if strings.TrimSpace(rest) == ";" {
+ // Ignore trailing semicolons.
+ // Not an error.
+ break
+ }
+ // Parse error.
+ return mediatype, nil, ErrInvalidMediaParameter
+ }
+
+ pmap := params
+ if baseName, _, ok := strings.Cut(key, "*"); ok {
+ if continuation == nil {
+ continuation = make(map[string]map[string]string)
+ }
+ var ok bool
+ if pmap, ok = continuation[baseName]; !ok {
+ continuation[baseName] = make(map[string]string)
+ pmap = continuation[baseName]
+ }
+ }
+ if v, exists := pmap[key]; exists && v != value {
+ // Duplicate parameter names are incorrect, but we allow them if they are equal.
+ return "", nil, errors.New("mime: duplicate parameter name")
+ }
+ pmap[key] = value
+ v = rest
+ }
+
+ // Stitch together any continuations or things with stars
+ // (i.e. RFC 2231 things with stars: "foo*0" or "foo*")
+ var buf strings.Builder
+ for key, pieceMap := range continuation {
+ singlePartKey := key + "*"
+ if v, ok := pieceMap[singlePartKey]; ok {
+ if decv, ok := decode2231Enc(v); ok {
+ params[key] = decv
+ }
+ continue
+ }
+
+ buf.Reset()
+ valid := false
+ for n := 0; ; n++ {
+ simplePart := fmt.Sprintf("%s*%d", key, n)
+ if v, ok := pieceMap[simplePart]; ok {
+ valid = true
+ buf.WriteString(v)
+ continue
+ }
+ encodedPart := simplePart + "*"
+ v, ok := pieceMap[encodedPart]
+ if !ok {
+ break
+ }
+ valid = true
+ if n == 0 {
+ if decv, ok := decode2231Enc(v); ok {
+ buf.WriteString(decv)
+ }
+ } else {
+ decv, _ := percentHexUnescape(v)
+ buf.WriteString(decv)
+ }
+ }
+ if valid {
+ params[key] = buf.String()
+ }
+ }
+
+ return
+}
+
+func decode2231Enc(v string) (string, bool) {
+ sv := strings.SplitN(v, "'", 3)
+ if len(sv) != 3 {
+ return "", false
+ }
+ // TODO: ignoring lang in sv[1] for now. If anybody needs it we'll
+ // need to decide how to expose it in the API. But I'm not sure
+ // anybody uses it in practice.
+ charset := strings.ToLower(sv[0])
+ if len(charset) == 0 {
+ return "", false
+ }
+ if charset != "us-ascii" && charset != "utf-8" {
+ // TODO: unsupported encoding
+ return "", false
+ }
+ encv, err := percentHexUnescape(sv[2])
+ if err != nil {
+ return "", false
+ }
+ return encv, true
+}
+
+func isNotTokenChar(r rune) bool {
+ return !isTokenChar(r)
+}
+
+// consumeToken consumes a token from the beginning of provided
+// string, per RFC 2045 section 5.1 (referenced from 2183), and return
+// the token consumed and the rest of the string. Returns ("", v) on
+// failure to consume at least one character.
+func consumeToken(v string) (token, rest string) {
+ notPos := strings.IndexFunc(v, isNotTokenChar)
+ if notPos == -1 {
+ return v, ""
+ }
+ if notPos == 0 {
+ return "", v
+ }
+ return v[0:notPos], v[notPos:]
+}
+
+// consumeValue consumes a "value" per RFC 2045, where a value is
+// either a 'token' or a 'quoted-string'. On success, consumeValue
+// returns the value consumed (and de-quoted/escaped, if a
+// quoted-string) and the rest of the string. On failure, returns
+// ("", v).
+func consumeValue(v string) (value, rest string) {
+ if v == "" {
+ return
+ }
+ if v[0] != '"' {
+ return consumeToken(v)
+ }
+
+ // parse a quoted-string
+ buffer := new(strings.Builder)
+ for i := 1; i < len(v); i++ {
+ r := v[i]
+ if r == '"' {
+ return buffer.String(), v[i+1:]
+ }
+ // When MSIE sends a full file path (in "intranet mode"), it does not
+ // escape backslashes: "C:\dev\go\foo.txt", not "C:\\dev\\go\\foo.txt".
+ //
+ // No known MIME generators emit unnecessary backslash escapes
+ // for simple token characters like numbers and letters.
+ //
+ // If we see an unnecessary backslash escape, assume it is from MSIE
+ // and intended as a literal backslash. This makes Go servers deal better
+ // with MSIE without affecting the way they handle conforming MIME
+ // generators.
+ if r == '\\' && i+1 < len(v) && isTSpecial(rune(v[i+1])) {
+ buffer.WriteByte(v[i+1])
+ i++
+ continue
+ }
+ if r == '\r' || r == '\n' {
+ return "", v
+ }
+ buffer.WriteByte(v[i])
+ }
+ // Did not find end quote.
+ return "", v
+}
+
+func consumeMediaParam(v string) (param, value, rest string) {
+ rest = strings.TrimLeftFunc(v, unicode.IsSpace)
+ if !strings.HasPrefix(rest, ";") {
+ return "", "", v
+ }
+
+ rest = rest[1:] // consume semicolon
+ rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
+ param, rest = consumeToken(rest)
+ param = strings.ToLower(param)
+ if param == "" {
+ return "", "", v
+ }
+
+ rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
+ if !strings.HasPrefix(rest, "=") {
+ return "", "", v
+ }
+ rest = rest[1:] // consume equals sign
+ rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
+ value, rest2 := consumeValue(rest)
+ if value == "" && rest2 == rest {
+ return "", "", v
+ }
+ rest = rest2
+ return param, value, rest
+}
+
+func percentHexUnescape(s string) (string, error) {
+ // Count %, check that they're well-formed.
+ percents := 0
+ for i := 0; i < len(s); {
+ if s[i] != '%' {
+ i++
+ continue
+ }
+ percents++
+ if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
+ s = s[i:]
+ if len(s) > 3 {
+ s = s[0:3]
+ }
+ return "", fmt.Errorf("mime: bogus characters after %%: %q", s)
+ }
+ i += 3
+ }
+ if percents == 0 {
+ return s, nil
+ }
+
+ t := make([]byte, len(s)-2*percents)
+ j := 0
+ for i := 0; i < len(s); {
+ switch s[i] {
+ case '%':
+ t[j] = unhex(s[i+1])<<4 | unhex(s[i+2])
+ j++
+ i += 3
+ default:
+ t[j] = s[i]
+ j++
+ i++
+ }
+ }
+ return string(t), nil
+}
+
+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
+}
+
+func unhex(c byte) byte {
+ switch {
+ case '0' <= c && c <= '9':
+ return c - '0'
+ case 'a' <= c && c <= 'f':
+ return c - 'a' + 10
+ case 'A' <= c && c <= 'F':
+ return c - 'A' + 10
+ }
+ return 0
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/mediatype_test.go b/platform/dbops/binaries/go/go/src/mime/mediatype_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1458cdb6e2dd824f2b34ae8a425675fd8682ae2e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/mediatype_test.go
@@ -0,0 +1,540 @@
+// 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 mime
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestConsumeToken(t *testing.T) {
+ tests := [...][3]string{
+ {"foo bar", "foo", " bar"},
+ {"bar", "bar", ""},
+ {"", "", ""},
+ {" foo", "", " foo"},
+ }
+ for _, test := range tests {
+ token, rest := consumeToken(test[0])
+ expectedToken := test[1]
+ expectedRest := test[2]
+ if token != expectedToken {
+ t.Errorf("expected to consume token '%s', not '%s' from '%s'",
+ expectedToken, token, test[0])
+ } else if rest != expectedRest {
+ t.Errorf("expected to have left '%s', not '%s' after reading token '%s' from '%s'",
+ expectedRest, rest, token, test[0])
+ }
+ }
+}
+
+func TestConsumeValue(t *testing.T) {
+ tests := [...][3]string{
+ {"foo bar", "foo", " bar"},
+ {"bar", "bar", ""},
+ {" bar ", "", " bar "},
+ {`"My value"end`, "My value", "end"},
+ {`"My value" end`, "My value", " end"},
+ {`"\\" rest`, "\\", " rest"},
+ {`"My \" value"end`, "My \" value", "end"},
+ {`"\" rest`, "", `"\" rest`},
+ {`"C:\dev\go\robots.txt"`, `C:\dev\go\robots.txt`, ""},
+ {`"C:\新建文件夹\中文第二次测试.mp4"`, `C:\新建文件夹\中文第二次测试.mp4`, ""},
+ }
+ for _, test := range tests {
+ value, rest := consumeValue(test[0])
+ expectedValue := test[1]
+ expectedRest := test[2]
+ if value != expectedValue {
+ t.Errorf("expected to consume value [%s], not [%s] from [%s]",
+ expectedValue, value, test[0])
+ } else if rest != expectedRest {
+ t.Errorf("expected to have left [%s], not [%s] after reading value [%s] from [%s]",
+ expectedRest, rest, value, test[0])
+ }
+ }
+}
+
+func TestConsumeMediaParam(t *testing.T) {
+ tests := [...][4]string{
+ {" ; foo=bar", "foo", "bar", ""},
+ {"; foo=bar", "foo", "bar", ""},
+ {";foo=bar", "foo", "bar", ""},
+ {";FOO=bar", "foo", "bar", ""},
+ {`;foo="bar"`, "foo", "bar", ""},
+ {`;foo="bar"; `, "foo", "bar", "; "},
+ {`;foo="bar"; foo=baz`, "foo", "bar", "; foo=baz"},
+ {` ; boundary=----CUT;`, "boundary", "----CUT", ";"},
+ {` ; key=value; blah="value";name="foo" `, "key", "value", `; blah="value";name="foo" `},
+ {`; blah="value";name="foo" `, "blah", "value", `;name="foo" `},
+ {`;name="foo" `, "name", "foo", ` `},
+ }
+ for _, test := range tests {
+ param, value, rest := consumeMediaParam(test[0])
+ expectedParam := test[1]
+ expectedValue := test[2]
+ expectedRest := test[3]
+ if param != expectedParam {
+ t.Errorf("expected to consume param [%s], not [%s] from [%s]",
+ expectedParam, param, test[0])
+ } else if value != expectedValue {
+ t.Errorf("expected to consume value [%s], not [%s] from [%s]",
+ expectedValue, value, test[0])
+ } else if rest != expectedRest {
+ t.Errorf("expected to have left [%s], not [%s] after reading [%s/%s] from [%s]",
+ expectedRest, rest, param, value, test[0])
+ }
+ }
+}
+
+type mediaTypeTest struct {
+ in string
+ t string
+ p map[string]string
+}
+
+func TestParseMediaType(t *testing.T) {
+ // Convenience map initializer
+ m := func(s ...string) map[string]string {
+ sm := make(map[string]string)
+ for i := 0; i < len(s); i += 2 {
+ sm[s[i]] = s[i+1]
+ }
+ return sm
+ }
+
+ nameFoo := map[string]string{"name": "foo"}
+ tests := []mediaTypeTest{
+ {`form-data; name="foo"`, "form-data", nameFoo},
+ {` form-data ; name=foo`, "form-data", nameFoo},
+ {`FORM-DATA;name="foo"`, "form-data", nameFoo},
+ {` FORM-DATA ; name="foo"`, "form-data", nameFoo},
+ {` FORM-DATA ; name="foo"`, "form-data", nameFoo},
+
+ {`form-data; key=value; blah="value";name="foo" `,
+ "form-data",
+ m("key", "value", "blah", "value", "name", "foo")},
+
+ {`foo; key=val1; key=the-key-appears-again-which-is-bogus`,
+ "", m()},
+
+ // From RFC 2231:
+ {`application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A`,
+ "application/x-stuff",
+ m("title", "This is ***fun***")},
+
+ {`message/external-body; access-type=URL; ` +
+ `URL*0="ftp://";` +
+ `URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"`,
+ "message/external-body",
+ m("access-type", "URL",
+ "url", "ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar")},
+
+ {`application/x-stuff; ` +
+ `title*0*=us-ascii'en'This%20is%20even%20more%20; ` +
+ `title*1*=%2A%2A%2Afun%2A%2A%2A%20; ` +
+ `title*2="isn't it!"`,
+ "application/x-stuff",
+ m("title", "This is even more ***fun*** isn't it!")},
+
+ // Tests from http://greenbytes.de/tech/tc2231/
+ // Note: Backslash escape handling is a bit loose, like MSIE.
+
+ // #attonly
+ {`attachment`,
+ "attachment",
+ m()},
+ // #attonlyucase
+ {`ATTACHMENT`,
+ "attachment",
+ m()},
+ // #attwithasciifilename
+ {`attachment; filename="foo.html"`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attwithasciifilename25
+ {`attachment; filename="0000000000111111111122222"`,
+ "attachment",
+ m("filename", "0000000000111111111122222")},
+ // #attwithasciifilename35
+ {`attachment; filename="00000000001111111111222222222233333"`,
+ "attachment",
+ m("filename", "00000000001111111111222222222233333")},
+ // #attwithasciifnescapedchar
+ {`attachment; filename="f\oo.html"`,
+ "attachment",
+ m("filename", "f\\oo.html")},
+ // #attwithasciifnescapedquote
+ {`attachment; filename="\"quoting\" tested.html"`,
+ "attachment",
+ m("filename", `"quoting" tested.html`)},
+ // #attwithquotedsemicolon
+ {`attachment; filename="Here's a semicolon;.html"`,
+ "attachment",
+ m("filename", "Here's a semicolon;.html")},
+ // #attwithfilenameandextparam
+ {`attachment; foo="bar"; filename="foo.html"`,
+ "attachment",
+ m("foo", "bar", "filename", "foo.html")},
+ // #attwithfilenameandextparamescaped
+ {`attachment; foo="\"\\";filename="foo.html"`,
+ "attachment",
+ m("foo", "\"\\", "filename", "foo.html")},
+ // #attwithasciifilenameucase
+ {`attachment; FILENAME="foo.html"`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attwithasciifilenamenq
+ {`attachment; filename=foo.html`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attwithasciifilenamenqs
+ {`attachment; filename=foo.html ;`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attwithfntokensq
+ {`attachment; filename='foo.html'`,
+ "attachment",
+ m("filename", "'foo.html'")},
+ // #attwithisofnplain
+ {`attachment; filename="foo-ä.html"`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithutf8fnplain
+ {`attachment; filename="foo-ä.html"`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithfnrawpctenca
+ {`attachment; filename="foo-%41.html"`,
+ "attachment",
+ m("filename", "foo-%41.html")},
+ // #attwithfnusingpct
+ {`attachment; filename="50%.html"`,
+ "attachment",
+ m("filename", "50%.html")},
+ // #attwithfnrawpctencaq
+ {`attachment; filename="foo-%\41.html"`,
+ "attachment",
+ m("filename", "foo-%\\41.html")},
+ // #attwithnamepct
+ {`attachment; name="foo-%41.html"`,
+ "attachment",
+ m("name", "foo-%41.html")},
+ // #attwithfilenamepctandiso
+ {`attachment; name="ä-%41.html"`,
+ "attachment",
+ m("name", "ä-%41.html")},
+ // #attwithfnrawpctenclong
+ {`attachment; filename="foo-%c3%a4-%e2%82%ac.html"`,
+ "attachment",
+ m("filename", "foo-%c3%a4-%e2%82%ac.html")},
+ // #attwithasciifilenamews1
+ {`attachment; filename ="foo.html"`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attmissingdisposition
+ {`filename=foo.html`,
+ "", m()},
+ // #attmissingdisposition2
+ {`x=y; filename=foo.html`,
+ "", m()},
+ // #attmissingdisposition3
+ {`"foo; filename=bar;baz"; filename=qux`,
+ "", m()},
+ // #attmissingdisposition4
+ {`filename=foo.html, filename=bar.html`,
+ "", m()},
+ // #emptydisposition
+ {`; filename=foo.html`,
+ "", m()},
+ // #doublecolon
+ {`: inline; attachment; filename=foo.html`,
+ "", m()},
+ // #attandinline
+ {`inline; attachment; filename=foo.html`,
+ "", m()},
+ // #attandinline2
+ {`attachment; inline; filename=foo.html`,
+ "", m()},
+ // #attbrokenquotedfn
+ {`attachment; filename="foo.html".txt`,
+ "", m()},
+ // #attbrokenquotedfn2
+ {`attachment; filename="bar`,
+ "", m()},
+ // #attbrokenquotedfn3
+ {`attachment; filename=foo"bar;baz"qux`,
+ "", m()},
+ // #attmultinstances
+ {`attachment; filename=foo.html, attachment; filename=bar.html`,
+ "", m()},
+ // #attmissingdelim
+ {`attachment; foo=foo filename=bar`,
+ "", m()},
+ // #attmissingdelim2
+ {`attachment; filename=bar foo=foo`,
+ "", m()},
+ // #attmissingdelim3
+ {`attachment filename=bar`,
+ "", m()},
+ // #attreversed
+ {`filename=foo.html; attachment`,
+ "", m()},
+ // #attconfusedparam
+ {`attachment; xfilename=foo.html`,
+ "attachment",
+ m("xfilename", "foo.html")},
+ // #attcdate
+ {`attachment; creation-date="Wed, 12 Feb 1997 16:29:51 -0500"`,
+ "attachment",
+ m("creation-date", "Wed, 12 Feb 1997 16:29:51 -0500")},
+ // #attmdate
+ {`attachment; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"`,
+ "attachment",
+ m("modification-date", "Wed, 12 Feb 1997 16:29:51 -0500")},
+ // #dispext
+ {`foobar`, "foobar", m()},
+ // #dispextbadfn
+ {`attachment; example="filename=example.txt"`,
+ "attachment",
+ m("example", "filename=example.txt")},
+ // #attwithfn2231utf8
+ {`attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html`,
+ "attachment",
+ m("filename", "foo-ä-€.html")},
+ // #attwithfn2231noc
+ {`attachment; filename*=''foo-%c3%a4-%e2%82%ac.html`,
+ "attachment",
+ m()},
+ // #attwithfn2231utf8comp
+ {`attachment; filename*=UTF-8''foo-a%cc%88.html`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithfn2231ws2
+ {`attachment; filename*= UTF-8''foo-%c3%a4.html`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithfn2231ws3
+ {`attachment; filename* =UTF-8''foo-%c3%a4.html`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithfn2231quot
+ {`attachment; filename*="UTF-8''foo-%c3%a4.html"`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attwithfn2231quot2
+ {`attachment; filename*="foo%20bar.html"`,
+ "attachment",
+ m()},
+ // #attwithfn2231singleqmissing
+ {`attachment; filename*=UTF-8'foo-%c3%a4.html`,
+ "attachment",
+ m()},
+ // #attwithfn2231nbadpct1
+ {`attachment; filename*=UTF-8''foo%`,
+ "attachment",
+ m()},
+ // #attwithfn2231nbadpct2
+ {`attachment; filename*=UTF-8''f%oo.html`,
+ "attachment",
+ m()},
+ // #attwithfn2231dpct
+ {`attachment; filename*=UTF-8''A-%2541.html`,
+ "attachment",
+ m("filename", "A-%41.html")},
+ // #attfncont
+ {`attachment; filename*0="foo."; filename*1="html"`,
+ "attachment",
+ m("filename", "foo.html")},
+ // #attfncontenc
+ {`attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=".html"`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attfncontlz
+ {`attachment; filename*0="foo"; filename*01="bar"`,
+ "attachment",
+ m("filename", "foo")},
+ // #attfncontnc
+ {`attachment; filename*0="foo"; filename*2="bar"`,
+ "attachment",
+ m("filename", "foo")},
+ // #attfnconts1
+ {`attachment; filename*1="foo."; filename*2="html"`,
+ "attachment", m()},
+ // #attfncontord
+ {`attachment; filename*1="bar"; filename*0="foo"`,
+ "attachment",
+ m("filename", "foobar")},
+ // #attfnboth
+ {`attachment; filename="foo-ae.html"; filename*=UTF-8''foo-%c3%a4.html`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attfnboth2
+ {`attachment; filename*=UTF-8''foo-%c3%a4.html; filename="foo-ae.html"`,
+ "attachment",
+ m("filename", "foo-ä.html")},
+ // #attfnboth3
+ {`attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; filename*=ISO-8859-1''currency-sign%3d%a4`,
+ "attachment",
+ m()},
+ // #attnewandfn
+ {`attachment; foobar=x; filename="foo.html"`,
+ "attachment",
+ m("foobar", "x", "filename", "foo.html")},
+
+ // Browsers also just send UTF-8 directly without RFC 2231,
+ // at least when the source page is served with UTF-8.
+ {`form-data; firstname="Брэд"; lastname="Фицпатрик"`,
+ "form-data",
+ m("firstname", "Брэд", "lastname", "Фицпатрик")},
+
+ // Empty string used to be mishandled.
+ {`foo; bar=""`, "foo", m("bar", "")},
+
+ // Microsoft browsers in intranet mode do not think they need to escape \ in file name.
+ {`form-data; name="file"; filename="C:\dev\go\robots.txt"`, "form-data", m("name", "file", "filename", `C:\dev\go\robots.txt`)},
+ {`form-data; name="file"; filename="C:\新建文件夹\中文第二次测试.mp4"`, "form-data", m("name", "file", "filename", `C:\新建文件夹\中文第二次测试.mp4`)},
+
+ // issue #46323 (https://github.com/golang/go/issues/46323)
+ {
+ // example from rfc2231-p.3 (https://datatracker.ietf.org/doc/html/rfc2231)
+ `message/external-body; access-type=URL;
+ URL*0="ftp://";
+ URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar";`, // <-- trailing semicolon
+ `message/external-body`,
+ m("access-type", "URL", "url", "ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar"),
+ },
+
+ // Issue #48866: duplicate parameters containing equal values should be allowed
+ {`text; charset=utf-8; charset=utf-8; format=fixed`, "text", m("charset", "utf-8", "format", "fixed")},
+ {`text; charset=utf-8; format=flowed; charset=utf-8`, "text", m("charset", "utf-8", "format", "flowed")},
+ }
+ for _, test := range tests {
+ mt, params, err := ParseMediaType(test.in)
+ if err != nil {
+ if test.t != "" {
+ t.Errorf("for input %#q, unexpected error: %v", test.in, err)
+ continue
+ }
+ continue
+ }
+ if g, e := mt, test.t; g != e {
+ t.Errorf("for input %#q, expected type %q, got %q",
+ test.in, e, g)
+ continue
+ }
+ if len(params) == 0 && len(test.p) == 0 {
+ continue
+ }
+ if !reflect.DeepEqual(params, test.p) {
+ t.Errorf("for input %#q, wrong params.\n"+
+ "expected: %#v\n"+
+ " got: %#v",
+ test.in, test.p, params)
+ }
+ }
+}
+
+type badMediaTypeTest struct {
+ in string
+ mt string
+ err string
+}
+
+var badMediaTypeTests = []badMediaTypeTest{
+ {"bogus ;=========", "bogus", "mime: invalid media parameter"},
+ // The following example is from real email delivered by gmail (error: missing semicolon)
+ // and it is there to check behavior described in #19498
+ {"application/pdf; x-mac-type=\"3F3F3F3F\"; x-mac-creator=\"3F3F3F3F\" name=\"a.pdf\";",
+ "application/pdf", "mime: invalid media parameter"},
+ {"bogus/", "", "mime: expected token after slash"},
+ {"bogus/bogus", "", "mime: unexpected content after media subtype"},
+ // Tests from http://greenbytes.de/tech/tc2231/
+ {`"attachment"`, "attachment", "mime: no media type"},
+ {"attachment; filename=foo,bar.html", "attachment", "mime: invalid media parameter"},
+ {"attachment; ;filename=foo", "attachment", "mime: invalid media parameter"},
+ {"attachment; filename=foo bar.html", "attachment", "mime: invalid media parameter"},
+ {`attachment; filename="foo.html"; filename="bar.html"`, "attachment", "mime: duplicate parameter name"},
+ {"attachment; filename=foo[1](2).html", "attachment", "mime: invalid media parameter"},
+ {"attachment; filename=foo-ä.html", "attachment", "mime: invalid media parameter"},
+ {"attachment; filename=foo-ä.html", "attachment", "mime: invalid media parameter"},
+ {`attachment; filename *=UTF-8''foo-%c3%a4.html`, "attachment", "mime: invalid media parameter"},
+}
+
+func TestParseMediaTypeBogus(t *testing.T) {
+ for _, tt := range badMediaTypeTests {
+ mt, params, err := ParseMediaType(tt.in)
+ if err == nil {
+ t.Errorf("ParseMediaType(%q) = nil error; want parse error", tt.in)
+ continue
+ }
+ if err.Error() != tt.err {
+ t.Errorf("ParseMediaType(%q) = err %q; want %q", tt.in, err.Error(), tt.err)
+ }
+ if params != nil {
+ t.Errorf("ParseMediaType(%q): got non-nil params on error", tt.in)
+ }
+ if err != ErrInvalidMediaParameter && mt != "" {
+ t.Errorf("ParseMediaType(%q): got unexpected non-empty media type string", tt.in)
+ }
+ if err == ErrInvalidMediaParameter && mt != tt.mt {
+ t.Errorf("ParseMediaType(%q): in case of invalid parameters: expected type %q, got %q", tt.in, tt.mt, mt)
+ }
+ }
+}
+
+type formatTest struct {
+ typ string
+ params map[string]string
+ want string
+}
+
+var formatTests = []formatTest{
+ {"noslash", map[string]string{"X": "Y"}, "noslash; x=Y"}, // e.g. Content-Disposition values (RFC 2183); issue 11289
+ {"foo bar/baz", nil, ""},
+ {"foo/bar baz", nil, ""},
+ {"attachment", map[string]string{"filename": "ĄĄŽŽČČŠŠ"}, "attachment; filename*=utf-8''%C4%84%C4%84%C5%BD%C5%BD%C4%8C%C4%8C%C5%A0%C5%A0"},
+ {"attachment", map[string]string{"filename": "ÁÁÊÊÇÇÎÎ"}, "attachment; filename*=utf-8''%C3%81%C3%81%C3%8A%C3%8A%C3%87%C3%87%C3%8E%C3%8E"},
+ {"attachment", map[string]string{"filename": "数据统计.png"}, "attachment; filename*=utf-8''%E6%95%B0%E6%8D%AE%E7%BB%9F%E8%AE%A1.png"},
+ {"foo/BAR", nil, "foo/bar"},
+ {"foo/BAR", map[string]string{"X": "Y"}, "foo/bar; x=Y"},
+ {"foo/BAR", map[string]string{"space": "With space"}, `foo/bar; space="With space"`},
+ {"foo/BAR", map[string]string{"quote": `With "quote`}, `foo/bar; quote="With \"quote"`},
+ {"foo/BAR", map[string]string{"bslash": `With \backslash`}, `foo/bar; bslash="With \\backslash"`},
+ {"foo/BAR", map[string]string{"both": `With \backslash and "quote`}, `foo/bar; both="With \\backslash and \"quote"`},
+ {"foo/BAR", map[string]string{"": "empty attribute"}, ""},
+ {"foo/BAR", map[string]string{"bad attribute": "baz"}, ""},
+ {"foo/BAR", map[string]string{"nonascii": "not an ascii character: ä"}, "foo/bar; nonascii*=utf-8''not%20an%20ascii%20character%3A%20%C3%A4"},
+ {"foo/BAR", map[string]string{"ctl": "newline: \n nil: \000"}, "foo/bar; ctl*=utf-8''newline%3A%20%0A%20nil%3A%20%00"},
+ {"foo/bar", map[string]string{"a": "av", "b": "bv", "c": "cv"}, "foo/bar; a=av; b=bv; c=cv"},
+ {"foo/bar", map[string]string{"0": "'", "9": "'"}, "foo/bar; 0='; 9='"},
+ {"foo", map[string]string{"bar": ""}, `foo; bar=""`},
+}
+
+func TestFormatMediaType(t *testing.T) {
+ for i, tt := range formatTests {
+ got := FormatMediaType(tt.typ, tt.params)
+ if got != tt.want {
+ t.Errorf("%d. FormatMediaType(%q, %v) = %q; want %q", i, tt.typ, tt.params, got, tt.want)
+ }
+ if got == "" {
+ continue
+ }
+ typ, params, err := ParseMediaType(got)
+ if err != nil {
+ t.Errorf("%d. ParseMediaType(%q) err: %v", i, got, err)
+ }
+ if typ != strings.ToLower(tt.typ) {
+ t.Errorf("%d. ParseMediaType(%q) typ = %q; want %q", i, got, typ, tt.typ)
+ }
+ for k, v := range tt.params {
+ k = strings.ToLower(k)
+ if params[k] != v {
+ t.Errorf("%d. ParseMediaType(%q) params[%s] = %q; want %q", i, got, k, params[k], v)
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type.go b/platform/dbops/binaries/go/go/src/mime/type.go
new file mode 100644
index 0000000000000000000000000000000000000000..465ecf0d599ccbac420a313fb9cb7603ec1b0504
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type.go
@@ -0,0 +1,202 @@
+// 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 mime implements parts of the MIME spec.
+package mime
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+)
+
+var (
+ mimeTypes sync.Map // map[string]string; ".Z" => "application/x-compress"
+ mimeTypesLower sync.Map // map[string]string; ".z" => "application/x-compress"
+
+ // extensions maps from MIME type to list of lowercase file
+ // extensions: "image/jpeg" => [".jpg", ".jpeg"]
+ extensionsMu sync.Mutex // Guards stores (but not loads) on extensions.
+ extensions sync.Map // map[string][]string; slice values are append-only.
+)
+
+func clearSyncMap(m *sync.Map) {
+ m.Range(func(k, _ any) bool {
+ m.Delete(k)
+ return true
+ })
+}
+
+// setMimeTypes is used by initMime's non-test path, and by tests.
+func setMimeTypes(lowerExt, mixExt map[string]string) {
+ clearSyncMap(&mimeTypes)
+ clearSyncMap(&mimeTypesLower)
+ clearSyncMap(&extensions)
+
+ for k, v := range lowerExt {
+ mimeTypesLower.Store(k, v)
+ }
+ for k, v := range mixExt {
+ mimeTypes.Store(k, v)
+ }
+
+ extensionsMu.Lock()
+ defer extensionsMu.Unlock()
+ for k, v := range lowerExt {
+ justType, _, err := ParseMediaType(v)
+ if err != nil {
+ panic(err)
+ }
+ var exts []string
+ if ei, ok := extensions.Load(justType); ok {
+ exts = ei.([]string)
+ }
+ extensions.Store(justType, append(exts, k))
+ }
+}
+
+var builtinTypesLower = map[string]string{
+ ".avif": "image/avif",
+ ".css": "text/css; charset=utf-8",
+ ".gif": "image/gif",
+ ".htm": "text/html; charset=utf-8",
+ ".html": "text/html; charset=utf-8",
+ ".jpeg": "image/jpeg",
+ ".jpg": "image/jpeg",
+ ".js": "text/javascript; charset=utf-8",
+ ".json": "application/json",
+ ".mjs": "text/javascript; charset=utf-8",
+ ".pdf": "application/pdf",
+ ".png": "image/png",
+ ".svg": "image/svg+xml",
+ ".wasm": "application/wasm",
+ ".webp": "image/webp",
+ ".xml": "text/xml; charset=utf-8",
+}
+
+var once sync.Once // guards initMime
+
+var testInitMime, osInitMime func()
+
+func initMime() {
+ if fn := testInitMime; fn != nil {
+ fn()
+ } else {
+ setMimeTypes(builtinTypesLower, builtinTypesLower)
+ osInitMime()
+ }
+}
+
+// TypeByExtension returns the MIME type associated with the file extension ext.
+// The extension ext should begin with a leading dot, as in ".html".
+// When ext has no associated type, TypeByExtension returns "".
+//
+// Extensions are looked up first case-sensitively, then case-insensitively.
+//
+// The built-in table is small but on unix it is augmented by the local
+// system's MIME-info database or mime.types file(s) if available under one or
+// more of these names:
+//
+// /usr/local/share/mime/globs2
+// /usr/share/mime/globs2
+// /etc/mime.types
+// /etc/apache2/mime.types
+// /etc/apache/mime.types
+//
+// On Windows, MIME types are extracted from the registry.
+//
+// Text types have the charset parameter set to "utf-8" by default.
+func TypeByExtension(ext string) string {
+ once.Do(initMime)
+
+ // Case-sensitive lookup.
+ if v, ok := mimeTypes.Load(ext); ok {
+ return v.(string)
+ }
+
+ // Case-insensitive lookup.
+ // Optimistically assume a short ASCII extension and be
+ // allocation-free in that case.
+ var buf [10]byte
+ lower := buf[:0]
+ const utf8RuneSelf = 0x80 // from utf8 package, but not importing it.
+ for i := 0; i < len(ext); i++ {
+ c := ext[i]
+ if c >= utf8RuneSelf {
+ // Slow path.
+ si, _ := mimeTypesLower.Load(strings.ToLower(ext))
+ s, _ := si.(string)
+ return s
+ }
+ if 'A' <= c && c <= 'Z' {
+ lower = append(lower, c+('a'-'A'))
+ } else {
+ lower = append(lower, c)
+ }
+ }
+ si, _ := mimeTypesLower.Load(string(lower))
+ s, _ := si.(string)
+ return s
+}
+
+// ExtensionsByType returns the extensions known to be associated with the MIME
+// type typ. The returned extensions will each begin with a leading dot, as in
+// ".html". When typ has no associated extensions, ExtensionsByType returns an
+// nil slice.
+func ExtensionsByType(typ string) ([]string, error) {
+ justType, _, err := ParseMediaType(typ)
+ if err != nil {
+ return nil, err
+ }
+
+ once.Do(initMime)
+ s, ok := extensions.Load(justType)
+ if !ok {
+ return nil, nil
+ }
+ ret := append([]string(nil), s.([]string)...)
+ sort.Strings(ret)
+ return ret, nil
+}
+
+// AddExtensionType sets the MIME type associated with
+// the extension ext to typ. The extension should begin with
+// a leading dot, as in ".html".
+func AddExtensionType(ext, typ string) error {
+ if !strings.HasPrefix(ext, ".") {
+ return fmt.Errorf("mime: extension %q missing leading dot", ext)
+ }
+ once.Do(initMime)
+ return setExtensionType(ext, typ)
+}
+
+func setExtensionType(extension, mimeType string) error {
+ justType, param, err := ParseMediaType(mimeType)
+ if err != nil {
+ return err
+ }
+ if strings.HasPrefix(mimeType, "text/") && param["charset"] == "" {
+ param["charset"] = "utf-8"
+ mimeType = FormatMediaType(mimeType, param)
+ }
+ extLower := strings.ToLower(extension)
+
+ mimeTypes.Store(extension, mimeType)
+ mimeTypesLower.Store(extLower, mimeType)
+
+ extensionsMu.Lock()
+ defer extensionsMu.Unlock()
+ var exts []string
+ if ei, ok := extensions.Load(justType); ok {
+ exts = ei.([]string)
+ }
+ for _, v := range exts {
+ if v == extLower {
+ return nil
+ }
+ }
+ extensions.Store(justType, append(exts, extLower))
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_dragonfly.go b/platform/dbops/binaries/go/go/src/mime/type_dragonfly.go
new file mode 100644
index 0000000000000000000000000000000000000000..d09d74a9cce251236f2831a3ef71575fdd138c87
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_dragonfly.go
@@ -0,0 +1,9 @@
+// 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 mime
+
+func init() {
+ typeFiles = append(typeFiles, "/usr/local/etc/mime.types")
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_freebsd.go b/platform/dbops/binaries/go/go/src/mime/type_freebsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..d09d74a9cce251236f2831a3ef71575fdd138c87
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_freebsd.go
@@ -0,0 +1,9 @@
+// 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 mime
+
+func init() {
+ typeFiles = append(typeFiles, "/usr/local/etc/mime.types")
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_openbsd.go b/platform/dbops/binaries/go/go/src/mime/type_openbsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..c3b1abb99fc0a457373b9f01b8d45fc7e7251154
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_openbsd.go
@@ -0,0 +1,9 @@
+// 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 mime
+
+func init() {
+ typeFiles = append(typeFiles, "/usr/share/misc/mime.types")
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_plan9.go b/platform/dbops/binaries/go/go/src/mime/type_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..14ff973405186392163ed42dd5db5b1d6e47fec7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_plan9.go
@@ -0,0 +1,57 @@
+// 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 mime
+
+import (
+ "bufio"
+ "os"
+ "strings"
+)
+
+func init() {
+ osInitMime = initMimePlan9
+}
+
+func initMimePlan9() {
+ for _, filename := range typeFiles {
+ loadMimeFile(filename)
+ }
+}
+
+var typeFiles = []string{
+ "/sys/lib/mimetype",
+}
+
+func initMimeForTests() map[string]string {
+ typeFiles = []string{"testdata/test.types.plan9"}
+ return map[string]string{
+ ".t1": "application/test",
+ ".t2": "text/test; charset=utf-8",
+ ".pNg": "image/png",
+ }
+}
+
+func loadMimeFile(filename string) {
+ f, err := os.Open(filename)
+ if err != nil {
+ return
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ fields := strings.Fields(scanner.Text())
+ if len(fields) <= 2 || fields[0][0] != '.' {
+ continue
+ }
+ if fields[1] == "-" || fields[2] == "-" {
+ continue
+ }
+ setExtensionType(fields[0], fields[1]+"/"+fields[2])
+ }
+ if err := scanner.Err(); err != nil {
+ panic(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_test.go b/platform/dbops/binaries/go/go/src/mime/type_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d8368e8846f62794e98ce2ebc5f439c240374e30
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_test.go
@@ -0,0 +1,220 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package mime
+
+import (
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func setMimeInit(fn func()) (cleanup func()) {
+ once = sync.Once{}
+ testInitMime = fn
+ return func() {
+ testInitMime = nil
+ once = sync.Once{}
+ }
+}
+
+func clearMimeTypes() {
+ setMimeTypes(map[string]string{}, map[string]string{})
+}
+
+func setType(ext, typ string) {
+ if !strings.HasPrefix(ext, ".") {
+ panic("missing leading dot")
+ }
+ if err := setExtensionType(ext, typ); err != nil {
+ panic("bad test data: " + err.Error())
+ }
+}
+
+func TestTypeByExtension(t *testing.T) {
+ once = sync.Once{}
+ // initMimeForTests returns the platform-specific extension =>
+ // type tests. On Unix and Plan 9, this also tests the parsing
+ // of MIME text files (in testdata/*). On Windows, we test the
+ // real registry on the machine and assume that ".png" exists
+ // there, which empirically it always has, for all versions of
+ // Windows.
+ typeTests := initMimeForTests()
+
+ for ext, want := range typeTests {
+ val := TypeByExtension(ext)
+ if val != want {
+ t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want)
+ }
+ }
+}
+
+func TestTypeByExtension_LocalData(t *testing.T) {
+ cleanup := setMimeInit(func() {
+ clearMimeTypes()
+ setType(".foo", "x/foo")
+ setType(".bar", "x/bar")
+ setType(".Bar", "x/bar; capital=1")
+ })
+ defer cleanup()
+
+ tests := map[string]string{
+ ".foo": "x/foo",
+ ".bar": "x/bar",
+ ".Bar": "x/bar; capital=1",
+ ".sdlkfjskdlfj": "",
+ ".t1": "", // testdata shouldn't be used
+ }
+
+ for ext, want := range tests {
+ val := TypeByExtension(ext)
+ if val != want {
+ t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want)
+ }
+ }
+}
+
+func TestTypeByExtensionCase(t *testing.T) {
+ const custom = "test/test; charset=iso-8859-1"
+ const caps = "test/test; WAS=ALLCAPS"
+
+ cleanup := setMimeInit(func() {
+ clearMimeTypes()
+ setType(".TEST", caps)
+ setType(".tesT", custom)
+ })
+ defer cleanup()
+
+ // case-sensitive lookup
+ if got := TypeByExtension(".tesT"); got != custom {
+ t.Fatalf("for .tesT, got %q; want %q", got, custom)
+ }
+ if got := TypeByExtension(".TEST"); got != caps {
+ t.Fatalf("for .TEST, got %q; want %s", got, caps)
+ }
+
+ // case-insensitive
+ if got := TypeByExtension(".TesT"); got != custom {
+ t.Fatalf("for .TesT, got %q; want %q", got, custom)
+ }
+}
+
+func TestExtensionsByType(t *testing.T) {
+ cleanup := setMimeInit(func() {
+ clearMimeTypes()
+ setType(".gif", "image/gif")
+ setType(".a", "foo/letter")
+ setType(".b", "foo/letter")
+ setType(".B", "foo/letter")
+ setType(".PNG", "image/png")
+ })
+ defer cleanup()
+
+ tests := []struct {
+ typ string
+ want []string
+ wantErr string
+ }{
+ {typ: "image/gif", want: []string{".gif"}},
+ {typ: "image/png", want: []string{".png"}}, // lowercase
+ {typ: "foo/letter", want: []string{".a", ".b"}},
+ {typ: "x/unknown", want: nil},
+ }
+
+ for _, tt := range tests {
+ got, err := ExtensionsByType(tt.typ)
+ if err != nil && tt.wantErr != "" && strings.Contains(err.Error(), tt.wantErr) {
+ continue
+ }
+ if err != nil {
+ t.Errorf("ExtensionsByType(%q) error: %v", tt.typ, err)
+ continue
+ }
+ if tt.wantErr != "" {
+ t.Errorf("ExtensionsByType(%q) = %q, %v; want error substring %q", tt.typ, got, err, tt.wantErr)
+ continue
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want)
+ }
+ }
+}
+
+func TestLookupMallocs(t *testing.T) {
+ n := testing.AllocsPerRun(10000, func() {
+ TypeByExtension(".html")
+ TypeByExtension(".HtML")
+ })
+ if n > 0 {
+ t.Errorf("allocs = %v; want 0", n)
+ }
+}
+
+func BenchmarkTypeByExtension(b *testing.B) {
+ initMime()
+ b.ResetTimer()
+
+ for _, ext := range []string{
+ ".html",
+ ".HTML",
+ ".unused",
+ } {
+ b.Run(ext, func(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ TypeByExtension(ext)
+ }
+ })
+ })
+ }
+}
+
+func BenchmarkExtensionsByType(b *testing.B) {
+ initMime()
+ b.ResetTimer()
+
+ for _, typ := range []string{
+ "text/html",
+ "text/html; charset=utf-8",
+ "application/octet-stream",
+ } {
+ b.Run(typ, func(b *testing.B) {
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ if _, err := ExtensionsByType(typ); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+ })
+ }
+}
+
+func TestExtensionsByType2(t *testing.T) {
+ cleanup := setMimeInit(func() {
+ clearMimeTypes()
+ // Initialize built-in types like in type.go before osInitMime.
+ setMimeTypes(builtinTypesLower, builtinTypesLower)
+ })
+ defer cleanup()
+
+ tests := []struct {
+ typ string
+ want []string
+ }{
+ {typ: "image/jpeg", want: []string{".jpeg", ".jpg"}},
+ }
+
+ for _, tt := range tests {
+ got, err := ExtensionsByType(tt.typ)
+ if err != nil {
+ t.Errorf("ExtensionsByType(%q): %v", tt.typ, err)
+ continue
+ }
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_unix.go b/platform/dbops/binaries/go/go/src/mime/type_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..90414c1a18d06fa745be402f66b731a61923e4a1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_unix.go
@@ -0,0 +1,126 @@
+// 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 unix || (js && wasm) || wasip1
+
+package mime
+
+import (
+ "bufio"
+ "os"
+ "strings"
+)
+
+func init() {
+ osInitMime = initMimeUnix
+}
+
+// See https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-0.21.html
+// for the FreeDesktop Shared MIME-info Database specification.
+var mimeGlobs = []string{
+ "/usr/local/share/mime/globs2",
+ "/usr/share/mime/globs2",
+}
+
+// Common locations for mime.types files on unix.
+var typeFiles = []string{
+ "/etc/mime.types",
+ "/etc/apache2/mime.types",
+ "/etc/apache/mime.types",
+ "/etc/httpd/conf/mime.types",
+}
+
+func loadMimeGlobsFile(filename string) error {
+ f, err := os.Open(filename)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ // Each line should be of format: weight:mimetype:glob[:morefields...]
+ fields := strings.Split(scanner.Text(), ":")
+ if len(fields) < 3 || len(fields[0]) < 1 || len(fields[2]) < 3 {
+ continue
+ } else if fields[0][0] == '#' || fields[2][0] != '*' || fields[2][1] != '.' {
+ continue
+ }
+
+ extension := fields[2][1:]
+ if strings.ContainsAny(extension, "?*[") {
+ // Not a bare extension, but a glob. Ignore for now:
+ // - we do not have an implementation for this glob
+ // syntax (translation to path/filepath.Match could
+ // be possible)
+ // - support for globs with weight ordering would have
+ // performance impact to all lookups to support the
+ // rarely seen glob entries
+ // - trying to match glob metacharacters literally is
+ // not useful
+ continue
+ }
+ if _, ok := mimeTypes.Load(extension); ok {
+ // We've already seen this extension.
+ // The file is in weight order, so we keep
+ // the first entry that we see.
+ continue
+ }
+
+ setExtensionType(extension, fields[1])
+ }
+ if err := scanner.Err(); err != nil {
+ panic(err)
+ }
+ return nil
+}
+
+func loadMimeFile(filename string) {
+ f, err := os.Open(filename)
+ if err != nil {
+ return
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ fields := strings.Fields(scanner.Text())
+ if len(fields) <= 1 || fields[0][0] == '#' {
+ continue
+ }
+ mimeType := fields[0]
+ for _, ext := range fields[1:] {
+ if ext[0] == '#' {
+ break
+ }
+ setExtensionType("."+ext, mimeType)
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ panic(err)
+ }
+}
+
+func initMimeUnix() {
+ for _, filename := range mimeGlobs {
+ if err := loadMimeGlobsFile(filename); err == nil {
+ return // Stop checking more files if mimetype database is found.
+ }
+ }
+
+ // Fallback if no system-generated mimetype database exists.
+ for _, filename := range typeFiles {
+ loadMimeFile(filename)
+ }
+}
+
+func initMimeForTests() map[string]string {
+ mimeGlobs = []string{""}
+ typeFiles = []string{"testdata/test.types"}
+ return map[string]string{
+ ".T1": "application/test",
+ ".t2": "text/test; charset=utf-8",
+ ".png": "image/png",
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_unix_test.go b/platform/dbops/binaries/go/go/src/mime/type_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7b8db79d272a986b3a0df156a5489187d0fabf80
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_unix_test.go
@@ -0,0 +1,44 @@
+// Copyright 2021 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build unix || (js && wasm)
+
+package mime
+
+import (
+ "testing"
+)
+
+func initMimeUnixTest(t *testing.T) {
+ once.Do(initMime)
+ err := loadMimeGlobsFile("testdata/test.types.globs2")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ loadMimeFile("testdata/test.types")
+}
+
+func TestTypeByExtensionUNIX(t *testing.T) {
+ initMimeUnixTest(t)
+ typeTests := map[string]string{
+ ".T1": "application/test",
+ ".t2": "text/test; charset=utf-8",
+ ".t3": "document/test",
+ ".t4": "example/test",
+ ".png": "image/png",
+ ",v": "",
+ "~": "",
+ ".foo?ar": "",
+ ".foo*r": "",
+ ".foo[1-3]": "",
+ }
+
+ for ext, want := range typeTests {
+ val := TypeByExtension(ext)
+ if val != want {
+ t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/mime/type_windows.go b/platform/dbops/binaries/go/go/src/mime/type_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..93802141c532d0f79daeecd356d022a89cbd6167
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/mime/type_windows.go
@@ -0,0 +1,52 @@
+// 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 mime
+
+import (
+ "internal/syscall/windows/registry"
+)
+
+func init() {
+ osInitMime = initMimeWindows
+}
+
+func initMimeWindows() {
+ names, err := registry.CLASSES_ROOT.ReadSubKeyNames()
+ if err != nil {
+ return
+ }
+ for _, name := range names {
+ if len(name) < 2 || name[0] != '.' { // looking for extensions only
+ continue
+ }
+ k, err := registry.OpenKey(registry.CLASSES_ROOT, name, registry.READ)
+ if err != nil {
+ continue
+ }
+ v, _, err := k.GetStringValue("Content Type")
+ k.Close()
+ if err != nil {
+ continue
+ }
+
+ // There is a long-standing problem on Windows: the
+ // registry sometimes records that the ".js" extension
+ // should be "text/plain". See issue #32350. While
+ // normally local configuration should override
+ // defaults, this problem is common enough that we
+ // handle it here by ignoring that registry setting.
+ if name == ".js" && (v == "text/plain" || v == "text/plain; charset=utf-8") {
+ continue
+ }
+
+ setExtensionType(name, v)
+ }
+}
+
+func initMimeForTests() map[string]string {
+ return map[string]string{
+ ".PnG": "image/png",
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/addrselect.go b/platform/dbops/binaries/go/go/src/net/addrselect.go
new file mode 100644
index 0000000000000000000000000000000000000000..4f07032c4a01dbac7e13ff4e4a42ad164215eb20
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/addrselect.go
@@ -0,0 +1,376 @@
+// 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.
+
+// Minimal RFC 6724 address selection.
+
+package net
+
+import (
+ "net/netip"
+ "sort"
+)
+
+func sortByRFC6724(addrs []IPAddr) {
+ if len(addrs) < 2 {
+ return
+ }
+ sortByRFC6724withSrcs(addrs, srcAddrs(addrs))
+}
+
+func sortByRFC6724withSrcs(addrs []IPAddr, srcs []netip.Addr) {
+ if len(addrs) != len(srcs) {
+ panic("internal error")
+ }
+ addrAttr := make([]ipAttr, len(addrs))
+ srcAttr := make([]ipAttr, len(srcs))
+ for i, v := range addrs {
+ addrAttrIP, _ := netip.AddrFromSlice(v.IP)
+ addrAttr[i] = ipAttrOf(addrAttrIP)
+ srcAttr[i] = ipAttrOf(srcs[i])
+ }
+ sort.Stable(&byRFC6724{
+ addrs: addrs,
+ addrAttr: addrAttr,
+ srcs: srcs,
+ srcAttr: srcAttr,
+ })
+}
+
+// srcAddrs tries to UDP-connect to each address to see if it has a
+// route. (This doesn't send any packets). The destination port
+// number is irrelevant.
+func srcAddrs(addrs []IPAddr) []netip.Addr {
+ srcs := make([]netip.Addr, len(addrs))
+ dst := UDPAddr{Port: 9}
+ for i := range addrs {
+ dst.IP = addrs[i].IP
+ dst.Zone = addrs[i].Zone
+ c, err := DialUDP("udp", nil, &dst)
+ if err == nil {
+ if src, ok := c.LocalAddr().(*UDPAddr); ok {
+ srcs[i], _ = netip.AddrFromSlice(src.IP)
+ }
+ c.Close()
+ }
+ }
+ return srcs
+}
+
+type ipAttr struct {
+ Scope scope
+ Precedence uint8
+ Label uint8
+}
+
+func ipAttrOf(ip netip.Addr) ipAttr {
+ if !ip.IsValid() {
+ return ipAttr{}
+ }
+ match := rfc6724policyTable.Classify(ip)
+ return ipAttr{
+ Scope: classifyScope(ip),
+ Precedence: match.Precedence,
+ Label: match.Label,
+ }
+}
+
+type byRFC6724 struct {
+ addrs []IPAddr // addrs to sort
+ addrAttr []ipAttr
+ srcs []netip.Addr // or not valid addr if unreachable
+ srcAttr []ipAttr
+}
+
+func (s *byRFC6724) Len() int { return len(s.addrs) }
+
+func (s *byRFC6724) Swap(i, j int) {
+ s.addrs[i], s.addrs[j] = s.addrs[j], s.addrs[i]
+ s.srcs[i], s.srcs[j] = s.srcs[j], s.srcs[i]
+ s.addrAttr[i], s.addrAttr[j] = s.addrAttr[j], s.addrAttr[i]
+ s.srcAttr[i], s.srcAttr[j] = s.srcAttr[j], s.srcAttr[i]
+}
+
+// Less reports whether i is a better destination address for this
+// host than j.
+//
+// The algorithm and variable names comes from RFC 6724 section 6.
+func (s *byRFC6724) Less(i, j int) bool {
+ DA := s.addrs[i].IP
+ DB := s.addrs[j].IP
+ SourceDA := s.srcs[i]
+ SourceDB := s.srcs[j]
+ attrDA := &s.addrAttr[i]
+ attrDB := &s.addrAttr[j]
+ attrSourceDA := &s.srcAttr[i]
+ attrSourceDB := &s.srcAttr[j]
+
+ const preferDA = true
+ const preferDB = false
+
+ // Rule 1: Avoid unusable destinations.
+ // If DB is known to be unreachable or if Source(DB) is undefined, then
+ // prefer DA. Similarly, if DA is known to be unreachable or if
+ // Source(DA) is undefined, then prefer DB.
+ if !SourceDA.IsValid() && !SourceDB.IsValid() {
+ return false // "equal"
+ }
+ if !SourceDB.IsValid() {
+ return preferDA
+ }
+ if !SourceDA.IsValid() {
+ return preferDB
+ }
+
+ // Rule 2: Prefer matching scope.
+ // If Scope(DA) = Scope(Source(DA)) and Scope(DB) <> Scope(Source(DB)),
+ // then prefer DA. Similarly, if Scope(DA) <> Scope(Source(DA)) and
+ // Scope(DB) = Scope(Source(DB)), then prefer DB.
+ if attrDA.Scope == attrSourceDA.Scope && attrDB.Scope != attrSourceDB.Scope {
+ return preferDA
+ }
+ if attrDA.Scope != attrSourceDA.Scope && attrDB.Scope == attrSourceDB.Scope {
+ return preferDB
+ }
+
+ // Rule 3: Avoid deprecated addresses.
+ // If Source(DA) is deprecated and Source(DB) is not, then prefer DB.
+ // Similarly, if Source(DA) is not deprecated and Source(DB) is
+ // deprecated, then prefer DA.
+
+ // TODO(bradfitz): implement? low priority for now.
+
+ // Rule 4: Prefer home addresses.
+ // If Source(DA) is simultaneously a home address and care-of address
+ // and Source(DB) is not, then prefer DA. Similarly, if Source(DB) is
+ // simultaneously a home address and care-of address and Source(DA) is
+ // not, then prefer DB.
+
+ // TODO(bradfitz): implement? low priority for now.
+
+ // Rule 5: Prefer matching label.
+ // If Label(Source(DA)) = Label(DA) and Label(Source(DB)) <> Label(DB),
+ // then prefer DA. Similarly, if Label(Source(DA)) <> Label(DA) and
+ // Label(Source(DB)) = Label(DB), then prefer DB.
+ if attrSourceDA.Label == attrDA.Label &&
+ attrSourceDB.Label != attrDB.Label {
+ return preferDA
+ }
+ if attrSourceDA.Label != attrDA.Label &&
+ attrSourceDB.Label == attrDB.Label {
+ return preferDB
+ }
+
+ // Rule 6: Prefer higher precedence.
+ // If Precedence(DA) > Precedence(DB), then prefer DA. Similarly, if
+ // Precedence(DA) < Precedence(DB), then prefer DB.
+ if attrDA.Precedence > attrDB.Precedence {
+ return preferDA
+ }
+ if attrDA.Precedence < attrDB.Precedence {
+ return preferDB
+ }
+
+ // Rule 7: Prefer native transport.
+ // If DA is reached via an encapsulating transition mechanism (e.g.,
+ // IPv6 in IPv4) and DB is not, then prefer DB. Similarly, if DB is
+ // reached via encapsulation and DA is not, then prefer DA.
+
+ // TODO(bradfitz): implement? low priority for now.
+
+ // Rule 8: Prefer smaller scope.
+ // If Scope(DA) < Scope(DB), then prefer DA. Similarly, if Scope(DA) >
+ // Scope(DB), then prefer DB.
+ if attrDA.Scope < attrDB.Scope {
+ return preferDA
+ }
+ if attrDA.Scope > attrDB.Scope {
+ return preferDB
+ }
+
+ // Rule 9: Use the longest matching prefix.
+ // When DA and DB belong to the same address family (both are IPv6 or
+ // both are IPv4 [but see below]): If CommonPrefixLen(Source(DA), DA) >
+ // CommonPrefixLen(Source(DB), DB), then prefer DA. Similarly, if
+ // CommonPrefixLen(Source(DA), DA) < CommonPrefixLen(Source(DB), DB),
+ // then prefer DB.
+ //
+ // However, applying this rule to IPv4 addresses causes
+ // problems (see issues 13283 and 18518), so limit to IPv6.
+ if DA.To4() == nil && DB.To4() == nil {
+ commonA := commonPrefixLen(SourceDA, DA)
+ commonB := commonPrefixLen(SourceDB, DB)
+
+ if commonA > commonB {
+ return preferDA
+ }
+ if commonA < commonB {
+ return preferDB
+ }
+ }
+
+ // Rule 10: Otherwise, leave the order unchanged.
+ // If DA preceded DB in the original list, prefer DA.
+ // Otherwise, prefer DB.
+ return false // "equal"
+}
+
+type policyTableEntry struct {
+ Prefix netip.Prefix
+ Precedence uint8
+ Label uint8
+}
+
+type policyTable []policyTableEntry
+
+// RFC 6724 section 2.1.
+// Items are sorted by the size of their Prefix.Mask.Size,
+var rfc6724policyTable = policyTable{
+ {
+ // "::1/128"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}), 128),
+ Precedence: 50,
+ Label: 0,
+ },
+ {
+ // "::ffff:0:0/96"
+ // IPv4-compatible, etc.
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}), 96),
+ Precedence: 35,
+ Label: 4,
+ },
+ {
+ // "::/96"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{}), 96),
+ Precedence: 1,
+ Label: 3,
+ },
+ {
+ // "2001::/32"
+ // Teredo
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x20, 0x01}), 32),
+ Precedence: 5,
+ Label: 5,
+ },
+ {
+ // "2002::/16"
+ // 6to4
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x20, 0x02}), 16),
+ Precedence: 30,
+ Label: 2,
+ },
+ {
+ // "3ffe::/16"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0x3f, 0xfe}), 16),
+ Precedence: 1,
+ Label: 12,
+ },
+ {
+ // "fec0::/10"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0xfe, 0xc0}), 10),
+ Precedence: 1,
+ Label: 11,
+ },
+ {
+ // "fc00::/7"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{0xfc}), 7),
+ Precedence: 3,
+ Label: 13,
+ },
+ {
+ // "::/0"
+ Prefix: netip.PrefixFrom(netip.AddrFrom16([16]byte{}), 0),
+ Precedence: 40,
+ Label: 1,
+ },
+}
+
+// Classify returns the policyTableEntry of the entry with the longest
+// matching prefix that contains ip.
+// The table t must be sorted from largest mask size to smallest.
+func (t policyTable) Classify(ip netip.Addr) policyTableEntry {
+ // Prefix.Contains() will not match an IPv6 prefix for an IPv4 address.
+ if ip.Is4() {
+ ip = netip.AddrFrom16(ip.As16())
+ }
+ for _, ent := range t {
+ if ent.Prefix.Contains(ip) {
+ return ent
+ }
+ }
+ return policyTableEntry{}
+}
+
+// RFC 6724 section 3.1.
+type scope uint8
+
+const (
+ scopeInterfaceLocal scope = 0x1
+ scopeLinkLocal scope = 0x2
+ scopeAdminLocal scope = 0x4
+ scopeSiteLocal scope = 0x5
+ scopeOrgLocal scope = 0x8
+ scopeGlobal scope = 0xe
+)
+
+func classifyScope(ip netip.Addr) scope {
+ if ip.IsLoopback() || ip.IsLinkLocalUnicast() {
+ return scopeLinkLocal
+ }
+ ipv6 := ip.Is6() && !ip.Is4In6()
+ ipv6AsBytes := ip.As16()
+ if ipv6 && ip.IsMulticast() {
+ return scope(ipv6AsBytes[1] & 0xf)
+ }
+ // Site-local addresses are defined in RFC 3513 section 2.5.6
+ // (and deprecated in RFC 3879).
+ if ipv6 && ipv6AsBytes[0] == 0xfe && ipv6AsBytes[1]&0xc0 == 0xc0 {
+ return scopeSiteLocal
+ }
+ return scopeGlobal
+}
+
+// commonPrefixLen reports the length of the longest prefix (looking
+// at the most significant, or leftmost, bits) that the
+// two addresses have in common, up to the length of a's prefix (i.e.,
+// the portion of the address not including the interface ID).
+//
+// If a or b is an IPv4 address as an IPv6 address, the IPv4 addresses
+// are compared (with max common prefix length of 32).
+// If a and b are different IP versions, 0 is returned.
+//
+// See https://tools.ietf.org/html/rfc6724#section-2.2
+func commonPrefixLen(a netip.Addr, b IP) (cpl int) {
+ if b4 := b.To4(); b4 != nil {
+ b = b4
+ }
+ aAsSlice := a.AsSlice()
+ if len(aAsSlice) != len(b) {
+ return 0
+ }
+ // If IPv6, only up to the prefix (first 64 bits)
+ if len(aAsSlice) > 8 {
+ aAsSlice = aAsSlice[:8]
+ b = b[:8]
+ }
+ for len(aAsSlice) > 0 {
+ if aAsSlice[0] == b[0] {
+ cpl += 8
+ aAsSlice = aAsSlice[1:]
+ b = b[1:]
+ continue
+ }
+ bits := 8
+ ab, bb := aAsSlice[0], b[0]
+ for {
+ ab >>= 1
+ bb >>= 1
+ bits--
+ if ab == bb {
+ cpl += bits
+ return
+ }
+ }
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/net/addrselect_test.go b/platform/dbops/binaries/go/go/src/net/addrselect_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7e8134d754447b2d97eef3b8e4e979a5f1a729d1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/addrselect_test.go
@@ -0,0 +1,312 @@
+// 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 darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
+
+package net
+
+import (
+ "net/netip"
+ "reflect"
+ "testing"
+)
+
+func TestSortByRFC6724(t *testing.T) {
+ tests := []struct {
+ in []IPAddr
+ srcs []netip.Addr
+ want []IPAddr
+ reverse bool // also test it starting backwards
+ }{
+ // Examples from RFC 6724 section 10.2:
+
+ // Prefer matching scope.
+ {
+ in: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("198.51.100.121")},
+ },
+ srcs: []netip.Addr{
+ netip.MustParseAddr("2001:db8:1::2"),
+ netip.MustParseAddr("169.254.13.78"),
+ },
+ want: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("198.51.100.121")},
+ },
+ reverse: true,
+ },
+
+ // Prefer matching scope.
+ {
+ in: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("198.51.100.121")},
+ },
+ srcs: []netip.Addr{
+ netip.MustParseAddr("fe80::1"),
+ netip.MustParseAddr("198.51.100.117"),
+ },
+ want: []IPAddr{
+ {IP: ParseIP("198.51.100.121")},
+ {IP: ParseIP("2001:db8:1::1")},
+ },
+ reverse: true,
+ },
+
+ // Prefer higher precedence.
+ {
+ in: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("10.1.2.3")},
+ },
+ srcs: []netip.Addr{
+ netip.MustParseAddr("2001:db8:1::2"),
+ netip.MustParseAddr("10.1.2.4"),
+ },
+ want: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("10.1.2.3")},
+ },
+ reverse: true,
+ },
+
+ // Prefer smaller scope.
+ {
+ in: []IPAddr{
+ {IP: ParseIP("2001:db8:1::1")},
+ {IP: ParseIP("fe80::1")},
+ },
+ srcs: []netip.Addr{
+ netip.MustParseAddr("2001:db8:1::2"),
+ netip.MustParseAddr("fe80::2"),
+ },
+ want: []IPAddr{
+ {IP: ParseIP("fe80::1")},
+ {IP: ParseIP("2001:db8:1::1")},
+ },
+ reverse: true,
+ },
+
+ // Issue 13283. Having a 10/8 source address does not
+ // mean we should prefer 23/8 destination addresses.
+ {
+ in: []IPAddr{
+ {IP: ParseIP("54.83.193.112")},
+ {IP: ParseIP("184.72.238.214")},
+ {IP: ParseIP("23.23.172.185")},
+ {IP: ParseIP("75.101.148.21")},
+ {IP: ParseIP("23.23.134.56")},
+ {IP: ParseIP("23.21.50.150")},
+ },
+ srcs: []netip.Addr{
+ netip.MustParseAddr("10.2.3.4"),
+ netip.MustParseAddr("10.2.3.4"),
+ netip.MustParseAddr("10.2.3.4"),
+ netip.MustParseAddr("10.2.3.4"),
+ netip.MustParseAddr("10.2.3.4"),
+ netip.MustParseAddr("10.2.3.4"),
+ },
+ want: []IPAddr{
+ {IP: ParseIP("54.83.193.112")},
+ {IP: ParseIP("184.72.238.214")},
+ {IP: ParseIP("23.23.172.185")},
+ {IP: ParseIP("75.101.148.21")},
+ {IP: ParseIP("23.23.134.56")},
+ {IP: ParseIP("23.21.50.150")},
+ },
+ reverse: false,
+ },
+ }
+ for i, tt := range tests {
+ inCopy := make([]IPAddr, len(tt.in))
+ copy(inCopy, tt.in)
+ srcCopy := make([]netip.Addr, len(tt.in))
+ copy(srcCopy, tt.srcs)
+ sortByRFC6724withSrcs(inCopy, srcCopy)
+ if !reflect.DeepEqual(inCopy, tt.want) {
+ t.Errorf("test %d:\nin = %s\ngot: %s\nwant: %s\n", i, tt.in, inCopy, tt.want)
+ }
+ if tt.reverse {
+ copy(inCopy, tt.in)
+ copy(srcCopy, tt.srcs)
+ for j := 0; j < len(inCopy)/2; j++ {
+ k := len(inCopy) - j - 1
+ inCopy[j], inCopy[k] = inCopy[k], inCopy[j]
+ srcCopy[j], srcCopy[k] = srcCopy[k], srcCopy[j]
+ }
+ sortByRFC6724withSrcs(inCopy, srcCopy)
+ if !reflect.DeepEqual(inCopy, tt.want) {
+ t.Errorf("test %d, starting backwards:\nin = %s\ngot: %s\nwant: %s\n", i, tt.in, inCopy, tt.want)
+ }
+ }
+
+ }
+
+}
+
+func TestRFC6724PolicyTableOrder(t *testing.T) {
+ for i := 0; i < len(rfc6724policyTable)-1; i++ {
+ if !(rfc6724policyTable[i].Prefix.Bits() >= rfc6724policyTable[i+1].Prefix.Bits()) {
+ t.Errorf("rfc6724policyTable item number %d sorted in wrong order = %d bits, next item = %d bits;", i, rfc6724policyTable[i].Prefix.Bits(), rfc6724policyTable[i+1].Prefix.Bits())
+ }
+ }
+}
+
+func TestRFC6724PolicyTableContent(t *testing.T) {
+ expectedRfc6724policyTable := policyTable{
+ {
+ Prefix: netip.MustParsePrefix("::1/128"),
+ Precedence: 50,
+ Label: 0,
+ },
+ {
+ Prefix: netip.MustParsePrefix("::ffff:0:0/96"),
+ Precedence: 35,
+ Label: 4,
+ },
+ {
+ Prefix: netip.MustParsePrefix("::/96"),
+ Precedence: 1,
+ Label: 3,
+ },
+ {
+ Prefix: netip.MustParsePrefix("2001::/32"),
+ Precedence: 5,
+ Label: 5,
+ },
+ {
+ Prefix: netip.MustParsePrefix("2002::/16"),
+ Precedence: 30,
+ Label: 2,
+ },
+ {
+ Prefix: netip.MustParsePrefix("3ffe::/16"),
+ Precedence: 1,
+ Label: 12,
+ },
+ {
+ Prefix: netip.MustParsePrefix("fec0::/10"),
+ Precedence: 1,
+ Label: 11,
+ },
+ {
+ Prefix: netip.MustParsePrefix("fc00::/7"),
+ Precedence: 3,
+ Label: 13,
+ },
+ {
+ Prefix: netip.MustParsePrefix("::/0"),
+ Precedence: 40,
+ Label: 1,
+ },
+ }
+ if !reflect.DeepEqual(rfc6724policyTable, expectedRfc6724policyTable) {
+ t.Errorf("rfc6724policyTable has wrong contend = %v; want %v", rfc6724policyTable, expectedRfc6724policyTable)
+ }
+}
+
+func TestRFC6724PolicyTableClassify(t *testing.T) {
+ tests := []struct {
+ ip netip.Addr
+ want policyTableEntry
+ }{
+ {
+ ip: netip.MustParseAddr("127.0.0.1"),
+ want: policyTableEntry{
+ Prefix: netip.MustParsePrefix("::ffff:0:0/96"),
+ Precedence: 35,
+ Label: 4,
+ },
+ },
+ {
+ ip: netip.MustParseAddr("2601:645:8002:a500:986f:1db8:c836:bd65"),
+ want: policyTableEntry{
+ Prefix: netip.MustParsePrefix("::/0"),
+ Precedence: 40,
+ Label: 1,
+ },
+ },
+ {
+ ip: netip.MustParseAddr("::1"),
+ want: policyTableEntry{
+ Prefix: netip.MustParsePrefix("::1/128"),
+ Precedence: 50,
+ Label: 0,
+ },
+ },
+ {
+ ip: netip.MustParseAddr("2002::ab12"),
+ want: policyTableEntry{
+ Prefix: netip.MustParsePrefix("2002::/16"),
+ Precedence: 30,
+ Label: 2,
+ },
+ },
+ }
+ for i, tt := range tests {
+ got := rfc6724policyTable.Classify(tt.ip)
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("%d. Classify(%s) = %v; want %v", i, tt.ip, got, tt.want)
+ }
+ }
+}
+
+func TestRFC6724ClassifyScope(t *testing.T) {
+ tests := []struct {
+ ip netip.Addr
+ want scope
+ }{
+ {netip.MustParseAddr("127.0.0.1"), scopeLinkLocal}, // rfc6724#section-3.2
+ {netip.MustParseAddr("::1"), scopeLinkLocal}, // rfc4007#section-4
+ {netip.MustParseAddr("169.254.1.2"), scopeLinkLocal}, // rfc6724#section-3.2
+ {netip.MustParseAddr("fec0::1"), scopeSiteLocal},
+ {netip.MustParseAddr("8.8.8.8"), scopeGlobal},
+
+ {netip.MustParseAddr("ff02::"), scopeLinkLocal}, // IPv6 multicast
+ {netip.MustParseAddr("ff05::"), scopeSiteLocal}, // IPv6 multicast
+ {netip.MustParseAddr("ff04::"), scopeAdminLocal}, // IPv6 multicast
+ {netip.MustParseAddr("ff0e::"), scopeGlobal}, // IPv6 multicast
+
+ {netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xe0, 0, 0, 0}), scopeGlobal}, // IPv4 link-local multicast as 16 bytes
+ {netip.AddrFrom16([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xe0, 2, 2, 2}), scopeGlobal}, // IPv4 global multicast as 16 bytes
+ {netip.AddrFrom4([4]byte{0xe0, 0, 0, 0}), scopeGlobal}, // IPv4 link-local multicast as 4 bytes
+ {netip.AddrFrom4([4]byte{0xe0, 2, 2, 2}), scopeGlobal}, // IPv4 global multicast as 4 bytes
+ }
+ for i, tt := range tests {
+ got := classifyScope(tt.ip)
+ if got != tt.want {
+ t.Errorf("%d. classifyScope(%s) = %x; want %x", i, tt.ip, got, tt.want)
+ }
+ }
+}
+
+func TestRFC6724CommonPrefixLength(t *testing.T) {
+ tests := []struct {
+ a netip.Addr
+ b IP
+ want int
+ }{
+ {netip.MustParseAddr("fe80::1"), ParseIP("fe80::2"), 64},
+ {netip.MustParseAddr("fe81::1"), ParseIP("fe80::2"), 15},
+ {netip.MustParseAddr("127.0.0.1"), ParseIP("fe80::1"), 0}, // diff size
+ {netip.AddrFrom4([4]byte{1, 2, 3, 4}), IP{1, 2, 3, 4}, 32},
+ {netip.AddrFrom4([4]byte{1, 2, 255, 255}), IP{1, 2, 0, 0}, 16},
+ {netip.AddrFrom4([4]byte{1, 2, 127, 255}), IP{1, 2, 0, 0}, 17},
+ {netip.AddrFrom4([4]byte{1, 2, 63, 255}), IP{1, 2, 0, 0}, 18},
+ {netip.AddrFrom4([4]byte{1, 2, 31, 255}), IP{1, 2, 0, 0}, 19},
+ {netip.AddrFrom4([4]byte{1, 2, 15, 255}), IP{1, 2, 0, 0}, 20},
+ {netip.AddrFrom4([4]byte{1, 2, 7, 255}), IP{1, 2, 0, 0}, 21},
+ {netip.AddrFrom4([4]byte{1, 2, 3, 255}), IP{1, 2, 0, 0}, 22},
+ {netip.AddrFrom4([4]byte{1, 2, 1, 255}), IP{1, 2, 0, 0}, 23},
+ {netip.AddrFrom4([4]byte{1, 2, 0, 255}), IP{1, 2, 0, 0}, 24},
+ }
+ for i, tt := range tests {
+ got := commonPrefixLen(tt.a, tt.b)
+ if got != tt.want {
+ t.Errorf("%d. commonPrefixLen(%s, %s) = %d; want %d", i, tt.a, tt.b, got, tt.want)
+ }
+ }
+
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_aix.go b/platform/dbops/binaries/go/go/src/net/cgo_aix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3478148b4f60e352dec179b9c5e8304c446f6e2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_aix.go
@@ -0,0 +1,24 @@
+// 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 cgo && !netgo
+
+package net
+
+/*
+#include
+#include
+
+#include
+*/
+import "C"
+
+import "unsafe"
+
+const cgoAddrInfoFlags = C.AI_CANONNAME
+
+func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) {
+ gerrno, err := C.getnameinfo(sa, C.size_t(salen), (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b)), nil, 0, C.NI_NAMEREQD)
+ return int(gerrno), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_android.go b/platform/dbops/binaries/go/go/src/net/cgo_android.go
new file mode 100644
index 0000000000000000000000000000000000000000..5ab8b5fedea13aacbdc9bb0758c5e4b9da232b73
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_android.go
@@ -0,0 +1,12 @@
+// 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.
+
+//go:build cgo && !netgo
+
+package net
+
+//#include
+import "C"
+
+const cgoAddrInfoFlags = C.AI_CANONNAME
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_bsd.go b/platform/dbops/binaries/go/go/src/net/cgo_bsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..082e91faa8afb737bbbe92f95202872d560939da
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_bsd.go
@@ -0,0 +1,14 @@
+// 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.
+
+//go:build cgo && !netgo && (dragonfly || freebsd)
+
+package net
+
+/*
+#include
+*/
+import "C"
+
+const cgoAddrInfoFlags = (C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL) & C.AI_MASK
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_darwin.go b/platform/dbops/binaries/go/go/src/net/cgo_darwin.go
new file mode 100644
index 0000000000000000000000000000000000000000..129dd937fe0778c48a656dc99390e5f0f3be2073
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_darwin.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 net
+
+import "internal/syscall/unix"
+
+const cgoAddrInfoFlags = (unix.AI_CANONNAME | unix.AI_V4MAPPED | unix.AI_ALL) & unix.AI_MASK
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_linux.go b/platform/dbops/binaries/go/go/src/net/cgo_linux.go
new file mode 100644
index 0000000000000000000000000000000000000000..de6e87f17622df6a46a73c1b99ae2e21be6672c4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_linux.go
@@ -0,0 +1,20 @@
+// 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.
+
+//go:build !android && cgo && !netgo
+
+package net
+
+/*
+#include
+*/
+import "C"
+
+// NOTE(rsc): In theory there are approximately balanced
+// arguments for and against including AI_ADDRCONFIG
+// in the flags (it includes IPv4 results only on IPv4 systems,
+// and similarly for IPv6), but in practice setting it causes
+// getaddrinfo to return the wrong canonical name on Linux.
+// So definitely leave it out.
+const cgoAddrInfoFlags = C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_netbsd.go b/platform/dbops/binaries/go/go/src/net/cgo_netbsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..03392e8ff34c596a979e6b20469e8f636a4925c2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_netbsd.go
@@ -0,0 +1,14 @@
+// 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.
+
+//go:build cgo && !netgo
+
+package net
+
+/*
+#include
+*/
+import "C"
+
+const cgoAddrInfoFlags = C.AI_CANONNAME
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_openbsd.go b/platform/dbops/binaries/go/go/src/net/cgo_openbsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..03392e8ff34c596a979e6b20469e8f636a4925c2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_openbsd.go
@@ -0,0 +1,14 @@
+// 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.
+
+//go:build cgo && !netgo
+
+package net
+
+/*
+#include
+*/
+import "C"
+
+const cgoAddrInfoFlags = C.AI_CANONNAME
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_resnew.go b/platform/dbops/binaries/go/go/src/net/cgo_resnew.go
new file mode 100644
index 0000000000000000000000000000000000000000..3f21c5c4c4fd5bb899cbe9a174b681c905f45c5a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_resnew.go
@@ -0,0 +1,22 @@
+// 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 cgo && !netgo && ((linux && !android) || netbsd || solaris)
+
+package net
+
+/*
+#include
+#include
+
+#include
+*/
+import "C"
+
+import "unsafe"
+
+func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) {
+ gerrno, err := C.getnameinfo(sa, salen, (*C.char)(unsafe.Pointer(&b[0])), C.socklen_t(len(b)), nil, 0, C.NI_NAMEREQD)
+ return int(gerrno), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_resold.go b/platform/dbops/binaries/go/go/src/net/cgo_resold.go
new file mode 100644
index 0000000000000000000000000000000000000000..37c75527f95c0dedf8b36792cc94fb22eb89abc9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_resold.go
@@ -0,0 +1,22 @@
+// 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 cgo && !netgo && (android || freebsd || dragonfly || openbsd)
+
+package net
+
+/*
+#include
+#include
+
+#include
+*/
+import "C"
+
+import "unsafe"
+
+func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error) {
+ gerrno, err := C.getnameinfo(sa, salen, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(len(b)), nil, 0, C.NI_NAMEREQD)
+ return int(gerrno), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_socknew.go b/platform/dbops/binaries/go/go/src/net/cgo_socknew.go
new file mode 100644
index 0000000000000000000000000000000000000000..fbb9e10f3401967f2018f477392fb8428f7df752
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_socknew.go
@@ -0,0 +1,32 @@
+// 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 cgo && !netgo && (android || linux || solaris)
+
+package net
+
+/*
+#include
+#include
+
+#include
+*/
+import "C"
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func cgoSockaddrInet4(ip IP) *C.struct_sockaddr {
+ sa := syscall.RawSockaddrInet4{Family: syscall.AF_INET}
+ copy(sa.Addr[:], ip)
+ return (*C.struct_sockaddr)(unsafe.Pointer(&sa))
+}
+
+func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr {
+ sa := syscall.RawSockaddrInet6{Family: syscall.AF_INET6, Scope_id: uint32(zone)}
+ copy(sa.Addr[:], ip)
+ return (*C.struct_sockaddr)(unsafe.Pointer(&sa))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_sockold.go b/platform/dbops/binaries/go/go/src/net/cgo_sockold.go
new file mode 100644
index 0000000000000000000000000000000000000000..d0a99e073d82c2b98c812b01969cba08761a1350
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_sockold.go
@@ -0,0 +1,32 @@
+// 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 cgo && !netgo && (aix || dragonfly || freebsd || netbsd || openbsd)
+
+package net
+
+/*
+#include
+#include
+
+#include
+*/
+import "C"
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func cgoSockaddrInet4(ip IP) *C.struct_sockaddr {
+ sa := syscall.RawSockaddrInet4{Len: syscall.SizeofSockaddrInet4, Family: syscall.AF_INET}
+ copy(sa.Addr[:], ip)
+ return (*C.struct_sockaddr)(unsafe.Pointer(&sa))
+}
+
+func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr {
+ sa := syscall.RawSockaddrInet6{Len: syscall.SizeofSockaddrInet6, Family: syscall.AF_INET6, Scope_id: uint32(zone)}
+ copy(sa.Addr[:], ip)
+ return (*C.struct_sockaddr)(unsafe.Pointer(&sa))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_solaris.go b/platform/dbops/binaries/go/go/src/net/cgo_solaris.go
new file mode 100644
index 0000000000000000000000000000000000000000..cde9c957fee53c33d5dc074b3b6ce8a879202479
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_solaris.go
@@ -0,0 +1,15 @@
+// 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 cgo && !netgo
+
+package net
+
+/*
+#cgo LDFLAGS: -lsocket -lnsl -lsendfile
+#include
+*/
+import "C"
+
+const cgoAddrInfoFlags = C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_stub.go b/platform/dbops/binaries/go/go/src/net/cgo_stub.go
new file mode 100644
index 0000000000000000000000000000000000000000..a4f6b4b0e8d8b7c5cf55248b69f2d9c0840edb53
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_stub.go
@@ -0,0 +1,40 @@
+// 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 holds stub versions of the cgo functions called on Unix systems.
+// We build this file:
+// - if using the netgo build tag on a Unix system
+// - on a Unix system without the cgo resolver functions
+// (Darwin always provides the cgo functions, in cgo_unix_syscall.go)
+// - on wasip1, where cgo is never available
+
+//go:build (netgo && unix) || (unix && !cgo && !darwin) || js || wasip1
+
+package net
+
+import "context"
+
+// cgoAvailable set to false to indicate that the cgo resolver
+// is not available on this system.
+const cgoAvailable = false
+
+func cgoLookupHost(ctx context.Context, name string) (addrs []string, err error) {
+ panic("cgo stub: cgo not available")
+}
+
+func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) {
+ panic("cgo stub: cgo not available")
+}
+
+func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) {
+ panic("cgo stub: cgo not available")
+}
+
+func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool) {
+ panic("cgo stub: cgo not available")
+}
+
+func cgoLookupPTR(ctx context.Context, addr string) (ptrs []string, err error) {
+ panic("cgo stub: cgo not available")
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix.go b/platform/dbops/binaries/go/go/src/net/cgo_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..7ed5daad73a6316dae79de46a926fe8d2b690e35
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix.go
@@ -0,0 +1,379 @@
+// 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 called cgo_unix.go, but to allow syscalls-to-libc-based
+// implementations to share the code, it does not use cgo directly.
+// Instead of C.foo it uses _C_foo, which is defined in either
+// cgo_unix_cgo.go or cgo_unix_syscall.go
+
+//go:build !netgo && ((cgo && unix) || darwin)
+
+package net
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// cgoAvailable set to true to indicate that the cgo resolver
+// is available on this system.
+const cgoAvailable = true
+
+// An addrinfoErrno represents a getaddrinfo, getnameinfo-specific
+// error number. It's a signed number and a zero value is a non-error
+// by convention.
+type addrinfoErrno int
+
+func (eai addrinfoErrno) Error() string { return _C_gai_strerror(_C_int(eai)) }
+func (eai addrinfoErrno) Temporary() bool { return eai == _C_EAI_AGAIN }
+func (eai addrinfoErrno) Timeout() bool { return false }
+
+// isAddrinfoErrno is just for testing purposes.
+func (eai addrinfoErrno) isAddrinfoErrno() {}
+
+// doBlockingWithCtx executes a blocking function in a separate goroutine when the provided
+// context is cancellable. It is intended for use with calls that don't support context
+// cancellation (cgo, syscalls). blocking func may still be running after this function finishes.
+func doBlockingWithCtx[T any](ctx context.Context, blocking func() (T, error)) (T, error) {
+ if ctx.Done() == nil {
+ return blocking()
+ }
+
+ type result struct {
+ res T
+ err error
+ }
+
+ res := make(chan result, 1)
+ go func() {
+ var r result
+ r.res, r.err = blocking()
+ res <- r
+ }()
+
+ select {
+ case r := <-res:
+ return r.res, r.err
+ case <-ctx.Done():
+ var zero T
+ return zero, mapErr(ctx.Err())
+ }
+}
+
+func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error) {
+ addrs, err := cgoLookupIP(ctx, "ip", name)
+ if err != nil {
+ return nil, err
+ }
+ for _, addr := range addrs {
+ hosts = append(hosts, addr.String())
+ }
+ return hosts, nil
+}
+
+func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) {
+ var hints _C_struct_addrinfo
+ switch network {
+ case "ip": // no hints
+ case "tcp", "tcp4", "tcp6":
+ *_C_ai_socktype(&hints) = _C_SOCK_STREAM
+ *_C_ai_protocol(&hints) = _C_IPPROTO_TCP
+ case "udp", "udp4", "udp6":
+ *_C_ai_socktype(&hints) = _C_SOCK_DGRAM
+ *_C_ai_protocol(&hints) = _C_IPPROTO_UDP
+ default:
+ return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
+ }
+ switch ipVersion(network) {
+ case '4':
+ *_C_ai_family(&hints) = _C_AF_INET
+ case '6':
+ *_C_ai_family(&hints) = _C_AF_INET6
+ }
+
+ return doBlockingWithCtx(ctx, func() (int, error) {
+ return cgoLookupServicePort(&hints, network, service)
+ })
+}
+
+func cgoLookupServicePort(hints *_C_struct_addrinfo, network, service string) (port int, err error) {
+ cservice, err := syscall.ByteSliceFromString(service)
+ if err != nil {
+ return 0, &DNSError{Err: err.Error(), Name: network + "/" + service}
+ }
+ // Lowercase the C service name.
+ for i, b := range cservice[:len(service)] {
+ cservice[i] = lowerASCII(b)
+ }
+ var res *_C_struct_addrinfo
+ gerrno, err := _C_getaddrinfo(nil, (*_C_char)(unsafe.Pointer(&cservice[0])), hints, &res)
+ if gerrno != 0 {
+ isTemporary := false
+ switch gerrno {
+ case _C_EAI_SYSTEM:
+ if err == nil { // see golang.org/issue/6232
+ err = syscall.EMFILE
+ }
+ case _C_EAI_SERVICE, _C_EAI_NONAME: // Darwin returns EAI_NONAME.
+ return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
+ default:
+ err = addrinfoErrno(gerrno)
+ isTemporary = addrinfoErrno(gerrno).Temporary()
+ }
+ return 0, &DNSError{Err: err.Error(), Name: network + "/" + service, IsTemporary: isTemporary}
+ }
+ defer _C_freeaddrinfo(res)
+
+ for r := res; r != nil; r = *_C_ai_next(r) {
+ switch *_C_ai_family(r) {
+ case _C_AF_INET:
+ sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
+ p := (*[2]byte)(unsafe.Pointer(&sa.Port))
+ return int(p[0])<<8 | int(p[1]), nil
+ case _C_AF_INET6:
+ sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
+ p := (*[2]byte)(unsafe.Pointer(&sa.Port))
+ return int(p[0])<<8 | int(p[1]), nil
+ }
+ }
+ return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
+}
+
+func cgoLookupHostIP(network, name string) (addrs []IPAddr, err error) {
+ acquireThread()
+ defer releaseThread()
+
+ var hints _C_struct_addrinfo
+ *_C_ai_flags(&hints) = cgoAddrInfoFlags
+ *_C_ai_socktype(&hints) = _C_SOCK_STREAM
+ *_C_ai_family(&hints) = _C_AF_UNSPEC
+ switch ipVersion(network) {
+ case '4':
+ *_C_ai_family(&hints) = _C_AF_INET
+ case '6':
+ *_C_ai_family(&hints) = _C_AF_INET6
+ }
+
+ h, err := syscall.BytePtrFromString(name)
+ if err != nil {
+ return nil, &DNSError{Err: err.Error(), Name: name}
+ }
+ var res *_C_struct_addrinfo
+ gerrno, err := _C_getaddrinfo((*_C_char)(unsafe.Pointer(h)), nil, &hints, &res)
+ if gerrno != 0 {
+ isErrorNoSuchHost := false
+ isTemporary := false
+ switch gerrno {
+ case _C_EAI_SYSTEM:
+ if err == nil {
+ // err should not be nil, but sometimes getaddrinfo returns
+ // gerrno == _C_EAI_SYSTEM with err == nil on Linux.
+ // The report claims that it happens when we have too many
+ // open files, so use syscall.EMFILE (too many open files in system).
+ // Most system calls would return ENFILE (too many open files),
+ // so at the least EMFILE should be easy to recognize if this
+ // comes up again. golang.org/issue/6232.
+ err = syscall.EMFILE
+ }
+ case _C_EAI_NONAME, _C_EAI_NODATA:
+ err = errNoSuchHost
+ isErrorNoSuchHost = true
+ default:
+ err = addrinfoErrno(gerrno)
+ isTemporary = addrinfoErrno(gerrno).Temporary()
+ }
+
+ return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: isErrorNoSuchHost, IsTemporary: isTemporary}
+ }
+ defer _C_freeaddrinfo(res)
+
+ for r := res; r != nil; r = *_C_ai_next(r) {
+ // We only asked for SOCK_STREAM, but check anyhow.
+ if *_C_ai_socktype(r) != _C_SOCK_STREAM {
+ continue
+ }
+ switch *_C_ai_family(r) {
+ case _C_AF_INET:
+ sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
+ addr := IPAddr{IP: copyIP(sa.Addr[:])}
+ addrs = append(addrs, addr)
+ case _C_AF_INET6:
+ sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
+ addr := IPAddr{IP: copyIP(sa.Addr[:]), Zone: zoneCache.name(int(sa.Scope_id))}
+ addrs = append(addrs, addr)
+ }
+ }
+ return addrs, nil
+}
+
+func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) {
+ return doBlockingWithCtx(ctx, func() ([]IPAddr, error) {
+ return cgoLookupHostIP(network, name)
+ })
+}
+
+// These are roughly enough for the following:
+//
+// Source Encoding Maximum length of single name entry
+// Unicast DNS ASCII or <=253 + a NUL terminator
+// Unicode in RFC 5892 252 * total number of labels + delimiters + a NUL terminator
+// Multicast DNS UTF-8 in RFC 5198 or <=253 + a NUL terminator
+// the same as unicast DNS ASCII <=253 + a NUL terminator
+// Local database various depends on implementation
+const (
+ nameinfoLen = 64
+ maxNameinfoLen = 4096
+)
+
+func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error) {
+ ip, err := netip.ParseAddr(addr)
+ if err != nil {
+ return nil, &DNSError{Err: "invalid address", Name: addr}
+ }
+ sa, salen := cgoSockaddr(IP(ip.AsSlice()), ip.Zone())
+ if sa == nil {
+ return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}
+ }
+
+ return doBlockingWithCtx(ctx, func() ([]string, error) {
+ return cgoLookupAddrPTR(addr, sa, salen)
+ })
+}
+
+func cgoLookupAddrPTR(addr string, sa *_C_struct_sockaddr, salen _C_socklen_t) (names []string, err error) {
+ acquireThread()
+ defer releaseThread()
+
+ var gerrno int
+ var b []byte
+ for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 {
+ b = make([]byte, l)
+ gerrno, err = cgoNameinfoPTR(b, sa, salen)
+ if gerrno == 0 || gerrno != _C_EAI_OVERFLOW {
+ break
+ }
+ }
+ if gerrno != 0 {
+ isErrorNoSuchHost := false
+ isTemporary := false
+ switch gerrno {
+ case _C_EAI_SYSTEM:
+ if err == nil { // see golang.org/issue/6232
+ err = syscall.EMFILE
+ }
+ case _C_EAI_NONAME:
+ err = errNoSuchHost
+ isErrorNoSuchHost = true
+ default:
+ err = addrinfoErrno(gerrno)
+ isTemporary = addrinfoErrno(gerrno).Temporary()
+ }
+ return nil, &DNSError{Err: err.Error(), Name: addr, IsTemporary: isTemporary, IsNotFound: isErrorNoSuchHost}
+ }
+ for i := 0; i < len(b); i++ {
+ if b[i] == 0 {
+ b = b[:i]
+ break
+ }
+ }
+ return []string{absDomainName(string(b))}, nil
+}
+
+func cgoSockaddr(ip IP, zone string) (*_C_struct_sockaddr, _C_socklen_t) {
+ if ip4 := ip.To4(); ip4 != nil {
+ return cgoSockaddrInet4(ip4), _C_socklen_t(syscall.SizeofSockaddrInet4)
+ }
+ if ip6 := ip.To16(); ip6 != nil {
+ return cgoSockaddrInet6(ip6, zoneCache.index(zone)), _C_socklen_t(syscall.SizeofSockaddrInet6)
+ }
+ return nil, 0
+}
+
+func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool) {
+ resources, err := resSearch(ctx, name, int(dnsmessage.TypeCNAME), int(dnsmessage.ClassINET))
+ if err != nil {
+ return
+ }
+ cname, err = parseCNAMEFromResources(resources)
+ if err != nil {
+ return "", err, false
+ }
+ return cname, nil, true
+}
+
+// resSearch will make a call to the 'res_nsearch' routine in the C library
+// and parse the output as a slice of DNS resources.
+func resSearch(ctx context.Context, hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
+ return doBlockingWithCtx(ctx, func() ([]dnsmessage.Resource, error) {
+ return cgoResSearch(hostname, rtype, class)
+ })
+}
+
+func cgoResSearch(hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
+ acquireThread()
+ defer releaseThread()
+
+ resStateSize := unsafe.Sizeof(_C_struct___res_state{})
+ var state *_C_struct___res_state
+ if resStateSize > 0 {
+ mem := _C_malloc(resStateSize)
+ defer _C_free(mem)
+ memSlice := unsafe.Slice((*byte)(mem), resStateSize)
+ clear(memSlice)
+ state = (*_C_struct___res_state)(unsafe.Pointer(&memSlice[0]))
+ }
+ if err := _C_res_ninit(state); err != nil {
+ return nil, errors.New("res_ninit failure: " + err.Error())
+ }
+ defer _C_res_nclose(state)
+
+ // Some res_nsearch implementations (like macOS) do not set errno.
+ // They set h_errno, which is not per-thread and useless to us.
+ // res_nsearch returns the size of the DNS response packet.
+ // But if the DNS response packet contains failure-like response codes,
+ // res_search returns -1 even though it has copied the packet into buf,
+ // giving us no way to find out how big the packet is.
+ // For now, we are willing to take res_search's word that there's nothing
+ // useful in the response, even though there *is* a response.
+ bufSize := maxDNSPacketSize
+ buf := (*_C_uchar)(_C_malloc(uintptr(bufSize)))
+ defer _C_free(unsafe.Pointer(buf))
+
+ s, err := syscall.BytePtrFromString(hostname)
+ if err != nil {
+ return nil, err
+ }
+
+ var size int
+ for {
+ size, _ = _C_res_nsearch(state, (*_C_char)(unsafe.Pointer(s)), class, rtype, buf, bufSize)
+ if size <= 0 || size > 0xffff {
+ return nil, errors.New("res_nsearch failure")
+ }
+ if size <= bufSize {
+ break
+ }
+
+ // Allocate a bigger buffer to fit the entire msg.
+ _C_free(unsafe.Pointer(buf))
+ bufSize = size
+ buf = (*_C_uchar)(_C_malloc(uintptr(bufSize)))
+ }
+
+ var p dnsmessage.Parser
+ if _, err := p.Start(unsafe.Slice((*byte)(unsafe.Pointer(buf)), size)); err != nil {
+ return nil, err
+ }
+ p.SkipAllQuestions()
+ resources, err := p.AllAnswers()
+ if err != nil {
+ return nil, err
+ }
+ return resources, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo.go
new file mode 100644
index 0000000000000000000000000000000000000000..7c609eddbf76cdd56e2f50f1bb33a47cbc7e21d8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo.go
@@ -0,0 +1,80 @@
+// 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 cgo && !netgo && unix && !darwin
+
+package net
+
+/*
+#define _GNU_SOURCE
+
+#cgo CFLAGS: -fno-stack-protector
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef EAI_NODATA
+#define EAI_NODATA -5
+#endif
+
+// If nothing else defined EAI_OVERFLOW, make sure it has a value.
+#ifndef EAI_OVERFLOW
+#define EAI_OVERFLOW -12
+#endif
+*/
+import "C"
+import "unsafe"
+
+const (
+ _C_AF_INET = C.AF_INET
+ _C_AF_INET6 = C.AF_INET6
+ _C_AF_UNSPEC = C.AF_UNSPEC
+ _C_EAI_AGAIN = C.EAI_AGAIN
+ _C_EAI_NODATA = C.EAI_NODATA
+ _C_EAI_NONAME = C.EAI_NONAME
+ _C_EAI_SERVICE = C.EAI_SERVICE
+ _C_EAI_OVERFLOW = C.EAI_OVERFLOW
+ _C_EAI_SYSTEM = C.EAI_SYSTEM
+ _C_IPPROTO_TCP = C.IPPROTO_TCP
+ _C_IPPROTO_UDP = C.IPPROTO_UDP
+ _C_SOCK_DGRAM = C.SOCK_DGRAM
+ _C_SOCK_STREAM = C.SOCK_STREAM
+)
+
+type (
+ _C_char = C.char
+ _C_uchar = C.uchar
+ _C_int = C.int
+ _C_uint = C.uint
+ _C_socklen_t = C.socklen_t
+ _C_struct_addrinfo = C.struct_addrinfo
+ _C_struct_sockaddr = C.struct_sockaddr
+)
+
+func _C_malloc(n uintptr) unsafe.Pointer { return C.malloc(C.size_t(n)) }
+func _C_free(p unsafe.Pointer) { C.free(p) }
+
+func _C_ai_addr(ai *_C_struct_addrinfo) **_C_struct_sockaddr { return &ai.ai_addr }
+func _C_ai_family(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_family }
+func _C_ai_flags(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_flags }
+func _C_ai_next(ai *_C_struct_addrinfo) **_C_struct_addrinfo { return &ai.ai_next }
+func _C_ai_protocol(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_protocol }
+func _C_ai_socktype(ai *_C_struct_addrinfo) *_C_int { return &ai.ai_socktype }
+
+func _C_freeaddrinfo(ai *_C_struct_addrinfo) {
+ C.freeaddrinfo(ai)
+}
+
+func _C_gai_strerror(eai _C_int) string {
+ return C.GoString(C.gai_strerror(eai))
+}
+
+func _C_getaddrinfo(hostname, servname *_C_char, hints *_C_struct_addrinfo, res **_C_struct_addrinfo) (int, error) {
+ x, err := C.getaddrinfo(hostname, servname, hints, res)
+ return int(x), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_darwin.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_darwin.go
new file mode 100644
index 0000000000000000000000000000000000000000..40d5e426f25ce564d1d00ccdcbb23acc62cbe711
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_darwin.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.
+
+//go:build !netgo && cgo && darwin
+
+package net
+
+/*
+#include
+*/
+import "C"
+
+import (
+ "internal/syscall/unix"
+ "unsafe"
+)
+
+// This will cause a compile error when the size of
+// unix.ResState is too small.
+type _ [unsafe.Sizeof(unix.ResState{}) - unsafe.Sizeof(C.struct___res_state{})]byte
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_res.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_res.go
new file mode 100644
index 0000000000000000000000000000000000000000..37bbc9a762d8ae288ea256aa1fd538f8d0b9fabf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_res.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.
+
+// res_search, for cgo systems where that is thread-safe.
+
+//go:build cgo && !netgo && (linux || openbsd)
+
+package net
+
+/*
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#cgo !android,!openbsd LDFLAGS: -lresolv
+*/
+import "C"
+
+type _C_struct___res_state = struct{}
+
+func _C_res_ninit(state *_C_struct___res_state) error {
+ return nil
+}
+
+func _C_res_nclose(state *_C_struct___res_state) {
+ return
+}
+
+func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_uchar, anslen int) (int, error) {
+ x, err := C.res_search(dname, C.int(class), C.int(typ), ans, C.int(anslen))
+ return int(x), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_resn.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_resn.go
new file mode 100644
index 0000000000000000000000000000000000000000..4a5ff165dfae238b72270e0d69d0aa82984df11a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_cgo_resn.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.
+
+// res_nsearch, for cgo systems where that's available.
+
+//go:build cgo && !netgo && unix && !(darwin || linux || openbsd)
+
+package net
+
+/*
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#cgo !aix,!dragonfly,!freebsd LDFLAGS: -lresolv
+*/
+import "C"
+
+type _C_struct___res_state = C.struct___res_state
+
+func _C_res_ninit(state *_C_struct___res_state) error {
+ _, err := C.res_ninit(state)
+ return err
+}
+
+func _C_res_nclose(state *_C_struct___res_state) {
+ C.res_nclose(state)
+}
+
+func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_uchar, anslen int) (int, error) {
+ x, err := C.res_nsearch(state, dname, C.int(class), C.int(typ), ans, C.int(anslen))
+ return int(x), err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_syscall.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_syscall.go
new file mode 100644
index 0000000000000000000000000000000000000000..ac9aaa78fe7c2b35b410dfd5570ee0457296e104
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_syscall.go
@@ -0,0 +1,99 @@
+// 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 !netgo && darwin
+
+package net
+
+import (
+ "internal/syscall/unix"
+ "runtime"
+ "syscall"
+ "unsafe"
+)
+
+const (
+ _C_AF_INET = syscall.AF_INET
+ _C_AF_INET6 = syscall.AF_INET6
+ _C_AF_UNSPEC = syscall.AF_UNSPEC
+ _C_EAI_AGAIN = unix.EAI_AGAIN
+ _C_EAI_NONAME = unix.EAI_NONAME
+ _C_EAI_SERVICE = unix.EAI_SERVICE
+ _C_EAI_NODATA = unix.EAI_NODATA
+ _C_EAI_OVERFLOW = unix.EAI_OVERFLOW
+ _C_EAI_SYSTEM = unix.EAI_SYSTEM
+ _C_IPPROTO_TCP = syscall.IPPROTO_TCP
+ _C_IPPROTO_UDP = syscall.IPPROTO_UDP
+ _C_SOCK_DGRAM = syscall.SOCK_DGRAM
+ _C_SOCK_STREAM = syscall.SOCK_STREAM
+)
+
+type (
+ _C_char = byte
+ _C_int = int32
+ _C_uchar = byte
+ _C_uint = uint32
+ _C_socklen_t = int
+ _C_struct___res_state = unix.ResState
+ _C_struct_addrinfo = unix.Addrinfo
+ _C_struct_sockaddr = syscall.RawSockaddr
+)
+
+func _C_free(p unsafe.Pointer) { runtime.KeepAlive(p) }
+
+func _C_malloc(n uintptr) unsafe.Pointer {
+ if n <= 0 {
+ n = 1
+ }
+ return unsafe.Pointer(&make([]byte, n)[0])
+}
+
+func _C_ai_addr(ai *_C_struct_addrinfo) **_C_struct_sockaddr { return &ai.Addr }
+func _C_ai_family(ai *_C_struct_addrinfo) *_C_int { return &ai.Family }
+func _C_ai_flags(ai *_C_struct_addrinfo) *_C_int { return &ai.Flags }
+func _C_ai_next(ai *_C_struct_addrinfo) **_C_struct_addrinfo { return &ai.Next }
+func _C_ai_protocol(ai *_C_struct_addrinfo) *_C_int { return &ai.Protocol }
+func _C_ai_socktype(ai *_C_struct_addrinfo) *_C_int { return &ai.Socktype }
+
+func _C_freeaddrinfo(ai *_C_struct_addrinfo) {
+ unix.Freeaddrinfo(ai)
+}
+
+func _C_gai_strerror(eai _C_int) string {
+ return unix.GaiStrerror(int(eai))
+}
+
+func _C_getaddrinfo(hostname, servname *byte, hints *_C_struct_addrinfo, res **_C_struct_addrinfo) (int, error) {
+ return unix.Getaddrinfo(hostname, servname, hints, res)
+}
+
+func _C_res_ninit(state *_C_struct___res_state) error {
+ unix.ResNinit(state)
+ return nil
+}
+
+func _C_res_nsearch(state *_C_struct___res_state, dname *_C_char, class, typ int, ans *_C_char, anslen int) (int, error) {
+ return unix.ResNsearch(state, dname, class, typ, ans, anslen)
+}
+
+func _C_res_nclose(state *_C_struct___res_state) {
+ unix.ResNclose(state)
+}
+
+func cgoNameinfoPTR(b []byte, sa *syscall.RawSockaddr, salen int) (int, error) {
+ gerrno, err := unix.Getnameinfo(sa, salen, &b[0], len(b), nil, 0, unix.NI_NAMEREQD)
+ return int(gerrno), err
+}
+
+func cgoSockaddrInet4(ip IP) *syscall.RawSockaddr {
+ sa := syscall.RawSockaddrInet4{Len: syscall.SizeofSockaddrInet4, Family: syscall.AF_INET}
+ copy(sa.Addr[:], ip)
+ return (*syscall.RawSockaddr)(unsafe.Pointer(&sa))
+}
+
+func cgoSockaddrInet6(ip IP, zone int) *syscall.RawSockaddr {
+ sa := syscall.RawSockaddrInet6{Len: syscall.SizeofSockaddrInet6, Family: syscall.AF_INET6, Scope_id: uint32(zone)}
+ copy(sa.Addr[:], ip)
+ return (*syscall.RawSockaddr)(unsafe.Pointer(&sa))
+}
diff --git a/platform/dbops/binaries/go/go/src/net/cgo_unix_test.go b/platform/dbops/binaries/go/go/src/net/cgo_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d8233dfaf229609551fd2bb635f20efe781ecae5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/cgo_unix_test.go
@@ -0,0 +1,69 @@
+// 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 !netgo && ((cgo && unix) || darwin)
+
+package net
+
+import (
+ "context"
+ "testing"
+)
+
+func TestCgoLookupIP(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx := context.Background()
+ _, err := cgoLookupIP(ctx, "ip", "localhost")
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestCgoLookupIPWithCancel(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, err := cgoLookupIP(ctx, "ip", "localhost")
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestCgoLookupPort(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx := context.Background()
+ _, err := cgoLookupPort(ctx, "tcp", "smtp")
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestCgoLookupPortWithCancel(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, err := cgoLookupPort(ctx, "tcp", "smtp")
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestCgoLookupPTR(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx := context.Background()
+ _, err := cgoLookupPTR(ctx, "127.0.0.1")
+ if err != nil {
+ t.Error(err)
+ }
+}
+
+func TestCgoLookupPTRWithCancel(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, err := cgoLookupPTR(ctx, "127.0.0.1")
+ if err != nil {
+ t.Error(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/conf.go b/platform/dbops/binaries/go/go/src/net/conf.go
new file mode 100644
index 0000000000000000000000000000000000000000..15d73cf6ce1a45aadb2b24594d4711b9a145408c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/conf.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.
+
+package net
+
+import (
+ "errors"
+ "internal/bytealg"
+ "internal/godebug"
+ "io/fs"
+ "os"
+ "runtime"
+ "sync"
+ "syscall"
+)
+
+// The net package's name resolution is rather complicated.
+// There are two main approaches, go and cgo.
+// The cgo resolver uses C functions like getaddrinfo.
+// The go resolver reads system files directly and
+// sends DNS packets directly to servers.
+//
+// The netgo build tag prefers the go resolver.
+// The netcgo build tag prefers the cgo resolver.
+//
+// The netgo build tag also prohibits the use of the cgo tool.
+// However, on Darwin, Plan 9, and Windows the cgo resolver is still available.
+// On those systems the cgo resolver does not require the cgo tool.
+// (The term "cgo resolver" was locked in by GODEBUG settings
+// at a time when the cgo resolver did require the cgo tool.)
+//
+// Adding netdns=go to GODEBUG will prefer the go resolver.
+// Adding netdns=cgo to GODEBUG will prefer the cgo resolver.
+//
+// The Resolver struct has a PreferGo field that user code
+// may set to prefer the go resolver. It is documented as being
+// equivalent to adding netdns=go to GODEBUG.
+//
+// When deciding which resolver to use, we first check the PreferGo field.
+// If that is not set, we check the GODEBUG setting.
+// If that is not set, we check the netgo or netcgo build tag.
+// If none of those are set, we normally prefer the go resolver by default.
+// However, if the cgo resolver is available,
+// there is a complex set of conditions for which we prefer the cgo resolver.
+//
+// Other files define the netGoBuildTag, netCgoBuildTag, and cgoAvailable
+// constants.
+
+// conf is used to determine name resolution configuration.
+type conf struct {
+ netGo bool // prefer go approach, based on build tag and GODEBUG
+ netCgo bool // prefer cgo approach, based on build tag and GODEBUG
+
+ dnsDebugLevel int // from GODEBUG
+
+ preferCgo bool // if no explicit preference, use cgo
+
+ goos string // copy of runtime.GOOS, used for testing
+ mdnsTest mdnsTest // assume /etc/mdns.allow exists, for testing
+}
+
+// mdnsTest is for testing only.
+type mdnsTest int
+
+const (
+ mdnsFromSystem mdnsTest = iota
+ mdnsAssumeExists
+ mdnsAssumeDoesNotExist
+)
+
+var (
+ confOnce sync.Once // guards init of confVal via initConfVal
+ confVal = &conf{goos: runtime.GOOS}
+)
+
+// systemConf returns the machine's network configuration.
+func systemConf() *conf {
+ confOnce.Do(initConfVal)
+ return confVal
+}
+
+// initConfVal initializes confVal based on the environment
+// that will not change during program execution.
+func initConfVal() {
+ dnsMode, debugLevel := goDebugNetDNS()
+ confVal.netGo = netGoBuildTag || dnsMode == "go"
+ confVal.netCgo = netCgoBuildTag || dnsMode == "cgo"
+ confVal.dnsDebugLevel = debugLevel
+
+ if confVal.dnsDebugLevel > 0 {
+ defer func() {
+ if confVal.dnsDebugLevel > 1 {
+ println("go package net: confVal.netCgo =", confVal.netCgo, " netGo =", confVal.netGo)
+ }
+ switch {
+ case confVal.netGo:
+ if netGoBuildTag {
+ println("go package net: built with netgo build tag; using Go's DNS resolver")
+ } else {
+ println("go package net: GODEBUG setting forcing use of Go's resolver")
+ }
+ case !cgoAvailable:
+ println("go package net: cgo resolver not supported; using Go's DNS resolver")
+ case confVal.netCgo || confVal.preferCgo:
+ println("go package net: using cgo DNS resolver")
+ default:
+ println("go package net: dynamic selection of DNS resolver")
+ }
+ }()
+ }
+
+ // The remainder of this function sets preferCgo based on
+ // conditions that will not change during program execution.
+
+ // By default, prefer the go resolver.
+ confVal.preferCgo = false
+
+ // If the cgo resolver is not available, we can't prefer it.
+ if !cgoAvailable {
+ return
+ }
+
+ // Some operating systems always prefer the cgo resolver.
+ if goosPrefersCgo() {
+ confVal.preferCgo = true
+ return
+ }
+
+ // The remaining checks are specific to Unix systems.
+ switch runtime.GOOS {
+ case "plan9", "windows", "js", "wasip1":
+ return
+ }
+
+ // If any environment-specified resolver options are specified,
+ // prefer the cgo resolver.
+ // Note that LOCALDOMAIN can change behavior merely by being
+ // specified with the empty string.
+ _, localDomainDefined := syscall.Getenv("LOCALDOMAIN")
+ if localDomainDefined || os.Getenv("RES_OPTIONS") != "" || os.Getenv("HOSTALIASES") != "" {
+ confVal.preferCgo = true
+ return
+ }
+
+ // OpenBSD apparently lets you override the location of resolv.conf
+ // with ASR_CONFIG. If we notice that, defer to libc.
+ if runtime.GOOS == "openbsd" && os.Getenv("ASR_CONFIG") != "" {
+ confVal.preferCgo = true
+ return
+ }
+}
+
+// goosPrefersCgo reports whether the GOOS value passed in prefers
+// the cgo resolver.
+func goosPrefersCgo() bool {
+ switch runtime.GOOS {
+ // Historically on Windows and Plan 9 we prefer the
+ // cgo resolver (which doesn't use the cgo tool) rather than
+ // the go resolver. This is because originally these
+ // systems did not support the go resolver.
+ // Keep it this way for better compatibility.
+ // Perhaps we can revisit this some day.
+ case "windows", "plan9":
+ return true
+
+ // Darwin pops up annoying dialog boxes if programs try to
+ // do their own DNS requests, so prefer cgo.
+ case "darwin", "ios":
+ return true
+
+ // DNS requests don't work on Android, so prefer the cgo resolver.
+ // Issue #10714.
+ case "android":
+ return true
+
+ default:
+ return false
+ }
+}
+
+// mustUseGoResolver reports whether a DNS lookup of any sort is
+// required to use the go resolver. The provided Resolver is optional.
+// This will report true if the cgo resolver is not available.
+func (c *conf) mustUseGoResolver(r *Resolver) bool {
+ if !cgoAvailable {
+ return true
+ }
+
+ if runtime.GOOS == "plan9" {
+ // TODO(bradfitz): for now we only permit use of the PreferGo
+ // implementation when there's a non-nil Resolver with a
+ // non-nil Dialer. This is a sign that they the code is trying
+ // to use their DNS-speaking net.Conn (such as an in-memory
+ // DNS cache) and they don't want to actually hit the network.
+ // Once we add support for looking the default DNS servers
+ // from plan9, though, then we can relax this.
+ if r == nil || r.Dial == nil {
+ return false
+ }
+ }
+
+ return c.netGo || r.preferGo()
+}
+
+// addrLookupOrder determines which strategy to use to resolve addresses.
+// The provided Resolver is optional. nil means to not consider its options.
+// It also returns dnsConfig when it was used to determine the lookup order.
+func (c *conf) addrLookupOrder(r *Resolver, addr string) (ret hostLookupOrder, dnsConf *dnsConfig) {
+ if c.dnsDebugLevel > 1 {
+ defer func() {
+ print("go package net: addrLookupOrder(", addr, ") = ", ret.String(), "\n")
+ }()
+ }
+ return c.lookupOrder(r, "")
+}
+
+// hostLookupOrder determines which strategy to use to resolve hostname.
+// The provided Resolver is optional. nil means to not consider its options.
+// It also returns dnsConfig when it was used to determine the lookup order.
+func (c *conf) hostLookupOrder(r *Resolver, hostname string) (ret hostLookupOrder, dnsConf *dnsConfig) {
+ if c.dnsDebugLevel > 1 {
+ defer func() {
+ print("go package net: hostLookupOrder(", hostname, ") = ", ret.String(), "\n")
+ }()
+ }
+ return c.lookupOrder(r, hostname)
+}
+
+func (c *conf) lookupOrder(r *Resolver, hostname string) (ret hostLookupOrder, dnsConf *dnsConfig) {
+ // fallbackOrder is the order we return if we can't figure it out.
+ var fallbackOrder hostLookupOrder
+
+ var canUseCgo bool
+ if c.mustUseGoResolver(r) {
+ // Go resolver was explicitly requested
+ // or cgo resolver is not available.
+ // Figure out the order below.
+ fallbackOrder = hostLookupFilesDNS
+ canUseCgo = false
+ } else if c.netCgo {
+ // Cgo resolver was explicitly requested.
+ return hostLookupCgo, nil
+ } else if c.preferCgo {
+ // Given a choice, we prefer the cgo resolver.
+ return hostLookupCgo, nil
+ } else {
+ // Neither resolver was explicitly requested
+ // and we have no preference.
+
+ if bytealg.IndexByteString(hostname, '\\') != -1 || bytealg.IndexByteString(hostname, '%') != -1 {
+ // Don't deal with special form hostnames
+ // with backslashes or '%'.
+ return hostLookupCgo, nil
+ }
+
+ // If something is unrecognized, use cgo.
+ fallbackOrder = hostLookupCgo
+ canUseCgo = true
+ }
+
+ // On systems that don't use /etc/resolv.conf or /etc/nsswitch.conf, we are done.
+ switch c.goos {
+ case "windows", "plan9", "android", "ios":
+ return fallbackOrder, nil
+ }
+
+ // Try to figure out the order to use for searches.
+ // If we don't recognize something, use fallbackOrder.
+ // That will use cgo unless the Go resolver was explicitly requested.
+ // If we do figure out the order, return something other
+ // than fallbackOrder to use the Go resolver with that order.
+
+ dnsConf = getSystemDNSConfig()
+
+ if canUseCgo && dnsConf.err != nil && !errors.Is(dnsConf.err, fs.ErrNotExist) && !errors.Is(dnsConf.err, fs.ErrPermission) {
+ // We can't read the resolv.conf file, so use cgo if we can.
+ return hostLookupCgo, dnsConf
+ }
+
+ if canUseCgo && dnsConf.unknownOpt {
+ // We didn't recognize something in resolv.conf,
+ // so use cgo if we can.
+ return hostLookupCgo, dnsConf
+ }
+
+ // OpenBSD is unique and doesn't use nsswitch.conf.
+ // It also doesn't support mDNS.
+ if c.goos == "openbsd" {
+ // OpenBSD's resolv.conf manpage says that a
+ // non-existent resolv.conf means "lookup" defaults
+ // to only "files", without DNS lookups.
+ if errors.Is(dnsConf.err, fs.ErrNotExist) {
+ return hostLookupFiles, dnsConf
+ }
+
+ lookup := dnsConf.lookup
+ if len(lookup) == 0 {
+ // https://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/resolv.conf.5
+ // "If the lookup keyword is not used in the
+ // system's resolv.conf file then the assumed
+ // order is 'bind file'"
+ return hostLookupDNSFiles, dnsConf
+ }
+ if len(lookup) < 1 || len(lookup) > 2 {
+ // We don't recognize this format.
+ return fallbackOrder, dnsConf
+ }
+ switch lookup[0] {
+ case "bind":
+ if len(lookup) == 2 {
+ if lookup[1] == "file" {
+ return hostLookupDNSFiles, dnsConf
+ }
+ // Unrecognized.
+ return fallbackOrder, dnsConf
+ }
+ return hostLookupDNS, dnsConf
+ case "file":
+ if len(lookup) == 2 {
+ if lookup[1] == "bind" {
+ return hostLookupFilesDNS, dnsConf
+ }
+ // Unrecognized.
+ return fallbackOrder, dnsConf
+ }
+ return hostLookupFiles, dnsConf
+ default:
+ // Unrecognized.
+ return fallbackOrder, dnsConf
+ }
+
+ // We always return before this point.
+ // The code below is for non-OpenBSD.
+ }
+
+ // Canonicalize the hostname by removing any trailing dot.
+ if stringsHasSuffix(hostname, ".") {
+ hostname = hostname[:len(hostname)-1]
+ }
+ if canUseCgo && stringsHasSuffixFold(hostname, ".local") {
+ // Per RFC 6762, the ".local" TLD is special. And
+ // because Go's native resolver doesn't do mDNS or
+ // similar local resolution mechanisms, assume that
+ // libc might (via Avahi, etc) and use cgo.
+ return hostLookupCgo, dnsConf
+ }
+
+ nss := getSystemNSS()
+ srcs := nss.sources["hosts"]
+ // If /etc/nsswitch.conf doesn't exist or doesn't specify any
+ // sources for "hosts", assume Go's DNS will work fine.
+ if errors.Is(nss.err, fs.ErrNotExist) || (nss.err == nil && len(srcs) == 0) {
+ if canUseCgo && c.goos == "solaris" {
+ // illumos defaults to
+ // "nis [NOTFOUND=return] files",
+ // which the go resolver doesn't support.
+ return hostLookupCgo, dnsConf
+ }
+
+ return hostLookupFilesDNS, dnsConf
+ }
+ if nss.err != nil {
+ // We failed to parse or open nsswitch.conf, so
+ // we have nothing to base an order on.
+ return fallbackOrder, dnsConf
+ }
+
+ var hasDNSSource bool
+ var hasDNSSourceChecked bool
+
+ var filesSource, dnsSource bool
+ var first string
+ for i, src := range srcs {
+ if src.source == "files" || src.source == "dns" {
+ if canUseCgo && !src.standardCriteria() {
+ // non-standard; let libc deal with it.
+ return hostLookupCgo, dnsConf
+ }
+ if src.source == "files" {
+ filesSource = true
+ } else {
+ hasDNSSource = true
+ hasDNSSourceChecked = true
+ dnsSource = true
+ }
+ if first == "" {
+ first = src.source
+ }
+ continue
+ }
+
+ if canUseCgo {
+ switch {
+ case hostname != "" && src.source == "myhostname":
+ // Let the cgo resolver handle myhostname
+ // if we are looking up the local hostname.
+ if isLocalhost(hostname) || isGateway(hostname) || isOutbound(hostname) {
+ return hostLookupCgo, dnsConf
+ }
+ hn, err := getHostname()
+ if err != nil || stringsEqualFold(hostname, hn) {
+ return hostLookupCgo, dnsConf
+ }
+ continue
+ case hostname != "" && stringsHasPrefix(src.source, "mdns"):
+ // e.g. "mdns4", "mdns4_minimal"
+ // We already returned true before if it was *.local.
+ // libc wouldn't have found a hit on this anyway.
+
+ // We don't parse mdns.allow files. They're rare. If one
+ // exists, it might list other TLDs (besides .local) or even
+ // '*', so just let libc deal with it.
+ var haveMDNSAllow bool
+ switch c.mdnsTest {
+ case mdnsFromSystem:
+ _, err := os.Stat("/etc/mdns.allow")
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
+ // Let libc figure out what is going on.
+ return hostLookupCgo, dnsConf
+ }
+ haveMDNSAllow = err == nil
+ case mdnsAssumeExists:
+ haveMDNSAllow = true
+ case mdnsAssumeDoesNotExist:
+ haveMDNSAllow = false
+ }
+ if haveMDNSAllow {
+ return hostLookupCgo, dnsConf
+ }
+ continue
+ default:
+ // Some source we don't know how to deal with.
+ return hostLookupCgo, dnsConf
+ }
+ }
+
+ if !hasDNSSourceChecked {
+ hasDNSSourceChecked = true
+ for _, v := range srcs[i+1:] {
+ if v.source == "dns" {
+ hasDNSSource = true
+ break
+ }
+ }
+ }
+
+ // If we saw a source we don't recognize, which can only
+ // happen if we can't use the cgo resolver, treat it as DNS,
+ // but only when there is no dns in all other sources.
+ if !hasDNSSource {
+ dnsSource = true
+ if first == "" {
+ first = "dns"
+ }
+ }
+ }
+
+ // Cases where Go can handle it without cgo and C thread overhead,
+ // or where the Go resolver has been forced.
+ switch {
+ case filesSource && dnsSource:
+ if first == "files" {
+ return hostLookupFilesDNS, dnsConf
+ } else {
+ return hostLookupDNSFiles, dnsConf
+ }
+ case filesSource:
+ return hostLookupFiles, dnsConf
+ case dnsSource:
+ return hostLookupDNS, dnsConf
+ }
+
+ // Something weird. Fallback to the default.
+ return fallbackOrder, dnsConf
+}
+
+var netdns = godebug.New("netdns")
+
+// goDebugNetDNS parses the value of the GODEBUG "netdns" value.
+// The netdns value can be of the form:
+//
+// 1 // debug level 1
+// 2 // debug level 2
+// cgo // use cgo for DNS lookups
+// go // use go for DNS lookups
+// cgo+1 // use cgo for DNS lookups + debug level 1
+// 1+cgo // same
+// cgo+2 // same, but debug level 2
+//
+// etc.
+func goDebugNetDNS() (dnsMode string, debugLevel int) {
+ goDebug := netdns.Value()
+ parsePart := func(s string) {
+ if s == "" {
+ return
+ }
+ if '0' <= s[0] && s[0] <= '9' {
+ debugLevel, _, _ = dtoi(s)
+ } else {
+ dnsMode = s
+ }
+ }
+ if i := bytealg.IndexByteString(goDebug, '+'); i != -1 {
+ parsePart(goDebug[:i])
+ parsePart(goDebug[i+1:])
+ return
+ }
+ parsePart(goDebug)
+ return
+}
+
+// isLocalhost reports whether h should be considered a "localhost"
+// name for the myhostname NSS module.
+func isLocalhost(h string) bool {
+ return stringsEqualFold(h, "localhost") || stringsEqualFold(h, "localhost.localdomain") || stringsHasSuffixFold(h, ".localhost") || stringsHasSuffixFold(h, ".localhost.localdomain")
+}
+
+// isGateway reports whether h should be considered a "gateway"
+// name for the myhostname NSS module.
+func isGateway(h string) bool {
+ return stringsEqualFold(h, "_gateway")
+}
+
+// isOutbound reports whether h should be considered an "outbound"
+// name for the myhostname NSS module.
+func isOutbound(h string) bool {
+ return stringsEqualFold(h, "_outbound")
+}
diff --git a/platform/dbops/binaries/go/go/src/net/conf_test.go b/platform/dbops/binaries/go/go/src/net/conf_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0f324b245aef12269d3160a97879317ac9803c5f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/conf_test.go
@@ -0,0 +1,461 @@
+// 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 unix
+
+package net
+
+import (
+ "io/fs"
+ "os"
+ "testing"
+ "time"
+)
+
+type nssHostTest struct {
+ host string
+ localhost string
+ want hostLookupOrder
+}
+
+func nssStr(t *testing.T, s string) *nssConf {
+ f, err := os.CreateTemp(t.TempDir(), "nss")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.WriteString(s); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return parseNSSConfFile(f.Name())
+}
+
+// represents a dnsConfig returned by parsing a nonexistent resolv.conf
+var defaultResolvConf = &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ timeout: 5,
+ attempts: 2,
+ err: fs.ErrNotExist,
+}
+
+func TestConfHostLookupOrder(t *testing.T) {
+ // These tests are written for a system with cgo available,
+ // without using the netgo tag.
+ if netGoBuildTag {
+ t.Skip("skipping test because net package built with netgo tag")
+ }
+ if !cgoAvailable {
+ t.Skip("skipping test because cgo resolver not available")
+ }
+
+ tests := []struct {
+ name string
+ c *conf
+ nss *nssConf
+ resolver *Resolver
+ resolv *dnsConfig
+ hostTests []nssHostTest
+ }{
+ {
+ name: "force",
+ c: &conf{
+ preferCgo: true,
+ netCgo: true,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "foo: bar"),
+ hostTests: []nssHostTest{
+ {"foo.local", "myhostname", hostLookupCgo},
+ {"google.com", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "netgo_dns_before_files",
+ c: &conf{
+ netGo: true,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns files"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ {
+ name: "netgo_fallback_on_cgo",
+ c: &conf{
+ netGo: true,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns files something_custom"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ {
+ name: "ubuntu_trusty_avahi",
+ c: &conf{
+ mdnsTest: mdnsAssumeDoesNotExist,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4"),
+ hostTests: []nssHostTest{
+ {"foo.local", "myhostname", hostLookupCgo},
+ {"foo.local.", "myhostname", hostLookupCgo},
+ {"foo.LOCAL", "myhostname", hostLookupCgo},
+ {"foo.LOCAL.", "myhostname", hostLookupCgo},
+ {"google.com", "myhostname", hostLookupFilesDNS},
+ },
+ },
+ {
+ name: "freebsdlinux_no_resolv_conf",
+ c: &conf{
+ goos: "freebsd",
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "foo: bar"),
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}},
+ },
+ // On OpenBSD, no resolv.conf means no DNS.
+ {
+ name: "openbsd_no_resolv_conf",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: defaultResolvConf,
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFiles}},
+ },
+ {
+ name: "solaris_no_nsswitch",
+ c: &conf{
+ goos: "solaris",
+ },
+ resolv: defaultResolvConf,
+ nss: &nssConf{err: fs.ErrNotExist},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}},
+ },
+ {
+ name: "openbsd_lookup_bind_file",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"bind", "file"}},
+ hostTests: []nssHostTest{
+ {"google.com", "myhostname", hostLookupDNSFiles},
+ {"foo.local", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ {
+ name: "openbsd_lookup_file_bind",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"file", "bind"}},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}},
+ },
+ {
+ name: "openbsd_lookup_bind",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"bind"}},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupDNS}},
+ },
+ {
+ name: "openbsd_lookup_file",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"file"}},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFiles}},
+ },
+ {
+ name: "openbsd_lookup_yp",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"file", "bind", "yp"}},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}},
+ },
+ {
+ name: "openbsd_lookup_two",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: []string{"file", "foo"}},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}},
+ },
+ {
+ name: "openbsd_lookup_empty",
+ c: &conf{
+ goos: "openbsd",
+ },
+ resolv: &dnsConfig{lookup: nil},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupDNSFiles}},
+ },
+ {
+ name: "linux_no_nsswitch.conf",
+ c: &conf{
+ goos: "linux",
+ },
+ resolv: defaultResolvConf,
+ nss: &nssConf{err: fs.ErrNotExist},
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}},
+ },
+ {
+ name: "linux_empty_nsswitch.conf",
+ c: &conf{
+ goos: "linux",
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, ""),
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupFilesDNS}},
+ },
+ {
+ name: "files_mdns_dns",
+ c: &conf{
+ mdnsTest: mdnsAssumeDoesNotExist,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files mdns dns"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupFilesDNS},
+ {"x.local", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "dns_special_hostnames",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNS},
+ {"x\\.com", "myhostname", hostLookupCgo}, // punt on weird glibc escape
+ {"foo.com%en0", "myhostname", hostLookupCgo}, // and IPv6 zones
+ },
+ },
+ {
+ name: "mdns_allow",
+ c: &conf{
+ mdnsTest: mdnsAssumeExists,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files mdns dns"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupCgo},
+ {"x.local", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "files_dns",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files dns"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupFilesDNS},
+ {"x", "myhostname", hostLookupFilesDNS},
+ {"x.local", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "dns_files",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns files"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ {"x", "myhostname", hostLookupDNSFiles},
+ {"x.local", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "something_custom",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns files something_custom"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupCgo},
+ },
+ },
+ {
+ name: "myhostname",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files dns myhostname"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupFilesDNS},
+ {"myhostname", "myhostname", hostLookupCgo},
+ {"myHostname", "myhostname", hostLookupCgo},
+ {"myhostname.dot", "myhostname.dot", hostLookupCgo},
+ {"myHostname.dot", "myhostname.dot", hostLookupCgo},
+ {"_gateway", "myhostname", hostLookupCgo},
+ {"_Gateway", "myhostname", hostLookupCgo},
+ {"_outbound", "myhostname", hostLookupCgo},
+ {"_Outbound", "myhostname", hostLookupCgo},
+ {"localhost", "myhostname", hostLookupCgo},
+ {"Localhost", "myhostname", hostLookupCgo},
+ {"anything.localhost", "myhostname", hostLookupCgo},
+ {"Anything.localhost", "myhostname", hostLookupCgo},
+ {"localhost.localdomain", "myhostname", hostLookupCgo},
+ {"Localhost.Localdomain", "myhostname", hostLookupCgo},
+ {"anything.localhost.localdomain", "myhostname", hostLookupCgo},
+ {"Anything.Localhost.Localdomain", "myhostname", hostLookupCgo},
+ {"somehostname", "myhostname", hostLookupFilesDNS},
+ },
+ },
+ {
+ name: "ubuntu14.04.02",
+ c: &conf{
+ mdnsTest: mdnsAssumeDoesNotExist,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: files myhostname mdns4_minimal [NOTFOUND=return] dns mdns4"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupFilesDNS},
+ {"somehostname", "myhostname", hostLookupFilesDNS},
+ {"myhostname", "myhostname", hostLookupCgo},
+ },
+ },
+ // Debian Squeeze is just "dns,files", but lists all
+ // the default criteria for dns, but then has a
+ // non-standard but redundant notfound=return for the
+ // files.
+ {
+ name: "debian_squeeze",
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns [success=return notfound=continue unavail=continue tryagain=continue] files [notfound=return]"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ {"somehostname", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ {
+ name: "resolv.conf-unknown",
+ c: &conf{},
+ resolv: &dnsConfig{servers: defaultNS, ndots: 1, timeout: 5, attempts: 2, unknownOpt: true},
+ nss: nssStr(t, "foo: bar"),
+ hostTests: []nssHostTest{{"google.com", "myhostname", hostLookupCgo}},
+ },
+ // Issue 24393: make sure "Resolver.PreferGo = true" acts like netgo.
+ {
+ name: "resolver-prefergo",
+ resolver: &Resolver{PreferGo: true},
+ c: &conf{
+ preferCgo: true,
+ netCgo: true,
+ },
+ resolv: defaultResolvConf,
+ nss: nssStr(t, ""),
+ hostTests: []nssHostTest{
+ {"localhost", "myhostname", hostLookupFilesDNS},
+ },
+ },
+ {
+ name: "unknown-source",
+ resolver: &Resolver{PreferGo: true},
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: resolve files"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ {
+ name: "dns-among-unknown-sources",
+ resolver: &Resolver{PreferGo: true},
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: mymachines files dns"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupFilesDNS},
+ },
+ },
+ {
+ name: "dns-among-unknown-sources-2",
+ resolver: &Resolver{PreferGo: true},
+ c: &conf{},
+ resolv: defaultResolvConf,
+ nss: nssStr(t, "hosts: dns mymachines files"),
+ hostTests: []nssHostTest{
+ {"x.com", "myhostname", hostLookupDNSFiles},
+ },
+ },
+ }
+
+ origGetHostname := getHostname
+ defer func() { getHostname = origGetHostname }()
+ defer setSystemNSS(getSystemNSS(), 0)
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ for _, tt := range tests {
+ if !conf.forceUpdateConf(tt.resolv, time.Now().Add(time.Hour)) {
+ t.Errorf("%s: failed to change resolv config", tt.name)
+ }
+ for _, ht := range tt.hostTests {
+ getHostname = func() (string, error) { return ht.localhost, nil }
+ setSystemNSS(tt.nss, time.Hour)
+
+ gotOrder, _ := tt.c.hostLookupOrder(tt.resolver, ht.host)
+ if gotOrder != ht.want {
+ t.Errorf("%s: hostLookupOrder(%q) = %v; want %v", tt.name, ht.host, gotOrder, ht.want)
+ }
+ }
+ }
+}
+
+func TestAddrLookupOrder(t *testing.T) {
+ // This test is written for a system with cgo available,
+ // without using the netgo tag.
+ if netGoBuildTag {
+ t.Skip("skipping test because net package built with netgo tag")
+ }
+ if !cgoAvailable {
+ t.Skip("skipping test because cgo resolver not available")
+ }
+
+ defer setSystemNSS(getSystemNSS(), 0)
+ c, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.teardown()
+
+ if !c.forceUpdateConf(defaultResolvConf, time.Now().Add(time.Hour)) {
+ t.Fatal("failed to change resolv config")
+ }
+
+ setSystemNSS(nssStr(t, "hosts: files myhostname dns"), time.Hour)
+ cnf := &conf{}
+ order, _ := cnf.addrLookupOrder(nil, "192.0.2.1")
+ if order != hostLookupCgo {
+ t.Errorf("addrLookupOrder returned: %v, want cgo", order)
+ }
+
+ setSystemNSS(nssStr(t, "hosts: files mdns4 dns"), time.Hour)
+ order, _ = cnf.addrLookupOrder(nil, "192.0.2.1")
+ if order != hostLookupCgo {
+ t.Errorf("addrLookupOrder returned: %v, want cgo", order)
+ }
+
+}
+
+func setSystemNSS(nss *nssConf, addDur time.Duration) {
+ nssConfig.mu.Lock()
+ nssConfig.nssConf = nss
+ nssConfig.mu.Unlock()
+ nssConfig.acquireSema()
+ nssConfig.lastChecked = time.Now().Add(addDur)
+ nssConfig.releaseSema()
+}
+
+func TestSystemConf(t *testing.T) {
+ systemConf()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/conn_test.go b/platform/dbops/binaries/go/go/src/net/conn_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d1e1e7bf1cdf321b321a764aa165b26d279d69fb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/conn_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 API tests across platforms and should never have a build
+// constraint.
+
+package net
+
+import (
+ "testing"
+ "time"
+)
+
+// someTimeout is used just to test that net.Conn implementations
+// don't explode when their SetFooDeadline methods are called.
+// It isn't actually used for testing timeouts.
+const someTimeout = 1 * time.Hour
+
+func TestConnAndListener(t *testing.T) {
+ for i, network := range []string{"tcp", "unix", "unixpacket"} {
+ i, network := i, network
+ t.Run(network, func(t *testing.T) {
+ if !testableNetwork(network) {
+ t.Skipf("skipping %s test", network)
+ }
+
+ ls := newLocalServer(t, network)
+ defer ls.teardown()
+ ch := make(chan error, 1)
+ handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) }
+ if err := ls.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+ if ls.Listener.Addr().Network() != network {
+ t.Fatalf("got %s; want %s", ls.Listener.Addr().Network(), network)
+ }
+
+ c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network {
+ t.Fatalf("got %s->%s; want %s->%s", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network)
+ }
+ c.SetDeadline(time.Now().Add(someTimeout))
+ c.SetReadDeadline(time.Now().Add(someTimeout))
+ c.SetWriteDeadline(time.Now().Add(someTimeout))
+
+ if _, err := c.Write([]byte("CONN AND LISTENER TEST")); err != nil {
+ t.Fatal(err)
+ }
+ rb := make([]byte, 128)
+ if _, err := c.Read(rb); err != nil {
+ t.Fatal(err)
+ }
+
+ for err := range ch {
+ t.Errorf("#%d: %v", i, err)
+ }
+ })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dial.go b/platform/dbops/binaries/go/go/src/net/dial.go
new file mode 100644
index 0000000000000000000000000000000000000000..a6565c3ce5d13b8fcd81e73f194ecca72de379d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dial.go
@@ -0,0 +1,839 @@
+// 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 net
+
+import (
+ "context"
+ "internal/bytealg"
+ "internal/godebug"
+ "internal/nettrace"
+ "syscall"
+ "time"
+)
+
+const (
+ // defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
+ // See go.dev/issue/31510
+ defaultTCPKeepAlive = 15 * time.Second
+
+ // For the moment, MultiPath TCP is not used by default
+ // See go.dev/issue/56539
+ defaultMPTCPEnabled = false
+)
+
+var multipathtcp = godebug.New("multipathtcp")
+
+// mptcpStatus is a tristate for Multipath TCP, see go.dev/issue/56539
+type mptcpStatus uint8
+
+const (
+ // The value 0 is the system default, linked to defaultMPTCPEnabled
+ mptcpUseDefault mptcpStatus = iota
+ mptcpEnabled
+ mptcpDisabled
+)
+
+func (m *mptcpStatus) get() bool {
+ switch *m {
+ case mptcpEnabled:
+ return true
+ case mptcpDisabled:
+ return false
+ }
+
+ // If MPTCP is forced via GODEBUG=multipathtcp=1
+ if multipathtcp.Value() == "1" {
+ multipathtcp.IncNonDefault()
+
+ return true
+ }
+
+ return defaultMPTCPEnabled
+}
+
+func (m *mptcpStatus) set(use bool) {
+ if use {
+ *m = mptcpEnabled
+ } else {
+ *m = mptcpDisabled
+ }
+}
+
+// A Dialer contains options for connecting to an address.
+//
+// The zero value for each field is equivalent to dialing
+// without that option. Dialing with the zero value of Dialer
+// is therefore equivalent to just calling the [Dial] function.
+//
+// It is safe to call Dialer's methods concurrently.
+type Dialer struct {
+ // Timeout is the maximum amount of time a dial will wait for
+ // a connect to complete. If Deadline is also set, it may fail
+ // earlier.
+ //
+ // The default is no timeout.
+ //
+ // When using TCP and dialing a host name with multiple IP
+ // addresses, the timeout may be divided between them.
+ //
+ // With or without a timeout, the operating system may impose
+ // its own earlier timeout. For instance, TCP timeouts are
+ // often around 3 minutes.
+ Timeout time.Duration
+
+ // Deadline is the absolute point in time after which dials
+ // will fail. If Timeout is set, it may fail earlier.
+ // Zero means no deadline, or dependent on the operating system
+ // as with the Timeout option.
+ Deadline time.Time
+
+ // LocalAddr is the local address to use when dialing an
+ // address. The address must be of a compatible type for the
+ // network being dialed.
+ // If nil, a local address is automatically chosen.
+ LocalAddr Addr
+
+ // DualStack previously enabled RFC 6555 Fast Fallback
+ // support, also known as "Happy Eyeballs", in which IPv4 is
+ // tried soon if IPv6 appears to be misconfigured and
+ // hanging.
+ //
+ // Deprecated: Fast Fallback is enabled by default. To
+ // disable, set FallbackDelay to a negative value.
+ DualStack bool
+
+ // FallbackDelay specifies the length of time to wait before
+ // spawning a RFC 6555 Fast Fallback connection. That is, this
+ // is the amount of time to wait for IPv6 to succeed before
+ // assuming that IPv6 is misconfigured and falling back to
+ // IPv4.
+ //
+ // If zero, a default delay of 300ms is used.
+ // A negative value disables Fast Fallback support.
+ FallbackDelay time.Duration
+
+ // KeepAlive specifies the interval between keep-alive
+ // probes for an active network connection.
+ // If zero, keep-alive probes are sent with a default value
+ // (currently 15 seconds), if supported by the protocol and operating
+ // system. Network protocols or operating systems that do
+ // not support keep-alives ignore this field.
+ // If negative, keep-alive probes are disabled.
+ KeepAlive time.Duration
+
+ // Resolver optionally specifies an alternate resolver to use.
+ Resolver *Resolver
+
+ // Cancel is an optional channel whose closure indicates that
+ // the dial should be canceled. Not all types of dials support
+ // cancellation.
+ //
+ // Deprecated: Use DialContext instead.
+ Cancel <-chan struct{}
+
+ // If Control is not nil, it is called after creating the network
+ // connection but before actually dialing.
+ //
+ // Network and address parameters passed to Control function are not
+ // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
+ // will cause the Control function to be called with "tcp4" or "tcp6".
+ //
+ // Control is ignored if ControlContext is not nil.
+ Control func(network, address string, c syscall.RawConn) error
+
+ // If ControlContext is not nil, it is called after creating the network
+ // connection but before actually dialing.
+ //
+ // Network and address parameters passed to ControlContext function are not
+ // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
+ // will cause the ControlContext function to be called with "tcp4" or "tcp6".
+ //
+ // If ControlContext is not nil, Control is ignored.
+ ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error
+
+ // If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
+ // used, any call to Dial with "tcp(4|6)" as network will use MPTCP if
+ // supported by the operating system.
+ mptcpStatus mptcpStatus
+}
+
+func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 }
+
+func minNonzeroTime(a, b time.Time) time.Time {
+ if a.IsZero() {
+ return b
+ }
+ if b.IsZero() || a.Before(b) {
+ return a
+ }
+ return b
+}
+
+// deadline returns the earliest of:
+// - now+Timeout
+// - d.Deadline
+// - the context's deadline
+//
+// Or zero, if none of Timeout, Deadline, or context's deadline is set.
+func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
+ if d.Timeout != 0 { // including negative, for historical reasons
+ earliest = now.Add(d.Timeout)
+ }
+ if d, ok := ctx.Deadline(); ok {
+ earliest = minNonzeroTime(earliest, d)
+ }
+ return minNonzeroTime(earliest, d.Deadline)
+}
+
+func (d *Dialer) resolver() *Resolver {
+ if d.Resolver != nil {
+ return d.Resolver
+ }
+ return DefaultResolver
+}
+
+// partialDeadline returns the deadline to use for a single address,
+// when multiple addresses are pending.
+func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
+ if deadline.IsZero() {
+ return deadline, nil
+ }
+ timeRemaining := deadline.Sub(now)
+ if timeRemaining <= 0 {
+ return time.Time{}, errTimeout
+ }
+ // Tentatively allocate equal time to each remaining address.
+ timeout := timeRemaining / time.Duration(addrsRemaining)
+ // If the time per address is too short, steal from the end of the list.
+ const saneMinimum = 2 * time.Second
+ if timeout < saneMinimum {
+ if timeRemaining < saneMinimum {
+ timeout = timeRemaining
+ } else {
+ timeout = saneMinimum
+ }
+ }
+ return now.Add(timeout), nil
+}
+
+func (d *Dialer) fallbackDelay() time.Duration {
+ if d.FallbackDelay > 0 {
+ return d.FallbackDelay
+ } else {
+ return 300 * time.Millisecond
+ }
+}
+
+func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) {
+ i := bytealg.LastIndexByteString(network, ':')
+ if i < 0 { // no colon
+ switch network {
+ case "tcp", "tcp4", "tcp6":
+ case "udp", "udp4", "udp6":
+ case "ip", "ip4", "ip6":
+ if needsProto {
+ return "", 0, UnknownNetworkError(network)
+ }
+ case "unix", "unixgram", "unixpacket":
+ default:
+ return "", 0, UnknownNetworkError(network)
+ }
+ return network, 0, nil
+ }
+ afnet = network[:i]
+ switch afnet {
+ case "ip", "ip4", "ip6":
+ protostr := network[i+1:]
+ proto, i, ok := dtoi(protostr)
+ if !ok || i != len(protostr) {
+ proto, err = lookupProtocol(ctx, protostr)
+ if err != nil {
+ return "", 0, err
+ }
+ }
+ return afnet, proto, nil
+ }
+ return "", 0, UnknownNetworkError(network)
+}
+
+// resolveAddrList resolves addr using hint and returns a list of
+// addresses. The result contains at least one address when error is
+// nil.
+func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) {
+ afnet, _, err := parseNetwork(ctx, network, true)
+ if err != nil {
+ return nil, err
+ }
+ if op == "dial" && addr == "" {
+ return nil, errMissingAddress
+ }
+ switch afnet {
+ case "unix", "unixgram", "unixpacket":
+ addr, err := ResolveUnixAddr(afnet, addr)
+ if err != nil {
+ return nil, err
+ }
+ if op == "dial" && hint != nil && addr.Network() != hint.Network() {
+ return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
+ }
+ return addrList{addr}, nil
+ }
+ addrs, err := r.internetAddrList(ctx, afnet, addr)
+ if err != nil || op != "dial" || hint == nil {
+ return addrs, err
+ }
+ var (
+ tcp *TCPAddr
+ udp *UDPAddr
+ ip *IPAddr
+ wildcard bool
+ )
+ switch hint := hint.(type) {
+ case *TCPAddr:
+ tcp = hint
+ wildcard = tcp.isWildcard()
+ case *UDPAddr:
+ udp = hint
+ wildcard = udp.isWildcard()
+ case *IPAddr:
+ ip = hint
+ wildcard = ip.isWildcard()
+ }
+ naddrs := addrs[:0]
+ for _, addr := range addrs {
+ if addr.Network() != hint.Network() {
+ return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
+ }
+ switch addr := addr.(type) {
+ case *TCPAddr:
+ if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) {
+ continue
+ }
+ naddrs = append(naddrs, addr)
+ case *UDPAddr:
+ if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) {
+ continue
+ }
+ naddrs = append(naddrs, addr)
+ case *IPAddr:
+ if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) {
+ continue
+ }
+ naddrs = append(naddrs, addr)
+ }
+ }
+ if len(naddrs) == 0 {
+ return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()}
+ }
+ return naddrs, nil
+}
+
+// MultipathTCP reports whether MPTCP will be used.
+//
+// This method doesn't check if MPTCP is supported by the operating
+// system or not.
+func (d *Dialer) MultipathTCP() bool {
+ return d.mptcpStatus.get()
+}
+
+// SetMultipathTCP directs the [Dial] methods to use, or not use, MPTCP,
+// if supported by the operating system. This method overrides the
+// system default and the GODEBUG=multipathtcp=... setting if any.
+//
+// If MPTCP is not available on the host or not supported by the server,
+// the Dial methods will fall back to TCP.
+func (d *Dialer) SetMultipathTCP(use bool) {
+ d.mptcpStatus.set(use)
+}
+
+// Dial connects to the address on the named network.
+//
+// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
+// "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
+// (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
+// "unixpacket".
+//
+// For TCP and UDP networks, the address has the form "host:port".
+// The host must be a literal IP address, or a host name that can be
+// resolved to IP addresses.
+// The port must be a literal port number or a service name.
+// If the host is a literal IPv6 address it must be enclosed in square
+// brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
+// The zone specifies the scope of the literal IPv6 address as defined
+// in RFC 4007.
+// The functions [JoinHostPort] and [SplitHostPort] manipulate a pair of
+// host and port in this form.
+// When using TCP, and the host resolves to multiple IP addresses,
+// Dial will try each IP address in order until one succeeds.
+//
+// Examples:
+//
+// Dial("tcp", "golang.org:http")
+// Dial("tcp", "192.0.2.1:http")
+// Dial("tcp", "198.51.100.1:80")
+// Dial("udp", "[2001:db8::1]:domain")
+// Dial("udp", "[fe80::1%lo0]:53")
+// Dial("tcp", ":80")
+//
+// For IP networks, the network must be "ip", "ip4" or "ip6" followed
+// by a colon and a literal protocol number or a protocol name, and
+// the address has the form "host". The host must be a literal IP
+// address or a literal IPv6 address with zone.
+// It depends on each operating system how the operating system
+// behaves with a non-well known protocol number such as "0" or "255".
+//
+// Examples:
+//
+// Dial("ip4:1", "192.0.2.1")
+// Dial("ip6:ipv6-icmp", "2001:db8::1")
+// Dial("ip6:58", "fe80::1%lo0")
+//
+// For TCP, UDP and IP networks, if the host is empty or a literal
+// unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
+// TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
+// assumed.
+//
+// For Unix networks, the address must be a file system path.
+func Dial(network, address string) (Conn, error) {
+ var d Dialer
+ return d.Dial(network, address)
+}
+
+// DialTimeout acts like [Dial] but takes a timeout.
+//
+// The timeout includes name resolution, if required.
+// When using TCP, and the host in the address parameter resolves to
+// multiple IP addresses, the timeout is spread over each consecutive
+// dial, such that each is given an appropriate fraction of the time
+// to connect.
+//
+// See func Dial for a description of the network and address
+// parameters.
+func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
+ d := Dialer{Timeout: timeout}
+ return d.Dial(network, address)
+}
+
+// sysDialer contains a Dial's parameters and configuration.
+type sysDialer struct {
+ Dialer
+ network, address string
+ testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error)
+}
+
+// Dial connects to the address on the named network.
+//
+// See func Dial for a description of the network and address
+// parameters.
+//
+// Dial uses [context.Background] internally; to specify the context, use
+// [Dialer.DialContext].
+func (d *Dialer) Dial(network, address string) (Conn, error) {
+ return d.DialContext(context.Background(), network, address)
+}
+
+// DialContext connects to the address on the named network using
+// the provided context.
+//
+// The provided Context must be non-nil. If the context expires before
+// the connection is complete, an error is returned. Once successfully
+// connected, any expiration of the context will not affect the
+// connection.
+//
+// When using TCP, and the host in the address parameter resolves to multiple
+// network addresses, any dial timeout (from d.Timeout or ctx) is spread
+// over each consecutive dial, such that each is given an appropriate
+// fraction of the time to connect.
+// For example, if a host has 4 IP addresses and the timeout is 1 minute,
+// the connect to each single address will be given 15 seconds to complete
+// before trying the next one.
+//
+// See func [Dial] for a description of the network and address
+// parameters.
+func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) {
+ if ctx == nil {
+ panic("nil context")
+ }
+ deadline := d.deadline(ctx, time.Now())
+ if !deadline.IsZero() {
+ testHookStepTime()
+ if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
+ subCtx, cancel := context.WithDeadline(ctx, deadline)
+ defer cancel()
+ ctx = subCtx
+ }
+ }
+ if oldCancel := d.Cancel; oldCancel != nil {
+ subCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ go func() {
+ select {
+ case <-oldCancel:
+ cancel()
+ case <-subCtx.Done():
+ }
+ }()
+ ctx = subCtx
+ }
+
+ // Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups.
+ resolveCtx := ctx
+ if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil {
+ shadow := *trace
+ shadow.ConnectStart = nil
+ shadow.ConnectDone = nil
+ resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow)
+ }
+
+ addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr)
+ if err != nil {
+ return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
+ }
+
+ sd := &sysDialer{
+ Dialer: *d,
+ network: network,
+ address: address,
+ }
+
+ var primaries, fallbacks addrList
+ if d.dualStack() && network == "tcp" {
+ primaries, fallbacks = addrs.partition(isIPv4)
+ } else {
+ primaries = addrs
+ }
+
+ return sd.dialParallel(ctx, primaries, fallbacks)
+}
+
+// dialParallel races two copies of dialSerial, giving the first a
+// head start. It returns the first established connection and
+// closes the others. Otherwise it returns an error from the first
+// primary address.
+func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) {
+ if len(fallbacks) == 0 {
+ return sd.dialSerial(ctx, primaries)
+ }
+
+ returned := make(chan struct{})
+ defer close(returned)
+
+ type dialResult struct {
+ Conn
+ error
+ primary bool
+ done bool
+ }
+ results := make(chan dialResult) // unbuffered
+
+ startRacer := func(ctx context.Context, primary bool) {
+ ras := primaries
+ if !primary {
+ ras = fallbacks
+ }
+ c, err := sd.dialSerial(ctx, ras)
+ select {
+ case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
+ case <-returned:
+ if c != nil {
+ c.Close()
+ }
+ }
+ }
+
+ var primary, fallback dialResult
+
+ // Start the main racer.
+ primaryCtx, primaryCancel := context.WithCancel(ctx)
+ defer primaryCancel()
+ go startRacer(primaryCtx, true)
+
+ // Start the timer for the fallback racer.
+ fallbackTimer := time.NewTimer(sd.fallbackDelay())
+ defer fallbackTimer.Stop()
+
+ for {
+ select {
+ case <-fallbackTimer.C:
+ fallbackCtx, fallbackCancel := context.WithCancel(ctx)
+ defer fallbackCancel()
+ go startRacer(fallbackCtx, false)
+
+ case res := <-results:
+ if res.error == nil {
+ return res.Conn, nil
+ }
+ if res.primary {
+ primary = res
+ } else {
+ fallback = res
+ }
+ if primary.done && fallback.done {
+ return nil, primary.error
+ }
+ if res.primary && fallbackTimer.Stop() {
+ // If we were able to stop the timer, that means it
+ // was running (hadn't yet started the fallback), but
+ // we just got an error on the primary path, so start
+ // the fallback immediately (in 0 nanoseconds).
+ fallbackTimer.Reset(0)
+ }
+ }
+ }
+}
+
+// dialSerial connects to a list of addresses in sequence, returning
+// either the first successful connection, or the first error.
+func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) {
+ var firstErr error // The error from the first address is most relevant.
+
+ for i, ra := range ras {
+ select {
+ case <-ctx.Done():
+ return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())}
+ default:
+ }
+
+ dialCtx := ctx
+ if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
+ partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
+ if err != nil {
+ // Ran out of time.
+ if firstErr == nil {
+ firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err}
+ }
+ break
+ }
+ if partialDeadline.Before(deadline) {
+ var cancel context.CancelFunc
+ dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
+ defer cancel()
+ }
+ }
+
+ c, err := sd.dialSingle(dialCtx, ra)
+ if err == nil {
+ return c, nil
+ }
+ if firstErr == nil {
+ firstErr = err
+ }
+ }
+
+ if firstErr == nil {
+ firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress}
+ }
+ return nil, firstErr
+}
+
+// dialSingle attempts to establish and returns a single connection to
+// the destination address.
+func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) {
+ trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
+ if trace != nil {
+ raStr := ra.String()
+ if trace.ConnectStart != nil {
+ trace.ConnectStart(sd.network, raStr)
+ }
+ if trace.ConnectDone != nil {
+ defer func() { trace.ConnectDone(sd.network, raStr, err) }()
+ }
+ }
+ la := sd.LocalAddr
+ switch ra := ra.(type) {
+ case *TCPAddr:
+ la, _ := la.(*TCPAddr)
+ if sd.MultipathTCP() {
+ c, err = sd.dialMPTCP(ctx, la, ra)
+ } else {
+ c, err = sd.dialTCP(ctx, la, ra)
+ }
+ case *UDPAddr:
+ la, _ := la.(*UDPAddr)
+ c, err = sd.dialUDP(ctx, la, ra)
+ case *IPAddr:
+ la, _ := la.(*IPAddr)
+ c, err = sd.dialIP(ctx, la, ra)
+ case *UnixAddr:
+ la, _ := la.(*UnixAddr)
+ c, err = sd.dialUnix(ctx, la, ra)
+ default:
+ return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}}
+ }
+ if err != nil {
+ return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer
+ }
+ return c, nil
+}
+
+// ListenConfig contains options for listening to an address.
+type ListenConfig struct {
+ // If Control is not nil, it is called after creating the network
+ // connection but before binding it to the operating system.
+ //
+ // Network and address parameters passed to Control method are not
+ // necessarily the ones passed to Listen. For example, passing "tcp" to
+ // Listen will cause the Control function to be called with "tcp4" or "tcp6".
+ Control func(network, address string, c syscall.RawConn) error
+
+ // KeepAlive specifies the keep-alive period for network
+ // connections accepted by this listener.
+ // If zero, keep-alives are enabled if supported by the protocol
+ // and operating system. Network protocols or operating systems
+ // that do not support keep-alives ignore this field.
+ // If negative, keep-alives are disabled.
+ KeepAlive time.Duration
+
+ // If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
+ // used, any call to Listen with "tcp(4|6)" as network will use MPTCP if
+ // supported by the operating system.
+ mptcpStatus mptcpStatus
+}
+
+// MultipathTCP reports whether MPTCP will be used.
+//
+// This method doesn't check if MPTCP is supported by the operating
+// system or not.
+func (lc *ListenConfig) MultipathTCP() bool {
+ return lc.mptcpStatus.get()
+}
+
+// SetMultipathTCP directs the [Listen] method to use, or not use, MPTCP,
+// if supported by the operating system. This method overrides the
+// system default and the GODEBUG=multipathtcp=... setting if any.
+//
+// If MPTCP is not available on the host or not supported by the client,
+// the Listen method will fall back to TCP.
+func (lc *ListenConfig) SetMultipathTCP(use bool) {
+ lc.mptcpStatus.set(use)
+}
+
+// Listen announces on the local network address.
+//
+// See func Listen for a description of the network and address
+// parameters.
+func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) {
+ addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
+ if err != nil {
+ return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
+ }
+ sl := &sysListener{
+ ListenConfig: *lc,
+ network: network,
+ address: address,
+ }
+ var l Listener
+ la := addrs.first(isIPv4)
+ switch la := la.(type) {
+ case *TCPAddr:
+ if sl.MultipathTCP() {
+ l, err = sl.listenMPTCP(ctx, la)
+ } else {
+ l, err = sl.listenTCP(ctx, la)
+ }
+ case *UnixAddr:
+ l, err = sl.listenUnix(ctx, la)
+ default:
+ return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
+ }
+ if err != nil {
+ return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer
+ }
+ return l, nil
+}
+
+// ListenPacket announces on the local network address.
+//
+// See func ListenPacket for a description of the network and address
+// parameters.
+func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
+ addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
+ if err != nil {
+ return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
+ }
+ sl := &sysListener{
+ ListenConfig: *lc,
+ network: network,
+ address: address,
+ }
+ var c PacketConn
+ la := addrs.first(isIPv4)
+ switch la := la.(type) {
+ case *UDPAddr:
+ c, err = sl.listenUDP(ctx, la)
+ case *IPAddr:
+ c, err = sl.listenIP(ctx, la)
+ case *UnixAddr:
+ c, err = sl.listenUnixgram(ctx, la)
+ default:
+ return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
+ }
+ if err != nil {
+ return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer
+ }
+ return c, nil
+}
+
+// sysListener contains a Listen's parameters and configuration.
+type sysListener struct {
+ ListenConfig
+ network, address string
+}
+
+// Listen announces on the local network address.
+//
+// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
+//
+// For TCP networks, if the host in the address parameter is empty or
+// a literal unspecified IP address, Listen listens on all available
+// unicast and anycast IP addresses of the local system.
+// To only use IPv4, use network "tcp4".
+// The address can use a host name, but this is not recommended,
+// because it will create a listener for at most one of the host's IP
+// addresses.
+// If the port in the address parameter is empty or "0", as in
+// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
+// The [Addr] method of [Listener] can be used to discover the chosen
+// port.
+//
+// See func [Dial] for a description of the network and address
+// parameters.
+//
+// Listen uses context.Background internally; to specify the context, use
+// [ListenConfig.Listen].
+func Listen(network, address string) (Listener, error) {
+ var lc ListenConfig
+ return lc.Listen(context.Background(), network, address)
+}
+
+// ListenPacket announces on the local network address.
+//
+// The network must be "udp", "udp4", "udp6", "unixgram", or an IP
+// transport. The IP transports are "ip", "ip4", or "ip6" followed by
+// a colon and a literal protocol number or a protocol name, as in
+// "ip:1" or "ip:icmp".
+//
+// For UDP and IP networks, if the host in the address parameter is
+// empty or a literal unspecified IP address, ListenPacket listens on
+// all available IP addresses of the local system except multicast IP
+// addresses.
+// To only use IPv4, use network "udp4" or "ip4:proto".
+// The address can use a host name, but this is not recommended,
+// because it will create a listener for at most one of the host's IP
+// addresses.
+// If the port in the address parameter is empty or "0", as in
+// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
+// The LocalAddr method of [PacketConn] can be used to discover the
+// chosen port.
+//
+// See func [Dial] for a description of the network and address
+// parameters.
+//
+// ListenPacket uses context.Background internally; to specify the context, use
+// [ListenConfig.ListenPacket].
+func ListenPacket(network, address string) (PacketConn, error) {
+ var lc ListenConfig
+ return lc.ListenPacket(context.Background(), network, address)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dial_test.go b/platform/dbops/binaries/go/go/src/net/dial_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..1d0832e46ee56819fb32ba9b0ef541b95847254c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dial_test.go
@@ -0,0 +1,1101 @@
+// 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 net
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "internal/testenv"
+ "io"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+)
+
+var prohibitionaryDialArgTests = []struct {
+ network string
+ address string
+}{
+ {"tcp6", "127.0.0.1"},
+ {"tcp6", "::ffff:127.0.0.1"},
+}
+
+func TestProhibitionaryDialArg(t *testing.T) {
+ testenv.MustHaveExternalNetwork(t)
+
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+ if !supportsIPv4map() {
+ t.Skip("mapping ipv4 address inside ipv6 address not supported")
+ }
+
+ ln, err := Listen("tcp", "[::]:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+
+ _, port, err := SplitHostPort(ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for i, tt := range prohibitionaryDialArgTests {
+ c, err := Dial(tt.network, JoinHostPort(tt.address, port))
+ if err == nil {
+ c.Close()
+ t.Errorf("#%d: %v", i, err)
+ }
+ }
+}
+
+func TestDialLocal(t *testing.T) {
+ ln := newLocalListener(t, "tcp")
+ defer ln.Close()
+ _, port, err := SplitHostPort(ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := Dial("tcp", JoinHostPort("", port))
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Close()
+}
+
+func TestDialerDualStackFDLeak(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
+ case "windows":
+ t.Skipf("not implemented a way to cancel dial racers in TCP SYN-SENT state on %s", runtime.GOOS)
+ case "openbsd":
+ testenv.SkipFlaky(t, 15157)
+ }
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ before := sw.Sockets()
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = lookupLocalhost
+ handler := func(dss *dualStackServer, ln Listener) {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }
+ dss, err := newDualStackServer()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := dss.buildup(handler); err != nil {
+ dss.teardown()
+ t.Fatal(err)
+ }
+
+ const N = 10
+ var wg sync.WaitGroup
+ wg.Add(N)
+ d := &Dialer{DualStack: true, Timeout: 5 * time.Second}
+ for i := 0; i < N; i++ {
+ go func() {
+ defer wg.Done()
+ c, err := d.Dial("tcp", JoinHostPort("localhost", dss.port))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ c.Close()
+ }()
+ }
+ wg.Wait()
+ dss.teardown()
+ after := sw.Sockets()
+ if len(after) != len(before) {
+ t.Errorf("got %d; want %d", len(after), len(before))
+ }
+}
+
+// Define a pair of blackholed (IPv4, IPv6) addresses, for which dialTCP is
+// expected to hang until the timeout elapses. These addresses are reserved
+// for benchmarking by RFC 6890.
+const (
+ slowDst4 = "198.18.0.254"
+ slowDst6 = "2001:2::254"
+)
+
+// In some environments, the slow IPs may be explicitly unreachable, and fail
+// more quickly than expected. This test hook prevents dialTCP from returning
+// before the deadline.
+func slowDialTCP(ctx context.Context, network string, laddr, raddr *TCPAddr) (*TCPConn, error) {
+ sd := &sysDialer{network: network, address: raddr.String()}
+ c, err := sd.doDialTCP(ctx, laddr, raddr)
+ if ParseIP(slowDst4).Equal(raddr.IP) || ParseIP(slowDst6).Equal(raddr.IP) {
+ // Wait for the deadline, or indefinitely if none exists.
+ <-ctx.Done()
+ }
+ return c, err
+}
+
+func dialClosedPort(t *testing.T) (dialLatency time.Duration) {
+ // On most platforms, dialing a closed port should be nearly instantaneous —
+ // less than a few hundred milliseconds. However, on some platforms it may be
+ // much slower: on Windows and OpenBSD, it has been observed to take up to a
+ // few seconds.
+
+ l, err := Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("dialClosedPort: Listen failed: %v", err)
+ }
+ addr := l.Addr().String()
+ l.Close()
+
+ startTime := time.Now()
+ c, err := Dial("tcp", addr)
+ if err == nil {
+ c.Close()
+ }
+ elapsed := time.Since(startTime)
+ t.Logf("dialClosedPort: measured delay %v", elapsed)
+ return elapsed
+}
+
+func TestDialParallel(t *testing.T) {
+ const instant time.Duration = 0
+ const fallbackDelay = 200 * time.Millisecond
+
+ nCopies := func(s string, n int) []string {
+ out := make([]string, n)
+ for i := 0; i < n; i++ {
+ out[i] = s
+ }
+ return out
+ }
+
+ var testCases = []struct {
+ primaries []string
+ fallbacks []string
+ teardownNetwork string
+ expectOk bool
+ expectElapsed time.Duration
+ }{
+ // These should just work on the first try.
+ {[]string{"127.0.0.1"}, []string{}, "", true, instant},
+ {[]string{"::1"}, []string{}, "", true, instant},
+ {[]string{"127.0.0.1", "::1"}, []string{slowDst6}, "tcp6", true, instant},
+ {[]string{"::1", "127.0.0.1"}, []string{slowDst4}, "tcp4", true, instant},
+ // Primary is slow; fallback should kick in.
+ {[]string{slowDst4}, []string{"::1"}, "", true, fallbackDelay},
+ // Skip a "connection refused" in the primary thread.
+ {[]string{"127.0.0.1", "::1"}, []string{}, "tcp4", true, instant},
+ {[]string{"::1", "127.0.0.1"}, []string{}, "tcp6", true, instant},
+ // Skip a "connection refused" in the fallback thread.
+ {[]string{slowDst4, slowDst6}, []string{"::1", "127.0.0.1"}, "tcp6", true, fallbackDelay},
+ // Primary refused, fallback without delay.
+ {[]string{"127.0.0.1"}, []string{"::1"}, "tcp4", true, instant},
+ {[]string{"::1"}, []string{"127.0.0.1"}, "tcp6", true, instant},
+ // Everything is refused.
+ {[]string{"127.0.0.1"}, []string{}, "tcp4", false, instant},
+ // Nothing to do; fail instantly.
+ {[]string{}, []string{}, "", false, instant},
+ // Connecting to tons of addresses should not trip the deadline.
+ {nCopies("::1", 1000), []string{}, "", true, instant},
+ }
+
+ // Convert a list of IP strings into TCPAddrs.
+ makeAddrs := func(ips []string, port string) addrList {
+ var out addrList
+ for _, ip := range ips {
+ addr, err := ResolveTCPAddr("tcp", JoinHostPort(ip, port))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, addr)
+ }
+ return out
+ }
+
+ for i, tt := range testCases {
+ i, tt := i, tt
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ dialTCP := func(ctx context.Context, network string, laddr, raddr *TCPAddr) (*TCPConn, error) {
+ n := "tcp6"
+ if raddr.IP.To4() != nil {
+ n = "tcp4"
+ }
+ if n == tt.teardownNetwork {
+ return nil, errors.New("unreachable")
+ }
+ if r := raddr.IP.String(); r == slowDst4 || r == slowDst6 {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ return &TCPConn{}, nil
+ }
+
+ primaries := makeAddrs(tt.primaries, "80")
+ fallbacks := makeAddrs(tt.fallbacks, "80")
+ d := Dialer{
+ FallbackDelay: fallbackDelay,
+ }
+ const forever = 60 * time.Minute
+ if tt.expectElapsed == instant {
+ d.FallbackDelay = forever
+ }
+ startTime := time.Now()
+ sd := &sysDialer{
+ Dialer: d,
+ network: "tcp",
+ address: "?",
+ testHookDialTCP: dialTCP,
+ }
+ c, err := sd.dialParallel(context.Background(), primaries, fallbacks)
+ elapsed := time.Since(startTime)
+
+ if c != nil {
+ c.Close()
+ }
+
+ if tt.expectOk && err != nil {
+ t.Errorf("#%d: got %v; want nil", i, err)
+ } else if !tt.expectOk && err == nil {
+ t.Errorf("#%d: got nil; want non-nil", i)
+ }
+
+ if elapsed < tt.expectElapsed || elapsed >= forever {
+ t.Errorf("#%d: got %v; want >= %v, < forever", i, elapsed, tt.expectElapsed)
+ }
+
+ // Repeat each case, ensuring that it can be canceled.
+ ctx, cancel := context.WithCancel(context.Background())
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ time.Sleep(5 * time.Millisecond)
+ cancel()
+ wg.Done()
+ }()
+ // Ignore errors, since all we care about is that the
+ // call can be canceled.
+ c, _ = sd.dialParallel(ctx, primaries, fallbacks)
+ if c != nil {
+ c.Close()
+ }
+ wg.Wait()
+ })
+ }
+}
+
+func lookupSlowFast(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
+ switch host {
+ case "slow6loopback4":
+ // Returns a slow IPv6 address, and a local IPv4 address.
+ return []IPAddr{
+ {IP: ParseIP(slowDst6)},
+ {IP: ParseIP("127.0.0.1")},
+ }, nil
+ default:
+ return fn(ctx, network, host)
+ }
+}
+
+func TestDialerFallbackDelay(t *testing.T) {
+ testenv.MustHaveExternalNetwork(t)
+
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = lookupSlowFast
+
+ origTestHookDialTCP := testHookDialTCP
+ defer func() { testHookDialTCP = origTestHookDialTCP }()
+ testHookDialTCP = slowDialTCP
+
+ var testCases = []struct {
+ dualstack bool
+ delay time.Duration
+ expectElapsed time.Duration
+ }{
+ // Use a very brief delay, which should fallback immediately.
+ {true, 1 * time.Nanosecond, 0},
+ // Use a 200ms explicit timeout.
+ {true, 200 * time.Millisecond, 200 * time.Millisecond},
+ // The default is 300ms.
+ {true, 0, 300 * time.Millisecond},
+ }
+
+ handler := func(dss *dualStackServer, ln Listener) {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }
+ dss, err := newDualStackServer()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dss.teardown()
+ if err := dss.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+
+ for i, tt := range testCases {
+ d := &Dialer{DualStack: tt.dualstack, FallbackDelay: tt.delay}
+
+ startTime := time.Now()
+ c, err := d.Dial("tcp", JoinHostPort("slow6loopback4", dss.port))
+ elapsed := time.Since(startTime)
+ if err == nil {
+ c.Close()
+ } else if tt.dualstack {
+ t.Error(err)
+ }
+ expectMin := tt.expectElapsed - 1*time.Millisecond
+ expectMax := tt.expectElapsed + 95*time.Millisecond
+ if elapsed < expectMin {
+ t.Errorf("#%d: got %v; want >= %v", i, elapsed, expectMin)
+ }
+ if elapsed > expectMax {
+ t.Errorf("#%d: got %v; want <= %v", i, elapsed, expectMax)
+ }
+ }
+}
+
+func TestDialParallelSpuriousConnection(t *testing.T) {
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ var readDeadline time.Time
+ if td, ok := t.Deadline(); ok {
+ const arbitraryCleanupMargin = 1 * time.Second
+ readDeadline = td.Add(-arbitraryCleanupMargin)
+ } else {
+ readDeadline = time.Now().Add(5 * time.Second)
+ }
+
+ var closed sync.WaitGroup
+ closed.Add(2)
+ handler := func(dss *dualStackServer, ln Listener) {
+ // Accept one connection per address.
+ c, err := ln.Accept()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Workaround for https://go.dev/issue/37795.
+ // On arm64 macOS (current as of macOS 12.4),
+ // reading from a socket at the same time as the client
+ // is closing it occasionally hangs for 60 seconds before
+ // returning ECONNRESET. Sleep for a bit to give the
+ // socket time to close before trying to read from it.
+ if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ // The client should close itself, without sending data.
+ c.SetReadDeadline(readDeadline)
+ var b [1]byte
+ if _, err := c.Read(b[:]); err != io.EOF {
+ t.Errorf("got %v; want %v", err, io.EOF)
+ }
+ c.Close()
+ closed.Done()
+ }
+ dss, err := newDualStackServer()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dss.teardown()
+ if err := dss.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+
+ const fallbackDelay = 100 * time.Millisecond
+
+ var dialing sync.WaitGroup
+ dialing.Add(2)
+ origTestHookDialTCP := testHookDialTCP
+ defer func() { testHookDialTCP = origTestHookDialTCP }()
+ testHookDialTCP = func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
+ // Wait until Happy Eyeballs kicks in and both connections are dialing,
+ // and inhibit cancellation.
+ // This forces dialParallel to juggle two successful connections.
+ dialing.Done()
+ dialing.Wait()
+
+ // Now ignore the provided context (which will be canceled) and use a
+ // different one to make sure this completes with a valid connection,
+ // which we hope to be closed below:
+ sd := &sysDialer{network: net, address: raddr.String()}
+ return sd.doDialTCP(context.Background(), laddr, raddr)
+ }
+
+ d := Dialer{
+ FallbackDelay: fallbackDelay,
+ }
+ sd := &sysDialer{
+ Dialer: d,
+ network: "tcp",
+ address: "?",
+ }
+
+ makeAddr := func(ip string) addrList {
+ addr, err := ResolveTCPAddr("tcp", JoinHostPort(ip, dss.port))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return addrList{addr}
+ }
+
+ // dialParallel returns one connection (and closes the other.)
+ c, err := sd.dialParallel(context.Background(), makeAddr("127.0.0.1"), makeAddr("::1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Close()
+
+ // The server should've seen both connections.
+ closed.Wait()
+}
+
+func TestDialerPartialDeadline(t *testing.T) {
+ now := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)
+ var testCases = []struct {
+ now time.Time
+ deadline time.Time
+ addrs int
+ expectDeadline time.Time
+ expectErr error
+ }{
+ // Regular division.
+ {now, now.Add(12 * time.Second), 1, now.Add(12 * time.Second), nil},
+ {now, now.Add(12 * time.Second), 2, now.Add(6 * time.Second), nil},
+ {now, now.Add(12 * time.Second), 3, now.Add(4 * time.Second), nil},
+ // Bump against the 2-second sane minimum.
+ {now, now.Add(12 * time.Second), 999, now.Add(2 * time.Second), nil},
+ // Total available is now below the sane minimum.
+ {now, now.Add(1900 * time.Millisecond), 999, now.Add(1900 * time.Millisecond), nil},
+ // Null deadline.
+ {now, noDeadline, 1, noDeadline, nil},
+ // Step the clock forward and cross the deadline.
+ {now.Add(-1 * time.Millisecond), now, 1, now, nil},
+ {now.Add(0 * time.Millisecond), now, 1, noDeadline, errTimeout},
+ {now.Add(1 * time.Millisecond), now, 1, noDeadline, errTimeout},
+ }
+ for i, tt := range testCases {
+ deadline, err := partialDeadline(tt.now, tt.deadline, tt.addrs)
+ if err != tt.expectErr {
+ t.Errorf("#%d: got %v; want %v", i, err, tt.expectErr)
+ }
+ if !deadline.Equal(tt.expectDeadline) {
+ t.Errorf("#%d: got %v; want %v", i, deadline, tt.expectDeadline)
+ }
+ }
+}
+
+// isEADDRINUSE reports whether err is syscall.EADDRINUSE.
+var isEADDRINUSE = func(err error) bool { return false }
+
+func TestDialerLocalAddr(t *testing.T) {
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ type test struct {
+ network, raddr string
+ laddr Addr
+ error
+ }
+ var tests = []test{
+ {"tcp4", "127.0.0.1", nil, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{}, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, &AddrError{Err: "some error"}},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, nil},
+ {"tcp4", "127.0.0.1", &TCPAddr{IP: IPv6loopback}, errNoSuitableAddress},
+ {"tcp4", "127.0.0.1", &UDPAddr{}, &AddrError{Err: "some error"}},
+ {"tcp4", "127.0.0.1", &UnixAddr{}, &AddrError{Err: "some error"}},
+
+ {"tcp6", "::1", nil, nil},
+ {"tcp6", "::1", &TCPAddr{}, nil},
+ {"tcp6", "::1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil},
+ {"tcp6", "::1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil},
+ {"tcp6", "::1", &TCPAddr{IP: ParseIP("::")}, nil},
+ {"tcp6", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, errNoSuitableAddress},
+ {"tcp6", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, errNoSuitableAddress},
+ {"tcp6", "::1", &TCPAddr{IP: IPv6loopback}, nil},
+ {"tcp6", "::1", &UDPAddr{}, &AddrError{Err: "some error"}},
+ {"tcp6", "::1", &UnixAddr{}, &AddrError{Err: "some error"}},
+
+ {"tcp", "127.0.0.1", nil, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{}, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, nil},
+ {"tcp", "127.0.0.1", &TCPAddr{IP: IPv6loopback}, errNoSuitableAddress},
+ {"tcp", "127.0.0.1", &UDPAddr{}, &AddrError{Err: "some error"}},
+ {"tcp", "127.0.0.1", &UnixAddr{}, &AddrError{Err: "some error"}},
+
+ {"tcp", "::1", nil, nil},
+ {"tcp", "::1", &TCPAddr{}, nil},
+ {"tcp", "::1", &TCPAddr{IP: ParseIP("0.0.0.0")}, nil},
+ {"tcp", "::1", &TCPAddr{IP: ParseIP("0.0.0.0").To4()}, nil},
+ {"tcp", "::1", &TCPAddr{IP: ParseIP("::")}, nil},
+ {"tcp", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To4()}, errNoSuitableAddress},
+ {"tcp", "::1", &TCPAddr{IP: ParseIP("127.0.0.1").To16()}, errNoSuitableAddress},
+ {"tcp", "::1", &TCPAddr{IP: IPv6loopback}, nil},
+ {"tcp", "::1", &UDPAddr{}, &AddrError{Err: "some error"}},
+ {"tcp", "::1", &UnixAddr{}, &AddrError{Err: "some error"}},
+ }
+
+ issue34264Index := -1
+ if supportsIPv4map() {
+ issue34264Index = len(tests)
+ tests = append(tests, test{
+ "tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, nil,
+ })
+ } else {
+ tests = append(tests, test{
+ "tcp", "127.0.0.1", &TCPAddr{IP: ParseIP("::")}, &AddrError{Err: "some error"},
+ })
+ }
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = lookupLocalhost
+ handler := func(ls *localServer, ln Listener) {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }
+ var lss [2]*localServer
+ for i, network := range []string{"tcp4", "tcp6"} {
+ lss[i] = newLocalServer(t, network)
+ defer lss[i].teardown()
+ if err := lss[i].buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for i, tt := range tests {
+ d := &Dialer{LocalAddr: tt.laddr}
+ var addr string
+ ip := ParseIP(tt.raddr)
+ if ip.To4() != nil {
+ addr = lss[0].Listener.Addr().String()
+ }
+ if ip.To16() != nil && ip.To4() == nil {
+ addr = lss[1].Listener.Addr().String()
+ }
+ c, err := d.Dial(tt.network, addr)
+ if err == nil && tt.error != nil || err != nil && tt.error == nil {
+ if i == issue34264Index && runtime.GOOS == "freebsd" && isEADDRINUSE(err) {
+ // https://golang.org/issue/34264: FreeBSD through at least version 12.2
+ // has been observed to fail with EADDRINUSE when dialing from an IPv6
+ // local address to an IPv4 remote address.
+ t.Logf("%s %v->%s: got %v; want %v", tt.network, tt.laddr, tt.raddr, err, tt.error)
+ t.Logf("(spurious EADDRINUSE ignored on freebsd: see https://golang.org/issue/34264)")
+ } else {
+ t.Errorf("%s %v->%s: got %v; want %v", tt.network, tt.laddr, tt.raddr, err, tt.error)
+ }
+ }
+ if err != nil {
+ if perr := parseDialError(err); perr != nil {
+ t.Error(perr)
+ }
+ continue
+ }
+ c.Close()
+ }
+}
+
+func TestDialerDualStack(t *testing.T) {
+ testenv.SkipFlaky(t, 13324)
+
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ closedPortDelay := dialClosedPort(t)
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = lookupLocalhost
+ handler := func(dss *dualStackServer, ln Listener) {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }
+
+ var timeout = 150*time.Millisecond + closedPortDelay
+ for _, dualstack := range []bool{false, true} {
+ dss, err := newDualStackServer()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dss.teardown()
+ if err := dss.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+
+ d := &Dialer{DualStack: dualstack, Timeout: timeout}
+ for range dss.lns {
+ c, err := d.Dial("tcp", JoinHostPort("localhost", dss.port))
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ switch addr := c.LocalAddr().(*TCPAddr); {
+ case addr.IP.To4() != nil:
+ dss.teardownNetwork("tcp4")
+ case addr.IP.To16() != nil && addr.IP.To4() == nil:
+ dss.teardownNetwork("tcp6")
+ }
+ c.Close()
+ }
+ }
+}
+
+func TestDialerKeepAlive(t *testing.T) {
+ handler := func(ls *localServer, ln Listener) {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }
+ ls := newLocalServer(t, "tcp")
+ defer ls.teardown()
+ if err := ls.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { testHookSetKeepAlive = func(time.Duration) {} }()
+
+ tests := []struct {
+ ka time.Duration
+ expected time.Duration
+ }{
+ {-1, -1},
+ {0, 15 * time.Second},
+ {5 * time.Second, 5 * time.Second},
+ {30 * time.Second, 30 * time.Second},
+ }
+
+ for _, test := range tests {
+ var got time.Duration = -1
+ testHookSetKeepAlive = func(d time.Duration) { got = d }
+ d := Dialer{KeepAlive: test.ka}
+ c, err := d.Dial("tcp", ls.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Close()
+ if got != test.expected {
+ t.Errorf("Dialer.KeepAlive = %v: SetKeepAlive set to %v, want %v", d.KeepAlive, got, test.expected)
+ }
+ }
+}
+
+func TestDialCancel(t *testing.T) {
+ mustHaveExternalNetwork(t)
+
+ blackholeIPPort := JoinHostPort(slowDst4, "1234")
+ if !supportsIPv4() {
+ blackholeIPPort = JoinHostPort(slowDst6, "1234")
+ }
+
+ ticker := time.NewTicker(10 * time.Millisecond)
+ defer ticker.Stop()
+
+ const cancelTick = 5 // the timer tick we cancel the dial at
+ const timeoutTick = 100
+
+ var d Dialer
+ cancel := make(chan struct{})
+ d.Cancel = cancel
+ errc := make(chan error, 1)
+ connc := make(chan Conn, 1)
+ go func() {
+ if c, err := d.Dial("tcp", blackholeIPPort); err != nil {
+ errc <- err
+ } else {
+ connc <- c
+ }
+ }()
+ ticks := 0
+ for {
+ select {
+ case <-ticker.C:
+ ticks++
+ if ticks == cancelTick {
+ close(cancel)
+ }
+ if ticks == timeoutTick {
+ t.Fatal("timeout waiting for dial to fail")
+ }
+ case c := <-connc:
+ c.Close()
+ t.Fatal("unexpected successful connection")
+ case err := <-errc:
+ if perr := parseDialError(err); perr != nil {
+ t.Error(perr)
+ }
+ if ticks < cancelTick {
+ // Using strings.Contains is ugly but
+ // may work on plan9 and windows.
+ ignorable := []string{
+ "connection refused",
+ "unreachable",
+ "no route to host",
+ "invalid argument",
+ }
+ e := err.Error()
+ for _, ignore := range ignorable {
+ if strings.Contains(e, ignore) {
+ t.Skipf("connection to %v failed fast with %v", blackholeIPPort, err)
+ }
+ }
+
+ t.Fatalf("dial error after %d ticks (%d before cancel sent): %v",
+ ticks, cancelTick-ticks, err)
+ }
+ if oe, ok := err.(*OpError); !ok || oe.Err != errCanceled {
+ t.Fatalf("dial error = %v (%T); want OpError with Err == errCanceled", err, err)
+ }
+ return // success.
+ }
+ }
+}
+
+func TestCancelAfterDial(t *testing.T) {
+ if testing.Short() {
+ t.Skip("avoiding time.Sleep")
+ }
+
+ ln := newLocalListener(t, "tcp")
+
+ var wg sync.WaitGroup
+ wg.Add(1)
+ defer func() {
+ ln.Close()
+ wg.Wait()
+ }()
+
+ // Echo back the first line of each incoming connection.
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ break
+ }
+ rb := bufio.NewReader(c)
+ line, err := rb.ReadString('\n')
+ if err != nil {
+ t.Error(err)
+ c.Close()
+ continue
+ }
+ if _, err := c.Write([]byte(line)); err != nil {
+ t.Error(err)
+ }
+ c.Close()
+ }
+ wg.Done()
+ }()
+
+ try := func() {
+ cancel := make(chan struct{})
+ d := &Dialer{Cancel: cancel}
+ c, err := d.Dial("tcp", ln.Addr().String())
+
+ // Immediately after dialing, request cancellation and sleep.
+ // Before Issue 15078 was fixed, this would cause subsequent operations
+ // to fail with an i/o timeout roughly 50% of the time.
+ close(cancel)
+ time.Sleep(10 * time.Millisecond)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+
+ // Send some data to confirm that the connection is still alive.
+ const message = "echo!\n"
+ if _, err := c.Write([]byte(message)); err != nil {
+ t.Fatal(err)
+ }
+
+ // The server should echo the line, and close the connection.
+ rb := bufio.NewReader(c)
+ line, err := rb.ReadString('\n')
+ if err != nil {
+ t.Fatal(err)
+ }
+ if line != message {
+ t.Errorf("got %q; want %q", line, message)
+ }
+ if _, err := rb.ReadByte(); err != io.EOF {
+ t.Errorf("got %v; want %v", err, io.EOF)
+ }
+ }
+
+ // This bug manifested about 50% of the time, so try it a few times.
+ for i := 0; i < 10; i++ {
+ try()
+ }
+}
+
+func TestDialClosedPortFailFast(t *testing.T) {
+ if runtime.GOOS != "windows" {
+ // Reported by go.dev/issues/23366.
+ t.Skip("skipping windows only test")
+ }
+ for _, network := range []string{"tcp", "tcp4", "tcp6"} {
+ t.Run(network, func(t *testing.T) {
+ if !testableNetwork(network) {
+ t.Skipf("skipping: can't listen on %s", network)
+ }
+ // Reserve a local port till the end of the
+ // test by opening a listener and connecting to
+ // it using Dial.
+ ln := newLocalListener(t, network)
+ addr := ln.Addr().String()
+ conn1, err := Dial(network, addr)
+ if err != nil {
+ ln.Close()
+ t.Fatal(err)
+ }
+ defer conn1.Close()
+ // Now close the listener so the next Dial fails
+ // keeping conn1 alive so the port is not made
+ // available.
+ ln.Close()
+
+ maxElapsed := time.Second
+ // The host can be heavy-loaded and take
+ // longer than configured. Retry until
+ // Dial takes less than maxElapsed or
+ // the test times out.
+ for {
+ startTime := time.Now()
+ conn2, err := Dial(network, addr)
+ if err == nil {
+ conn2.Close()
+ t.Fatal("error expected")
+ }
+ elapsed := time.Since(startTime)
+ if elapsed < maxElapsed {
+ break
+ }
+ t.Logf("got %v; want < %v", elapsed, maxElapsed)
+ }
+ })
+ }
+}
+
+// Issue 18806: it should always be possible to net.Dial a
+// net.Listener().Addr().String when the listen address was ":n", even
+// if the machine has halfway configured IPv6 such that it can bind on
+// "::" not connect back to that same address.
+func TestDialListenerAddr(t *testing.T) {
+ if !testableNetwork("tcp4") {
+ t.Skipf("skipping: can't listen on tcp4")
+ }
+
+ // The original issue report was for listening on just ":0" on a system that
+ // supports both tcp4 and tcp6 for external traffic but only tcp4 for loopback
+ // traffic. However, the port opened by ":0" is externally-accessible, and may
+ // trigger firewall alerts or otherwise be mistaken for malicious activity
+ // (see https://go.dev/issue/59497). Moreover, it often does not reproduce
+ // the scenario in the issue, in which the port *cannot* be dialed as tcp6.
+ //
+ // To address both of those problems, we open a tcp4-only localhost port, but
+ // then dial the address string that the listener would have reported for a
+ // dual-stack port.
+ ln, err := Listen("tcp4", "localhost:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+
+ t.Logf("listening on %q", ln.Addr())
+ _, port, err := SplitHostPort(ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // If we had opened a dual-stack port without an explicit "localhost" address,
+ // the Listener would arbitrarily report an empty tcp6 address in its Addr
+ // string.
+ //
+ // The documentation for Dial says ‘if the host is empty or a literal
+ // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for TCP and
+ // UDP, "", "0.0.0.0" or "::" for IP, the local system is assumed.’
+ // In #18806, it was decided that that should include the local tcp4 host
+ // even if the string is in the tcp6 format.
+ dialAddr := "[::]:" + port
+ c, err := Dial("tcp4", dialAddr)
+ if err != nil {
+ t.Fatalf(`Dial("tcp4", %q): %v`, dialAddr, err)
+ }
+ c.Close()
+ t.Logf(`Dial("tcp4", %q) succeeded`, dialAddr)
+}
+
+func TestDialerControl(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ case "js", "wasip1":
+ t.Skipf("skipping: fake net does not support Dialer.Control")
+ }
+
+ t.Run("StreamDial", func(t *testing.T) {
+ for _, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} {
+ if !testableNetwork(network) {
+ continue
+ }
+ ln := newLocalListener(t, network)
+ defer ln.Close()
+ d := Dialer{Control: controlOnConnSetup}
+ c, err := d.Dial(network, ln.Addr().String())
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ c.Close()
+ }
+ })
+ t.Run("PacketDial", func(t *testing.T) {
+ for _, network := range []string{"udp", "udp4", "udp6", "unixgram"} {
+ if !testableNetwork(network) {
+ continue
+ }
+ c1 := newLocalPacketListener(t, network)
+ if network == "unixgram" {
+ defer os.Remove(c1.LocalAddr().String())
+ }
+ defer c1.Close()
+ d := Dialer{Control: controlOnConnSetup}
+ c2, err := d.Dial(network, c1.LocalAddr().String())
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ c2.Close()
+ }
+ })
+}
+
+func TestDialerControlContext(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
+ case "js", "wasip1":
+ t.Skipf("skipping: fake net does not support Dialer.ControlContext")
+ }
+ t.Run("StreamDial", func(t *testing.T) {
+ for i, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} {
+ t.Run(network, func(t *testing.T) {
+ if !testableNetwork(network) {
+ t.Skipf("skipping: %s not available", network)
+ }
+
+ ln := newLocalListener(t, network)
+ defer ln.Close()
+ var id int
+ d := Dialer{ControlContext: func(ctx context.Context, network string, address string, c syscall.RawConn) error {
+ id = ctx.Value("id").(int)
+ return controlOnConnSetup(network, address, c)
+ }}
+ c, err := d.DialContext(context.WithValue(context.Background(), "id", i+1), network, ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if id != i+1 {
+ t.Errorf("got id %d, want %d", id, i+1)
+ }
+ c.Close()
+ })
+ }
+ })
+}
+
+// mustHaveExternalNetwork is like testenv.MustHaveExternalNetwork
+// except on non-Linux, non-mobile builders it permits the test to
+// run in -short mode.
+func mustHaveExternalNetwork(t *testing.T) {
+ t.Helper()
+ definitelyHasLongtestBuilder := runtime.GOOS == "linux"
+ mobile := runtime.GOOS == "android" || runtime.GOOS == "ios"
+ fake := runtime.GOOS == "js" || runtime.GOOS == "wasip1"
+ if testenv.Builder() != "" && !definitelyHasLongtestBuilder && !mobile && !fake {
+ // On a non-Linux, non-mobile builder (e.g., freebsd-amd64-13_0).
+ //
+ // Don't skip testing because otherwise the test may never run on
+ // any builder if this port doesn't also have a -longtest builder.
+ return
+ }
+ testenv.MustHaveExternalNetwork(t)
+}
+
+type contextWithNonZeroDeadline struct {
+ context.Context
+}
+
+func (contextWithNonZeroDeadline) Deadline() (time.Time, bool) {
+ // Return non-zero time.Time value with false indicating that no deadline is set.
+ return time.Unix(0, 0), false
+}
+
+func TestDialWithNonZeroDeadline(t *testing.T) {
+ ln := newLocalListener(t, "tcp")
+ defer ln.Close()
+ _, port, err := SplitHostPort(ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := contextWithNonZeroDeadline{Context: context.Background()}
+ var dialer Dialer
+ c, err := dialer.DialContext(ctx, "tcp", JoinHostPort("", port))
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Close()
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dial_unix_test.go b/platform/dbops/binaries/go/go/src/net/dial_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..d0df0b71eaeea5fb6b624897140c25f20bbc4884
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dial_unix_test.go
@@ -0,0 +1,113 @@
+// 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 unix
+
+package net
+
+import (
+ "context"
+ "errors"
+ "syscall"
+ "testing"
+ "time"
+)
+
+func init() {
+ isEADDRINUSE = func(err error) bool {
+ return errors.Is(err, syscall.EADDRINUSE)
+ }
+}
+
+// Issue 16523
+func TestDialContextCancelRace(t *testing.T) {
+ oldConnectFunc := connectFunc
+ oldGetsockoptIntFunc := getsockoptIntFunc
+ oldTestHookCanceledDial := testHookCanceledDial
+ defer func() {
+ connectFunc = oldConnectFunc
+ getsockoptIntFunc = oldGetsockoptIntFunc
+ testHookCanceledDial = oldTestHookCanceledDial
+ }()
+
+ ln := newLocalListener(t, "tcp")
+ listenerDone := make(chan struct{})
+ go func() {
+ defer close(listenerDone)
+ c, err := ln.Accept()
+ if err == nil {
+ c.Close()
+ }
+ }()
+ defer func() { <-listenerDone }()
+ defer ln.Close()
+
+ sawCancel := make(chan bool, 1)
+ testHookCanceledDial = func() {
+ sawCancel <- true
+ }
+
+ ctx, cancelCtx := context.WithCancel(context.Background())
+
+ connectFunc = func(fd int, addr syscall.Sockaddr) error {
+ err := oldConnectFunc(fd, addr)
+ t.Logf("connect(%d, addr) = %v", fd, err)
+ if err == nil {
+ // On some operating systems, localhost
+ // connects _sometimes_ succeed immediately.
+ // Prevent that, so we exercise the code path
+ // we're interested in testing. This seems
+ // harmless. It makes FreeBSD 10.10 work when
+ // run with many iterations. It failed about
+ // half the time previously.
+ return syscall.EINPROGRESS
+ }
+ return err
+ }
+
+ getsockoptIntFunc = func(fd, level, opt int) (val int, err error) {
+ val, err = oldGetsockoptIntFunc(fd, level, opt)
+ t.Logf("getsockoptIntFunc(%d, %d, %d) = (%v, %v)", fd, level, opt, val, err)
+ if level == syscall.SOL_SOCKET && opt == syscall.SO_ERROR && err == nil && val == 0 {
+ t.Logf("canceling context")
+
+ // Cancel the context at just the moment which
+ // caused the race in issue 16523.
+ cancelCtx()
+
+ // And wait for the "interrupter" goroutine to
+ // cancel the dial by messing with its write
+ // timeout before returning.
+ select {
+ case <-sawCancel:
+ t.Logf("saw cancel")
+ case <-time.After(5 * time.Second):
+ t.Errorf("didn't see cancel after 5 seconds")
+ }
+ }
+ return
+ }
+
+ var d Dialer
+ c, err := d.DialContext(ctx, "tcp", ln.Addr().String())
+ if err == nil {
+ c.Close()
+ t.Fatal("unexpected successful dial; want context canceled error")
+ }
+
+ select {
+ case <-ctx.Done():
+ case <-time.After(5 * time.Second):
+ t.Fatal("expected context to be canceled")
+ }
+
+ oe, ok := err.(*OpError)
+ if !ok || oe.Op != "dial" {
+ t.Fatalf("Dial error = %#v; want dial *OpError", err)
+ }
+
+ if oe.Err != errCanceled {
+ t.Errorf("DialContext = (%v, %v); want OpError with error %v", c, err, errCanceled)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsclient.go b/platform/dbops/binaries/go/go/src/net/dnsclient.go
new file mode 100644
index 0000000000000000000000000000000000000000..204620b2edb8d0480d9aea392dfdaa580eca2992
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsclient.go
@@ -0,0 +1,230 @@
+// 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 net
+
+import (
+ "internal/bytealg"
+ "internal/itoa"
+ "sort"
+ _ "unsafe" // for go:linkname
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// provided by runtime
+//go:linkname runtime_rand runtime.rand
+func runtime_rand() uint64
+
+func randInt() int {
+ return int(uint(runtime_rand()) >> 1) // clear sign bit
+}
+
+func randIntn(n int) int {
+ return randInt() % n
+}
+
+// reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
+// address addr suitable for rDNS (PTR) record lookup or an error if it fails
+// to parse the IP address.
+func reverseaddr(addr string) (arpa string, err error) {
+ ip := ParseIP(addr)
+ if ip == nil {
+ return "", &DNSError{Err: "unrecognized address", Name: addr}
+ }
+ if ip.To4() != nil {
+ return itoa.Uitoa(uint(ip[15])) + "." + itoa.Uitoa(uint(ip[14])) + "." + itoa.Uitoa(uint(ip[13])) + "." + itoa.Uitoa(uint(ip[12])) + ".in-addr.arpa.", nil
+ }
+ // Must be IPv6
+ buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
+ // Add it, in reverse, to the buffer
+ for i := len(ip) - 1; i >= 0; i-- {
+ v := ip[i]
+ buf = append(buf, hexDigit[v&0xF],
+ '.',
+ hexDigit[v>>4],
+ '.')
+ }
+ // Append "ip6.arpa." and return (buf already has the final .)
+ buf = append(buf, "ip6.arpa."...)
+ return string(buf), nil
+}
+
+func equalASCIIName(x, y dnsmessage.Name) bool {
+ if x.Length != y.Length {
+ return false
+ }
+ for i := 0; i < int(x.Length); i++ {
+ a := x.Data[i]
+ b := y.Data[i]
+ if 'A' <= a && a <= 'Z' {
+ a += 0x20
+ }
+ if 'A' <= b && b <= 'Z' {
+ b += 0x20
+ }
+ if a != b {
+ return false
+ }
+ }
+ return true
+}
+
+// isDomainName checks if a string is a presentation-format domain name
+// (currently restricted to hostname-compatible "preferred name" LDH labels and
+// SRV-like "underscore labels"; see golang.org/issue/12421).
+func isDomainName(s string) bool {
+ // The root domain name is valid. See golang.org/issue/45715.
+ if s == "." {
+ return true
+ }
+
+ // See RFC 1035, RFC 3696.
+ // Presentation format has dots before every label except the first, and the
+ // terminal empty label is optional here because we assume fully-qualified
+ // (absolute) input. We must therefore reserve space for the first and last
+ // labels' length octets in wire format, where they are necessary and the
+ // maximum total length is 255.
+ // So our _effective_ maximum is 253, but 254 is not rejected if the last
+ // character is a dot.
+ l := len(s)
+ if l == 0 || l > 254 || l == 254 && s[l-1] != '.' {
+ return false
+ }
+
+ last := byte('.')
+ nonNumeric := false // true once we've seen a letter or hyphen
+ 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' || c == '_':
+ nonNumeric = true
+ partlen++
+ case '0' <= c && c <= '9':
+ // fine
+ partlen++
+ case c == '-':
+ // Byte before dash cannot be dot.
+ if last == '.' {
+ return false
+ }
+ partlen++
+ nonNumeric = true
+ 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 nonNumeric
+}
+
+// absDomainName returns an absolute domain name which ends with a
+// trailing dot to match pure Go reverse resolver and all other lookup
+// routines.
+// See golang.org/issue/12189.
+// But we don't want to add dots for local names from /etc/hosts.
+// It's hard to tell so we settle on the heuristic that names without dots
+// (like "localhost" or "myhost") do not get trailing dots, but any other
+// names do.
+func absDomainName(s string) string {
+ if bytealg.IndexByteString(s, '.') != -1 && s[len(s)-1] != '.' {
+ s += "."
+ }
+ return s
+}
+
+// An SRV represents a single DNS SRV record.
+type SRV struct {
+ Target string
+ Port uint16
+ Priority uint16
+ Weight uint16
+}
+
+// byPriorityWeight sorts SRV records by ascending priority and weight.
+type byPriorityWeight []*SRV
+
+func (s byPriorityWeight) Len() int { return len(s) }
+func (s byPriorityWeight) Less(i, j int) bool {
+ return s[i].Priority < s[j].Priority || (s[i].Priority == s[j].Priority && s[i].Weight < s[j].Weight)
+}
+func (s byPriorityWeight) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// shuffleByWeight shuffles SRV records by weight using the algorithm
+// described in RFC 2782.
+func (addrs byPriorityWeight) shuffleByWeight() {
+ sum := 0
+ for _, addr := range addrs {
+ sum += int(addr.Weight)
+ }
+ for sum > 0 && len(addrs) > 1 {
+ s := 0
+ n := randIntn(sum)
+ for i := range addrs {
+ s += int(addrs[i].Weight)
+ if s > n {
+ if i > 0 {
+ addrs[0], addrs[i] = addrs[i], addrs[0]
+ }
+ break
+ }
+ }
+ sum -= int(addrs[0].Weight)
+ addrs = addrs[1:]
+ }
+}
+
+// sort reorders SRV records as specified in RFC 2782.
+func (addrs byPriorityWeight) sort() {
+ sort.Sort(addrs)
+ i := 0
+ for j := 1; j < len(addrs); j++ {
+ if addrs[i].Priority != addrs[j].Priority {
+ addrs[i:j].shuffleByWeight()
+ i = j
+ }
+ }
+ addrs[i:].shuffleByWeight()
+}
+
+// An MX represents a single DNS MX record.
+type MX struct {
+ Host string
+ Pref uint16
+}
+
+// byPref implements sort.Interface to sort MX records by preference
+type byPref []*MX
+
+func (s byPref) Len() int { return len(s) }
+func (s byPref) Less(i, j int) bool { return s[i].Pref < s[j].Pref }
+func (s byPref) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// sort reorders MX records as specified in RFC 5321.
+func (s byPref) sort() {
+ for i := range s {
+ j := randIntn(i + 1)
+ s[i], s[j] = s[j], s[i]
+ }
+ sort.Sort(s)
+}
+
+// An NS represents a single DNS NS record.
+type NS struct {
+ Host string
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsclient_test.go b/platform/dbops/binaries/go/go/src/net/dnsclient_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..24cd69e13be25d932760cdd4e195c46625dd004f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsclient_test.go
@@ -0,0 +1,66 @@
+// 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 net
+
+import (
+ "testing"
+)
+
+func checkDistribution(t *testing.T, data []*SRV, margin float64) {
+ sum := 0
+ for _, srv := range data {
+ sum += int(srv.Weight)
+ }
+
+ results := make(map[string]int)
+
+ count := 10000
+ for j := 0; j < count; j++ {
+ d := make([]*SRV, len(data))
+ copy(d, data)
+ byPriorityWeight(d).shuffleByWeight()
+ key := d[0].Target
+ results[key] = results[key] + 1
+ }
+
+ actual := results[data[0].Target]
+ expected := float64(count) * float64(data[0].Weight) / float64(sum)
+ diff := float64(actual) - expected
+ t.Logf("actual: %v diff: %v e: %v m: %v", actual, diff, expected, margin)
+ if diff < 0 {
+ diff = -diff
+ }
+ if diff > (expected * margin) {
+ t.Errorf("missed target weight: expected %v, %v", expected, actual)
+ }
+}
+
+func testUniformity(t *testing.T, size int, margin float64) {
+ data := make([]*SRV, size)
+ for i := 0; i < size; i++ {
+ data[i] = &SRV{Target: string('a' + rune(i)), Weight: 1}
+ }
+ checkDistribution(t, data, margin)
+}
+
+func TestDNSSRVUniformity(t *testing.T) {
+ testUniformity(t, 2, 0.05)
+ testUniformity(t, 3, 0.10)
+ testUniformity(t, 10, 0.20)
+ testWeighting(t, 0.05)
+}
+
+func testWeighting(t *testing.T, margin float64) {
+ data := []*SRV{
+ {Target: "a", Weight: 60},
+ {Target: "b", Weight: 30},
+ {Target: "c", Weight: 10},
+ }
+ checkDistribution(t, data, margin)
+}
+
+func TestWeighting(t *testing.T) {
+ testWeighting(t, 0.05)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsclient_unix.go b/platform/dbops/binaries/go/go/src/net/dnsclient_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..8821641a016287fea8cf903563bc8a80a63e955d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsclient_unix.go
@@ -0,0 +1,906 @@
+// 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.
+
+// DNS client: see RFC 1035.
+// Has to be linked into package net for Dial.
+
+// TODO(rsc):
+// Could potentially handle many outstanding lookups faster.
+// Random UDP source port (net.Dial should do that for us).
+// Random request IDs.
+
+package net
+
+import (
+ "context"
+ "errors"
+ "internal/bytealg"
+ "internal/godebug"
+ "internal/itoa"
+ "io"
+ "os"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+const (
+ // to be used as a useTCP parameter to exchange
+ useTCPOnly = true
+ useUDPOrTCP = false
+
+ // Maximum DNS packet size.
+ // Value taken from https://dnsflagday.net/2020/.
+ maxDNSPacketSize = 1232
+)
+
+var (
+ errLameReferral = errors.New("lame referral")
+ errCannotUnmarshalDNSMessage = errors.New("cannot unmarshal DNS message")
+ errCannotMarshalDNSMessage = errors.New("cannot marshal DNS message")
+ errServerMisbehaving = errors.New("server misbehaving")
+ errInvalidDNSResponse = errors.New("invalid DNS response")
+ errNoAnswerFromDNSServer = errors.New("no answer from DNS server")
+
+ // errServerTemporarilyMisbehaving is like errServerMisbehaving, except
+ // that when it gets translated to a DNSError, the IsTemporary field
+ // gets set to true.
+ errServerTemporarilyMisbehaving = errors.New("server misbehaving")
+)
+
+// netedns0 controls whether we send an EDNS0 additional header.
+var netedns0 = godebug.New("netedns0")
+
+func newRequest(q dnsmessage.Question, ad bool) (id uint16, udpReq, tcpReq []byte, err error) {
+ id = uint16(randInt())
+ b := dnsmessage.NewBuilder(make([]byte, 2, 514), dnsmessage.Header{ID: id, RecursionDesired: true, AuthenticData: ad})
+ if err := b.StartQuestions(); err != nil {
+ return 0, nil, nil, err
+ }
+ if err := b.Question(q); err != nil {
+ return 0, nil, nil, err
+ }
+
+ if netedns0.Value() == "0" {
+ netedns0.IncNonDefault()
+ } else {
+ // Accept packets up to maxDNSPacketSize. RFC 6891.
+ if err := b.StartAdditionals(); err != nil {
+ return 0, nil, nil, err
+ }
+ var rh dnsmessage.ResourceHeader
+ if err := rh.SetEDNS0(maxDNSPacketSize, dnsmessage.RCodeSuccess, false); err != nil {
+ return 0, nil, nil, err
+ }
+ if err := b.OPTResource(rh, dnsmessage.OPTResource{}); err != nil {
+ return 0, nil, nil, err
+ }
+ }
+
+ tcpReq, err = b.Finish()
+ if err != nil {
+ return 0, nil, nil, err
+ }
+ udpReq = tcpReq[2:]
+ l := len(tcpReq) - 2
+ tcpReq[0] = byte(l >> 8)
+ tcpReq[1] = byte(l)
+ return id, udpReq, tcpReq, nil
+}
+
+func checkResponse(reqID uint16, reqQues dnsmessage.Question, respHdr dnsmessage.Header, respQues dnsmessage.Question) bool {
+ if !respHdr.Response {
+ return false
+ }
+ if reqID != respHdr.ID {
+ return false
+ }
+ if reqQues.Type != respQues.Type || reqQues.Class != respQues.Class || !equalASCIIName(reqQues.Name, respQues.Name) {
+ return false
+ }
+ return true
+}
+
+func dnsPacketRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error) {
+ if _, err := c.Write(b); err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+
+ b = make([]byte, maxDNSPacketSize)
+ for {
+ n, err := c.Read(b)
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+ var p dnsmessage.Parser
+ // Ignore invalid responses as they may be malicious
+ // forgery attempts. Instead continue waiting until
+ // timeout. See golang.org/issue/13281.
+ h, err := p.Start(b[:n])
+ if err != nil {
+ continue
+ }
+ q, err := p.Question()
+ if err != nil || !checkResponse(id, query, h, q) {
+ continue
+ }
+ return p, h, nil
+ }
+}
+
+func dnsStreamRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error) {
+ if _, err := c.Write(b); err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+
+ b = make([]byte, 1280) // 1280 is a reasonable initial size for IP over Ethernet, see RFC 4035
+ if _, err := io.ReadFull(c, b[:2]); err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+ l := int(b[0])<<8 | int(b[1])
+ if l > len(b) {
+ b = make([]byte, l)
+ }
+ n, err := io.ReadFull(c, b[:l])
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+ var p dnsmessage.Parser
+ h, err := p.Start(b[:n])
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotUnmarshalDNSMessage
+ }
+ q, err := p.Question()
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotUnmarshalDNSMessage
+ }
+ if !checkResponse(id, query, h, q) {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errInvalidDNSResponse
+ }
+ return p, h, nil
+}
+
+// exchange sends a query on the connection and hopes for a response.
+func (r *Resolver) exchange(ctx context.Context, server string, q dnsmessage.Question, timeout time.Duration, useTCP, ad bool) (dnsmessage.Parser, dnsmessage.Header, error) {
+ q.Class = dnsmessage.ClassINET
+ id, udpReq, tcpReq, err := newRequest(q, ad)
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errCannotMarshalDNSMessage
+ }
+ var networks []string
+ if useTCP {
+ networks = []string{"tcp"}
+ } else {
+ networks = []string{"udp", "tcp"}
+ }
+ for _, network := range networks {
+ ctx, cancel := context.WithDeadline(ctx, time.Now().Add(timeout))
+ defer cancel()
+
+ c, err := r.dial(ctx, network, server)
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, err
+ }
+ if d, ok := ctx.Deadline(); ok && !d.IsZero() {
+ c.SetDeadline(d)
+ }
+ var p dnsmessage.Parser
+ var h dnsmessage.Header
+ if _, ok := c.(PacketConn); ok {
+ p, h, err = dnsPacketRoundTrip(c, id, q, udpReq)
+ } else {
+ p, h, err = dnsStreamRoundTrip(c, id, q, tcpReq)
+ }
+ c.Close()
+ if err != nil {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, mapErr(err)
+ }
+ if err := p.SkipQuestion(); err != dnsmessage.ErrSectionDone {
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errInvalidDNSResponse
+ }
+ if h.Truncated { // see RFC 5966
+ continue
+ }
+ return p, h, nil
+ }
+ return dnsmessage.Parser{}, dnsmessage.Header{}, errNoAnswerFromDNSServer
+}
+
+// checkHeader performs basic sanity checks on the header.
+func checkHeader(p *dnsmessage.Parser, h dnsmessage.Header) error {
+ rcode := extractExtendedRCode(*p, h)
+
+ if rcode == dnsmessage.RCodeNameError {
+ return errNoSuchHost
+ }
+
+ _, err := p.AnswerHeader()
+ if err != nil && err != dnsmessage.ErrSectionDone {
+ return errCannotUnmarshalDNSMessage
+ }
+
+ // libresolv continues to the next server when it receives
+ // an invalid referral response. See golang.org/issue/15434.
+ if rcode == dnsmessage.RCodeSuccess && !h.Authoritative && !h.RecursionAvailable && err == dnsmessage.ErrSectionDone {
+ return errLameReferral
+ }
+
+ if rcode != dnsmessage.RCodeSuccess && rcode != dnsmessage.RCodeNameError {
+ // None of the error codes make sense
+ // for the query we sent. If we didn't get
+ // a name error and we didn't get success,
+ // the server is behaving incorrectly or
+ // having temporary trouble.
+ if rcode == dnsmessage.RCodeServerFailure {
+ return errServerTemporarilyMisbehaving
+ }
+ return errServerMisbehaving
+ }
+
+ return nil
+}
+
+func skipToAnswer(p *dnsmessage.Parser, qtype dnsmessage.Type) error {
+ for {
+ h, err := p.AnswerHeader()
+ if err == dnsmessage.ErrSectionDone {
+ return errNoSuchHost
+ }
+ if err != nil {
+ return errCannotUnmarshalDNSMessage
+ }
+ if h.Type == qtype {
+ return nil
+ }
+ if err := p.SkipAnswer(); err != nil {
+ return errCannotUnmarshalDNSMessage
+ }
+ }
+}
+
+// extractExtendedRCode extracts the extended RCode from the OPT resource (EDNS(0))
+// If an OPT record is not found, the RCode from the hdr is returned.
+func extractExtendedRCode(p dnsmessage.Parser, hdr dnsmessage.Header) dnsmessage.RCode {
+ p.SkipAllAnswers()
+ p.SkipAllAuthorities()
+ for {
+ ahdr, err := p.AdditionalHeader()
+ if err != nil {
+ return hdr.RCode
+ }
+ if ahdr.Type == dnsmessage.TypeOPT {
+ return ahdr.ExtendedRCode(hdr.RCode)
+ }
+ if err := p.SkipAdditional(); err != nil {
+ return hdr.RCode
+ }
+ }
+}
+
+// Do a lookup for a single name, which must be rooted
+// (otherwise answer will not find the answers).
+func (r *Resolver) tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error) {
+ var lastErr error
+ serverOffset := cfg.serverOffset()
+ sLen := uint32(len(cfg.servers))
+
+ n, err := dnsmessage.NewName(name)
+ if err != nil {
+ return dnsmessage.Parser{}, "", errCannotMarshalDNSMessage
+ }
+ q := dnsmessage.Question{
+ Name: n,
+ Type: qtype,
+ Class: dnsmessage.ClassINET,
+ }
+
+ for i := 0; i < cfg.attempts; i++ {
+ for j := uint32(0); j < sLen; j++ {
+ server := cfg.servers[(serverOffset+j)%sLen]
+
+ p, h, err := r.exchange(ctx, server, q, cfg.timeout, cfg.useTCP, cfg.trustAD)
+ if err != nil {
+ dnsErr := &DNSError{
+ Err: err.Error(),
+ Name: name,
+ Server: server,
+ }
+ if nerr, ok := err.(Error); ok && nerr.Timeout() {
+ dnsErr.IsTimeout = true
+ }
+ // Set IsTemporary for socket-level errors. Note that this flag
+ // may also be used to indicate a SERVFAIL response.
+ if _, ok := err.(*OpError); ok {
+ dnsErr.IsTemporary = true
+ }
+ lastErr = dnsErr
+ continue
+ }
+
+ if err := checkHeader(&p, h); err != nil {
+ dnsErr := &DNSError{
+ Err: err.Error(),
+ Name: name,
+ Server: server,
+ }
+ if err == errServerTemporarilyMisbehaving {
+ dnsErr.IsTemporary = true
+ }
+ if err == errNoSuchHost {
+ // The name does not exist, so trying
+ // another server won't help.
+
+ dnsErr.IsNotFound = true
+ return p, server, dnsErr
+ }
+ lastErr = dnsErr
+ continue
+ }
+
+ err = skipToAnswer(&p, qtype)
+ if err == nil {
+ return p, server, nil
+ }
+ lastErr = &DNSError{
+ Err: err.Error(),
+ Name: name,
+ Server: server,
+ }
+ if err == errNoSuchHost {
+ // The name does not exist, so trying another
+ // server won't help.
+
+ lastErr.(*DNSError).IsNotFound = true
+ return p, server, lastErr
+ }
+ }
+ }
+ return dnsmessage.Parser{}, "", lastErr
+}
+
+// A resolverConfig represents a DNS stub resolver configuration.
+type resolverConfig struct {
+ initOnce sync.Once // guards init of resolverConfig
+
+ // ch is used as a semaphore that only allows one lookup at a
+ // time to recheck resolv.conf.
+ ch chan struct{} // guards lastChecked and modTime
+ lastChecked time.Time // last time resolv.conf was checked
+
+ dnsConfig atomic.Pointer[dnsConfig] // parsed resolv.conf structure used in lookups
+}
+
+var resolvConf resolverConfig
+
+func getSystemDNSConfig() *dnsConfig {
+ resolvConf.tryUpdate("/etc/resolv.conf")
+ return resolvConf.dnsConfig.Load()
+}
+
+// init initializes conf and is only called via conf.initOnce.
+func (conf *resolverConfig) init() {
+ // Set dnsConfig and lastChecked so we don't parse
+ // resolv.conf twice the first time.
+ conf.dnsConfig.Store(dnsReadConfig("/etc/resolv.conf"))
+ conf.lastChecked = time.Now()
+
+ // Prepare ch so that only one update of resolverConfig may
+ // run at once.
+ conf.ch = make(chan struct{}, 1)
+}
+
+// tryUpdate tries to update conf with the named resolv.conf file.
+// The name variable only exists for testing. It is otherwise always
+// "/etc/resolv.conf".
+func (conf *resolverConfig) tryUpdate(name string) {
+ conf.initOnce.Do(conf.init)
+
+ if conf.dnsConfig.Load().noReload {
+ return
+ }
+
+ // Ensure only one update at a time checks resolv.conf.
+ if !conf.tryAcquireSema() {
+ return
+ }
+ defer conf.releaseSema()
+
+ now := time.Now()
+ if conf.lastChecked.After(now.Add(-5 * time.Second)) {
+ return
+ }
+ conf.lastChecked = now
+
+ switch runtime.GOOS {
+ case "windows":
+ // There's no file on disk, so don't bother checking
+ // and failing.
+ //
+ // The Windows implementation of dnsReadConfig (called
+ // below) ignores the name.
+ default:
+ var mtime time.Time
+ if fi, err := os.Stat(name); err == nil {
+ mtime = fi.ModTime()
+ }
+ if mtime.Equal(conf.dnsConfig.Load().mtime) {
+ return
+ }
+ }
+
+ dnsConf := dnsReadConfig(name)
+ conf.dnsConfig.Store(dnsConf)
+}
+
+func (conf *resolverConfig) tryAcquireSema() bool {
+ select {
+ case conf.ch <- struct{}{}:
+ return true
+ default:
+ return false
+ }
+}
+
+func (conf *resolverConfig) releaseSema() {
+ <-conf.ch
+}
+
+func (r *Resolver) lookup(ctx context.Context, name string, qtype dnsmessage.Type, conf *dnsConfig) (dnsmessage.Parser, string, error) {
+ if !isDomainName(name) {
+ // We used to use "invalid domain name" as the error,
+ // but that is a detail of the specific lookup mechanism.
+ // Other lookups might allow broader name syntax
+ // (for example Multicast DNS allows UTF-8; see RFC 6762).
+ // For consistency with libc resolvers, report no such host.
+ return dnsmessage.Parser{}, "", &DNSError{Err: errNoSuchHost.Error(), Name: name, IsNotFound: true}
+ }
+
+ if conf == nil {
+ conf = getSystemDNSConfig()
+ }
+
+ var (
+ p dnsmessage.Parser
+ server string
+ err error
+ )
+ for _, fqdn := range conf.nameList(name) {
+ p, server, err = r.tryOneName(ctx, conf, fqdn, qtype)
+ if err == nil {
+ break
+ }
+ if nerr, ok := err.(Error); ok && nerr.Temporary() && r.strictErrors() {
+ // If we hit a temporary error with StrictErrors enabled,
+ // stop immediately instead of trying more names.
+ break
+ }
+ }
+ if err == nil {
+ return p, server, nil
+ }
+ if err, ok := err.(*DNSError); ok {
+ // Show original name passed to lookup, not suffixed one.
+ // In general we might have tried many suffixes; showing
+ // just one is misleading. See also golang.org/issue/6324.
+ err.Name = name
+ }
+ return dnsmessage.Parser{}, "", err
+}
+
+// avoidDNS reports whether this is a hostname for which we should not
+// use DNS. Currently this includes only .onion, per RFC 7686. See
+// golang.org/issue/13705. Does not cover .local names (RFC 6762),
+// see golang.org/issue/16739.
+func avoidDNS(name string) bool {
+ if name == "" {
+ return true
+ }
+ if name[len(name)-1] == '.' {
+ name = name[:len(name)-1]
+ }
+ return stringsHasSuffixFold(name, ".onion")
+}
+
+// nameList returns a list of names for sequential DNS queries.
+func (conf *dnsConfig) nameList(name string) []string {
+ // Check name length (see isDomainName).
+ l := len(name)
+ rooted := l > 0 && name[l-1] == '.'
+ if l > 254 || l == 254 && !rooted {
+ return nil
+ }
+
+ // If name is rooted (trailing dot), try only that name.
+ if rooted {
+ if avoidDNS(name) {
+ return nil
+ }
+ return []string{name}
+ }
+
+ hasNdots := bytealg.CountString(name, '.') >= conf.ndots
+ name += "."
+ l++
+
+ // Build list of search choices.
+ names := make([]string, 0, 1+len(conf.search))
+ // If name has enough dots, try unsuffixed first.
+ if hasNdots && !avoidDNS(name) {
+ names = append(names, name)
+ }
+ // Try suffixes that are not too long (see isDomainName).
+ for _, suffix := range conf.search {
+ fqdn := name + suffix
+ if !avoidDNS(fqdn) && len(fqdn) <= 254 {
+ names = append(names, fqdn)
+ }
+ }
+ // Try unsuffixed, if not tried first above.
+ if !hasNdots && !avoidDNS(name) {
+ names = append(names, name)
+ }
+ return names
+}
+
+// hostLookupOrder specifies the order of LookupHost lookup strategies.
+// It is basically a simplified representation of nsswitch.conf.
+// "files" means /etc/hosts.
+type hostLookupOrder int
+
+const (
+ // hostLookupCgo means defer to cgo.
+ hostLookupCgo hostLookupOrder = iota
+ hostLookupFilesDNS // files first
+ hostLookupDNSFiles // dns first
+ hostLookupFiles // only files
+ hostLookupDNS // only DNS
+)
+
+var lookupOrderName = map[hostLookupOrder]string{
+ hostLookupCgo: "cgo",
+ hostLookupFilesDNS: "files,dns",
+ hostLookupDNSFiles: "dns,files",
+ hostLookupFiles: "files",
+ hostLookupDNS: "dns",
+}
+
+func (o hostLookupOrder) String() string {
+ if s, ok := lookupOrderName[o]; ok {
+ return s
+ }
+ return "hostLookupOrder=" + itoa.Itoa(int(o)) + "??"
+}
+
+func (r *Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder, conf *dnsConfig) (addrs []string, err error) {
+ if order == hostLookupFilesDNS || order == hostLookupFiles {
+ // Use entries from /etc/hosts if they match.
+ addrs, _ = lookupStaticHost(name)
+ if len(addrs) > 0 {
+ return
+ }
+
+ if order == hostLookupFiles {
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: name, IsNotFound: true}
+ }
+ }
+ ips, _, err := r.goLookupIPCNAMEOrder(ctx, "ip", name, order, conf)
+ if err != nil {
+ return
+ }
+ addrs = make([]string, 0, len(ips))
+ for _, ip := range ips {
+ addrs = append(addrs, ip.String())
+ }
+ return
+}
+
+// lookup entries from /etc/hosts
+func goLookupIPFiles(name string) (addrs []IPAddr, canonical string) {
+ addr, canonical := lookupStaticHost(name)
+ for _, haddr := range addr {
+ haddr, zone := splitHostZone(haddr)
+ if ip := ParseIP(haddr); ip != nil {
+ addr := IPAddr{IP: ip, Zone: zone}
+ addrs = append(addrs, addr)
+ }
+ }
+ sortByRFC6724(addrs)
+ return addrs, canonical
+}
+
+// goLookupIP is the native Go implementation of LookupIP.
+// The libc versions are in cgo_*.go.
+func (r *Resolver) goLookupIP(ctx context.Context, network, host string, order hostLookupOrder, conf *dnsConfig) (addrs []IPAddr, err error) {
+ addrs, _, err = r.goLookupIPCNAMEOrder(ctx, network, host, order, conf)
+ return
+}
+
+func (r *Resolver) goLookupIPCNAMEOrder(ctx context.Context, network, name string, order hostLookupOrder, conf *dnsConfig) (addrs []IPAddr, cname dnsmessage.Name, err error) {
+ if order == hostLookupFilesDNS || order == hostLookupFiles {
+ var canonical string
+ addrs, canonical = goLookupIPFiles(name)
+
+ if len(addrs) > 0 {
+ var err error
+ cname, err = dnsmessage.NewName(canonical)
+ if err != nil {
+ return nil, dnsmessage.Name{}, err
+ }
+ return addrs, cname, nil
+ }
+
+ if order == hostLookupFiles {
+ return nil, dnsmessage.Name{}, &DNSError{Err: errNoSuchHost.Error(), Name: name, IsNotFound: true}
+ }
+ }
+
+ if !isDomainName(name) {
+ // See comment in func lookup above about use of errNoSuchHost.
+ return nil, dnsmessage.Name{}, &DNSError{Err: errNoSuchHost.Error(), Name: name, IsNotFound: true}
+ }
+ type result struct {
+ p dnsmessage.Parser
+ server string
+ error
+ }
+
+ if conf == nil {
+ conf = getSystemDNSConfig()
+ }
+
+ lane := make(chan result, 1)
+ qtypes := []dnsmessage.Type{dnsmessage.TypeA, dnsmessage.TypeAAAA}
+ if network == "CNAME" {
+ qtypes = append(qtypes, dnsmessage.TypeCNAME)
+ }
+ switch ipVersion(network) {
+ case '4':
+ qtypes = []dnsmessage.Type{dnsmessage.TypeA}
+ case '6':
+ qtypes = []dnsmessage.Type{dnsmessage.TypeAAAA}
+ }
+ var queryFn func(fqdn string, qtype dnsmessage.Type)
+ var responseFn func(fqdn string, qtype dnsmessage.Type) result
+ if conf.singleRequest {
+ queryFn = func(fqdn string, qtype dnsmessage.Type) {}
+ responseFn = func(fqdn string, qtype dnsmessage.Type) result {
+ dnsWaitGroup.Add(1)
+ defer dnsWaitGroup.Done()
+ p, server, err := r.tryOneName(ctx, conf, fqdn, qtype)
+ return result{p, server, err}
+ }
+ } else {
+ queryFn = func(fqdn string, qtype dnsmessage.Type) {
+ dnsWaitGroup.Add(1)
+ go func(qtype dnsmessage.Type) {
+ p, server, err := r.tryOneName(ctx, conf, fqdn, qtype)
+ lane <- result{p, server, err}
+ dnsWaitGroup.Done()
+ }(qtype)
+ }
+ responseFn = func(fqdn string, qtype dnsmessage.Type) result {
+ return <-lane
+ }
+ }
+ var lastErr error
+ for _, fqdn := range conf.nameList(name) {
+ for _, qtype := range qtypes {
+ queryFn(fqdn, qtype)
+ }
+ hitStrictError := false
+ for _, qtype := range qtypes {
+ result := responseFn(fqdn, qtype)
+ if result.error != nil {
+ if nerr, ok := result.error.(Error); ok && nerr.Temporary() && r.strictErrors() {
+ // This error will abort the nameList loop.
+ hitStrictError = true
+ lastErr = result.error
+ } else if lastErr == nil || fqdn == name+"." {
+ // Prefer error for original name.
+ lastErr = result.error
+ }
+ continue
+ }
+
+ // Presotto says it's okay to assume that servers listed in
+ // /etc/resolv.conf are recursive resolvers.
+ //
+ // We asked for recursion, so it should have included all the
+ // answers we need in this one packet.
+ //
+ // Further, RFC 1034 section 4.3.1 says that "the recursive
+ // response to a query will be... The answer to the query,
+ // possibly preface by one or more CNAME RRs that specify
+ // aliases encountered on the way to an answer."
+ //
+ // Therefore, we should be able to assume that we can ignore
+ // CNAMEs and that the A and AAAA records we requested are
+ // for the canonical name.
+
+ loop:
+ for {
+ h, err := result.p.AnswerHeader()
+ if err != nil && err != dnsmessage.ErrSectionDone {
+ lastErr = &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: name,
+ Server: result.server,
+ }
+ }
+ if err != nil {
+ break
+ }
+ switch h.Type {
+ case dnsmessage.TypeA:
+ a, err := result.p.AResource()
+ if err != nil {
+ lastErr = &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: name,
+ Server: result.server,
+ }
+ break loop
+ }
+ addrs = append(addrs, IPAddr{IP: IP(a.A[:])})
+ if cname.Length == 0 && h.Name.Length != 0 {
+ cname = h.Name
+ }
+
+ case dnsmessage.TypeAAAA:
+ aaaa, err := result.p.AAAAResource()
+ if err != nil {
+ lastErr = &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: name,
+ Server: result.server,
+ }
+ break loop
+ }
+ addrs = append(addrs, IPAddr{IP: IP(aaaa.AAAA[:])})
+ if cname.Length == 0 && h.Name.Length != 0 {
+ cname = h.Name
+ }
+
+ case dnsmessage.TypeCNAME:
+ c, err := result.p.CNAMEResource()
+ if err != nil {
+ lastErr = &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: name,
+ Server: result.server,
+ }
+ break loop
+ }
+ if cname.Length == 0 && c.CNAME.Length > 0 {
+ cname = c.CNAME
+ }
+
+ default:
+ if err := result.p.SkipAnswer(); err != nil {
+ lastErr = &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: name,
+ Server: result.server,
+ }
+ break loop
+ }
+ continue
+ }
+ }
+ }
+ if hitStrictError {
+ // If either family hit an error with StrictErrors enabled,
+ // discard all addresses. This ensures that network flakiness
+ // cannot turn a dualstack hostname IPv4/IPv6-only.
+ addrs = nil
+ break
+ }
+ if len(addrs) > 0 || network == "CNAME" && cname.Length > 0 {
+ break
+ }
+ }
+ if lastErr, ok := lastErr.(*DNSError); ok {
+ // Show original name passed to lookup, not suffixed one.
+ // In general we might have tried many suffixes; showing
+ // just one is misleading. See also golang.org/issue/6324.
+ lastErr.Name = name
+ }
+ sortByRFC6724(addrs)
+ if len(addrs) == 0 && !(network == "CNAME" && cname.Length > 0) {
+ if order == hostLookupDNSFiles {
+ var canonical string
+ addrs, canonical = goLookupIPFiles(name)
+ if len(addrs) > 0 {
+ var err error
+ cname, err = dnsmessage.NewName(canonical)
+ if err != nil {
+ return nil, dnsmessage.Name{}, err
+ }
+ return addrs, cname, nil
+ }
+ }
+ if lastErr != nil {
+ return nil, dnsmessage.Name{}, lastErr
+ }
+ }
+ return addrs, cname, nil
+}
+
+// goLookupCNAME is the native Go (non-cgo) implementation of LookupCNAME.
+func (r *Resolver) goLookupCNAME(ctx context.Context, host string, order hostLookupOrder, conf *dnsConfig) (string, error) {
+ _, cname, err := r.goLookupIPCNAMEOrder(ctx, "CNAME", host, order, conf)
+ return cname.String(), err
+}
+
+// goLookupPTR is the native Go implementation of LookupAddr.
+func (r *Resolver) goLookupPTR(ctx context.Context, addr string, order hostLookupOrder, conf *dnsConfig) ([]string, error) {
+ if order == hostLookupFiles || order == hostLookupFilesDNS {
+ names := lookupStaticAddr(addr)
+ if len(names) > 0 {
+ return names, nil
+ }
+
+ if order == hostLookupFiles {
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: addr, IsNotFound: true}
+ }
+ }
+
+ arpa, err := reverseaddr(addr)
+ if err != nil {
+ return nil, err
+ }
+ p, server, err := r.lookup(ctx, arpa, dnsmessage.TypePTR, conf)
+ if err != nil {
+ var dnsErr *DNSError
+ if errors.As(err, &dnsErr) && dnsErr.IsNotFound {
+ if order == hostLookupDNSFiles {
+ names := lookupStaticAddr(addr)
+ if len(names) > 0 {
+ return names, nil
+ }
+ }
+ }
+ return nil, err
+ }
+ var ptrs []string
+ for {
+ h, err := p.AnswerHeader()
+ if err == dnsmessage.ErrSectionDone {
+ break
+ }
+ if err != nil {
+ return nil, &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: addr,
+ Server: server,
+ }
+ }
+ if h.Type != dnsmessage.TypePTR {
+ err := p.SkipAnswer()
+ if err != nil {
+ return nil, &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: addr,
+ Server: server,
+ }
+ }
+ continue
+ }
+ ptr, err := p.PTRResource()
+ if err != nil {
+ return nil, &DNSError{
+ Err: errCannotUnmarshalDNSMessage.Error(),
+ Name: addr,
+ Server: server,
+ }
+ }
+ ptrs = append(ptrs, ptr.PTR.String())
+
+ }
+
+ return ptrs, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsclient_unix_test.go b/platform/dbops/binaries/go/go/src/net/dnsclient_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f42fbfbf7b129af64d12052a58e5f517535345c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsclient_unix_test.go
@@ -0,0 +1,2680 @@
+// 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 unix
+
+package net
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+var goResolver = Resolver{PreferGo: true}
+
+// Test address from 192.0.2.0/24 block, reserved by RFC 5737 for documentation.
+var TestAddr = [4]byte{0xc0, 0x00, 0x02, 0x01}
+
+// Test address from 2001:db8::/32 block, reserved by RFC 3849 for documentation.
+var TestAddr6 = [16]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
+
+func mustNewName(name string) dnsmessage.Name {
+ nn, err := dnsmessage.NewName(name)
+ if err != nil {
+ panic(fmt.Sprint("creating name: ", err))
+ }
+ return nn
+}
+
+func mustQuestion(name string, qtype dnsmessage.Type, class dnsmessage.Class) dnsmessage.Question {
+ return dnsmessage.Question{
+ Name: mustNewName(name),
+ Type: qtype,
+ Class: class,
+ }
+}
+
+var dnsTransportFallbackTests = []struct {
+ server string
+ question dnsmessage.Question
+ timeout int
+ rcode dnsmessage.RCode
+}{
+ // Querying "com." with qtype=255 usually makes an answer
+ // which requires more than 512 bytes.
+ {"8.8.8.8:53", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), 2, dnsmessage.RCodeSuccess},
+ {"8.8.4.4:53", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), 4, dnsmessage.RCodeSuccess},
+}
+
+func TestDNSTransportFallback(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ }
+ if n == "udp" {
+ r.Header.Truncated = true
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ for _, tt := range dnsTransportFallbackTests {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, h, err := r.exchange(ctx, tt.server, tt.question, time.Second, useUDPOrTCP, false)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ if h.RCode != tt.rcode {
+ t.Errorf("got %v from %v; want %v", h.RCode, tt.server, tt.rcode)
+ continue
+ }
+ }
+}
+
+// See RFC 6761 for further information about the reserved, pseudo
+// domain names.
+var specialDomainNameTests = []struct {
+ question dnsmessage.Question
+ rcode dnsmessage.RCode
+}{
+ // Name resolution APIs and libraries should not recognize the
+ // followings as special.
+ {mustQuestion("1.0.168.192.in-addr.arpa.", dnsmessage.TypePTR, dnsmessage.ClassINET), dnsmessage.RCodeNameError},
+ {mustQuestion("test.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError},
+ {mustQuestion("example.com.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeSuccess},
+
+ // Name resolution APIs and libraries should recognize the
+ // followings as special and should not send any queries.
+ // Though, we test those names here for verifying negative
+ // answers at DNS query-response interaction level.
+ {mustQuestion("localhost.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError},
+ {mustQuestion("invalid.", dnsmessage.TypeALL, dnsmessage.ClassINET), dnsmessage.RCodeNameError},
+}
+
+func TestSpecialDomainName(t *testing.T) {
+ fake := fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+
+ switch q.Questions[0].Name.String() {
+ case "example.com.":
+ r.Header.RCode = dnsmessage.RCodeSuccess
+ default:
+ r.Header.RCode = dnsmessage.RCodeNameError
+ }
+
+ return r, nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ server := "8.8.8.8:53"
+ for _, tt := range specialDomainNameTests {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, h, err := r.exchange(ctx, server, tt.question, 3*time.Second, useUDPOrTCP, false)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ if h.RCode != tt.rcode {
+ t.Errorf("got %v from %v; want %v", h.RCode, server, tt.rcode)
+ continue
+ }
+ }
+}
+
+// Issue 13705: don't try to resolve onion addresses, etc
+func TestAvoidDNSName(t *testing.T) {
+ tests := []struct {
+ name string
+ avoid bool
+ }{
+ {"foo.com", false},
+ {"foo.com.", false},
+
+ {"foo.onion.", true},
+ {"foo.onion", true},
+ {"foo.ONION", true},
+ {"foo.ONION.", true},
+
+ // But do resolve *.local address; Issue 16739
+ {"foo.local.", false},
+ {"foo.local", false},
+ {"foo.LOCAL", false},
+ {"foo.LOCAL.", false},
+
+ {"", true}, // will be rejected earlier too
+
+ // Without stuff before onion/local, they're fine to
+ // use DNS. With a search path,
+ // "onion.vegetables.com" can use DNS. Without a
+ // search path (or with a trailing dot), the queries
+ // are just kinda useless, but don't reveal anything
+ // private.
+ {"local", false},
+ {"onion", false},
+ {"local.", false},
+ {"onion.", false},
+ }
+ for _, tt := range tests {
+ got := avoidDNS(tt.name)
+ if got != tt.avoid {
+ t.Errorf("avoidDNS(%q) = %v; want %v", tt.name, got, tt.avoid)
+ }
+ }
+}
+
+func TestNameListAvoidDNS(t *testing.T) {
+ c := &dnsConfig{search: []string{"go.dev.", "onion."}}
+ got := c.nameList("www")
+ if !slices.Equal(got, []string{"www.", "www.go.dev."}) {
+ t.Fatalf(`nameList("www") = %v, want "www.", "www.go.dev."`, got)
+ }
+
+ got = c.nameList("www.onion")
+ if !slices.Equal(got, []string{"www.onion.go.dev."}) {
+ t.Fatalf(`nameList("www.onion") = %v, want "www.onion.go.dev."`, got)
+ }
+}
+
+var fakeDNSServerSuccessful = fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+ if len(q.Questions) == 1 && q.Questions[0].Type == dnsmessage.TypeA {
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+ }
+ return r, nil
+}}
+
+// Issue 13705: don't try to resolve onion addresses, etc
+func TestLookupTorOnion(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ r := Resolver{PreferGo: true, Dial: fakeDNSServerSuccessful.DialContext}
+ addrs, err := r.LookupIPAddr(context.Background(), "foo.onion.")
+ if err != nil {
+ t.Fatalf("lookup = %v; want nil", err)
+ }
+ if len(addrs) > 0 {
+ t.Errorf("unexpected addresses: %v", addrs)
+ }
+}
+
+type resolvConfTest struct {
+ dir string
+ path string
+ *resolverConfig
+}
+
+func newResolvConfTest() (*resolvConfTest, error) {
+ dir, err := os.MkdirTemp("", "go-resolvconftest")
+ if err != nil {
+ return nil, err
+ }
+ conf := &resolvConfTest{
+ dir: dir,
+ path: path.Join(dir, "resolv.conf"),
+ resolverConfig: &resolvConf,
+ }
+ conf.initOnce.Do(conf.init)
+ return conf, nil
+}
+
+func (conf *resolvConfTest) write(lines []string) error {
+ f, err := os.OpenFile(conf.path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ if _, err := f.WriteString(strings.Join(lines, "\n")); err != nil {
+ f.Close()
+ return err
+ }
+ f.Close()
+ return nil
+}
+
+func (conf *resolvConfTest) writeAndUpdate(lines []string) error {
+ return conf.writeAndUpdateWithLastCheckedTime(lines, time.Now().Add(time.Hour))
+}
+
+func (conf *resolvConfTest) writeAndUpdateWithLastCheckedTime(lines []string, lastChecked time.Time) error {
+ if err := conf.write(lines); err != nil {
+ return err
+ }
+ return conf.forceUpdate(conf.path, lastChecked)
+}
+
+func (conf *resolvConfTest) forceUpdate(name string, lastChecked time.Time) error {
+ dnsConf := dnsReadConfig(name)
+ if !conf.forceUpdateConf(dnsConf, lastChecked) {
+ return fmt.Errorf("tryAcquireSema for %s failed", name)
+ }
+ return nil
+}
+
+func (conf *resolvConfTest) forceUpdateConf(c *dnsConfig, lastChecked time.Time) bool {
+ conf.dnsConfig.Store(c)
+ for i := 0; i < 5; i++ {
+ if conf.tryAcquireSema() {
+ conf.lastChecked = lastChecked
+ conf.releaseSema()
+ return true
+ }
+ }
+ return false
+}
+
+func (conf *resolvConfTest) servers() []string {
+ return conf.dnsConfig.Load().servers
+}
+
+func (conf *resolvConfTest) teardown() error {
+ err := conf.forceUpdate("/etc/resolv.conf", time.Time{})
+ os.RemoveAll(conf.dir)
+ return err
+}
+
+var updateResolvConfTests = []struct {
+ name string // query name
+ lines []string // resolver configuration lines
+ servers []string // expected name servers
+}{
+ {
+ name: "golang.org",
+ lines: []string{"nameserver 8.8.8.8"},
+ servers: []string{"8.8.8.8:53"},
+ },
+ {
+ name: "",
+ lines: nil, // an empty resolv.conf should use defaultNS as name servers
+ servers: defaultNS,
+ },
+ {
+ name: "www.example.com",
+ lines: []string{"nameserver 8.8.4.4"},
+ servers: []string{"8.8.4.4:53"},
+ },
+}
+
+func TestUpdateResolvConf(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ r := Resolver{PreferGo: true, Dial: fakeDNSServerSuccessful.DialContext}
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ for i, tt := range updateResolvConfTests {
+ if err := conf.writeAndUpdate(tt.lines); err != nil {
+ t.Error(err)
+ continue
+ }
+ if tt.name != "" {
+ var wg sync.WaitGroup
+ const N = 10
+ wg.Add(N)
+ for j := 0; j < N; j++ {
+ go func(name string) {
+ defer wg.Done()
+ ips, err := r.LookupIPAddr(context.Background(), name)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if len(ips) == 0 {
+ t.Errorf("no records for %s", name)
+ return
+ }
+ }(tt.name)
+ }
+ wg.Wait()
+ }
+ servers := conf.servers()
+ if !reflect.DeepEqual(servers, tt.servers) {
+ t.Errorf("#%d: got %v; want %v", i, servers, tt.servers)
+ continue
+ }
+ }
+}
+
+var goLookupIPWithResolverConfigTests = []struct {
+ name string
+ lines []string // resolver configuration lines
+ error
+ a, aaaa bool // whether response contains A, AAAA-record
+}{
+ // no records, transport timeout
+ {
+ "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j",
+ []string{
+ "options timeout:1 attempts:1",
+ "nameserver 255.255.255.255", // please forgive us for abuse of limited broadcast address
+ },
+ &DNSError{Name: "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", Server: "255.255.255.255:53", IsTimeout: true},
+ false, false,
+ },
+
+ // no records, non-existent domain
+ {
+ "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j",
+ []string{
+ "options timeout:3 attempts:1",
+ "nameserver 8.8.8.8",
+ },
+ &DNSError{Name: "jgahvsekduiv9bw4b3qhn4ykdfgj0493iohkrjfhdvhjiu4j", Server: "8.8.8.8:53", IsTimeout: false},
+ false, false,
+ },
+
+ // a few A records, no AAAA records
+ {
+ "ipv4.google.com.",
+ []string{
+ "nameserver 8.8.8.8",
+ "nameserver 2001:4860:4860::8888",
+ },
+ nil,
+ true, false,
+ },
+ {
+ "ipv4.google.com",
+ []string{
+ "domain golang.org",
+ "nameserver 2001:4860:4860::8888",
+ "nameserver 8.8.8.8",
+ },
+ nil,
+ true, false,
+ },
+ {
+ "ipv4.google.com",
+ []string{
+ "search x.golang.org y.golang.org",
+ "nameserver 2001:4860:4860::8888",
+ "nameserver 8.8.8.8",
+ },
+ nil,
+ true, false,
+ },
+
+ // no A records, a few AAAA records
+ {
+ "ipv6.google.com.",
+ []string{
+ "nameserver 2001:4860:4860::8888",
+ "nameserver 8.8.8.8",
+ },
+ nil,
+ false, true,
+ },
+ {
+ "ipv6.google.com",
+ []string{
+ "domain golang.org",
+ "nameserver 8.8.8.8",
+ "nameserver 2001:4860:4860::8888",
+ },
+ nil,
+ false, true,
+ },
+ {
+ "ipv6.google.com",
+ []string{
+ "search x.golang.org y.golang.org",
+ "nameserver 8.8.8.8",
+ "nameserver 2001:4860:4860::8888",
+ },
+ nil,
+ false, true,
+ },
+
+ // both A and AAAA records
+ {
+ "hostname.as112.net", // see RFC 7534
+ []string{
+ "domain golang.org",
+ "nameserver 2001:4860:4860::8888",
+ "nameserver 8.8.8.8",
+ },
+ nil,
+ true, true,
+ },
+ {
+ "hostname.as112.net", // see RFC 7534
+ []string{
+ "search x.golang.org y.golang.org",
+ "nameserver 2001:4860:4860::8888",
+ "nameserver 8.8.8.8",
+ },
+ nil,
+ true, true,
+ },
+}
+
+func TestGoLookupIPWithResolverConfig(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ switch s {
+ case "[2001:4860:4860::8888]:53", "8.8.8.8:53":
+ break
+ default:
+ time.Sleep(10 * time.Millisecond)
+ return dnsmessage.Message{}, os.ErrDeadlineExceeded
+ }
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+ for _, question := range q.Questions {
+ switch question.Type {
+ case dnsmessage.TypeA:
+ switch question.Name.String() {
+ case "hostname.as112.net.":
+ break
+ case "ipv4.google.com.":
+ r.Answers = append(r.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ })
+ default:
+
+ }
+ case dnsmessage.TypeAAAA:
+ switch question.Name.String() {
+ case "hostname.as112.net.":
+ break
+ case "ipv6.google.com.":
+ r.Answers = append(r.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeAAAA,
+ Class: dnsmessage.ClassINET,
+ Length: 16,
+ },
+ Body: &dnsmessage.AAAAResource{
+ AAAA: TestAddr6,
+ },
+ })
+ }
+ }
+ }
+ return r, nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ for _, tt := range goLookupIPWithResolverConfigTests {
+ if err := conf.writeAndUpdate(tt.lines); err != nil {
+ t.Error(err)
+ continue
+ }
+ addrs, err := r.LookupIPAddr(context.Background(), tt.name)
+ if err != nil {
+ if err, ok := err.(*DNSError); !ok || tt.error != nil && (err.Name != tt.error.(*DNSError).Name || err.Server != tt.error.(*DNSError).Server || err.IsTimeout != tt.error.(*DNSError).IsTimeout) {
+ t.Errorf("got %v; want %v", err, tt.error)
+ }
+ continue
+ }
+ if len(addrs) == 0 {
+ t.Errorf("no records for %s", tt.name)
+ }
+ if !tt.a && !tt.aaaa && len(addrs) > 0 {
+ t.Errorf("unexpected %v for %s", addrs, tt.name)
+ }
+ for _, addr := range addrs {
+ if !tt.a && addr.IP.To4() != nil {
+ t.Errorf("got %v; must not be IPv4 address", addr)
+ }
+ if !tt.aaaa && addr.IP.To16() != nil && addr.IP.To4() == nil {
+ t.Errorf("got %v; must not be IPv6 address", addr)
+ }
+ }
+ }
+}
+
+// Test that goLookupIPOrder falls back to the host file when no DNS servers are available.
+func TestGoLookupIPOrderFallbackToFile(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, tm time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+ return r, nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ // Add a config that simulates no dns servers being available.
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ if err := conf.writeAndUpdate([]string{}); err != nil {
+ t.Fatal(err)
+ }
+ // Redirect host file lookups.
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ hostsFilePath = "testdata/hosts"
+
+ for _, order := range []hostLookupOrder{hostLookupFilesDNS, hostLookupDNSFiles} {
+ name := fmt.Sprintf("order %v", order)
+ // First ensure that we get an error when contacting a non-existent host.
+ _, _, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", "notarealhost", order, nil)
+ if err == nil {
+ t.Errorf("%s: expected error while looking up name not in hosts file", name)
+ continue
+ }
+
+ // Now check that we get an address when the name appears in the hosts file.
+ addrs, _, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", "thor", order, nil) // entry is in "testdata/hosts"
+ if err != nil {
+ t.Errorf("%s: expected to successfully lookup host entry", name)
+ continue
+ }
+ if len(addrs) != 1 {
+ t.Errorf("%s: expected exactly one result, but got %v", name, addrs)
+ continue
+ }
+ if got, want := addrs[0].String(), "127.1.1.1"; got != want {
+ t.Errorf("%s: address doesn't match expectation. got %v, want %v", name, got, want)
+ }
+ }
+}
+
+// Issue 12712.
+// When using search domains, return the error encountered
+// querying the original name instead of an error encountered
+// querying a generated name.
+func TestErrorForOriginalNameWhenSearching(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ const fqdn = "doesnotexist.domain"
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ if err := conf.writeAndUpdate([]string{"search servfail"}); err != nil {
+ t.Fatal(err)
+ }
+
+ fake := fakeDNSServer{rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+
+ switch q.Questions[0].Name.String() {
+ case fqdn + ".servfail.":
+ r.Header.RCode = dnsmessage.RCodeServerFailure
+ default:
+ r.Header.RCode = dnsmessage.RCodeNameError
+ }
+
+ return r, nil
+ }}
+
+ cases := []struct {
+ strictErrors bool
+ wantErr *DNSError
+ }{
+ {true, &DNSError{Name: fqdn, Err: "server misbehaving", IsTemporary: true}},
+ {false, &DNSError{Name: fqdn, Err: errNoSuchHost.Error(), IsNotFound: true}},
+ }
+ for _, tt := range cases {
+ r := Resolver{PreferGo: true, StrictErrors: tt.strictErrors, Dial: fake.DialContext}
+ _, err = r.LookupIPAddr(context.Background(), fqdn)
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+
+ want := tt.wantErr
+ if err, ok := err.(*DNSError); !ok || err.Name != want.Name || err.Err != want.Err || err.IsTemporary != want.IsTemporary {
+ t.Errorf("got %v; want %v", err, want)
+ }
+ }
+}
+
+// Issue 15434. If a name server gives a lame referral, continue to the next.
+func TestIgnoreLameReferrals(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ if err := conf.writeAndUpdate([]string{"nameserver 192.0.2.1", // the one that will give a lame referral
+ "nameserver 192.0.2.2"}); err != nil {
+ t.Fatal(err)
+ }
+
+ fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ t.Log(s, q)
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+
+ if s == "192.0.2.2:53" {
+ r.Header.RecursionAvailable = true
+ if q.Questions[0].Type == dnsmessage.TypeA {
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+ }
+ }
+
+ return r, nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ addrs, err := r.LookupIPAddr(context.Background(), "www.golang.org")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if got := len(addrs); got != 1 {
+ t.Fatalf("got %d addresses, want 1", got)
+ }
+
+ if got, want := addrs[0].String(), "192.0.2.1"; got != want {
+ t.Fatalf("got address %v, want %v", got, want)
+ }
+}
+
+func BenchmarkGoLookupIP(b *testing.B) {
+ testHookUninstaller.Do(uninstallTestHooks)
+ ctx := context.Background()
+ b.ReportAllocs()
+
+ for i := 0; i < b.N; i++ {
+ goResolver.LookupIPAddr(ctx, "www.example.com")
+ }
+}
+
+func BenchmarkGoLookupIPNoSuchHost(b *testing.B) {
+ testHookUninstaller.Do(uninstallTestHooks)
+ ctx := context.Background()
+ b.ReportAllocs()
+
+ for i := 0; i < b.N; i++ {
+ goResolver.LookupIPAddr(ctx, "some.nonexistent")
+ }
+}
+
+func BenchmarkGoLookupIPWithBrokenNameServer(b *testing.B) {
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer conf.teardown()
+
+ lines := []string{
+ "nameserver 203.0.113.254", // use TEST-NET-3 block, see RFC 5737
+ "nameserver 8.8.8.8",
+ }
+ if err := conf.writeAndUpdate(lines); err != nil {
+ b.Fatal(err)
+ }
+ ctx := context.Background()
+ b.ReportAllocs()
+
+ for i := 0; i < b.N; i++ {
+ goResolver.LookupIPAddr(ctx, "www.example.com")
+ }
+}
+
+type fakeDNSServer struct {
+ rh func(n, s string, q dnsmessage.Message, t time.Time) (dnsmessage.Message, error)
+ alwaysTCP bool
+}
+
+func (server *fakeDNSServer) DialContext(_ context.Context, n, s string) (Conn, error) {
+ if server.alwaysTCP || n == "tcp" || n == "tcp4" || n == "tcp6" {
+ return &fakeDNSConn{tcp: true, server: server, n: n, s: s}, nil
+ }
+ return &fakeDNSPacketConn{fakeDNSConn: fakeDNSConn{tcp: false, server: server, n: n, s: s}}, nil
+}
+
+type fakeDNSConn struct {
+ Conn
+ tcp bool
+ server *fakeDNSServer
+ n string
+ s string
+ q dnsmessage.Message
+ t time.Time
+ buf []byte
+}
+
+func (f *fakeDNSConn) Close() error {
+ return nil
+}
+
+func (f *fakeDNSConn) Read(b []byte) (int, error) {
+ if len(f.buf) > 0 {
+ n := copy(b, f.buf)
+ f.buf = f.buf[n:]
+ return n, nil
+ }
+
+ resp, err := f.server.rh(f.n, f.s, f.q, f.t)
+ if err != nil {
+ return 0, err
+ }
+
+ bb := make([]byte, 2, 514)
+ bb, err = resp.AppendPack(bb)
+ if err != nil {
+ return 0, fmt.Errorf("cannot marshal DNS message: %v", err)
+ }
+
+ if f.tcp {
+ l := len(bb) - 2
+ bb[0] = byte(l >> 8)
+ bb[1] = byte(l)
+ f.buf = bb
+ return f.Read(b)
+ }
+
+ bb = bb[2:]
+ if len(b) < len(bb) {
+ return 0, errors.New("read would fragment DNS message")
+ }
+
+ copy(b, bb)
+ return len(bb), nil
+}
+
+func (f *fakeDNSConn) Write(b []byte) (int, error) {
+ if f.tcp && len(b) >= 2 {
+ b = b[2:]
+ }
+ if f.q.Unpack(b) != nil {
+ return 0, fmt.Errorf("cannot unmarshal DNS message fake %s (%d)", f.n, len(b))
+ }
+ return len(b), nil
+}
+
+func (f *fakeDNSConn) SetDeadline(t time.Time) error {
+ f.t = t
+ return nil
+}
+
+type fakeDNSPacketConn struct {
+ PacketConn
+ fakeDNSConn
+}
+
+func (f *fakeDNSPacketConn) SetDeadline(t time.Time) error {
+ return f.fakeDNSConn.SetDeadline(t)
+}
+
+func (f *fakeDNSPacketConn) Close() error {
+ return f.fakeDNSConn.Close()
+}
+
+// UDP round-tripper algorithm should ignore invalid DNS responses (issue 13281).
+func TestIgnoreDNSForgeries(t *testing.T) {
+ c, s := Pipe()
+ go func() {
+ b := make([]byte, maxDNSPacketSize)
+ n, err := s.Read(b)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+
+ var msg dnsmessage.Message
+ if msg.Unpack(b[:n]) != nil {
+ t.Error("invalid DNS query:", err)
+ return
+ }
+
+ s.Write([]byte("garbage DNS response packet"))
+
+ msg.Header.Response = true
+ msg.Header.ID++ // make invalid ID
+
+ if b, err = msg.Pack(); err != nil {
+ t.Error("failed to pack DNS response:", err)
+ return
+ }
+ s.Write(b)
+
+ msg.Header.ID-- // restore original ID
+ msg.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: mustNewName("www.example.com."),
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+
+ b, err = msg.Pack()
+ if err != nil {
+ t.Error("failed to pack DNS response:", err)
+ return
+ }
+ s.Write(b)
+ }()
+
+ msg := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: 42,
+ },
+ Questions: []dnsmessage.Question{
+ {
+ Name: mustNewName("www.example.com."),
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ },
+ },
+ }
+
+ b, err := msg.Pack()
+ if err != nil {
+ t.Fatal("Pack failed:", err)
+ }
+
+ p, _, err := dnsPacketRoundTrip(c, 42, msg.Questions[0], b)
+ if err != nil {
+ t.Fatalf("dnsPacketRoundTrip failed: %v", err)
+ }
+
+ p.SkipAllQuestions()
+ as, err := p.AllAnswers()
+ if err != nil {
+ t.Fatal("AllAnswers failed:", err)
+ }
+ if got := as[0].Body.(*dnsmessage.AResource).A; got != TestAddr {
+ t.Errorf("got address %v, want %v", got, TestAddr)
+ }
+}
+
+// Issue 16865. If a name server times out, continue to the next.
+func TestRetryTimeout(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ testConf := []string{
+ "nameserver 192.0.2.1", // the one that will timeout
+ "nameserver 192.0.2.2",
+ }
+ if err := conf.writeAndUpdate(testConf); err != nil {
+ t.Fatal(err)
+ }
+
+ var deadline0 time.Time
+
+ fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) {
+ t.Log(s, q, deadline)
+
+ if deadline.IsZero() {
+ t.Error("zero deadline")
+ }
+
+ if s == "192.0.2.1:53" {
+ deadline0 = deadline
+ time.Sleep(10 * time.Millisecond)
+ return dnsmessage.Message{}, os.ErrDeadlineExceeded
+ }
+
+ if deadline.Equal(deadline0) {
+ t.Error("deadline didn't change")
+ }
+
+ return mockTXTResponse(q), nil
+ }}
+ r := &Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ _, err = r.LookupTXT(context.Background(), "www.golang.org")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if deadline0.IsZero() {
+ t.Error("deadline0 still zero", deadline0)
+ }
+}
+
+func TestRotate(t *testing.T) {
+ // without rotation, always uses the first server
+ testRotate(t, false, []string{"192.0.2.1", "192.0.2.2"}, []string{"192.0.2.1:53", "192.0.2.1:53", "192.0.2.1:53"})
+
+ // with rotation, rotates through back to first
+ testRotate(t, true, []string{"192.0.2.1", "192.0.2.2"}, []string{"192.0.2.1:53", "192.0.2.2:53", "192.0.2.1:53"})
+}
+
+func testRotate(t *testing.T, rotate bool, nameservers, wantServers []string) {
+ defer dnsWaitGroup.Wait()
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ var confLines []string
+ for _, ns := range nameservers {
+ confLines = append(confLines, "nameserver "+ns)
+ }
+ if rotate {
+ confLines = append(confLines, "options rotate")
+ }
+
+ if err := conf.writeAndUpdate(confLines); err != nil {
+ t.Fatal(err)
+ }
+
+ var usedServers []string
+ fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) {
+ usedServers = append(usedServers, s)
+ return mockTXTResponse(q), nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ // len(nameservers) + 1 to allow rotation to get back to start
+ for i := 0; i < len(nameservers)+1; i++ {
+ if _, err := r.LookupTXT(context.Background(), "www.golang.org"); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if !reflect.DeepEqual(usedServers, wantServers) {
+ t.Errorf("rotate=%t got used servers:\n%v\nwant:\n%v", rotate, usedServers, wantServers)
+ }
+}
+
+func mockTXTResponse(q dnsmessage.Message) dnsmessage.Message {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RecursionAvailable: true,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeTXT,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.TXTResource{
+ TXT: []string{"ok"},
+ },
+ },
+ },
+ }
+
+ return r
+}
+
+// Issue 17448. With StrictErrors enabled, temporary errors should make
+// LookupIP fail rather than return a partial result.
+func TestStrictErrorsLookupIP(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ confData := []string{
+ "nameserver 192.0.2.53",
+ "search x.golang.org y.golang.org",
+ }
+ if err := conf.writeAndUpdate(confData); err != nil {
+ t.Fatal(err)
+ }
+
+ const name = "test-issue19592"
+ const server = "192.0.2.53:53"
+ const searchX = "test-issue19592.x.golang.org."
+ const searchY = "test-issue19592.y.golang.org."
+ const ip4 = "192.0.2.1"
+ const ip6 = "2001:db8::1"
+
+ type resolveWhichEnum int
+ const (
+ resolveOK resolveWhichEnum = iota
+ resolveOpError
+ resolveServfail
+ resolveTimeout
+ )
+
+ makeTempError := func(err string) error {
+ return &DNSError{
+ Err: err,
+ Name: name,
+ Server: server,
+ IsTemporary: true,
+ }
+ }
+ makeTimeout := func() error {
+ return &DNSError{
+ Err: os.ErrDeadlineExceeded.Error(),
+ Name: name,
+ Server: server,
+ IsTimeout: true,
+ }
+ }
+ makeNxDomain := func() error {
+ return &DNSError{
+ Err: errNoSuchHost.Error(),
+ Name: name,
+ Server: server,
+ IsNotFound: true,
+ }
+ }
+
+ cases := []struct {
+ desc string
+ resolveWhich func(quest dnsmessage.Question) resolveWhichEnum
+ wantStrictErr error
+ wantLaxErr error
+ wantIPs []string
+ }{
+ {
+ desc: "No errors",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ return resolveOK
+ },
+ wantIPs: []string{ip4, ip6},
+ },
+ {
+ desc: "searchX error fails in strict mode",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchX {
+ return resolveTimeout
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTimeout(),
+ wantIPs: []string{ip4, ip6},
+ },
+ {
+ desc: "searchX IPv4-only timeout fails in strict mode",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchX && quest.Type == dnsmessage.TypeA {
+ return resolveTimeout
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTimeout(),
+ wantIPs: []string{ip4, ip6},
+ },
+ {
+ desc: "searchX IPv6-only servfail fails in strict mode",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchX && quest.Type == dnsmessage.TypeAAAA {
+ return resolveServfail
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTempError("server misbehaving"),
+ wantIPs: []string{ip4, ip6},
+ },
+ {
+ desc: "searchY error always fails",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchY {
+ return resolveTimeout
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTimeout(),
+ wantLaxErr: makeNxDomain(), // This one reaches the "test." FQDN.
+ },
+ {
+ desc: "searchY IPv4-only socket error fails in strict mode",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchY && quest.Type == dnsmessage.TypeA {
+ return resolveOpError
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTempError("write: socket on fire"),
+ wantIPs: []string{ip6},
+ },
+ {
+ desc: "searchY IPv6-only timeout fails in strict mode",
+ resolveWhich: func(quest dnsmessage.Question) resolveWhichEnum {
+ if quest.Name.String() == searchY && quest.Type == dnsmessage.TypeAAAA {
+ return resolveTimeout
+ }
+ return resolveOK
+ },
+ wantStrictErr: makeTimeout(),
+ wantIPs: []string{ip4},
+ },
+ }
+
+ for i, tt := range cases {
+ fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) {
+ t.Log(s, q)
+
+ switch tt.resolveWhich(q.Questions[0]) {
+ case resolveOK:
+ // Handle below.
+ case resolveOpError:
+ return dnsmessage.Message{}, &OpError{Op: "write", Err: fmt.Errorf("socket on fire")}
+ case resolveServfail:
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeServerFailure,
+ },
+ Questions: q.Questions,
+ }, nil
+ case resolveTimeout:
+ return dnsmessage.Message{}, os.ErrDeadlineExceeded
+ default:
+ t.Fatal("Impossible resolveWhich")
+ }
+
+ switch q.Questions[0].Name.String() {
+ case searchX, name + ".":
+ // Return NXDOMAIN to utilize the search list.
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeNameError,
+ },
+ Questions: q.Questions,
+ }, nil
+ case searchY:
+ // Return records below.
+ default:
+ return dnsmessage.Message{}, fmt.Errorf("Unexpected Name: %v", q.Questions[0].Name)
+ }
+
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+ switch q.Questions[0].Type {
+ case dnsmessage.TypeA:
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+ case dnsmessage.TypeAAAA:
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeAAAA,
+ Class: dnsmessage.ClassINET,
+ Length: 16,
+ },
+ Body: &dnsmessage.AAAAResource{
+ AAAA: TestAddr6,
+ },
+ },
+ }
+ default:
+ return dnsmessage.Message{}, fmt.Errorf("Unexpected Type: %v", q.Questions[0].Type)
+ }
+ return r, nil
+ }}
+
+ for _, strict := range []bool{true, false} {
+ r := Resolver{PreferGo: true, StrictErrors: strict, Dial: fake.DialContext}
+ ips, err := r.LookupIPAddr(context.Background(), name)
+
+ var wantErr error
+ if strict {
+ wantErr = tt.wantStrictErr
+ } else {
+ wantErr = tt.wantLaxErr
+ }
+ if !reflect.DeepEqual(err, wantErr) {
+ t.Errorf("#%d (%s) strict=%v: got err %#v; want %#v", i, tt.desc, strict, err, wantErr)
+ }
+
+ gotIPs := map[string]struct{}{}
+ for _, ip := range ips {
+ gotIPs[ip.String()] = struct{}{}
+ }
+ wantIPs := map[string]struct{}{}
+ if wantErr == nil {
+ for _, ip := range tt.wantIPs {
+ wantIPs[ip] = struct{}{}
+ }
+ }
+ if !reflect.DeepEqual(gotIPs, wantIPs) {
+ t.Errorf("#%d (%s) strict=%v: got ips %v; want %v", i, tt.desc, strict, gotIPs, wantIPs)
+ }
+ }
+ }
+}
+
+// Issue 17448. With StrictErrors enabled, temporary errors should make
+// LookupTXT stop walking the search list.
+func TestStrictErrorsLookupTXT(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ confData := []string{
+ "nameserver 192.0.2.53",
+ "search x.golang.org y.golang.org",
+ }
+ if err := conf.writeAndUpdate(confData); err != nil {
+ t.Fatal(err)
+ }
+
+ const name = "test"
+ const server = "192.0.2.53:53"
+ const searchX = "test.x.golang.org."
+ const searchY = "test.y.golang.org."
+ const txt = "Hello World"
+
+ fake := fakeDNSServer{rh: func(_, s string, q dnsmessage.Message, deadline time.Time) (dnsmessage.Message, error) {
+ t.Log(s, q)
+
+ switch q.Questions[0].Name.String() {
+ case searchX:
+ return dnsmessage.Message{}, os.ErrDeadlineExceeded
+ case searchY:
+ return mockTXTResponse(q), nil
+ default:
+ return dnsmessage.Message{}, fmt.Errorf("Unexpected Name: %v", q.Questions[0].Name)
+ }
+ }}
+
+ for _, strict := range []bool{true, false} {
+ r := Resolver{StrictErrors: strict, Dial: fake.DialContext}
+ p, _, err := r.lookup(context.Background(), name, dnsmessage.TypeTXT, nil)
+ var wantErr error
+ var wantRRs int
+ if strict {
+ wantErr = &DNSError{
+ Err: os.ErrDeadlineExceeded.Error(),
+ Name: name,
+ Server: server,
+ IsTimeout: true,
+ }
+ } else {
+ wantRRs = 1
+ }
+ if !reflect.DeepEqual(err, wantErr) {
+ t.Errorf("strict=%v: got err %#v; want %#v", strict, err, wantErr)
+ }
+ a, err := p.AllAnswers()
+ if err != nil {
+ a = nil
+ }
+ if len(a) != wantRRs {
+ t.Errorf("strict=%v: got %v; want %v", strict, len(a), wantRRs)
+ }
+ }
+}
+
+// Test for a race between uninstalling the test hooks and closing a
+// socket connection. This used to fail when testing with -race.
+func TestDNSGoroutineRace(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+
+ fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, t time.Time) (dnsmessage.Message, error) {
+ time.Sleep(10 * time.Microsecond)
+ return dnsmessage.Message{}, os.ErrDeadlineExceeded
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ // The timeout here is less than the timeout used by the server,
+ // so the goroutine started to query the (fake) server will hang
+ // around after this test is done if we don't call dnsWaitGroup.Wait.
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Microsecond)
+ defer cancel()
+ _, err := r.LookupIPAddr(ctx, "where.are.they.now")
+ if err == nil {
+ t.Fatal("fake DNS lookup unexpectedly succeeded")
+ }
+}
+
+func lookupWithFake(fake fakeDNSServer, name string, typ dnsmessage.Type) error {
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ conf := getSystemDNSConfig()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ _, _, err := r.tryOneName(ctx, conf, name, typ)
+ return err
+}
+
+// Issue 8434: verify that Temporary returns true on an error when rcode
+// is SERVFAIL
+func TestIssue8434(t *testing.T) {
+ err := lookupWithFake(fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeServerFailure,
+ },
+ Questions: q.Questions,
+ }, nil
+ },
+ }, "golang.org.", dnsmessage.TypeALL)
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if ne, ok := err.(Error); !ok {
+ t.Fatalf("err = %#v; wanted something supporting net.Error", err)
+ } else if !ne.Temporary() {
+ t.Fatalf("Temporary = false for err = %#v; want Temporary == true", err)
+ }
+ if de, ok := err.(*DNSError); !ok {
+ t.Fatalf("err = %#v; wanted a *net.DNSError", err)
+ } else if !de.IsTemporary {
+ t.Fatalf("IsTemporary = false for err = %#v; want IsTemporary == true", err)
+ }
+}
+
+func TestIssueNoSuchHostExists(t *testing.T) {
+ err := lookupWithFake(fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeNameError,
+ },
+ Questions: q.Questions,
+ }, nil
+ },
+ }, "golang.org.", dnsmessage.TypeALL)
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if _, ok := err.(Error); !ok {
+ t.Fatalf("err = %#v; wanted something supporting net.Error", err)
+ }
+ if de, ok := err.(*DNSError); !ok {
+ t.Fatalf("err = %#v; wanted a *net.DNSError", err)
+ } else if !de.IsNotFound {
+ t.Fatalf("IsNotFound = false for err = %#v; want IsNotFound == true", err)
+ }
+}
+
+// TestNoSuchHost verifies that tryOneName works correctly when the domain does
+// not exist.
+//
+// Issue 12778: verify that NXDOMAIN without RA bit errors as "no such host"
+// and not "server misbehaving"
+//
+// Issue 25336: verify that NXDOMAIN errors fail fast.
+//
+// Issue 27525: verify that empty answers fail fast.
+func TestNoSuchHost(t *testing.T) {
+ tests := []struct {
+ name string
+ f func(string, string, dnsmessage.Message, time.Time) (dnsmessage.Message, error)
+ }{
+ {
+ "NXDOMAIN",
+ func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeNameError,
+ RecursionAvailable: false,
+ },
+ Questions: q.Questions,
+ }, nil
+ },
+ },
+ {
+ "no answers",
+ func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ RecursionAvailable: false,
+ Authoritative: true,
+ },
+ Questions: q.Questions,
+ }, nil
+ },
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ lookups := 0
+ err := lookupWithFake(fakeDNSServer{
+ rh: func(n, s string, q dnsmessage.Message, d time.Time) (dnsmessage.Message, error) {
+ lookups++
+ return test.f(n, s, q, d)
+ },
+ }, ".", dnsmessage.TypeALL)
+
+ if lookups != 1 {
+ t.Errorf("got %d lookups, wanted 1", lookups)
+ }
+
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ de, ok := err.(*DNSError)
+ if !ok {
+ t.Fatalf("err = %#v; wanted a *net.DNSError", err)
+ }
+ if de.Err != errNoSuchHost.Error() {
+ t.Fatalf("Err = %#v; wanted %q", de.Err, errNoSuchHost.Error())
+ }
+ if !de.IsNotFound {
+ t.Fatalf("IsNotFound = %v wanted true", de.IsNotFound)
+ }
+ })
+ }
+}
+
+// Issue 26573: verify that Conns that don't implement PacketConn are treated
+// as streams even when udp was requested.
+func TestDNSDialTCP(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ }
+ return r, nil
+ },
+ alwaysTCP: true,
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ ctx := context.Background()
+ _, _, err := r.exchange(ctx, "0.0.0.0", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), time.Second, useUDPOrTCP, false)
+ if err != nil {
+ t.Fatal("exchange failed:", err)
+ }
+}
+
+// Issue 27763: verify that two strings in one TXT record are concatenated.
+func TestTXTRecordTwoStrings(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.TXTResource{
+ TXT: []string{"string1 ", "string2"},
+ },
+ },
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.TXTResource{
+ TXT: []string{"onestring"},
+ },
+ },
+ },
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ txt, err := r.lookupTXT(context.Background(), "golang.org")
+ if err != nil {
+ t.Fatal("LookupTXT failed:", err)
+ }
+ if want := 2; len(txt) != want {
+ t.Fatalf("len(txt), got %d, want %d", len(txt), want)
+ }
+ if want := "string1 string2"; txt[0] != want {
+ t.Errorf("txt[0], got %q, want %q", txt[0], want)
+ }
+ if want := "onestring"; txt[1] != want {
+ t.Errorf("txt[1], got %q, want %q", txt[1], want)
+ }
+}
+
+// Issue 29644: support single-request resolv.conf option in pure Go resolver.
+// The A and AAAA queries will be sent sequentially, not in parallel.
+func TestSingleRequestLookup(t *testing.T) {
+ defer dnsWaitGroup.Wait()
+ var (
+ firstcalled int32
+ ipv4 int32 = 1
+ ipv6 int32 = 2
+ )
+ fake := fakeDNSServer{rh: func(n, s string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.ID,
+ Response: true,
+ },
+ Questions: q.Questions,
+ }
+ for _, question := range q.Questions {
+ switch question.Type {
+ case dnsmessage.TypeA:
+ if question.Name.String() == "slowipv4.example.net." {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !atomic.CompareAndSwapInt32(&firstcalled, 0, ipv4) {
+ t.Errorf("the A query was received after the AAAA query !")
+ }
+ r.Answers = append(r.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ })
+ case dnsmessage.TypeAAAA:
+ atomic.CompareAndSwapInt32(&firstcalled, 0, ipv6)
+ r.Answers = append(r.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeAAAA,
+ Class: dnsmessage.ClassINET,
+ Length: 16,
+ },
+ Body: &dnsmessage.AAAAResource{
+ AAAA: TestAddr6,
+ },
+ })
+ }
+ }
+ return r, nil
+ }}
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+ if err := conf.writeAndUpdate([]string{"options single-request"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"hostname.example.net", "slowipv4.example.net"} {
+ firstcalled = 0
+ _, err := r.LookupIPAddr(context.Background(), name)
+ if err != nil {
+ t.Error(err)
+ }
+ }
+}
+
+// Issue 29358. Add configuration knob to force TCP-only DNS requests in the pure Go resolver.
+func TestDNSUseTCP(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ }
+ if n == "udp" {
+ t.Fatal("udp protocol was used instead of tcp")
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, _, err := r.exchange(ctx, "0.0.0.0", mustQuestion("com.", dnsmessage.TypeALL, dnsmessage.ClassINET), time.Second, useTCPOnly, false)
+ if err != nil {
+ t.Fatal("exchange failed:", err)
+ }
+}
+
+// Issue 34660: PTR response with non-PTR answers should ignore non-PTR
+func TestPTRandNonPTR(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypePTR,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.PTRResource{
+ PTR: dnsmessage.MustNewName("golang.org."),
+ },
+ },
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeTXT,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.TXTResource{
+ TXT: []string{"PTR 8 6 60 ..."}, // fake RRSIG
+ },
+ },
+ },
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ names, err := r.lookupAddr(context.Background(), "192.0.2.123")
+ if err != nil {
+ t.Fatalf("LookupAddr: %v", err)
+ }
+ if want := []string{"golang.org."}; !reflect.DeepEqual(names, want) {
+ t.Errorf("names = %q; want %q", names, want)
+ }
+}
+
+func TestCVE202133195(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ RecursionAvailable: true,
+ },
+ Questions: q.Questions,
+ }
+ switch q.Questions[0].Type {
+ case dnsmessage.TypeCNAME:
+ r.Answers = []dnsmessage.Resource{}
+ case dnsmessage.TypeA: // CNAME lookup uses a A/AAAA as a proxy
+ r.Answers = append(r.Answers,
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName(".golang.org."),
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ )
+ case dnsmessage.TypeSRV:
+ n := q.Questions[0].Name
+ if n.String() == "_hdr._tcp.golang.org." {
+ n = dnsmessage.MustNewName(".golang.org.")
+ }
+ r.Answers = append(r.Answers,
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: n,
+ Type: dnsmessage.TypeSRV,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.SRVResource{
+ Target: dnsmessage.MustNewName(".golang.org."),
+ },
+ },
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: n,
+ Type: dnsmessage.TypeSRV,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.SRVResource{
+ Target: dnsmessage.MustNewName("good.golang.org."),
+ },
+ },
+ )
+ case dnsmessage.TypeMX:
+ r.Answers = append(r.Answers,
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName(".golang.org."),
+ Type: dnsmessage.TypeMX,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.MXResource{
+ MX: dnsmessage.MustNewName(".golang.org."),
+ },
+ },
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName("good.golang.org."),
+ Type: dnsmessage.TypeMX,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.MXResource{
+ MX: dnsmessage.MustNewName("good.golang.org."),
+ },
+ },
+ )
+ case dnsmessage.TypeNS:
+ r.Answers = append(r.Answers,
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName(".golang.org."),
+ Type: dnsmessage.TypeNS,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.NSResource{
+ NS: dnsmessage.MustNewName(".golang.org."),
+ },
+ },
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName("good.golang.org."),
+ Type: dnsmessage.TypeNS,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.NSResource{
+ NS: dnsmessage.MustNewName("good.golang.org."),
+ },
+ },
+ )
+ case dnsmessage.TypePTR:
+ r.Answers = append(r.Answers,
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName(".golang.org."),
+ Type: dnsmessage.TypePTR,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.PTRResource{
+ PTR: dnsmessage.MustNewName(".golang.org."),
+ },
+ },
+ dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{
+ Name: dnsmessage.MustNewName("good.golang.org."),
+ Type: dnsmessage.TypePTR,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.PTRResource{
+ PTR: dnsmessage.MustNewName("good.golang.org."),
+ },
+ },
+ )
+ }
+ return r, nil
+ },
+ }
+
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ // Change the default resolver to match our manipulated resolver
+ originalDefault := DefaultResolver
+ DefaultResolver = &r
+ defer func() { DefaultResolver = originalDefault }()
+ // Redirect host file lookups.
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ hostsFilePath = "testdata/hosts"
+
+ tests := []struct {
+ name string
+ f func(*testing.T)
+ }{
+ {
+ name: "CNAME",
+ f: func(t *testing.T) {
+ expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"}
+ _, err := r.LookupCNAME(context.Background(), "golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ _, err = LookupCNAME("golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ },
+ },
+ {
+ name: "SRV (bad record)",
+ f: func(t *testing.T) {
+ expected := []*SRV{
+ {
+ Target: "good.golang.org.",
+ },
+ }
+ expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"}
+ _, records, err := r.LookupSRV(context.Background(), "target", "tcp", "golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ _, records, err = LookupSRV("target", "tcp", "golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Errorf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ },
+ },
+ {
+ name: "SRV (bad header)",
+ f: func(t *testing.T) {
+ _, _, err := r.LookupSRV(context.Background(), "hdr", "tcp", "golang.org.")
+ if expected := "lookup golang.org.: SRV header name is invalid"; err == nil || err.Error() != expected {
+ t.Errorf("Resolver.LookupSRV returned unexpected error, got %q, want %q", err, expected)
+ }
+ _, _, err = LookupSRV("hdr", "tcp", "golang.org.")
+ if expected := "lookup golang.org.: SRV header name is invalid"; err == nil || err.Error() != expected {
+ t.Errorf("LookupSRV returned unexpected error, got %q, want %q", err, expected)
+ }
+ },
+ },
+ {
+ name: "MX",
+ f: func(t *testing.T) {
+ expected := []*MX{
+ {
+ Host: "good.golang.org.",
+ },
+ }
+ expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"}
+ records, err := r.LookupMX(context.Background(), "golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ records, err = LookupMX("golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ },
+ },
+ {
+ name: "NS",
+ f: func(t *testing.T) {
+ expected := []*NS{
+ {
+ Host: "good.golang.org.",
+ },
+ }
+ expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "golang.org"}
+ records, err := r.LookupNS(context.Background(), "golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ records, err = LookupNS("golang.org")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ },
+ },
+ {
+ name: "Addr",
+ f: func(t *testing.T) {
+ expected := []string{"good.golang.org."}
+ expectedErr := &DNSError{Err: errMalformedDNSRecordsDetail, Name: "192.0.2.42"}
+ records, err := r.LookupAddr(context.Background(), "192.0.2.42")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ records, err = LookupAddr("192.0.2.42")
+ if err.Error() != expectedErr.Error() {
+ t.Fatalf("unexpected error: %s", err)
+ }
+ if !reflect.DeepEqual(records, expected) {
+ t.Error("Unexpected record set")
+ }
+ },
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, tc.f)
+ }
+
+}
+
+func TestNullMX(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeMX,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.MXResource{
+ MX: dnsmessage.MustNewName("."),
+ },
+ },
+ },
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ rrset, err := r.LookupMX(context.Background(), "golang.org")
+ if err != nil {
+ t.Fatalf("LookupMX: %v", err)
+ }
+ if want := []*MX{&MX{Host: "."}}; !reflect.DeepEqual(rrset, want) {
+ records := []string{}
+ for _, rr := range rrset {
+ records = append(records, fmt.Sprintf("%v", rr))
+ }
+ t.Errorf("records = [%v]; want [%v]", strings.Join(records, " "), want[0])
+ }
+}
+
+func TestRootNS(t *testing.T) {
+ // See https://golang.org/issue/45715.
+ fake := fakeDNSServer{
+ rh: func(n, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeNS,
+ Class: dnsmessage.ClassINET,
+ },
+ Body: &dnsmessage.NSResource{
+ NS: dnsmessage.MustNewName("i.root-servers.net."),
+ },
+ },
+ },
+ }
+ return r, nil
+ },
+ }
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ rrset, err := r.LookupNS(context.Background(), ".")
+ if err != nil {
+ t.Fatalf("LookupNS: %v", err)
+ }
+ if want := []*NS{&NS{Host: "i.root-servers.net."}}; !reflect.DeepEqual(rrset, want) {
+ records := []string{}
+ for _, rr := range rrset {
+ records = append(records, fmt.Sprintf("%v", rr))
+ }
+ t.Errorf("records = [%v]; want [%v]", strings.Join(records, " "), want[0])
+ }
+}
+
+func TestGoLookupIPCNAMEOrderHostsAliasesFilesOnlyMode(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ hostsFilePath = "testdata/aliases"
+ mode := hostLookupFiles
+
+ for _, v := range lookupStaticHostAliasesTest {
+ testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res))
+ }
+}
+
+func TestGoLookupIPCNAMEOrderHostsAliasesFilesDNSMode(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ hostsFilePath = "testdata/aliases"
+ mode := hostLookupFilesDNS
+
+ for _, v := range lookupStaticHostAliasesTest {
+ testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res))
+ }
+}
+
+var goLookupIPCNAMEOrderDNSFilesModeTests = []struct {
+ lookup, res string
+}{
+ // 127.0.1.1
+ {"invalid.invalid", "invalid.test"},
+}
+
+func TestGoLookupIPCNAMEOrderHostsAliasesDNSFilesMode(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ hostsFilePath = "testdata/aliases"
+ mode := hostLookupDNSFiles
+
+ for _, v := range goLookupIPCNAMEOrderDNSFilesModeTests {
+ testGoLookupIPCNAMEOrderHostsAliases(t, mode, v.lookup, absDomainName(v.res))
+ }
+}
+
+func testGoLookupIPCNAMEOrderHostsAliases(t *testing.T, mode hostLookupOrder, lookup, lookupRes string) {
+ fake := fakeDNSServer{
+ rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ var answers []dnsmessage.Resource
+
+ if mode != hostLookupDNSFiles {
+ t.Fatal("received unexpected DNS query")
+ }
+
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ },
+ Questions: []dnsmessage.Question{q.Questions[0]},
+ Answers: answers,
+ }, nil
+ },
+ }
+
+ r := Resolver{PreferGo: true, Dial: fake.DialContext}
+ ins := []string{lookup, absDomainName(lookup), strings.ToLower(lookup), strings.ToUpper(lookup)}
+ for _, in := range ins {
+ _, res, err := r.goLookupIPCNAMEOrder(context.Background(), "ip", in, mode, nil)
+ if err != nil {
+ t.Errorf("expected err == nil, but got error: %v", err)
+ }
+ if res.String() != lookupRes {
+ t.Errorf("goLookupIPCNAMEOrder(%v): got %v, want %v", in, res, lookupRes)
+ }
+ }
+}
+
+// Test that we advertise support for a larger DNS packet size.
+// This isn't a great test as it just tests the dnsmessage package
+// against itself.
+func TestDNSPacketSize(t *testing.T) {
+ t.Run("enabled", func(t *testing.T) {
+ testDNSPacketSize(t, false)
+ })
+ t.Run("disabled", func(t *testing.T) {
+ testDNSPacketSize(t, true)
+ })
+}
+
+func testDNSPacketSize(t *testing.T, disable bool) {
+ fake := fakeDNSServer{
+ rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ if disable {
+ if len(q.Additionals) > 0 {
+ t.Error("unexpected additional record")
+ }
+ } else {
+ if len(q.Additionals) == 0 {
+ t.Error("missing EDNS record")
+ } else if opt, ok := q.Additionals[0].Body.(*dnsmessage.OPTResource); !ok {
+ t.Errorf("additional record type %T, expected OPTResource", q.Additionals[0])
+ } else if len(opt.Options) != 0 {
+ t.Errorf("found %d Options, expected none", len(opt.Options))
+ } else {
+ got := int(q.Additionals[0].Header.Class)
+ t.Logf("EDNS packet size == %d", got)
+ if got != maxDNSPacketSize {
+ t.Errorf("EDNS packet size == %d, want %d", got, maxDNSPacketSize)
+ }
+ }
+ }
+
+ // Hand back a dummy answer to verify that
+ // LookupIPAddr completes.
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ }
+ if q.Questions[0].Type == dnsmessage.TypeA {
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+ }
+ return r, nil
+ },
+ }
+
+ if disable {
+ t.Setenv("GODEBUG", "netedns0=0")
+ }
+
+ r := &Resolver{PreferGo: true, Dial: fake.DialContext}
+ if _, err := r.LookupIPAddr(context.Background(), "go.dev"); err != nil {
+ t.Errorf("lookup failed: %v", err)
+ }
+}
+
+func TestLongDNSNames(t *testing.T) {
+ const longDNSsuffix = ".go.dev."
+ const longDNSsuffixNoEndingDot = ".go.dev"
+
+ var longDNSPrefix = strings.Repeat("verylongdomainlabel.", 20)
+
+ var longDNSNamesTests = []struct {
+ req string
+ fail bool
+ }{
+ {req: longDNSPrefix[:255-len(longDNSsuffix)] + longDNSsuffix, fail: true},
+ {req: longDNSPrefix[:254-len(longDNSsuffix)] + longDNSsuffix},
+ {req: longDNSPrefix[:253-len(longDNSsuffix)] + longDNSsuffix},
+
+ {req: longDNSPrefix[:253-len(longDNSsuffixNoEndingDot)] + longDNSsuffixNoEndingDot},
+ {req: longDNSPrefix[:254-len(longDNSsuffixNoEndingDot)] + longDNSsuffixNoEndingDot, fail: true},
+ }
+
+ fake := fakeDNSServer{
+ rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ Answers: []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: q.Questions[0].Type,
+ Class: dnsmessage.ClassINET,
+ },
+ },
+ },
+ }
+
+ switch q.Questions[0].Type {
+ case dnsmessage.TypeA:
+ r.Answers[0].Body = &dnsmessage.AResource{A: TestAddr}
+ case dnsmessage.TypeAAAA:
+ r.Answers[0].Body = &dnsmessage.AAAAResource{AAAA: TestAddr6}
+ case dnsmessage.TypeTXT:
+ r.Answers[0].Body = &dnsmessage.TXTResource{TXT: []string{"."}}
+ case dnsmessage.TypeMX:
+ r.Answers[0].Body = &dnsmessage.MXResource{
+ MX: dnsmessage.MustNewName("go.dev."),
+ }
+ case dnsmessage.TypeNS:
+ r.Answers[0].Body = &dnsmessage.NSResource{
+ NS: dnsmessage.MustNewName("go.dev."),
+ }
+ case dnsmessage.TypeSRV:
+ r.Answers[0].Body = &dnsmessage.SRVResource{
+ Target: dnsmessage.MustNewName("go.dev."),
+ }
+ case dnsmessage.TypeCNAME:
+ r.Answers[0].Body = &dnsmessage.CNAMEResource{
+ CNAME: dnsmessage.MustNewName("fake.cname."),
+ }
+ default:
+ panic("unknown dnsmessage type")
+ }
+
+ return r, nil
+ },
+ }
+
+ r := &Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ methodTests := []string{"CNAME", "Host", "IP", "IPAddr", "MX", "NS", "NetIP", "SRV", "TXT"}
+ query := func(t string, req string) error {
+ switch t {
+ case "CNAME":
+ _, err := r.LookupCNAME(context.Background(), req)
+ return err
+ case "Host":
+ _, err := r.LookupHost(context.Background(), req)
+ return err
+ case "IP":
+ _, err := r.LookupIP(context.Background(), "ip", req)
+ return err
+ case "IPAddr":
+ _, err := r.LookupIPAddr(context.Background(), req)
+ return err
+ case "MX":
+ _, err := r.LookupMX(context.Background(), req)
+ return err
+ case "NS":
+ _, err := r.LookupNS(context.Background(), req)
+ return err
+ case "NetIP":
+ _, err := r.LookupNetIP(context.Background(), "ip", req)
+ return err
+ case "SRV":
+ const service = "service"
+ const proto = "proto"
+ req = req[len(service)+len(proto)+4:]
+ _, _, err := r.LookupSRV(context.Background(), service, proto, req)
+ return err
+ case "TXT":
+ _, err := r.LookupTXT(context.Background(), req)
+ return err
+ }
+ panic("unknown query method")
+ }
+
+ for i, v := range longDNSNamesTests {
+ for _, testName := range methodTests {
+ err := query(testName, v.req)
+ if v.fail {
+ if err == nil {
+ t.Errorf("%v: Lookup%v: unexpected success", i, testName)
+ break
+ }
+
+ expectedErr := DNSError{Err: errNoSuchHost.Error(), Name: v.req, IsNotFound: true}
+ var dnsErr *DNSError
+ errors.As(err, &dnsErr)
+ if dnsErr == nil || *dnsErr != expectedErr {
+ t.Errorf("%v: Lookup%v: unexpected error: %v", i, testName, err)
+ }
+ break
+ }
+ if err != nil {
+ t.Errorf("%v: Lookup%v: unexpected error: %v", i, testName, err)
+ }
+ }
+ }
+}
+
+func TestDNSTrustAD(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ if q.Questions[0].Name.String() == "notrustad.go.dev." && q.Header.AuthenticData {
+ t.Error("unexpected AD bit")
+ }
+
+ if q.Questions[0].Name.String() == "trustad.go.dev." && !q.Header.AuthenticData {
+ t.Error("expected AD bit")
+ }
+
+ r := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: dnsmessage.RCodeSuccess,
+ },
+ Questions: q.Questions,
+ }
+ if q.Questions[0].Type == dnsmessage.TypeA {
+ r.Answers = []dnsmessage.Resource{
+ {
+ Header: dnsmessage.ResourceHeader{
+ Name: q.Questions[0].Name,
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ Length: 4,
+ },
+ Body: &dnsmessage.AResource{
+ A: TestAddr,
+ },
+ },
+ }
+ }
+
+ return r, nil
+ }}
+
+ r := &Resolver{PreferGo: true, Dial: fake.DialContext}
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ err = conf.writeAndUpdate([]string{"nameserver 127.0.0.1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := r.LookupIPAddr(context.Background(), "notrustad.go.dev"); err != nil {
+ t.Errorf("lookup failed: %v", err)
+ }
+
+ err = conf.writeAndUpdate([]string{"nameserver 127.0.0.1", "options trust-ad"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := r.LookupIPAddr(context.Background(), "trustad.go.dev"); err != nil {
+ t.Errorf("lookup failed: %v", err)
+ }
+}
+
+func TestDNSConfigNoReload(t *testing.T) {
+ r := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) {
+ if address != "192.0.2.1:53" {
+ return nil, errors.New("configuration unexpectedly changed")
+ }
+ return fakeDNSServerSuccessful.DialContext(ctx, network, address)
+ }}
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ err = conf.writeAndUpdateWithLastCheckedTime([]string{"nameserver 192.0.2.1", "options no-reload"}, time.Now().Add(-time.Hour))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err = r.LookupHost(context.Background(), "go.dev"); err != nil {
+ t.Fatal(err)
+ }
+
+ err = conf.write([]string{"nameserver 192.0.2.200"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err = r.LookupHost(context.Background(), "go.dev"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestLookupOrderFilesNoSuchHost(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+ if runtime.GOOS != "openbsd" {
+ defer setSystemNSS(getSystemNSS(), 0)
+ setSystemNSS(nssStr(t, "hosts: files"), time.Hour)
+ }
+
+ conf, err := newResolvConfTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conf.teardown()
+
+ resolvConf := dnsConfig{servers: defaultNS}
+ if runtime.GOOS == "openbsd" {
+ // Set error to ErrNotExist, so that the hostLookupOrder
+ // returns hostLookupFiles for openbsd.
+ resolvConf.err = os.ErrNotExist
+ }
+
+ if !conf.forceUpdateConf(&resolvConf, time.Now().Add(time.Hour)) {
+ t.Fatal("failed to update resolv config")
+ }
+
+ tmpFile := filepath.Join(t.TempDir(), "hosts")
+ if err := os.WriteFile(tmpFile, []byte{}, 0660); err != nil {
+ t.Fatal(err)
+ }
+ hostsFilePath = tmpFile
+
+ const testName = "test.invalid"
+
+ order, _ := systemConf().hostLookupOrder(DefaultResolver, testName)
+ if order != hostLookupFiles {
+ // skip test for systems which do not return hostLookupFiles
+ t.Skipf("hostLookupOrder did not return hostLookupFiles")
+ }
+
+ var lookupTests = []struct {
+ name string
+ lookup func(name string) error
+ }{
+ {
+ name: "Host",
+ lookup: func(name string) error {
+ _, err = DefaultResolver.LookupHost(context.Background(), name)
+ return err
+ },
+ },
+ {
+ name: "IP",
+ lookup: func(name string) error {
+ _, err = DefaultResolver.LookupIP(context.Background(), "ip", name)
+ return err
+ },
+ },
+ {
+ name: "IPAddr",
+ lookup: func(name string) error {
+ _, err = DefaultResolver.LookupIPAddr(context.Background(), name)
+ return err
+ },
+ },
+ {
+ name: "NetIP",
+ lookup: func(name string) error {
+ _, err = DefaultResolver.LookupNetIP(context.Background(), "ip", name)
+ return err
+ },
+ },
+ }
+
+ for _, v := range lookupTests {
+ err := v.lookup(testName)
+
+ if err == nil {
+ t.Errorf("Lookup%v: unexpected success", v.name)
+ continue
+ }
+
+ expectedErr := DNSError{Err: errNoSuchHost.Error(), Name: testName, IsNotFound: true}
+ var dnsErr *DNSError
+ errors.As(err, &dnsErr)
+ if dnsErr == nil || *dnsErr != expectedErr {
+ t.Errorf("Lookup%v: unexpected error: %v", v.name, err)
+ }
+ }
+}
+
+func TestExtendedRCode(t *testing.T) {
+ fake := fakeDNSServer{
+ rh: func(_, _ string, q dnsmessage.Message, _ time.Time) (dnsmessage.Message, error) {
+ fraudSuccessCode := dnsmessage.RCodeSuccess | 1<<10
+
+ var edns0Hdr dnsmessage.ResourceHeader
+ edns0Hdr.SetEDNS0(maxDNSPacketSize, fraudSuccessCode, false)
+
+ return dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: q.Header.ID,
+ Response: true,
+ RCode: fraudSuccessCode,
+ },
+ Questions: []dnsmessage.Question{q.Questions[0]},
+ Additionals: []dnsmessage.Resource{{
+ Header: edns0Hdr,
+ Body: &dnsmessage.OPTResource{},
+ }},
+ }, nil
+ },
+ }
+
+ r := &Resolver{PreferGo: true, Dial: fake.DialContext}
+ _, _, err := r.tryOneName(context.Background(), getSystemDNSConfig(), "go.dev.", dnsmessage.TypeA)
+ var dnsErr *DNSError
+ if !(errors.As(err, &dnsErr) && dnsErr.Err == errServerMisbehaving.Error()) {
+ t.Fatalf("r.tryOneName(): unexpected error: %v", err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsconfig.go b/platform/dbops/binaries/go/go/src/net/dnsconfig.go
new file mode 100644
index 0000000000000000000000000000000000000000..c86a70be5afd57aaab851f7b2c354460a350bd84
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsconfig.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 net
+
+import (
+ "os"
+ "sync/atomic"
+ "time"
+)
+
+var (
+ defaultNS = []string{"127.0.0.1:53", "[::1]:53"}
+ getHostname = os.Hostname // variable for testing
+)
+
+type dnsConfig struct {
+ servers []string // server addresses (in host:port form) to use
+ search []string // rooted suffixes to append to local name
+ ndots int // number of dots in name to trigger absolute lookup
+ timeout time.Duration // wait before giving up on a query, including retries
+ attempts int // lost packets before giving up on server
+ rotate bool // round robin among servers
+ unknownOpt bool // anything unknown was encountered
+ lookup []string // OpenBSD top-level database "lookup" order
+ err error // any error that occurs during open of resolv.conf
+ mtime time.Time // time of resolv.conf modification
+ soffset uint32 // used by serverOffset
+ singleRequest bool // use sequential A and AAAA queries instead of parallel queries
+ useTCP bool // force usage of TCP for DNS resolutions
+ trustAD bool // add AD flag to queries
+ noReload bool // do not check for config file updates
+}
+
+// serverOffset returns an offset that can be used to determine
+// indices of servers in c.servers when making queries.
+// When the rotate option is enabled, this offset increases.
+// Otherwise it is always 0.
+func (c *dnsConfig) serverOffset() uint32 {
+ if c.rotate {
+ return atomic.AddUint32(&c.soffset, 1) - 1 // return 0 to start
+ }
+ return 0
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsconfig_unix.go b/platform/dbops/binaries/go/go/src/net/dnsconfig_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..b0a318279b99b614e274dabea4cc0a462cd6f312
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsconfig_unix.go
@@ -0,0 +1,167 @@
+// 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
+
+// Read system DNS config from /etc/resolv.conf
+
+package net
+
+import (
+ "internal/bytealg"
+ "net/netip"
+ "time"
+)
+
+// See resolv.conf(5) on a Linux machine.
+func dnsReadConfig(filename string) *dnsConfig {
+ conf := &dnsConfig{
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ }
+ file, err := open(filename)
+ if err != nil {
+ conf.servers = defaultNS
+ conf.search = dnsDefaultSearch()
+ conf.err = err
+ return conf
+ }
+ defer file.close()
+ if fi, err := file.file.Stat(); err == nil {
+ conf.mtime = fi.ModTime()
+ } else {
+ conf.servers = defaultNS
+ conf.search = dnsDefaultSearch()
+ conf.err = err
+ return conf
+ }
+ for line, ok := file.readLine(); ok; line, ok = file.readLine() {
+ if len(line) > 0 && (line[0] == ';' || line[0] == '#') {
+ // comment.
+ continue
+ }
+ f := getFields(line)
+ if len(f) < 1 {
+ continue
+ }
+ switch f[0] {
+ case "nameserver": // add one name server
+ if len(f) > 1 && len(conf.servers) < 3 { // small, but the standard limit
+ // One more check: make sure server name is
+ // just an IP address. Otherwise we need DNS
+ // to look it up.
+ if _, err := netip.ParseAddr(f[1]); err == nil {
+ conf.servers = append(conf.servers, JoinHostPort(f[1], "53"))
+ }
+ }
+
+ case "domain": // set search path to just this domain
+ if len(f) > 1 {
+ conf.search = []string{ensureRooted(f[1])}
+ }
+
+ case "search": // set search path to given servers
+ conf.search = make([]string, 0, len(f)-1)
+ for i := 1; i < len(f); i++ {
+ name := ensureRooted(f[i])
+ if name == "." {
+ continue
+ }
+ conf.search = append(conf.search, name)
+ }
+
+ case "options": // magic options
+ for _, s := range f[1:] {
+ switch {
+ case hasPrefix(s, "ndots:"):
+ n, _, _ := dtoi(s[6:])
+ if n < 0 {
+ n = 0
+ } else if n > 15 {
+ n = 15
+ }
+ conf.ndots = n
+ case hasPrefix(s, "timeout:"):
+ n, _, _ := dtoi(s[8:])
+ if n < 1 {
+ n = 1
+ }
+ conf.timeout = time.Duration(n) * time.Second
+ case hasPrefix(s, "attempts:"):
+ n, _, _ := dtoi(s[9:])
+ if n < 1 {
+ n = 1
+ }
+ conf.attempts = n
+ case s == "rotate":
+ conf.rotate = true
+ case s == "single-request" || s == "single-request-reopen":
+ // Linux option:
+ // http://man7.org/linux/man-pages/man5/resolv.conf.5.html
+ // "By default, glibc performs IPv4 and IPv6 lookups in parallel [...]
+ // This option disables the behavior and makes glibc
+ // perform the IPv6 and IPv4 requests sequentially."
+ conf.singleRequest = true
+ case s == "use-vc" || s == "usevc" || s == "tcp":
+ // Linux (use-vc), FreeBSD (usevc) and OpenBSD (tcp) option:
+ // http://man7.org/linux/man-pages/man5/resolv.conf.5.html
+ // "Sets RES_USEVC in _res.options.
+ // This option forces the use of TCP for DNS resolutions."
+ // https://www.freebsd.org/cgi/man.cgi?query=resolv.conf&sektion=5&manpath=freebsd-release-ports
+ // https://man.openbsd.org/resolv.conf.5
+ conf.useTCP = true
+ case s == "trust-ad":
+ conf.trustAD = true
+ case s == "edns0":
+ // We use EDNS by default.
+ // Ignore this option.
+ case s == "no-reload":
+ conf.noReload = true
+ default:
+ conf.unknownOpt = true
+ }
+ }
+
+ case "lookup":
+ // OpenBSD option:
+ // https://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/resolv.conf.5
+ // "the legal space-separated values are: bind, file, yp"
+ conf.lookup = f[1:]
+
+ default:
+ conf.unknownOpt = true
+ }
+ }
+ if len(conf.servers) == 0 {
+ conf.servers = defaultNS
+ }
+ if len(conf.search) == 0 {
+ conf.search = dnsDefaultSearch()
+ }
+ return conf
+}
+
+func dnsDefaultSearch() []string {
+ hn, err := getHostname()
+ if err != nil {
+ // best effort
+ return nil
+ }
+ if i := bytealg.IndexByteString(hn, '.'); i >= 0 && i < len(hn)-1 {
+ return []string{ensureRooted(hn[i+1:])}
+ }
+ return nil
+}
+
+func hasPrefix(s, prefix string) bool {
+ return len(s) >= len(prefix) && s[:len(prefix)] == prefix
+}
+
+func ensureRooted(s string) string {
+ if len(s) > 0 && s[len(s)-1] == '.' {
+ return s
+ }
+ return s + "."
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsconfig_unix_test.go b/platform/dbops/binaries/go/go/src/net/dnsconfig_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0aae2ba85b8c32377c55c01d5f18715846711597
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsconfig_unix_test.go
@@ -0,0 +1,314 @@
+// 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 unix
+
+package net
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+var dnsReadConfigTests = []struct {
+ name string
+ want *dnsConfig
+}{
+ {
+ name: "testdata/resolv.conf",
+ want: &dnsConfig{
+ servers: []string{"8.8.8.8:53", "[2001:4860:4860::8888]:53", "[fe80::1%lo0]:53"},
+ search: []string{"localdomain."},
+ ndots: 5,
+ timeout: 10 * time.Second,
+ attempts: 3,
+ rotate: true,
+ unknownOpt: true, // the "options attempts 3" line
+ },
+ },
+ {
+ name: "testdata/domain-resolv.conf",
+ want: &dnsConfig{
+ servers: []string{"8.8.8.8:53"},
+ search: []string{"localdomain."},
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ },
+ },
+ {
+ name: "testdata/search-resolv.conf",
+ want: &dnsConfig{
+ servers: []string{"8.8.8.8:53"},
+ search: []string{"test.", "invalid."},
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ },
+ },
+ {
+ name: "testdata/search-single-dot-resolv.conf",
+ want: &dnsConfig{
+ servers: []string{"8.8.8.8:53"},
+ search: []string{},
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ },
+ },
+ {
+ name: "testdata/empty-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/invalid-ndots-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 0,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/large-ndots-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 15,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/negative-ndots-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 0,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/openbsd-resolv.conf",
+ want: &dnsConfig{
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ lookup: []string{"file", "bind"},
+ servers: []string{"169.254.169.254:53", "10.240.0.1:53"},
+ search: []string{"c.symbolic-datum-552.internal."},
+ },
+ },
+ {
+ name: "testdata/single-request-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ singleRequest: true,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/single-request-reopen-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ singleRequest: true,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/linux-use-vc-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ useTCP: true,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/freebsd-usevc-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ useTCP: true,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+ {
+ name: "testdata/openbsd-tcp-resolv.conf",
+ want: &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ useTCP: true,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ },
+ },
+}
+
+func TestDNSReadConfig(t *testing.T) {
+ origGetHostname := getHostname
+ defer func() { getHostname = origGetHostname }()
+ getHostname = func() (string, error) { return "host.domain.local", nil }
+
+ for _, tt := range dnsReadConfigTests {
+ want := *tt.want
+ if len(want.search) == 0 {
+ want.search = dnsDefaultSearch()
+ }
+ conf := dnsReadConfig(tt.name)
+ if conf.err != nil {
+ t.Fatal(conf.err)
+ }
+ conf.mtime = time.Time{}
+ if !reflect.DeepEqual(conf, &want) {
+ t.Errorf("%s:\ngot: %+v\nwant: %+v", tt.name, conf, want)
+ }
+ }
+}
+
+func TestDNSReadMissingFile(t *testing.T) {
+ origGetHostname := getHostname
+ defer func() { getHostname = origGetHostname }()
+ getHostname = func() (string, error) { return "host.domain.local", nil }
+
+ conf := dnsReadConfig("a-nonexistent-file")
+ if !os.IsNotExist(conf.err) {
+ t.Errorf("missing resolv.conf:\ngot: %v\nwant: %v", conf.err, fs.ErrNotExist)
+ }
+ conf.err = nil
+ want := &dnsConfig{
+ servers: defaultNS,
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ search: []string{"domain.local."},
+ }
+ if !reflect.DeepEqual(conf, want) {
+ t.Errorf("missing resolv.conf:\ngot: %+v\nwant: %+v", conf, want)
+ }
+}
+
+var dnsDefaultSearchTests = []struct {
+ name string
+ err error
+ want []string
+}{
+ {
+ name: "host.long.domain.local",
+ want: []string{"long.domain.local."},
+ },
+ {
+ name: "host.local",
+ want: []string{"local."},
+ },
+ {
+ name: "host",
+ want: nil,
+ },
+ {
+ name: "host.domain.local",
+ err: errors.New("errored"),
+ want: nil,
+ },
+ {
+ // ensures we don't return []string{""}
+ // which causes duplicate lookups
+ name: "foo.",
+ want: nil,
+ },
+}
+
+func TestDNSDefaultSearch(t *testing.T) {
+ origGetHostname := getHostname
+ defer func() { getHostname = origGetHostname }()
+
+ for _, tt := range dnsDefaultSearchTests {
+ getHostname = func() (string, error) { return tt.name, tt.err }
+ got := dnsDefaultSearch()
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("dnsDefaultSearch with hostname %q and error %+v = %q, wanted %q", tt.name, tt.err, got, tt.want)
+ }
+ }
+}
+
+func TestDNSNameLength(t *testing.T) {
+ origGetHostname := getHostname
+ defer func() { getHostname = origGetHostname }()
+ getHostname = func() (string, error) { return "host.domain.local", nil }
+
+ var char63 = ""
+ for i := 0; i < 63; i++ {
+ char63 += "a"
+ }
+ longDomain := strings.Repeat(char63+".", 5) + "example"
+
+ for _, tt := range dnsReadConfigTests {
+ conf := dnsReadConfig(tt.name)
+ if conf.err != nil {
+ t.Fatal(conf.err)
+ }
+
+ suffixList := tt.want.search
+ if len(suffixList) == 0 {
+ suffixList = dnsDefaultSearch()
+ }
+
+ var shortestSuffix int
+ for _, suffix := range suffixList {
+ if shortestSuffix == 0 || len(suffix) < shortestSuffix {
+ shortestSuffix = len(suffix)
+ }
+ }
+
+ // Test a name that will be maximally long when prefixing the shortest
+ // suffix (accounting for the intervening dot).
+ longName := longDomain[len(longDomain)-254+1+shortestSuffix:]
+ if longName[0] == '.' || longName[1] == '.' {
+ longName = "aa." + longName[3:]
+ }
+ for _, fqdn := range conf.nameList(longName) {
+ if len(fqdn) > 254 {
+ t.Errorf("got %d; want less than or equal to 254", len(fqdn))
+ }
+ }
+
+ // Now test a name that's too long for suffixing.
+ unsuffixable := "a." + longName[1:]
+ unsuffixableResults := conf.nameList(unsuffixable)
+ if len(unsuffixableResults) != 1 {
+ t.Errorf("suffixed names %v; want []", unsuffixableResults[1:])
+ }
+
+ // Now test a name that's too long for DNS.
+ tooLong := "a." + longDomain
+ tooLongResults := conf.nameList(tooLong)
+ if tooLongResults != nil {
+ t.Errorf("suffixed names %v; want nil", tooLongResults)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsconfig_windows.go b/platform/dbops/binaries/go/go/src/net/dnsconfig_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..f3d242366ae2cd59f50672286277298bff8afd66
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsconfig_windows.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 net
+
+import (
+ "internal/syscall/windows"
+ "syscall"
+ "time"
+)
+
+func dnsReadConfig(ignoredFilename string) (conf *dnsConfig) {
+ conf = &dnsConfig{
+ ndots: 1,
+ timeout: 5 * time.Second,
+ attempts: 2,
+ }
+ defer func() {
+ if len(conf.servers) == 0 {
+ conf.servers = defaultNS
+ }
+ }()
+ aas, err := adapterAddresses()
+ if err != nil {
+ return
+ }
+ // TODO(bradfitz): this just collects all the DNS servers on all
+ // the interfaces in some random order. It should order it by
+ // default route, or only use the default route(s) instead.
+ // In practice, however, it mostly works.
+ for _, aa := range aas {
+ for dns := aa.FirstDnsServerAddress; dns != nil; dns = dns.Next {
+ // Only take interfaces whose OperStatus is IfOperStatusUp(0x01) into DNS configs.
+ if aa.OperStatus != windows.IfOperStatusUp {
+ continue
+ }
+ sa, err := dns.Address.Sockaddr.Sockaddr()
+ if err != nil {
+ continue
+ }
+ var ip IP
+ switch sa := sa.(type) {
+ case *syscall.SockaddrInet4:
+ ip = IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])
+ case *syscall.SockaddrInet6:
+ ip = make(IP, IPv6len)
+ copy(ip, sa.Addr[:])
+ if ip[0] == 0xfe && ip[1] == 0xc0 {
+ // Ignore these fec0/10 ones. Windows seems to
+ // populate them as defaults on its misc rando
+ // interfaces.
+ continue
+ }
+ default:
+ // Unexpected type.
+ continue
+ }
+ conf.servers = append(conf.servers, JoinHostPort(ip.String(), "53"))
+ }
+ }
+ return conf
+}
diff --git a/platform/dbops/binaries/go/go/src/net/dnsname_test.go b/platform/dbops/binaries/go/go/src/net/dnsname_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..601a33af9f4c0af4ea06c7d780064ed69a60112e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/dnsname_test.go
@@ -0,0 +1,84 @@
+// 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 net
+
+import (
+ "strings"
+ "testing"
+)
+
+type dnsNameTest struct {
+ name string
+ result bool
+}
+
+var dnsNameTests = []dnsNameTest{
+ // RFC 2181, section 11.
+ {"_xmpp-server._tcp.google.com", true},
+ {"foo.com", true},
+ {"1foo.com", true},
+ {"26.0.0.73.com", true},
+ {"10-0-0-1", true},
+ {"fo-o.com", true},
+ {"fo1o.com", true},
+ {"foo1.com", true},
+ {"a.b..com", false},
+ {"a.b-.com", false},
+ {"a.b.com-", false},
+ {"a.b..", false},
+ {"b.com.", true},
+}
+
+func emitDNSNameTest(ch chan<- dnsNameTest) {
+ defer close(ch)
+ var char63 = ""
+ for i := 0; i < 63; i++ {
+ char63 += "a"
+ }
+ char64 := char63 + "a"
+ longDomain := strings.Repeat(char63+".", 5) + "example"
+
+ for _, tc := range dnsNameTests {
+ ch <- tc
+ }
+
+ ch <- dnsNameTest{char63 + ".com", true}
+ ch <- dnsNameTest{char64 + ".com", false}
+
+ // Remember: wire format is two octets longer than presentation
+ // (length octets for the first and [root] last labels).
+ // 253 is fine:
+ ch <- dnsNameTest{longDomain[len(longDomain)-253:], true}
+ // A terminal dot doesn't contribute to length:
+ ch <- dnsNameTest{longDomain[len(longDomain)-253:] + ".", true}
+ // 254 is bad:
+ ch <- dnsNameTest{longDomain[len(longDomain)-254:], false}
+}
+
+func TestDNSName(t *testing.T) {
+ ch := make(chan dnsNameTest)
+ go emitDNSNameTest(ch)
+ for tc := range ch {
+ if isDomainName(tc.name) != tc.result {
+ t.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
+ }
+ }
+}
+
+func BenchmarkDNSName(b *testing.B) {
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ benchmarks := append(dnsNameTests, []dnsNameTest{
+ {strings.Repeat("a", 63), true},
+ {strings.Repeat("a", 64), false},
+ }...)
+ for n := 0; n < b.N; n++ {
+ for _, tc := range benchmarks {
+ if isDomainName(tc.name) != tc.result {
+ b.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_plan9.go b/platform/dbops/binaries/go/go/src/net/error_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..caad133b774dc5c43e60a06fedb0502ea3948d9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_plan9.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 net
+
+func isConnError(err error) bool {
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_plan9_test.go b/platform/dbops/binaries/go/go/src/net/error_plan9_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f86c96c0d2fbac145fa22f8f4983373e171e222f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_plan9_test.go
@@ -0,0 +1,22 @@
+// 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 net
+
+import "syscall"
+
+var (
+ errOpNotSupported = syscall.EPLAN9
+
+ abortedConnRequestErrors []error
+)
+
+func isPlatformError(err error) bool {
+ _, ok := err.(syscall.ErrorString)
+ return ok
+}
+
+func isENOBUFS(err error) bool {
+ return false // ENOBUFS is Unix-specific
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_posix.go b/platform/dbops/binaries/go/go/src/net/error_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..84f80440454b37dd01d6e01f56c7422d2f63e15c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_posix.go
@@ -0,0 +1,21 @@
+// 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 unix || js || wasip1 || windows
+
+package net
+
+import (
+ "os"
+ "syscall"
+)
+
+// wrapSyscallError takes an error and a syscall name. If the error is
+// a syscall.Errno, it wraps it in an os.SyscallError using the syscall name.
+func wrapSyscallError(name string, err error) error {
+ if _, ok := err.(syscall.Errno); ok {
+ err = os.NewSyscallError(name, err)
+ }
+ return err
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_posix_test.go b/platform/dbops/binaries/go/go/src/net/error_posix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..081176f771aebf72fa02563e862e82da678dc3f8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_posix_test.go
@@ -0,0 +1,34 @@
+// 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 !plan9
+
+package net
+
+import (
+ "os"
+ "syscall"
+ "testing"
+)
+
+func TestSpuriousENOTAVAIL(t *testing.T) {
+ for _, tt := range []struct {
+ error
+ ok bool
+ }{
+ {syscall.EADDRNOTAVAIL, true},
+ {&os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}, true},
+ {&OpError{Op: "op", Err: syscall.EADDRNOTAVAIL}, true},
+ {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EADDRNOTAVAIL}}, true},
+
+ {syscall.EINVAL, false},
+ {&os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}, false},
+ {&OpError{Op: "op", Err: syscall.EINVAL}, false},
+ {&OpError{Op: "op", Err: &os.SyscallError{Syscall: "syscall", Err: syscall.EINVAL}}, false},
+ } {
+ if ok := spuriousENOTAVAIL(tt.error); ok != tt.ok {
+ t.Errorf("spuriousENOTAVAIL(%v) = %v; want %v", tt.error, ok, tt.ok)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_test.go b/platform/dbops/binaries/go/go/src/net/error_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..f82e8633464176f95c49c1148729e63054cf9ff0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_test.go
@@ -0,0 +1,824 @@
+// 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 net
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "internal/poll"
+ "io"
+ "io/fs"
+ "net/internal/socktest"
+ "os"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func (e *OpError) isValid() error {
+ if e.Op == "" {
+ return fmt.Errorf("OpError.Op is empty: %v", e)
+ }
+ if e.Net == "" {
+ return fmt.Errorf("OpError.Net is empty: %v", e)
+ }
+ for _, addr := range []Addr{e.Source, e.Addr} {
+ switch addr := addr.(type) {
+ case nil:
+ case *TCPAddr:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case *UDPAddr:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case *IPAddr:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case *IPNet:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case *UnixAddr:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case *pipeAddr:
+ if addr == nil {
+ return fmt.Errorf("OpError.Source or Addr is non-nil interface: %#v, %v", addr, e)
+ }
+ case fileAddr:
+ if addr == "" {
+ return fmt.Errorf("OpError.Source or Addr is empty: %#v, %v", addr, e)
+ }
+ default:
+ return fmt.Errorf("OpError.Source or Addr is unknown type: %T, %v", addr, e)
+ }
+ }
+ if e.Err == nil {
+ return fmt.Errorf("OpError.Err is empty: %v", e)
+ }
+ return nil
+}
+
+// parseDialError parses nestedErr and reports whether it is a valid
+// error value from Dial, Listen functions.
+// It returns nil when nestedErr is valid.
+func parseDialError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *AddrError, *timeoutError, *DNSError, InvalidAddrError, *ParseError, *poll.DeadlineExceededError, UnknownNetworkError:
+ return nil
+ case interface{ isAddrinfoErrno() }:
+ return nil
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ case *fs.PathError: // for Plan 9
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case errCanceled, ErrClosed, errMissingAddress, errNoSuitableAddress,
+ context.DeadlineExceeded, context.Canceled:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+var dialErrorTests = []struct {
+ network, address string
+}{
+ {"foo", ""},
+ {"bar", "baz"},
+ {"datakit", "mh/astro/r70"},
+ {"tcp", ""},
+ {"tcp", "127.0.0.1:☺"},
+ {"tcp", "no-such-name:80"},
+ {"tcp", "mh/astro/r70:http"},
+
+ {"tcp", JoinHostPort("127.0.0.1", "-1")},
+ {"tcp", JoinHostPort("127.0.0.1", "123456789")},
+ {"udp", JoinHostPort("127.0.0.1", "-1")},
+ {"udp", JoinHostPort("127.0.0.1", "123456789")},
+ {"ip:icmp", "127.0.0.1"},
+
+ {"unix", "/path/to/somewhere"},
+ {"unixgram", "/path/to/somewhere"},
+ {"unixpacket", "/path/to/somewhere"},
+}
+
+func TestDialError(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
+ }
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
+ return nil, &DNSError{Err: "dial error test", Name: "name", Server: "server", IsTimeout: true}
+ }
+ sw.Set(socktest.FilterConnect, func(so *socktest.Status) (socktest.AfterFilter, error) {
+ return nil, errOpNotSupported
+ })
+ defer sw.Set(socktest.FilterConnect, nil)
+
+ d := Dialer{Timeout: someTimeout}
+ for i, tt := range dialErrorTests {
+ i, tt := i, tt
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ c, err := d.Dial(tt.network, tt.address)
+ if err == nil {
+ t.Errorf("should fail; %s:%s->%s", c.LocalAddr().Network(), c.LocalAddr(), c.RemoteAddr())
+ c.Close()
+ return
+ }
+ if tt.network == "tcp" || tt.network == "udp" {
+ nerr := err
+ if op, ok := nerr.(*OpError); ok {
+ nerr = op.Err
+ }
+ if sys, ok := nerr.(*os.SyscallError); ok {
+ nerr = sys.Err
+ }
+ if nerr == errOpNotSupported {
+ t.Fatalf("should fail without %v; %s:%s->", nerr, tt.network, tt.address)
+ }
+ }
+ if c != nil {
+ t.Errorf("Dial returned non-nil interface %T(%v) with err != nil", c, c)
+ }
+ if err = parseDialError(err); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+}
+
+func TestProtocolDialError(t *testing.T) {
+ switch runtime.GOOS {
+ case "solaris", "illumos":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ for _, network := range []string{"tcp", "udp", "ip:4294967296", "unix", "unixpacket", "unixgram"} {
+ var err error
+ switch network {
+ case "tcp":
+ _, err = DialTCP(network, nil, &TCPAddr{Port: 1 << 16})
+ case "udp":
+ _, err = DialUDP(network, nil, &UDPAddr{Port: 1 << 16})
+ case "ip:4294967296":
+ _, err = DialIP(network, nil, nil)
+ case "unix", "unixpacket", "unixgram":
+ _, err = DialUnix(network, nil, &UnixAddr{Name: "//"})
+ }
+ if err == nil {
+ t.Errorf("%s: should fail", network)
+ continue
+ }
+ if err := parseDialError(err); err != nil {
+ t.Errorf("%s: %v", network, err)
+ continue
+ }
+ t.Logf("%s: error as expected: %v", network, err)
+ }
+}
+
+func TestDialAddrError(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ if !supportsIPv4() || !supportsIPv6() {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ for _, tt := range []struct {
+ network string
+ lit string
+ addr *TCPAddr
+ }{
+ {"tcp4", "::1", nil},
+ {"tcp4", "", &TCPAddr{IP: IPv6loopback}},
+ // We don't test the {"tcp6", "byte sequence", nil}
+ // case for now because there is no easy way to
+ // control name resolution.
+ {"tcp6", "", &TCPAddr{IP: IP{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}}},
+ } {
+ desc := tt.lit
+ if desc == "" {
+ desc = tt.addr.String()
+ }
+ t.Run(fmt.Sprintf("%s/%s", tt.network, desc), func(t *testing.T) {
+ var err error
+ var c Conn
+ var op string
+ if tt.lit != "" {
+ c, err = Dial(tt.network, JoinHostPort(tt.lit, "0"))
+ op = fmt.Sprintf("Dial(%q, %q)", tt.network, JoinHostPort(tt.lit, "0"))
+ } else {
+ c, err = DialTCP(tt.network, nil, tt.addr)
+ op = fmt.Sprintf("DialTCP(%q, %q)", tt.network, tt.addr)
+ }
+ t.Logf("%s: %v", op, err)
+ if err == nil {
+ c.Close()
+ t.Fatalf("%s succeeded, want error", op)
+ }
+ if perr := parseDialError(err); perr != nil {
+ t.Fatal(perr)
+ }
+ operr := err.(*OpError).Err
+ aerr, ok := operr.(*AddrError)
+ if !ok {
+ t.Fatalf("OpError.Err is %T, want *AddrError", operr)
+ }
+ want := tt.lit
+ if tt.lit == "" {
+ want = tt.addr.IP.String()
+ }
+ if aerr.Addr != want {
+ t.Errorf("error Addr=%q, want %q", aerr.Addr, want)
+ }
+ })
+ }
+}
+
+var listenErrorTests = []struct {
+ network, address string
+}{
+ {"foo", ""},
+ {"bar", "baz"},
+ {"datakit", "mh/astro/r70"},
+ {"tcp", "127.0.0.1:☺"},
+ {"tcp", "no-such-name:80"},
+ {"tcp", "mh/astro/r70:http"},
+
+ {"tcp", JoinHostPort("127.0.0.1", "-1")},
+ {"tcp", JoinHostPort("127.0.0.1", "123456789")},
+
+ {"unix", "/path/to/somewhere"},
+ {"unixpacket", "/path/to/somewhere"},
+}
+
+func TestListenError(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
+ }
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = func(_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
+ return nil, &DNSError{Err: "listen error test", Name: "name", Server: "server", IsTimeout: true}
+ }
+ sw.Set(socktest.FilterListen, func(so *socktest.Status) (socktest.AfterFilter, error) {
+ return nil, errOpNotSupported
+ })
+ defer sw.Set(socktest.FilterListen, nil)
+
+ for i, tt := range listenErrorTests {
+ t.Run(fmt.Sprintf("%s_%s", tt.network, tt.address), func(t *testing.T) {
+ ln, err := Listen(tt.network, tt.address)
+ if err == nil {
+ t.Errorf("#%d: should fail; %s:%s->", i, ln.Addr().Network(), ln.Addr())
+ ln.Close()
+ return
+ }
+ if tt.network == "tcp" {
+ nerr := err
+ if op, ok := nerr.(*OpError); ok {
+ nerr = op.Err
+ }
+ if sys, ok := nerr.(*os.SyscallError); ok {
+ nerr = sys.Err
+ }
+ if nerr == errOpNotSupported {
+ t.Fatalf("#%d: should fail without %v; %s:%s->", i, nerr, tt.network, tt.address)
+ }
+ }
+ if ln != nil {
+ t.Errorf("Listen returned non-nil interface %T(%v) with err != nil", ln, ln)
+ }
+ if err = parseDialError(err); err != nil {
+ t.Errorf("#%d: %v", i, err)
+ }
+ })
+ }
+}
+
+var listenPacketErrorTests = []struct {
+ network, address string
+}{
+ {"foo", ""},
+ {"bar", "baz"},
+ {"datakit", "mh/astro/r70"},
+ {"udp", "127.0.0.1:☺"},
+ {"udp", "no-such-name:80"},
+ {"udp", "mh/astro/r70:http"},
+
+ {"udp", JoinHostPort("127.0.0.1", "-1")},
+ {"udp", JoinHostPort("127.0.0.1", "123456789")},
+}
+
+func TestListenPacketError(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
+ }
+
+ origTestHookLookupIP := testHookLookupIP
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
+ testHookLookupIP = func(_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
+ return nil, &DNSError{Err: "listen error test", Name: "name", Server: "server", IsTimeout: true}
+ }
+
+ for i, tt := range listenPacketErrorTests {
+ t.Run(fmt.Sprintf("%s_%s", tt.network, tt.address), func(t *testing.T) {
+ c, err := ListenPacket(tt.network, tt.address)
+ if err == nil {
+ t.Errorf("#%d: should fail; %s:%s->", i, c.LocalAddr().Network(), c.LocalAddr())
+ c.Close()
+ return
+ }
+ if c != nil {
+ t.Errorf("ListenPacket returned non-nil interface %T(%v) with err != nil", c, c)
+ }
+ if err = parseDialError(err); err != nil {
+ t.Errorf("#%d: %v", i, err)
+ }
+ })
+ }
+}
+
+func TestProtocolListenError(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ for _, network := range []string{"tcp", "udp", "ip:4294967296", "unix", "unixpacket", "unixgram"} {
+ var err error
+ switch network {
+ case "tcp":
+ _, err = ListenTCP(network, &TCPAddr{Port: 1 << 16})
+ case "udp":
+ _, err = ListenUDP(network, &UDPAddr{Port: 1 << 16})
+ case "ip:4294967296":
+ _, err = ListenIP(network, nil)
+ case "unix", "unixpacket":
+ _, err = ListenUnix(network, &UnixAddr{Name: "//"})
+ case "unixgram":
+ _, err = ListenUnixgram(network, &UnixAddr{Name: "//"})
+ }
+ if err == nil {
+ t.Errorf("%s: should fail", network)
+ continue
+ }
+ if err = parseDialError(err); err != nil {
+ t.Errorf("%s: %v", network, err)
+ continue
+ }
+ }
+}
+
+// parseReadError parses nestedErr and reports whether it is a valid
+// error value from Read functions.
+// It returns nil when nestedErr is valid.
+func parseReadError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ if nestedErr == io.EOF {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case ErrClosed, errTimeout, poll.ErrNotPollable, os.ErrDeadlineExceeded:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+// parseWriteError parses nestedErr and reports whether it is a valid
+// error value from Write functions.
+// It returns nil when nestedErr is valid.
+func parseWriteError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *AddrError, *timeoutError, *DNSError, InvalidAddrError, *ParseError, *poll.DeadlineExceededError, UnknownNetworkError:
+ return nil
+ case interface{ isAddrinfoErrno() }:
+ return nil
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case errCanceled, ErrClosed, errMissingAddress, errTimeout, os.ErrDeadlineExceeded, ErrWriteToConnected, io.ErrUnexpectedEOF:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+// parseCloseError parses nestedErr and reports whether it is a valid
+// error value from Close functions.
+// It returns nil when nestedErr is valid.
+func parseCloseError(nestedErr error, isShutdown bool) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ // Because historically we have not exported the error that we
+ // return for an operation on a closed network connection,
+ // there are programs that test for the exact error string.
+ // Verify that string here so that we don't break those
+ // programs unexpectedly. See issues #4373 and #19252.
+ want := "use of closed network connection"
+ if !isShutdown && !strings.Contains(nestedErr.Error(), want) {
+ return fmt.Errorf("error string %q does not contain expected string %q", nestedErr, want)
+ }
+
+ if !isShutdown && !errors.Is(nestedErr, ErrClosed) {
+ return fmt.Errorf("errors.Is(%v, errClosed) returns false, want true", nestedErr)
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ case *fs.PathError: // for Plan 9
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case ErrClosed:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch nestedErr {
+ case fs.ErrClosed: // for Plan 9
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+func TestCloseError(t *testing.T) {
+ t.Run("tcp", func(t *testing.T) {
+ ln := newLocalListener(t, "tcp")
+ defer ln.Close()
+ c, err := Dial(ln.Addr().Network(), ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+
+ for i := 0; i < 3; i++ {
+ err = c.(*TCPConn).CloseRead()
+ if perr := parseCloseError(err, true); perr != nil {
+ t.Errorf("#%d: %v", i, perr)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ err = c.(*TCPConn).CloseWrite()
+ if perr := parseCloseError(err, true); perr != nil {
+ t.Errorf("#%d: %v", i, perr)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ err = c.Close()
+ if perr := parseCloseError(err, false); perr != nil {
+ t.Errorf("#%d: %v", i, perr)
+ }
+ err = ln.Close()
+ if perr := parseCloseError(err, false); perr != nil {
+ t.Errorf("#%d: %v", i, perr)
+ }
+ }
+ })
+
+ t.Run("udp", func(t *testing.T) {
+ if !testableNetwork("udp") {
+ t.Skipf("skipping: udp not available")
+ }
+
+ pc, err := ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pc.Close()
+
+ for i := 0; i < 3; i++ {
+ err = pc.Close()
+ if perr := parseCloseError(err, false); perr != nil {
+ t.Errorf("#%d: %v", i, perr)
+ }
+ }
+ })
+}
+
+// parseAcceptError parses nestedErr and reports whether it is a valid
+// error value from Accept functions.
+// It returns nil when nestedErr is valid.
+func parseAcceptError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ case *fs.PathError: // for Plan 9
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case ErrClosed, errTimeout, poll.ErrNotPollable, os.ErrDeadlineExceeded:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+func TestAcceptError(t *testing.T) {
+ handler := func(ls *localServer, ln Listener) {
+ for {
+ ln.(*TCPListener).SetDeadline(time.Now().Add(5 * time.Millisecond))
+ c, err := ln.Accept()
+ if perr := parseAcceptError(err); perr != nil {
+ t.Error(perr)
+ }
+ if err != nil {
+ if c != nil {
+ t.Errorf("Accept returned non-nil interface %T(%v) with err != nil", c, c)
+ }
+ if nerr, ok := err.(Error); !ok || (!nerr.Timeout() && !nerr.Temporary()) {
+ return
+ }
+ continue
+ }
+ c.Close()
+ }
+ }
+ ls := newLocalServer(t, "tcp")
+ if err := ls.buildup(handler); err != nil {
+ ls.teardown()
+ t.Fatal(err)
+ }
+
+ time.Sleep(100 * time.Millisecond)
+ ls.teardown()
+}
+
+// parseCommonError parses nestedErr and reports whether it is a valid
+// error value from miscellaneous functions.
+// It returns nil when nestedErr is valid.
+func parseCommonError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch err := nestedErr.(type) {
+ case *OpError:
+ if err := err.isValid(); err != nil {
+ return err
+ }
+ nestedErr = err.Err
+ goto second
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+
+second:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ switch err := nestedErr.(type) {
+ case *os.SyscallError:
+ nestedErr = err.Err
+ goto third
+ case *os.LinkError:
+ nestedErr = err.Err
+ goto third
+ case *fs.PathError:
+ nestedErr = err.Err
+ goto third
+ }
+ switch nestedErr {
+ case ErrClosed:
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 2nd nested level: %T", nestedErr)
+
+third:
+ if isPlatformError(nestedErr) {
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 3rd nested level: %T", nestedErr)
+}
+
+func TestFileError(t *testing.T) {
+ switch runtime.GOOS {
+ case "windows":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ f, err := os.CreateTemp("", "go-nettest")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.Remove(f.Name())
+ defer f.Close()
+
+ c, err := FileConn(f)
+ if err != nil {
+ if c != nil {
+ t.Errorf("FileConn returned non-nil interface %T(%v) with err != nil", c, c)
+ }
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ } else {
+ c.Close()
+ t.Error("should fail")
+ }
+ ln, err := FileListener(f)
+ if err != nil {
+ if ln != nil {
+ t.Errorf("FileListener returned non-nil interface %T(%v) with err != nil", ln, ln)
+ }
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ } else {
+ ln.Close()
+ t.Error("should fail")
+ }
+ pc, err := FilePacketConn(f)
+ if err != nil {
+ if pc != nil {
+ t.Errorf("FilePacketConn returned non-nil interface %T(%v) with err != nil", pc, pc)
+ }
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ } else {
+ pc.Close()
+ t.Error("should fail")
+ }
+
+ ln = newLocalListener(t, "tcp")
+
+ for i := 0; i < 3; i++ {
+ f, err := ln.(*TCPListener).File()
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ } else {
+ f.Close()
+ }
+ ln.Close()
+ }
+}
+
+func parseLookupPortError(nestedErr error) error {
+ if nestedErr == nil {
+ return nil
+ }
+
+ switch nestedErr.(type) {
+ case *AddrError, *DNSError:
+ return nil
+ case *fs.PathError: // for Plan 9
+ return nil
+ }
+ return fmt.Errorf("unexpected type on 1st nested level: %T", nestedErr)
+}
+
+func TestContextError(t *testing.T) {
+ if !errors.Is(errCanceled, context.Canceled) {
+ t.Error("errCanceled is not context.Canceled")
+ }
+ if !errors.Is(errTimeout, context.DeadlineExceeded) {
+ t.Error("errTimeout is not context.DeadlineExceeded")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_unix.go b/platform/dbops/binaries/go/go/src/net/error_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..d6948670b6a305606753214e3f0398b5f4b6df9a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_unix.go
@@ -0,0 +1,16 @@
+// 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 unix || js || wasip1
+
+package net
+
+import "syscall"
+
+func isConnError(err error) bool {
+ if se, ok := err.(syscall.Errno); ok {
+ return se == syscall.ECONNRESET || se == syscall.ECONNABORTED
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_unix_test.go b/platform/dbops/binaries/go/go/src/net/error_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..963ba21f1a0ac1dd6ba05fe8886a258bdda6ee8d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_unix_test.go
@@ -0,0 +1,38 @@
+// 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 !plan9 && !windows
+
+package net
+
+import (
+ "errors"
+ "os"
+ "syscall"
+)
+
+var (
+ errOpNotSupported = syscall.EOPNOTSUPP
+
+ abortedConnRequestErrors = []error{syscall.ECONNABORTED} // see accept in fd_unix.go
+)
+
+func isPlatformError(err error) bool {
+ _, ok := err.(syscall.Errno)
+ return ok
+}
+
+func samePlatformError(err, want error) bool {
+ if op, ok := err.(*OpError); ok {
+ err = op.Err
+ }
+ if sys, ok := err.(*os.SyscallError); ok {
+ err = sys.Err
+ }
+ return err == want
+}
+
+func isENOBUFS(err error) bool {
+ return errors.Is(err, syscall.ENOBUFS)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_windows.go b/platform/dbops/binaries/go/go/src/net/error_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..570b97b278b7f90a46cdaadb74d73de3a1f45def
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_windows.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 net
+
+import "syscall"
+
+func isConnError(err error) bool {
+ if se, ok := err.(syscall.Errno); ok {
+ return se == syscall.WSAECONNRESET || se == syscall.WSAECONNABORTED
+ }
+ return false
+}
diff --git a/platform/dbops/binaries/go/go/src/net/error_windows_test.go b/platform/dbops/binaries/go/go/src/net/error_windows_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..7847af055160f332b06062dc7a6eb921efeb0b34
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/error_windows_test.go
@@ -0,0 +1,28 @@
+// 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 net
+
+import (
+ "errors"
+ "syscall"
+)
+
+var (
+ errOpNotSupported = syscall.EOPNOTSUPP
+
+ abortedConnRequestErrors = []error{syscall.ERROR_NETNAME_DELETED, syscall.WSAECONNRESET} // see accept in fd_windows.go
+)
+
+func isPlatformError(err error) bool {
+ _, ok := err.(syscall.Errno)
+ return ok
+}
+
+func isENOBUFS(err error) bool {
+ // syscall.ENOBUFS is a completely made-up value on Windows: we don't expect
+ // a real system call to ever actually return it. However, since it is already
+ // defined in the syscall package we may as well check for it.
+ return errors.Is(err, syscall.ENOBUFS)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/example_test.go b/platform/dbops/binaries/go/go/src/net/example_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..2c045d73a24bcb01ee8ea08f10afcac4ae305c03
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/example_test.go
@@ -0,0 +1,387 @@
+// 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 net_test
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "time"
+)
+
+func ExampleListener() {
+ // Listen on TCP port 2000 on all available unicast and
+ // anycast IP addresses of the local system.
+ l, err := net.Listen("tcp", ":2000")
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer l.Close()
+ for {
+ // Wait for a connection.
+ conn, err := l.Accept()
+ if err != nil {
+ log.Fatal(err)
+ }
+ // Handle the connection in a new goroutine.
+ // The loop then returns to accepting, so that
+ // multiple connections may be served concurrently.
+ go func(c net.Conn) {
+ // Echo all incoming data.
+ io.Copy(c, c)
+ // Shut down the connection.
+ c.Close()
+ }(conn)
+ }
+}
+
+func ExampleDialer() {
+ var d net.Dialer
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+
+ conn, err := d.DialContext(ctx, "tcp", "localhost:12345")
+ if err != nil {
+ log.Fatalf("Failed to dial: %v", err)
+ }
+ defer conn.Close()
+
+ if _, err := conn.Write([]byte("Hello, World!")); err != nil {
+ log.Fatal(err)
+ }
+}
+
+func ExampleDialer_unix() {
+ // DialUnix does not take a context.Context parameter. This example shows
+ // how to dial a Unix socket with a Context. Note that the Context only
+ // applies to the dial operation; it does not apply to the connection once
+ // it has been established.
+ var d net.Dialer
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+
+ d.LocalAddr = nil // if you have a local addr, add it here
+ raddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"}
+ conn, err := d.DialContext(ctx, "unix", raddr.String())
+ if err != nil {
+ log.Fatalf("Failed to dial: %v", err)
+ }
+ defer conn.Close()
+ if _, err := conn.Write([]byte("Hello, socket!")); err != nil {
+ log.Fatal(err)
+ }
+}
+
+func ExampleIPv4() {
+ fmt.Println(net.IPv4(8, 8, 8, 8))
+
+ // Output:
+ // 8.8.8.8
+}
+
+func ExampleParseCIDR() {
+ ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println(ipv4Addr)
+ fmt.Println(ipv4Net)
+
+ ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println(ipv6Addr)
+ fmt.Println(ipv6Net)
+
+ // Output:
+ // 192.0.2.1
+ // 192.0.2.0/24
+ // 2001:db8:a0b:12f0::1
+ // 2001:db8::/32
+}
+
+func ExampleParseIP() {
+ fmt.Println(net.ParseIP("192.0.2.1"))
+ fmt.Println(net.ParseIP("2001:db8::68"))
+ fmt.Println(net.ParseIP("192.0.2"))
+
+ // Output:
+ // 192.0.2.1
+ // 2001:db8::68
+ //
+}
+
+func ExampleIP_DefaultMask() {
+ ip := net.ParseIP("192.0.2.1")
+ fmt.Println(ip.DefaultMask())
+
+ // Output:
+ // ffffff00
+}
+
+func ExampleIP_Equal() {
+ ipv4DNS := net.ParseIP("8.8.8.8")
+ ipv4Lo := net.ParseIP("127.0.0.1")
+ ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808")
+
+ fmt.Println(ipv4DNS.Equal(ipv4DNS))
+ fmt.Println(ipv4DNS.Equal(ipv4Lo))
+ fmt.Println(ipv4DNS.Equal(ipv6DNS))
+
+ // Output:
+ // true
+ // false
+ // true
+}
+
+func ExampleIP_IsGlobalUnicast() {
+ ipv6Global := net.ParseIP("2000::")
+ ipv6UniqLocal := net.ParseIP("2000::")
+ ipv6Multi := net.ParseIP("FF00::")
+
+ ipv4Private := net.ParseIP("10.255.0.0")
+ ipv4Public := net.ParseIP("8.8.8.8")
+ ipv4Broadcast := net.ParseIP("255.255.255.255")
+
+ fmt.Println(ipv6Global.IsGlobalUnicast())
+ fmt.Println(ipv6UniqLocal.IsGlobalUnicast())
+ fmt.Println(ipv6Multi.IsGlobalUnicast())
+
+ fmt.Println(ipv4Private.IsGlobalUnicast())
+ fmt.Println(ipv4Public.IsGlobalUnicast())
+ fmt.Println(ipv4Broadcast.IsGlobalUnicast())
+
+ // Output:
+ // true
+ // true
+ // false
+ // true
+ // true
+ // false
+}
+
+func ExampleIP_IsInterfaceLocalMulticast() {
+ ipv6InterfaceLocalMulti := net.ParseIP("ff01::1")
+ ipv6Global := net.ParseIP("2000::")
+ ipv4 := net.ParseIP("255.0.0.0")
+
+ fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast())
+ fmt.Println(ipv6Global.IsInterfaceLocalMulticast())
+ fmt.Println(ipv4.IsInterfaceLocalMulticast())
+
+ // Output:
+ // true
+ // false
+ // false
+}
+
+func ExampleIP_IsLinkLocalMulticast() {
+ ipv6LinkLocalMulti := net.ParseIP("ff02::2")
+ ipv6LinkLocalUni := net.ParseIP("fe80::")
+ ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+ ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
+
+ fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast())
+ fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast())
+ fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast())
+ fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast())
+
+ // Output:
+ // true
+ // false
+ // true
+ // false
+}
+
+func ExampleIP_IsLinkLocalUnicast() {
+ ipv6LinkLocalUni := net.ParseIP("fe80::")
+ ipv6Global := net.ParseIP("2000::")
+ ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
+ ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+
+ fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast())
+ fmt.Println(ipv6Global.IsLinkLocalUnicast())
+ fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast())
+ fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast())
+
+ // Output:
+ // true
+ // false
+ // true
+ // false
+}
+
+func ExampleIP_IsLoopback() {
+ ipv6Lo := net.ParseIP("::1")
+ ipv6 := net.ParseIP("ff02::1")
+ ipv4Lo := net.ParseIP("127.0.0.0")
+ ipv4 := net.ParseIP("128.0.0.0")
+
+ fmt.Println(ipv6Lo.IsLoopback())
+ fmt.Println(ipv6.IsLoopback())
+ fmt.Println(ipv4Lo.IsLoopback())
+ fmt.Println(ipv4.IsLoopback())
+
+ // Output:
+ // true
+ // false
+ // true
+ // false
+}
+
+func ExampleIP_IsMulticast() {
+ ipv6Multi := net.ParseIP("FF00::")
+ ipv6LinkLocalMulti := net.ParseIP("ff02::1")
+ ipv6Lo := net.ParseIP("::1")
+ ipv4Multi := net.ParseIP("239.0.0.0")
+ ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
+ ipv4Lo := net.ParseIP("127.0.0.0")
+
+ fmt.Println(ipv6Multi.IsMulticast())
+ fmt.Println(ipv6LinkLocalMulti.IsMulticast())
+ fmt.Println(ipv6Lo.IsMulticast())
+ fmt.Println(ipv4Multi.IsMulticast())
+ fmt.Println(ipv4LinkLocalMulti.IsMulticast())
+ fmt.Println(ipv4Lo.IsMulticast())
+
+ // Output:
+ // true
+ // true
+ // false
+ // true
+ // true
+ // false
+}
+
+func ExampleIP_IsPrivate() {
+ ipv6Private := net.ParseIP("fc00::")
+ ipv6Public := net.ParseIP("fe00::")
+ ipv4Private := net.ParseIP("10.255.0.0")
+ ipv4Public := net.ParseIP("11.0.0.0")
+
+ fmt.Println(ipv6Private.IsPrivate())
+ fmt.Println(ipv6Public.IsPrivate())
+ fmt.Println(ipv4Private.IsPrivate())
+ fmt.Println(ipv4Public.IsPrivate())
+
+ // Output:
+ // true
+ // false
+ // true
+ // false
+}
+
+func ExampleIP_IsUnspecified() {
+ ipv6Unspecified := net.ParseIP("::")
+ ipv6Specified := net.ParseIP("fe00::")
+ ipv4Unspecified := net.ParseIP("0.0.0.0")
+ ipv4Specified := net.ParseIP("8.8.8.8")
+
+ fmt.Println(ipv6Unspecified.IsUnspecified())
+ fmt.Println(ipv6Specified.IsUnspecified())
+ fmt.Println(ipv4Unspecified.IsUnspecified())
+ fmt.Println(ipv4Specified.IsUnspecified())
+
+ // Output:
+ // true
+ // false
+ // true
+ // false
+}
+
+func ExampleIP_Mask() {
+ ipv4Addr := net.ParseIP("192.0.2.1")
+ // This mask corresponds to a /24 subnet for IPv4.
+ ipv4Mask := net.CIDRMask(24, 32)
+ fmt.Println(ipv4Addr.Mask(ipv4Mask))
+
+ ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")
+ // This mask corresponds to a /32 subnet for IPv6.
+ ipv6Mask := net.CIDRMask(32, 128)
+ fmt.Println(ipv6Addr.Mask(ipv6Mask))
+
+ // Output:
+ // 192.0.2.0
+ // 2001:db8::
+}
+
+func ExampleIP_String() {
+ ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ ipv4 := net.IPv4(10, 255, 0, 0)
+
+ fmt.Println(ipv6.String())
+ fmt.Println(ipv4.String())
+
+ // Output:
+ // fc00::
+ // 10.255.0.0
+}
+
+func ExampleIP_To16() {
+ ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ ipv4 := net.IPv4(10, 255, 0, 0)
+
+ fmt.Println(ipv6.To16())
+ fmt.Println(ipv4.To16())
+
+ // Output:
+ // fc00::
+ // 10.255.0.0
+}
+
+func ExampleIP_to4() {
+ ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ ipv4 := net.IPv4(10, 255, 0, 0)
+
+ fmt.Println(ipv6.To4())
+ fmt.Println(ipv4.To4())
+
+ // Output:
+ //
+ // 10.255.0.0
+}
+
+func ExampleCIDRMask() {
+ // This mask corresponds to a /31 subnet for IPv4.
+ fmt.Println(net.CIDRMask(31, 32))
+
+ // This mask corresponds to a /64 subnet for IPv6.
+ fmt.Println(net.CIDRMask(64, 128))
+
+ // Output:
+ // fffffffe
+ // ffffffffffffffff0000000000000000
+}
+
+func ExampleIPv4Mask() {
+ fmt.Println(net.IPv4Mask(255, 255, 255, 0))
+
+ // Output:
+ // ffffff00
+}
+
+func ExampleUDPConn_WriteTo() {
+ // Unlike Dial, ListenPacket creates a connection without any
+ // association with peers.
+ conn, err := net.ListenPacket("udp", ":0")
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer conn.Close()
+
+ dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ // The connection can write data to the desired address.
+ _, err = conn.WriteTo([]byte("data"), dst)
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/external_test.go b/platform/dbops/binaries/go/go/src/net/external_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..38788efc3d39b7caf5b91c8a875842b1abfb6b8e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/external_test.go
@@ -0,0 +1,166 @@
+// 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 net
+
+import (
+ "fmt"
+ "internal/testenv"
+ "io"
+ "strings"
+ "testing"
+)
+
+func TestResolveGoogle(t *testing.T) {
+ testenv.MustHaveExternalNetwork(t)
+
+ if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ for _, network := range []string{"tcp", "tcp4", "tcp6"} {
+ addr, err := ResolveTCPAddr(network, "www.google.com:http")
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+ switch {
+ case network == "tcp" && addr.IP.To4() == nil:
+ fallthrough
+ case network == "tcp4" && addr.IP.To4() == nil:
+ t.Errorf("got %v; want an IPv4 address on %s", addr, network)
+ case network == "tcp6" && (addr.IP.To16() == nil || addr.IP.To4() != nil):
+ t.Errorf("got %v; want an IPv6 address on %s", addr, network)
+ }
+ }
+}
+
+var dialGoogleTests = []struct {
+ dial func(string, string) (Conn, error)
+ unreachableNetwork string
+ networks []string
+ addrs []string
+}{
+ {
+ dial: (&Dialer{DualStack: true}).Dial,
+ networks: []string{"tcp", "tcp4", "tcp6"},
+ addrs: []string{"www.google.com:http"},
+ },
+ {
+ dial: Dial,
+ unreachableNetwork: "tcp6",
+ networks: []string{"tcp", "tcp4"},
+ },
+ {
+ dial: Dial,
+ unreachableNetwork: "tcp4",
+ networks: []string{"tcp", "tcp6"},
+ },
+}
+
+func TestDialGoogle(t *testing.T) {
+ testenv.MustHaveExternalNetwork(t)
+
+ if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 {
+ t.Skip("both IPv4 and IPv6 are required")
+ }
+
+ var err error
+ dialGoogleTests[1].addrs, dialGoogleTests[2].addrs, err = googleLiteralAddrs()
+ if err != nil {
+ t.Error(err)
+ }
+ for _, tt := range dialGoogleTests {
+ for _, network := range tt.networks {
+ disableSocketConnect(tt.unreachableNetwork)
+ for _, addr := range tt.addrs {
+ if err := fetchGoogle(tt.dial, network, addr); err != nil {
+ t.Error(err)
+ }
+ }
+ enableSocketConnect()
+ }
+ }
+}
+
+var (
+ literalAddrs4 = [...]string{
+ "%d.%d.%d.%d:80",
+ "www.google.com:80",
+ "%d.%d.%d.%d:http",
+ "www.google.com:http",
+ "%03d.%03d.%03d.%03d:0080",
+ "[::ffff:%d.%d.%d.%d]:80",
+ "[::ffff:%02x%02x:%02x%02x]:80",
+ "[0:0:0:0:0000:ffff:%d.%d.%d.%d]:80",
+ "[0:0:0:0:000000:ffff:%d.%d.%d.%d]:80",
+ "[0:0:0:0::ffff:%d.%d.%d.%d]:80",
+ }
+ literalAddrs6 = [...]string{
+ "[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]:80",
+ "ipv6.google.com:80",
+ "[%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x]:http",
+ "ipv6.google.com:http",
+ }
+)
+
+func googleLiteralAddrs() (lits4, lits6 []string, err error) {
+ ips, err := LookupIP("www.google.com")
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(ips) == 0 {
+ return nil, nil, nil
+ }
+ var ip4, ip6 IP
+ for _, ip := range ips {
+ if ip4 == nil && ip.To4() != nil {
+ ip4 = ip.To4()
+ }
+ if ip6 == nil && ip.To16() != nil && ip.To4() == nil {
+ ip6 = ip.To16()
+ }
+ if ip4 != nil && ip6 != nil {
+ break
+ }
+ }
+ if ip4 != nil {
+ for i, lit4 := range literalAddrs4 {
+ if strings.Contains(lit4, "%") {
+ literalAddrs4[i] = fmt.Sprintf(lit4, ip4[0], ip4[1], ip4[2], ip4[3])
+ }
+ }
+ lits4 = literalAddrs4[:]
+ }
+ if ip6 != nil {
+ for i, lit6 := range literalAddrs6 {
+ if strings.Contains(lit6, "%") {
+ literalAddrs6[i] = fmt.Sprintf(lit6, ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15])
+ }
+ }
+ lits6 = literalAddrs6[:]
+ }
+ return
+}
+
+func fetchGoogle(dial func(string, string) (Conn, error), network, address string) error {
+ c, err := dial(network, address)
+ if err != nil {
+ return err
+ }
+ defer c.Close()
+ req := []byte("GET /robots.txt HTTP/1.0\r\nHost: www.google.com\r\n\r\n")
+ if _, err := c.Write(req); err != nil {
+ return err
+ }
+ b := make([]byte, 1000)
+ n, err := io.ReadFull(c, b)
+ if err != nil {
+ return err
+ }
+ if n < 1000 {
+ return fmt.Errorf("short read from %s:%s->%s", network, c.RemoteAddr(), c.LocalAddr())
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_fake.go b/platform/dbops/binaries/go/go/src/net/fd_fake.go
new file mode 100644
index 0000000000000000000000000000000000000000..ae567acc6994e65a42f99a4199acfbe38c50e0e9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_fake.go
@@ -0,0 +1,169 @@
+// 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 js || wasip1
+
+package net
+
+import (
+ "internal/poll"
+ "runtime"
+ "time"
+)
+
+const (
+ readSyscallName = "fd_read"
+ writeSyscallName = "fd_write"
+)
+
+// Network file descriptor.
+type netFD struct {
+ pfd poll.FD
+
+ // immutable until Close
+ family int
+ sotype int
+ isConnected bool // handshake completed or use of association with peer
+ net string
+ laddr Addr
+ raddr Addr
+
+ // The only networking available in WASI preview 1 is the ability to
+ // sock_accept on a pre-opened socket, and then fd_read, fd_write,
+ // fd_close, and sock_shutdown on the resulting connection. We
+ // intercept applicable netFD calls on this instance, and then pass
+ // the remainder of the netFD calls to fakeNetFD.
+ *fakeNetFD
+}
+
+func newFD(net string, sysfd int) *netFD {
+ return newPollFD(net, poll.FD{
+ Sysfd: sysfd,
+ IsStream: true,
+ ZeroReadIsEOF: true,
+ })
+}
+
+func newPollFD(net string, pfd poll.FD) *netFD {
+ var laddr Addr
+ var raddr Addr
+ // WASI preview 1 does not have functions like getsockname/getpeername,
+ // so we cannot get access to the underlying IP address used by connections.
+ //
+ // However, listeners created by FileListener are of type *TCPListener,
+ // which can be asserted by a Go program. The (*TCPListener).Addr method
+ // documents that the returned value will be of type *TCPAddr, we satisfy
+ // the documented behavior by creating addresses of the expected type here.
+ switch net {
+ case "tcp":
+ laddr = new(TCPAddr)
+ raddr = new(TCPAddr)
+ case "udp":
+ laddr = new(UDPAddr)
+ raddr = new(UDPAddr)
+ default:
+ laddr = unknownAddr{}
+ raddr = unknownAddr{}
+ }
+ return &netFD{
+ pfd: pfd,
+ net: net,
+ laddr: laddr,
+ raddr: raddr,
+ }
+}
+
+func (fd *netFD) init() error {
+ return fd.pfd.Init(fd.net, true)
+}
+
+func (fd *netFD) name() string {
+ return "unknown"
+}
+
+func (fd *netFD) accept() (netfd *netFD, err error) {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.accept(fd.laddr)
+ }
+ d, _, errcall, err := fd.pfd.Accept()
+ if err != nil {
+ if errcall != "" {
+ err = wrapSyscallError(errcall, err)
+ }
+ return nil, err
+ }
+ netfd = newFD("tcp", d)
+ if err = netfd.init(); err != nil {
+ netfd.Close()
+ return nil, err
+ }
+ return netfd, nil
+}
+
+func (fd *netFD) setAddr(laddr, raddr Addr) {
+ fd.laddr = laddr
+ fd.raddr = raddr
+ runtime.SetFinalizer(fd, (*netFD).Close)
+}
+
+func (fd *netFD) Close() error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.Close()
+ }
+ runtime.SetFinalizer(fd, nil)
+ return fd.pfd.Close()
+}
+
+func (fd *netFD) shutdown(how int) error {
+ if fd.fakeNetFD != nil {
+ return nil
+ }
+ err := fd.pfd.Shutdown(how)
+ runtime.KeepAlive(fd)
+ return wrapSyscallError("shutdown", err)
+}
+
+func (fd *netFD) Read(p []byte) (n int, err error) {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.Read(p)
+ }
+ n, err = fd.pfd.Read(p)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(readSyscallName, err)
+}
+
+func (fd *netFD) Write(p []byte) (nn int, err error) {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.Write(p)
+ }
+ nn, err = fd.pfd.Write(p)
+ runtime.KeepAlive(fd)
+ return nn, wrapSyscallError(writeSyscallName, err)
+}
+
+func (fd *netFD) SetDeadline(t time.Time) error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.SetDeadline(t)
+ }
+ return fd.pfd.SetDeadline(t)
+}
+
+func (fd *netFD) SetReadDeadline(t time.Time) error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.SetReadDeadline(t)
+ }
+ return fd.pfd.SetReadDeadline(t)
+}
+
+func (fd *netFD) SetWriteDeadline(t time.Time) error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.SetWriteDeadline(t)
+ }
+ return fd.pfd.SetWriteDeadline(t)
+}
+
+type unknownAddr struct{}
+
+func (unknownAddr) Network() string { return "unknown" }
+func (unknownAddr) String() string { return "unknown" }
diff --git a/platform/dbops/binaries/go/go/src/net/fd_js.go b/platform/dbops/binaries/go/go/src/net/fd_js.go
new file mode 100644
index 0000000000000000000000000000000000000000..0fce036ef13c1cef33a1d603397801c1c4ec5553
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_js.go
@@ -0,0 +1,28 @@
+// 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.
+
+// Fake networking for js/wasm. It is intended to allow tests of other package to pass.
+
+//go:build js
+
+package net
+
+import (
+ "os"
+ "syscall"
+)
+
+func (fd *netFD) closeRead() error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.closeRead()
+ }
+ return os.NewSyscallError("closeRead", syscall.ENOTSUP)
+}
+
+func (fd *netFD) closeWrite() error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.closeWrite()
+ }
+ return os.NewSyscallError("closeRead", syscall.ENOTSUP)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_plan9.go b/platform/dbops/binaries/go/go/src/net/fd_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..da41bc0c34cac599b0c916b240777084ecc7c402
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_plan9.go
@@ -0,0 +1,187 @@
+// 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 net
+
+import (
+ "internal/poll"
+ "io"
+ "os"
+ "syscall"
+ "time"
+)
+
+// Network file descriptor.
+type netFD struct {
+ pfd poll.FD
+
+ // immutable until Close
+ net string
+ n string
+ dir string
+ listen, ctl, data *os.File
+ laddr, raddr Addr
+ isStream bool
+}
+
+var netdir = "/net" // default network
+
+func newFD(net, name string, listen, ctl, data *os.File, laddr, raddr Addr) (*netFD, error) {
+ ret := &netFD{
+ net: net,
+ n: name,
+ dir: netdir + "/" + net + "/" + name,
+ listen: listen,
+ ctl: ctl, data: data,
+ laddr: laddr,
+ raddr: raddr,
+ }
+ ret.pfd.Destroy = ret.destroy
+ return ret, nil
+}
+
+func (fd *netFD) init() error {
+ // stub for future fd.pd.Init(fd)
+ return nil
+}
+
+func (fd *netFD) name() string {
+ var ls, rs string
+ if fd.laddr != nil {
+ ls = fd.laddr.String()
+ }
+ if fd.raddr != nil {
+ rs = fd.raddr.String()
+ }
+ return fd.net + ":" + ls + "->" + rs
+}
+
+func (fd *netFD) ok() bool { return fd != nil && fd.ctl != nil }
+
+func (fd *netFD) destroy() {
+ if !fd.ok() {
+ return
+ }
+ err := fd.ctl.Close()
+ if fd.data != nil {
+ if err1 := fd.data.Close(); err1 != nil && err == nil {
+ err = err1
+ }
+ }
+ if fd.listen != nil {
+ if err1 := fd.listen.Close(); err1 != nil && err == nil {
+ err = err1
+ }
+ }
+ fd.ctl = nil
+ fd.data = nil
+ fd.listen = nil
+}
+
+func (fd *netFD) Read(b []byte) (n int, err error) {
+ if !fd.ok() || fd.data == nil {
+ return 0, syscall.EINVAL
+ }
+ n, err = fd.pfd.Read(fd.data.Read, b)
+ if fd.net == "udp" && err == io.EOF {
+ n = 0
+ err = nil
+ }
+ return
+}
+
+func (fd *netFD) Write(b []byte) (n int, err error) {
+ if !fd.ok() || fd.data == nil {
+ return 0, syscall.EINVAL
+ }
+ return fd.pfd.Write(fd.data.Write, b)
+}
+
+func (fd *netFD) closeRead() error {
+ if !fd.ok() {
+ return syscall.EINVAL
+ }
+ return syscall.EPLAN9
+}
+
+func (fd *netFD) closeWrite() error {
+ if !fd.ok() {
+ return syscall.EINVAL
+ }
+ return syscall.EPLAN9
+}
+
+func (fd *netFD) Close() error {
+ if err := fd.pfd.Close(); err != nil {
+ return err
+ }
+ if !fd.ok() {
+ return syscall.EINVAL
+ }
+ if fd.net == "tcp" {
+ // The following line is required to unblock Reads.
+ _, err := fd.ctl.WriteString("close")
+ if err != nil {
+ return err
+ }
+ }
+ err := fd.ctl.Close()
+ if fd.data != nil {
+ if err1 := fd.data.Close(); err1 != nil && err == nil {
+ err = err1
+ }
+ }
+ if fd.listen != nil {
+ if err1 := fd.listen.Close(); err1 != nil && err == nil {
+ err = err1
+ }
+ }
+ fd.ctl = nil
+ fd.data = nil
+ fd.listen = nil
+ return err
+}
+
+// This method is only called via Conn.
+func (fd *netFD) dup() (*os.File, error) {
+ if !fd.ok() || fd.data == nil {
+ return nil, syscall.EINVAL
+ }
+ return fd.file(fd.data, fd.dir+"/data")
+}
+
+func (l *TCPListener) dup() (*os.File, error) {
+ if !l.fd.ok() {
+ return nil, syscall.EINVAL
+ }
+ return l.fd.file(l.fd.ctl, l.fd.dir+"/ctl")
+}
+
+func (fd *netFD) file(f *os.File, s string) (*os.File, error) {
+ dfd, err := syscall.Dup(int(f.Fd()), -1)
+ if err != nil {
+ return nil, os.NewSyscallError("dup", err)
+ }
+ return os.NewFile(uintptr(dfd), s), nil
+}
+
+func setReadBuffer(fd *netFD, bytes int) error {
+ return syscall.EPLAN9
+}
+
+func setWriteBuffer(fd *netFD, bytes int) error {
+ return syscall.EPLAN9
+}
+
+func (fd *netFD) SetDeadline(t time.Time) error {
+ return fd.pfd.SetDeadline(t)
+}
+
+func (fd *netFD) SetReadDeadline(t time.Time) error {
+ return fd.pfd.SetReadDeadline(t)
+}
+
+func (fd *netFD) SetWriteDeadline(t time.Time) error {
+ return fd.pfd.SetWriteDeadline(t)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_posix.go b/platform/dbops/binaries/go/go/src/net/fd_posix.go
new file mode 100644
index 0000000000000000000000000000000000000000..ffb9bcf8b9e8ca06b68f01217727ca5b5a6bd226
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_posix.go
@@ -0,0 +1,147 @@
+// 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 unix || windows
+
+package net
+
+import (
+ "internal/poll"
+ "runtime"
+ "syscall"
+ "time"
+)
+
+// Network file descriptor.
+type netFD struct {
+ pfd poll.FD
+
+ // immutable until Close
+ family int
+ sotype int
+ isConnected bool // handshake completed or use of association with peer
+ net string
+ laddr Addr
+ raddr Addr
+}
+
+func (fd *netFD) setAddr(laddr, raddr Addr) {
+ fd.laddr = laddr
+ fd.raddr = raddr
+ runtime.SetFinalizer(fd, (*netFD).Close)
+}
+
+func (fd *netFD) Close() error {
+ runtime.SetFinalizer(fd, nil)
+ return fd.pfd.Close()
+}
+
+func (fd *netFD) shutdown(how int) error {
+ err := fd.pfd.Shutdown(how)
+ runtime.KeepAlive(fd)
+ return wrapSyscallError("shutdown", err)
+}
+
+func (fd *netFD) closeRead() error {
+ return fd.shutdown(syscall.SHUT_RD)
+}
+
+func (fd *netFD) closeWrite() error {
+ return fd.shutdown(syscall.SHUT_WR)
+}
+
+func (fd *netFD) Read(p []byte) (n int, err error) {
+ n, err = fd.pfd.Read(p)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(readSyscallName, err)
+}
+
+func (fd *netFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
+ n, sa, err = fd.pfd.ReadFrom(p)
+ runtime.KeepAlive(fd)
+ return n, sa, wrapSyscallError(readFromSyscallName, err)
+}
+func (fd *netFD) readFromInet4(p []byte, from *syscall.SockaddrInet4) (n int, err error) {
+ n, err = fd.pfd.ReadFromInet4(p, from)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(readFromSyscallName, err)
+}
+
+func (fd *netFD) readFromInet6(p []byte, from *syscall.SockaddrInet6) (n int, err error) {
+ n, err = fd.pfd.ReadFromInet6(p, from)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(readFromSyscallName, err)
+}
+
+func (fd *netFD) readMsg(p []byte, oob []byte, flags int) (n, oobn, retflags int, sa syscall.Sockaddr, err error) {
+ n, oobn, retflags, sa, err = fd.pfd.ReadMsg(p, oob, flags)
+ runtime.KeepAlive(fd)
+ return n, oobn, retflags, sa, wrapSyscallError(readMsgSyscallName, err)
+}
+
+func (fd *netFD) readMsgInet4(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet4) (n, oobn, retflags int, err error) {
+ n, oobn, retflags, err = fd.pfd.ReadMsgInet4(p, oob, flags, sa)
+ runtime.KeepAlive(fd)
+ return n, oobn, retflags, wrapSyscallError(readMsgSyscallName, err)
+}
+
+func (fd *netFD) readMsgInet6(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet6) (n, oobn, retflags int, err error) {
+ n, oobn, retflags, err = fd.pfd.ReadMsgInet6(p, oob, flags, sa)
+ runtime.KeepAlive(fd)
+ return n, oobn, retflags, wrapSyscallError(readMsgSyscallName, err)
+}
+
+func (fd *netFD) Write(p []byte) (nn int, err error) {
+ nn, err = fd.pfd.Write(p)
+ runtime.KeepAlive(fd)
+ return nn, wrapSyscallError(writeSyscallName, err)
+}
+
+func (fd *netFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
+ n, err = fd.pfd.WriteTo(p, sa)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(writeToSyscallName, err)
+}
+
+func (fd *netFD) writeToInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) {
+ n, err = fd.pfd.WriteToInet4(p, sa)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(writeToSyscallName, err)
+}
+
+func (fd *netFD) writeToInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) {
+ n, err = fd.pfd.WriteToInet6(p, sa)
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError(writeToSyscallName, err)
+}
+
+func (fd *netFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) {
+ n, oobn, err = fd.pfd.WriteMsg(p, oob, sa)
+ runtime.KeepAlive(fd)
+ return n, oobn, wrapSyscallError(writeMsgSyscallName, err)
+}
+
+func (fd *netFD) writeMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (n int, oobn int, err error) {
+ n, oobn, err = fd.pfd.WriteMsgInet4(p, oob, sa)
+ runtime.KeepAlive(fd)
+ return n, oobn, wrapSyscallError(writeMsgSyscallName, err)
+}
+
+func (fd *netFD) writeMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (n int, oobn int, err error) {
+ n, oobn, err = fd.pfd.WriteMsgInet6(p, oob, sa)
+ runtime.KeepAlive(fd)
+ return n, oobn, wrapSyscallError(writeMsgSyscallName, err)
+}
+
+func (fd *netFD) SetDeadline(t time.Time) error {
+ return fd.pfd.SetDeadline(t)
+}
+
+func (fd *netFD) SetReadDeadline(t time.Time) error {
+ return fd.pfd.SetReadDeadline(t)
+}
+
+func (fd *netFD) SetWriteDeadline(t time.Time) error {
+ return fd.pfd.SetWriteDeadline(t)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_unix.go b/platform/dbops/binaries/go/go/src/net/fd_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..a8d3a253a97b108945306f99dddaf5a025a44f71
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_unix.go
@@ -0,0 +1,206 @@
+// 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 unix
+
+package net
+
+import (
+ "context"
+ "internal/poll"
+ "os"
+ "runtime"
+ "syscall"
+)
+
+const (
+ readSyscallName = "read"
+ readFromSyscallName = "recvfrom"
+ readMsgSyscallName = "recvmsg"
+ writeSyscallName = "write"
+ writeToSyscallName = "sendto"
+ writeMsgSyscallName = "sendmsg"
+)
+
+func newFD(sysfd, family, sotype int, net string) (*netFD, error) {
+ ret := &netFD{
+ pfd: poll.FD{
+ Sysfd: sysfd,
+ IsStream: sotype == syscall.SOCK_STREAM,
+ ZeroReadIsEOF: sotype != syscall.SOCK_DGRAM && sotype != syscall.SOCK_RAW,
+ },
+ family: family,
+ sotype: sotype,
+ net: net,
+ }
+ return ret, nil
+}
+
+func (fd *netFD) init() error {
+ return fd.pfd.Init(fd.net, true)
+}
+
+func (fd *netFD) name() string {
+ var ls, rs string
+ if fd.laddr != nil {
+ ls = fd.laddr.String()
+ }
+ if fd.raddr != nil {
+ rs = fd.raddr.String()
+ }
+ return fd.net + ":" + ls + "->" + rs
+}
+
+func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (rsa syscall.Sockaddr, ret error) {
+ // Do not need to call fd.writeLock here,
+ // because fd is not yet accessible to user,
+ // so no concurrent operations are possible.
+ switch err := connectFunc(fd.pfd.Sysfd, ra); err {
+ case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR:
+ case nil, syscall.EISCONN:
+ select {
+ case <-ctx.Done():
+ return nil, mapErr(ctx.Err())
+ default:
+ }
+ if err := fd.pfd.Init(fd.net, true); err != nil {
+ return nil, err
+ }
+ runtime.KeepAlive(fd)
+ return nil, nil
+ case syscall.EINVAL:
+ // On Solaris and illumos we can see EINVAL if the socket has
+ // already been accepted and closed by the server. Treat this
+ // as a successful connection--writes to the socket will see
+ // EOF. For details and a test case in C see
+ // https://golang.org/issue/6828.
+ if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" {
+ return nil, nil
+ }
+ fallthrough
+ default:
+ return nil, os.NewSyscallError("connect", err)
+ }
+ if err := fd.pfd.Init(fd.net, true); err != nil {
+ return nil, err
+ }
+ if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
+ fd.pfd.SetWriteDeadline(deadline)
+ defer fd.pfd.SetWriteDeadline(noDeadline)
+ }
+
+ // Start the "interrupter" goroutine, if this context might be canceled.
+ //
+ // The interrupter goroutine waits for the context to be done and
+ // interrupts the dial (by altering the fd's write deadline, which
+ // wakes up waitWrite).
+ ctxDone := ctx.Done()
+ if ctxDone != nil {
+ // Wait for the interrupter goroutine to exit before returning
+ // from connect.
+ done := make(chan struct{})
+ interruptRes := make(chan error)
+ defer func() {
+ close(done)
+ if ctxErr := <-interruptRes; ctxErr != nil && ret == nil {
+ // The interrupter goroutine called SetWriteDeadline,
+ // but the connect code below had returned from
+ // waitWrite already and did a successful connect (ret
+ // == nil). Because we've now poisoned the connection
+ // by making it unwritable, don't return a successful
+ // dial. This was issue 16523.
+ ret = mapErr(ctxErr)
+ fd.Close() // prevent a leak
+ }
+ }()
+ go func() {
+ select {
+ case <-ctxDone:
+ // Force the runtime's poller to immediately give up
+ // waiting for writability, unblocking waitWrite
+ // below.
+ fd.pfd.SetWriteDeadline(aLongTimeAgo)
+ testHookCanceledDial()
+ interruptRes <- ctx.Err()
+ case <-done:
+ interruptRes <- nil
+ }
+ }()
+ }
+
+ for {
+ // Performing multiple connect system calls on a
+ // non-blocking socket under Unix variants does not
+ // necessarily result in earlier errors being
+ // returned. Instead, once runtime-integrated network
+ // poller tells us that the socket is ready, get the
+ // SO_ERROR socket option to see if the connection
+ // succeeded or failed. See issue 7474 for further
+ // details.
+ if err := fd.pfd.WaitWrite(); err != nil {
+ select {
+ case <-ctxDone:
+ return nil, mapErr(ctx.Err())
+ default:
+ }
+ return nil, err
+ }
+ nerr, err := getsockoptIntFunc(fd.pfd.Sysfd, syscall.SOL_SOCKET, syscall.SO_ERROR)
+ if err != nil {
+ return nil, os.NewSyscallError("getsockopt", err)
+ }
+ switch err := syscall.Errno(nerr); err {
+ case syscall.EINPROGRESS, syscall.EALREADY, syscall.EINTR:
+ case syscall.EISCONN:
+ return nil, nil
+ case syscall.Errno(0):
+ // The runtime poller can wake us up spuriously;
+ // see issues 14548 and 19289. Check that we are
+ // really connected; if not, wait again.
+ if rsa, err := syscall.Getpeername(fd.pfd.Sysfd); err == nil {
+ return rsa, nil
+ }
+ default:
+ return nil, os.NewSyscallError("connect", err)
+ }
+ runtime.KeepAlive(fd)
+ }
+}
+
+func (fd *netFD) accept() (netfd *netFD, err error) {
+ d, rsa, errcall, err := fd.pfd.Accept()
+ if err != nil {
+ if errcall != "" {
+ err = wrapSyscallError(errcall, err)
+ }
+ return nil, err
+ }
+
+ if netfd, err = newFD(d, fd.family, fd.sotype, fd.net); err != nil {
+ poll.CloseFunc(d)
+ return nil, err
+ }
+ if err = netfd.init(); err != nil {
+ netfd.Close()
+ return nil, err
+ }
+ lsa, _ := syscall.Getsockname(netfd.pfd.Sysfd)
+ netfd.setAddr(netfd.addrFunc()(lsa), netfd.addrFunc()(rsa))
+ return netfd, nil
+}
+
+// Defined in os package.
+func newUnixFile(fd int, name string) *os.File
+
+func (fd *netFD) dup() (f *os.File, err error) {
+ ns, call, err := fd.pfd.Dup()
+ if err != nil {
+ if call != "" {
+ err = os.NewSyscallError(call, err)
+ }
+ return nil, err
+ }
+
+ return newUnixFile(ns, fd.name()), nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_wasip1.go b/platform/dbops/binaries/go/go/src/net/fd_wasip1.go
new file mode 100644
index 0000000000000000000000000000000000000000..d50effc05d32bfb4430cadf001b33006f21d8d6f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_wasip1.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.
+
+//go:build wasip1
+
+package net
+
+import (
+ "syscall"
+)
+
+func (fd *netFD) closeRead() error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.closeRead()
+ }
+ return fd.shutdown(syscall.SHUT_RD)
+}
+
+func (fd *netFD) closeWrite() error {
+ if fd.fakeNetFD != nil {
+ return fd.fakeNetFD.closeWrite()
+ }
+ return fd.shutdown(syscall.SHUT_WR)
+}
diff --git a/platform/dbops/binaries/go/go/src/net/fd_windows.go b/platform/dbops/binaries/go/go/src/net/fd_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..45a10cf1eb0121c8f483c110e3045924b943d1ab
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/fd_windows.go
@@ -0,0 +1,217 @@
+// 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 net
+
+import (
+ "context"
+ "internal/poll"
+ "internal/syscall/windows"
+ "os"
+ "runtime"
+ "syscall"
+ "unsafe"
+)
+
+const (
+ readSyscallName = "wsarecv"
+ readFromSyscallName = "wsarecvfrom"
+ readMsgSyscallName = "wsarecvmsg"
+ writeSyscallName = "wsasend"
+ writeToSyscallName = "wsasendto"
+ writeMsgSyscallName = "wsasendmsg"
+)
+
+// canUseConnectEx reports whether we can use the ConnectEx Windows API call
+// for the given network type.
+func canUseConnectEx(net string) bool {
+ switch net {
+ case "tcp", "tcp4", "tcp6":
+ return true
+ }
+ // ConnectEx windows API does not support connectionless sockets.
+ return false
+}
+
+func newFD(sysfd syscall.Handle, family, sotype int, net string) (*netFD, error) {
+ ret := &netFD{
+ pfd: poll.FD{
+ Sysfd: sysfd,
+ IsStream: sotype == syscall.SOCK_STREAM,
+ ZeroReadIsEOF: sotype != syscall.SOCK_DGRAM && sotype != syscall.SOCK_RAW,
+ },
+ family: family,
+ sotype: sotype,
+ net: net,
+ }
+ return ret, nil
+}
+
+func (fd *netFD) init() error {
+ errcall, err := fd.pfd.Init(fd.net, true)
+ if errcall != "" {
+ err = wrapSyscallError(errcall, err)
+ }
+ return err
+}
+
+// Always returns nil for connected peer address result.
+func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (syscall.Sockaddr, error) {
+ // Do not need to call fd.writeLock here,
+ // because fd is not yet accessible to user,
+ // so no concurrent operations are possible.
+ if err := fd.init(); err != nil {
+ return nil, err
+ }
+
+ if ctx.Done() != nil {
+ // Propagate the Context's deadline and cancellation.
+ // If the context is already done, or if it has a nonzero deadline,
+ // ensure that that is applied before the call to ConnectEx begins
+ // so that we don't return spurious connections.
+ defer fd.pfd.SetWriteDeadline(noDeadline)
+
+ if ctx.Err() != nil {
+ fd.pfd.SetWriteDeadline(aLongTimeAgo)
+ } else {
+ if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() {
+ fd.pfd.SetWriteDeadline(deadline)
+ }
+
+ done := make(chan struct{})
+ stop := context.AfterFunc(ctx, func() {
+ // Force the runtime's poller to immediately give
+ // up waiting for writability.
+ fd.pfd.SetWriteDeadline(aLongTimeAgo)
+ close(done)
+ })
+ defer func() {
+ if !stop() {
+ // Wait for the call to SetWriteDeadline to complete so that we can
+ // reset the deadline if everything else succeeded.
+ <-done
+ }
+ }()
+ }
+ }
+
+ if !canUseConnectEx(fd.net) {
+ err := connectFunc(fd.pfd.Sysfd, ra)
+ return nil, os.NewSyscallError("connect", err)
+ }
+ // ConnectEx windows API requires an unconnected, previously bound socket.
+ if la == nil {
+ switch ra.(type) {
+ case *syscall.SockaddrInet4:
+ la = &syscall.SockaddrInet4{}
+ case *syscall.SockaddrInet6:
+ la = &syscall.SockaddrInet6{}
+ default:
+ panic("unexpected type in connect")
+ }
+ if err := syscall.Bind(fd.pfd.Sysfd, la); err != nil {
+ return nil, os.NewSyscallError("bind", err)
+ }
+ }
+
+ var isloopback bool
+ switch ra := ra.(type) {
+ case *syscall.SockaddrInet4:
+ isloopback = ra.Addr[0] == 127
+ case *syscall.SockaddrInet6:
+ isloopback = ra.Addr == [16]byte(IPv6loopback)
+ default:
+ panic("unexpected type in connect")
+ }
+ if isloopback {
+ // This makes ConnectEx() fails faster if the target port on the localhost
+ // is not reachable, instead of waiting for 2s.
+ params := windows.TCP_INITIAL_RTO_PARAMETERS{
+ Rtt: windows.TCP_INITIAL_RTO_UNSPECIFIED_RTT, // use the default or overridden by the Administrator
+ MaxSynRetransmissions: 1, // minimum possible value before Windows 10.0.16299
+ }
+ if windows.Support_TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS() {
+ // In Windows 10.0.16299 TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS makes ConnectEx() fails instantly.
+ params.MaxSynRetransmissions = windows.TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS
+ }
+ var out uint32
+ // Don't abort the connection if WSAIoctl fails, as it is only an optimization.
+ // If it fails reliably, we expect TestDialClosedPortFailFast to detect it.
+ _ = fd.pfd.WSAIoctl(windows.SIO_TCP_INITIAL_RTO, (*byte)(unsafe.Pointer(¶ms)), uint32(unsafe.Sizeof(params)), nil, 0, &out, nil, 0)
+ }
+
+ // Call ConnectEx API.
+ if err := fd.pfd.ConnectEx(ra); err != nil {
+ select {
+ case <-ctx.Done():
+ return nil, mapErr(ctx.Err())
+ default:
+ if _, ok := err.(syscall.Errno); ok {
+ err = os.NewSyscallError("connectex", err)
+ }
+ return nil, err
+ }
+ }
+ // Refresh socket properties.
+ return nil, os.NewSyscallError("setsockopt", syscall.Setsockopt(fd.pfd.Sysfd, syscall.SOL_SOCKET, syscall.SO_UPDATE_CONNECT_CONTEXT, (*byte)(unsafe.Pointer(&fd.pfd.Sysfd)), int32(unsafe.Sizeof(fd.pfd.Sysfd))))
+}
+
+func (c *conn) writeBuffers(v *Buffers) (int64, error) {
+ if !c.ok() {
+ return 0, syscall.EINVAL
+ }
+ n, err := c.fd.writeBuffers(v)
+ if err != nil {
+ return n, &OpError{Op: "wsasend", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
+ }
+ return n, nil
+}
+
+func (fd *netFD) writeBuffers(buf *Buffers) (int64, error) {
+ n, err := fd.pfd.Writev((*[][]byte)(buf))
+ runtime.KeepAlive(fd)
+ return n, wrapSyscallError("wsasend", err)
+}
+
+func (fd *netFD) accept() (*netFD, error) {
+ s, rawsa, rsan, errcall, err := fd.pfd.Accept(func() (syscall.Handle, error) {
+ return sysSocket(fd.family, fd.sotype, 0)
+ })
+
+ if err != nil {
+ if errcall != "" {
+ err = wrapSyscallError(errcall, err)
+ }
+ return nil, err
+ }
+
+ // Associate our new socket with IOCP.
+ netfd, err := newFD(s, fd.family, fd.sotype, fd.net)
+ if err != nil {
+ poll.CloseFunc(s)
+ return nil, err
+ }
+ if err := netfd.init(); err != nil {
+ fd.Close()
+ return nil, err
+ }
+
+ // Get local and peer addr out of AcceptEx buffer.
+ var lrsa, rrsa *syscall.RawSockaddrAny
+ var llen, rlen int32
+ syscall.GetAcceptExSockaddrs((*byte)(unsafe.Pointer(&rawsa[0])),
+ 0, rsan, rsan, &lrsa, &llen, &rrsa, &rlen)
+ lsa, _ := lrsa.Sockaddr()
+ rsa, _ := rrsa.Sockaddr()
+
+ netfd.setAddr(netfd.addrFunc()(lsa), netfd.addrFunc()(rsa))
+ return netfd, nil
+}
+
+// Unimplemented functions.
+
+func (fd *netFD) dup() (*os.File, error) {
+ // TODO: Implement this
+ return nil, syscall.EWINDOWS
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file.go b/platform/dbops/binaries/go/go/src/net/file.go
new file mode 100644
index 0000000000000000000000000000000000000000..c13332c188aeef25def410a3d1b9833256540cb3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file.go
@@ -0,0 +1,51 @@
+// 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 net
+
+import "os"
+
+// BUG(mikio): On JS and Windows, the FileConn, FileListener and
+// FilePacketConn functions are not implemented.
+
+type fileAddr string
+
+func (fileAddr) Network() string { return "file+net" }
+func (f fileAddr) String() string { return string(f) }
+
+// FileConn returns a copy of the network connection corresponding to
+// the open file f.
+// It is the caller's responsibility to close f when finished.
+// Closing c does not affect f, and closing f does not affect c.
+func FileConn(f *os.File) (c Conn, err error) {
+ c, err = fileConn(f)
+ if err != nil {
+ err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err}
+ }
+ return
+}
+
+// FileListener returns a copy of the network listener corresponding
+// to the open file f.
+// It is the caller's responsibility to close ln when finished.
+// Closing ln does not affect f, and closing f does not affect ln.
+func FileListener(f *os.File) (ln Listener, err error) {
+ ln, err = fileListener(f)
+ if err != nil {
+ err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err}
+ }
+ return
+}
+
+// FilePacketConn returns a copy of the packet network connection
+// corresponding to the open file f.
+// It is the caller's responsibility to close f when finished.
+// Closing c does not affect f, and closing f does not affect c.
+func FilePacketConn(f *os.File) (c PacketConn, err error) {
+ c, err = filePacketConn(f)
+ if err != nil {
+ err = &OpError{Op: "file", Net: "file+net", Source: nil, Addr: fileAddr(f.Name()), Err: err}
+ }
+ return
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_plan9.go b/platform/dbops/binaries/go/go/src/net/file_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..64aabf93ee54adc0abbc76a02872ac30f1aa1d04
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_plan9.go
@@ -0,0 +1,135 @@
+// 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 net
+
+import (
+ "errors"
+ "io"
+ "os"
+ "syscall"
+)
+
+func (fd *netFD) status(ln int) (string, error) {
+ if !fd.ok() {
+ return "", syscall.EINVAL
+ }
+
+ status, err := os.Open(fd.dir + "/status")
+ if err != nil {
+ return "", err
+ }
+ defer status.Close()
+ buf := make([]byte, ln)
+ n, err := io.ReadFull(status, buf[:])
+ if err != nil {
+ return "", err
+ }
+ return string(buf[:n]), nil
+}
+
+func newFileFD(f *os.File) (net *netFD, err error) {
+ var ctl *os.File
+ close := func(fd int) {
+ if err != nil {
+ syscall.Close(fd)
+ }
+ }
+
+ path, err := syscall.Fd2path(int(f.Fd()))
+ if err != nil {
+ return nil, os.NewSyscallError("fd2path", err)
+ }
+ comp := splitAtBytes(path, "/")
+ n := len(comp)
+ if n < 3 || comp[0][0:3] != "net" {
+ return nil, syscall.EPLAN9
+ }
+
+ name := comp[2]
+ switch file := comp[n-1]; file {
+ case "ctl", "clone":
+ fd, err := syscall.Dup(int(f.Fd()), -1)
+ if err != nil {
+ return nil, os.NewSyscallError("dup", err)
+ }
+ defer close(fd)
+
+ dir := netdir + "/" + comp[n-2]
+ ctl = os.NewFile(uintptr(fd), dir+"/"+file)
+ ctl.Seek(0, io.SeekStart)
+ var buf [16]byte
+ n, err := ctl.Read(buf[:])
+ if err != nil {
+ return nil, err
+ }
+ name = string(buf[:n])
+ default:
+ if len(comp) < 4 {
+ return nil, errors.New("could not find control file for connection")
+ }
+ dir := netdir + "/" + comp[1] + "/" + name
+ ctl, err = os.OpenFile(dir+"/ctl", os.O_RDWR, 0)
+ if err != nil {
+ return nil, err
+ }
+ defer close(int(ctl.Fd()))
+ }
+ dir := netdir + "/" + comp[1] + "/" + name
+ laddr, err := readPlan9Addr(comp[1], dir+"/local")
+ if err != nil {
+ return nil, err
+ }
+ return newFD(comp[1], name, nil, ctl, nil, laddr, nil)
+}
+
+func fileConn(f *os.File) (Conn, error) {
+ fd, err := newFileFD(f)
+ if err != nil {
+ return nil, err
+ }
+ if !fd.ok() {
+ return nil, syscall.EINVAL
+ }
+
+ fd.data, err = os.OpenFile(fd.dir+"/data", os.O_RDWR, 0)
+ if err != nil {
+ return nil, err
+ }
+
+ switch fd.laddr.(type) {
+ case *TCPAddr:
+ return newTCPConn(fd, defaultTCPKeepAlive, testHookSetKeepAlive), nil
+ case *UDPAddr:
+ return newUDPConn(fd), nil
+ }
+ return nil, syscall.EPLAN9
+}
+
+func fileListener(f *os.File) (Listener, error) {
+ fd, err := newFileFD(f)
+ if err != nil {
+ return nil, err
+ }
+ switch fd.laddr.(type) {
+ case *TCPAddr:
+ default:
+ return nil, syscall.EPLAN9
+ }
+
+ // check that file corresponds to a listener
+ s, err := fd.status(len("Listen"))
+ if err != nil {
+ return nil, err
+ }
+ if s != "Listen" {
+ return nil, errors.New("file does not represent a listener")
+ }
+
+ return &TCPListener{fd: fd}, nil
+}
+
+func filePacketConn(f *os.File) (PacketConn, error) {
+ return nil, syscall.EPLAN9
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_stub.go b/platform/dbops/binaries/go/go/src/net/file_stub.go
new file mode 100644
index 0000000000000000000000000000000000000000..6fd3eec48d9c09f4fe2802bd70cc09b61580de8a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_stub.go
@@ -0,0 +1,16 @@
+// 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.
+
+//go:build js
+
+package net
+
+import (
+ "os"
+ "syscall"
+)
+
+func fileConn(f *os.File) (Conn, error) { return nil, syscall.ENOPROTOOPT }
+func fileListener(f *os.File) (Listener, error) { return nil, syscall.ENOPROTOOPT }
+func filePacketConn(f *os.File) (PacketConn, error) { return nil, syscall.ENOPROTOOPT }
diff --git a/platform/dbops/binaries/go/go/src/net/file_test.go b/platform/dbops/binaries/go/go/src/net/file_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..c517af50c5ee2e11cf10664650154fb81aa5526c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_test.go
@@ -0,0 +1,338 @@
+// 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 net
+
+import (
+ "os"
+ "reflect"
+ "runtime"
+ "sync"
+ "testing"
+)
+
+// The full stack test cases for IPConn have been moved to the
+// following:
+// golang.org/x/net/ipv4
+// golang.org/x/net/ipv6
+// golang.org/x/net/icmp
+
+var fileConnTests = []struct {
+ network string
+}{
+ {"tcp"},
+ {"udp"},
+ {"unix"},
+ {"unixpacket"},
+}
+
+func TestFileConn(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9", "windows", "js", "wasip1":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ for _, tt := range fileConnTests {
+ if !testableNetwork(tt.network) {
+ t.Logf("skipping %s test", tt.network)
+ continue
+ }
+
+ var network, address string
+ switch tt.network {
+ case "udp":
+ c := newLocalPacketListener(t, tt.network)
+ defer c.Close()
+ network = c.LocalAddr().Network()
+ address = c.LocalAddr().String()
+ default:
+ handler := func(ls *localServer, ln Listener) {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ defer c.Close()
+ var b [1]byte
+ c.Read(b[:])
+ }
+ ls := newLocalServer(t, tt.network)
+ defer ls.teardown()
+ if err := ls.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+ network = ls.Listener.Addr().Network()
+ address = ls.Listener.Addr().String()
+ }
+
+ c1, err := Dial(network, address)
+ if err != nil {
+ if perr := parseDialError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ addr := c1.LocalAddr()
+
+ var f *os.File
+ switch c1 := c1.(type) {
+ case *TCPConn:
+ f, err = c1.File()
+ case *UDPConn:
+ f, err = c1.File()
+ case *UnixConn:
+ f, err = c1.File()
+ }
+ if err := c1.Close(); err != nil {
+ if perr := parseCloseError(err, false); perr != nil {
+ t.Error(perr)
+ }
+ t.Error(err)
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+
+ c2, err := FileConn(f)
+ if err := f.Close(); err != nil {
+ t.Error(err)
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ defer c2.Close()
+
+ if _, err := c2.Write([]byte("FILECONN TEST")); err != nil {
+ if perr := parseWriteError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(c2.LocalAddr(), addr) {
+ t.Fatalf("got %#v; want %#v", c2.LocalAddr(), addr)
+ }
+ }
+}
+
+var fileListenerTests = []struct {
+ network string
+}{
+ {"tcp"},
+ {"unix"},
+ {"unixpacket"},
+}
+
+func TestFileListener(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9", "windows", "js", "wasip1":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ for _, tt := range fileListenerTests {
+ if !testableNetwork(tt.network) {
+ t.Logf("skipping %s test", tt.network)
+ continue
+ }
+
+ ln1 := newLocalListener(t, tt.network)
+ switch tt.network {
+ case "unix", "unixpacket":
+ defer os.Remove(ln1.Addr().String())
+ }
+ addr := ln1.Addr()
+
+ var (
+ f *os.File
+ err error
+ )
+ switch ln1 := ln1.(type) {
+ case *TCPListener:
+ f, err = ln1.File()
+ case *UnixListener:
+ f, err = ln1.File()
+ }
+ switch tt.network {
+ case "unix", "unixpacket":
+ defer ln1.Close() // UnixListener.Close calls syscall.Unlink internally
+ default:
+ if err := ln1.Close(); err != nil {
+ t.Error(err)
+ }
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+
+ ln2, err := FileListener(f)
+ if err := f.Close(); err != nil {
+ t.Error(err)
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ defer ln2.Close()
+
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ c, err := Dial(ln2.Addr().Network(), ln2.Addr().String())
+ if err != nil {
+ if perr := parseDialError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Error(err)
+ return
+ }
+ c.Close()
+ }()
+ c, err := ln2.Accept()
+ if err != nil {
+ if perr := parseAcceptError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ c.Close()
+ wg.Wait()
+ if !reflect.DeepEqual(ln2.Addr(), addr) {
+ t.Fatalf("got %#v; want %#v", ln2.Addr(), addr)
+ }
+ }
+}
+
+var filePacketConnTests = []struct {
+ network string
+}{
+ {"udp"},
+ {"unixgram"},
+}
+
+func TestFilePacketConn(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9", "windows", "js", "wasip1":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+
+ for _, tt := range filePacketConnTests {
+ if !testableNetwork(tt.network) {
+ t.Logf("skipping %s test", tt.network)
+ continue
+ }
+
+ c1 := newLocalPacketListener(t, tt.network)
+ switch tt.network {
+ case "unixgram":
+ defer os.Remove(c1.LocalAddr().String())
+ }
+ addr := c1.LocalAddr()
+
+ var (
+ f *os.File
+ err error
+ )
+ switch c1 := c1.(type) {
+ case *UDPConn:
+ f, err = c1.File()
+ case *UnixConn:
+ f, err = c1.File()
+ }
+ if err := c1.Close(); err != nil {
+ if perr := parseCloseError(err, false); perr != nil {
+ t.Error(perr)
+ }
+ t.Error(err)
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+
+ c2, err := FilePacketConn(f)
+ if err := f.Close(); err != nil {
+ t.Error(err)
+ }
+ if err != nil {
+ if perr := parseCommonError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ defer c2.Close()
+
+ if _, err := c2.WriteTo([]byte("FILEPACKETCONN TEST"), addr); err != nil {
+ if perr := parseWriteError(err); perr != nil {
+ t.Error(perr)
+ }
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(c2.LocalAddr(), addr) {
+ t.Fatalf("got %#v; want %#v", c2.LocalAddr(), addr)
+ }
+ }
+}
+
+// Issue 24483.
+func TestFileCloseRace(t *testing.T) {
+ switch runtime.GOOS {
+ case "plan9", "windows", "js", "wasip1":
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+ if !testableNetwork("tcp") {
+ t.Skip("tcp not supported")
+ }
+
+ handler := func(ls *localServer, ln Listener) {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ defer c.Close()
+ var b [1]byte
+ c.Read(b[:])
+ }
+
+ ls := newLocalServer(t, "tcp")
+ defer ls.teardown()
+ if err := ls.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+
+ const tries = 100
+ for i := 0; i < tries; i++ {
+ c1, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ tc := c1.(*TCPConn)
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ f, err := tc.File()
+ if err == nil {
+ f.Close()
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ c1.Close()
+ }()
+ wg.Wait()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_unix.go b/platform/dbops/binaries/go/go/src/net/file_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..8b9fc38916f71be44d57ee01c4c084956aaf98df
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_unix.go
@@ -0,0 +1,119 @@
+// 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.
+
+//go:build unix
+
+package net
+
+import (
+ "internal/poll"
+ "os"
+ "syscall"
+)
+
+func dupSocket(f *os.File) (int, error) {
+ s, call, err := poll.DupCloseOnExec(int(f.Fd()))
+ if err != nil {
+ if call != "" {
+ err = os.NewSyscallError(call, err)
+ }
+ return -1, err
+ }
+ if err := syscall.SetNonblock(s, true); err != nil {
+ poll.CloseFunc(s)
+ return -1, os.NewSyscallError("setnonblock", err)
+ }
+ return s, nil
+}
+
+func newFileFD(f *os.File) (*netFD, error) {
+ s, err := dupSocket(f)
+ if err != nil {
+ return nil, err
+ }
+ family := syscall.AF_UNSPEC
+ sotype, err := syscall.GetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_TYPE)
+ if err != nil {
+ poll.CloseFunc(s)
+ return nil, os.NewSyscallError("getsockopt", err)
+ }
+ lsa, _ := syscall.Getsockname(s)
+ rsa, _ := syscall.Getpeername(s)
+ switch lsa.(type) {
+ case *syscall.SockaddrInet4:
+ family = syscall.AF_INET
+ case *syscall.SockaddrInet6:
+ family = syscall.AF_INET6
+ case *syscall.SockaddrUnix:
+ family = syscall.AF_UNIX
+ default:
+ poll.CloseFunc(s)
+ return nil, syscall.EPROTONOSUPPORT
+ }
+ fd, err := newFD(s, family, sotype, "")
+ if err != nil {
+ poll.CloseFunc(s)
+ return nil, err
+ }
+ laddr := fd.addrFunc()(lsa)
+ raddr := fd.addrFunc()(rsa)
+ fd.net = laddr.Network()
+ if err := fd.init(); err != nil {
+ fd.Close()
+ return nil, err
+ }
+ fd.setAddr(laddr, raddr)
+ return fd, nil
+}
+
+func fileConn(f *os.File) (Conn, error) {
+ fd, err := newFileFD(f)
+ if err != nil {
+ return nil, err
+ }
+ switch fd.laddr.(type) {
+ case *TCPAddr:
+ return newTCPConn(fd, defaultTCPKeepAlive, testHookSetKeepAlive), nil
+ case *UDPAddr:
+ return newUDPConn(fd), nil
+ case *IPAddr:
+ return newIPConn(fd), nil
+ case *UnixAddr:
+ return newUnixConn(fd), nil
+ }
+ fd.Close()
+ return nil, syscall.EINVAL
+}
+
+func fileListener(f *os.File) (Listener, error) {
+ fd, err := newFileFD(f)
+ if err != nil {
+ return nil, err
+ }
+ switch laddr := fd.laddr.(type) {
+ case *TCPAddr:
+ return &TCPListener{fd: fd}, nil
+ case *UnixAddr:
+ return &UnixListener{fd: fd, path: laddr.Name, unlink: false}, nil
+ }
+ fd.Close()
+ return nil, syscall.EINVAL
+}
+
+func filePacketConn(f *os.File) (PacketConn, error) {
+ fd, err := newFileFD(f)
+ if err != nil {
+ return nil, err
+ }
+ switch fd.laddr.(type) {
+ case *UDPAddr:
+ return newUDPConn(fd), nil
+ case *IPAddr:
+ return newIPConn(fd), nil
+ case *UnixAddr:
+ return newUnixConn(fd), nil
+ }
+ fd.Close()
+ return nil, syscall.EINVAL
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_unix_test.go b/platform/dbops/binaries/go/go/src/net/file_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0499a02404a3ac7cd2fd1521dd04e29d6a4cc068
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_unix_test.go
@@ -0,0 +1,101 @@
+// 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 unix
+
+package net
+
+import (
+ "internal/syscall/unix"
+ "testing"
+)
+
+// For backward compatibility, opening a net.Conn, turning it into an os.File,
+// and calling the Fd method should return a blocking descriptor.
+func TestFileFdBlocks(t *testing.T) {
+ if !testableNetwork("unix") {
+ t.Skipf("skipping: unix sockets not supported")
+ }
+
+ ls := newLocalServer(t, "unix")
+ defer ls.teardown()
+
+ errc := make(chan error, 1)
+ done := make(chan bool)
+ handler := func(ls *localServer, ln Listener) {
+ server, err := ln.Accept()
+ errc <- err
+ if err != nil {
+ return
+ }
+ defer server.Close()
+ <-done
+ }
+ if err := ls.buildup(handler); err != nil {
+ t.Fatal(err)
+ }
+ defer close(done)
+
+ client, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer client.Close()
+
+ if err := <-errc; err != nil {
+ t.Fatalf("server error: %v", err)
+ }
+
+ // The socket should be non-blocking.
+ rawconn, err := client.(*UnixConn).SyscallConn()
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = rawconn.Control(func(fd uintptr) {
+ nonblock, err := unix.IsNonblock(int(fd))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !nonblock {
+ t.Fatal("unix socket is in blocking mode")
+ }
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ file, err := client.(*UnixConn).File()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // At this point the descriptor should still be non-blocking.
+ rawconn, err = file.SyscallConn()
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = rawconn.Control(func(fd uintptr) {
+ nonblock, err := unix.IsNonblock(int(fd))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !nonblock {
+ t.Fatal("unix socket as os.File is in blocking mode")
+ }
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ fd := file.Fd()
+
+ // Calling Fd should have put the descriptor into blocking mode.
+ nonblock, err := unix.IsNonblock(int(fd))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if nonblock {
+ t.Error("unix socket through os.File.Fd is non-blocking")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_wasip1.go b/platform/dbops/binaries/go/go/src/net/file_wasip1.go
new file mode 100644
index 0000000000000000000000000000000000000000..a3624efb55e4ba904ee1806c7092957fa96beb2d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_wasip1.go
@@ -0,0 +1,102 @@
+// 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 wasip1
+
+package net
+
+import (
+ "os"
+ "syscall"
+ _ "unsafe" // for go:linkname
+)
+
+func fileListener(f *os.File) (Listener, error) {
+ filetype, err := fd_fdstat_get_type(f.PollFD().Sysfd)
+ if err != nil {
+ return nil, err
+ }
+ net, err := fileListenNet(filetype)
+ if err != nil {
+ return nil, err
+ }
+ pfd := f.PollFD().Copy()
+ fd := newPollFD(net, pfd)
+ if err := fd.init(); err != nil {
+ pfd.Close()
+ return nil, err
+ }
+ return newFileListener(fd), nil
+}
+
+func fileConn(f *os.File) (Conn, error) {
+ filetype, err := fd_fdstat_get_type(f.PollFD().Sysfd)
+ if err != nil {
+ return nil, err
+ }
+ net, err := fileConnNet(filetype)
+ if err != nil {
+ return nil, err
+ }
+ pfd := f.PollFD().Copy()
+ fd := newPollFD(net, pfd)
+ if err := fd.init(); err != nil {
+ pfd.Close()
+ return nil, err
+ }
+ return newFileConn(fd), nil
+}
+
+func filePacketConn(f *os.File) (PacketConn, error) {
+ return nil, syscall.ENOPROTOOPT
+}
+
+func fileListenNet(filetype syscall.Filetype) (string, error) {
+ switch filetype {
+ case syscall.FILETYPE_SOCKET_STREAM:
+ return "tcp", nil
+ case syscall.FILETYPE_SOCKET_DGRAM:
+ return "", syscall.EOPNOTSUPP
+ default:
+ return "", syscall.ENOTSOCK
+ }
+}
+
+func fileConnNet(filetype syscall.Filetype) (string, error) {
+ switch filetype {
+ case syscall.FILETYPE_SOCKET_STREAM:
+ return "tcp", nil
+ case syscall.FILETYPE_SOCKET_DGRAM:
+ return "udp", nil
+ default:
+ return "", syscall.ENOTSOCK
+ }
+}
+
+func newFileListener(fd *netFD) Listener {
+ switch fd.net {
+ case "tcp":
+ return &TCPListener{fd: fd}
+ default:
+ panic("unsupported network for file listener: " + fd.net)
+ }
+}
+
+func newFileConn(fd *netFD) Conn {
+ switch fd.net {
+ case "tcp":
+ return &TCPConn{conn{fd: fd}}
+ case "udp":
+ return &UDPConn{conn{fd: fd}}
+ default:
+ panic("unsupported network for file connection: " + fd.net)
+ }
+}
+
+// This helper is implemented in the syscall package. It means we don't have
+// to redefine the fd_fdstat_get host import or the fdstat struct it
+// populates.
+//
+//go:linkname fd_fdstat_get_type syscall.fd_fdstat_get_type
+func fd_fdstat_get_type(fd int) (uint8, error)
diff --git a/platform/dbops/binaries/go/go/src/net/file_wasip1_test.go b/platform/dbops/binaries/go/go/src/net/file_wasip1_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..4f4259069d1f739ee570110bc94125f6bc0fc1c4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_wasip1_test.go
@@ -0,0 +1,112 @@
+// 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 wasip1
+
+package net
+
+import (
+ "syscall"
+ "testing"
+)
+
+// The tests in this file intend to validate the ability for net.FileConn and
+// net.FileListener to handle both TCP and UDP sockets. Ideally we would test
+// the public interface by constructing an *os.File from a file descriptor
+// opened on a socket, but the WASI preview 1 specification is too limited to
+// support this approach for UDP sockets. Instead, we test the internals that
+// make it possible for WASI host runtimes and guest programs to integrate
+// socket extensions with the net package using net.FileConn/net.FileListener.
+//
+// Note that the creation of net.Conn and net.Listener values for TCP sockets
+// has an end-to-end test in src/runtime/internal/wasitest, here we are only
+// verifying the code paths specific to UDP, and error handling for invalid use
+// of the functions.
+
+func TestWasip1FileConnNet(t *testing.T) {
+ tests := []struct {
+ filetype syscall.Filetype
+ network string
+ error error
+ }{
+ {syscall.FILETYPE_SOCKET_STREAM, "tcp", nil},
+ {syscall.FILETYPE_SOCKET_DGRAM, "udp", nil},
+ {syscall.FILETYPE_BLOCK_DEVICE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_CHARACTER_DEVICE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_DIRECTORY, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_REGULAR_FILE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_SYMBOLIC_LINK, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_UNKNOWN, "", syscall.ENOTSOCK},
+ }
+ for _, test := range tests {
+ net, err := fileConnNet(test.filetype)
+ if net != test.network {
+ t.Errorf("fileConnNet: network mismatch: want=%q got=%q", test.network, net)
+ }
+ if err != test.error {
+ t.Errorf("fileConnNet: error mismatch: want=%v got=%v", test.error, err)
+ }
+ }
+}
+
+func TestWasip1FileListenNet(t *testing.T) {
+ tests := []struct {
+ filetype syscall.Filetype
+ network string
+ error error
+ }{
+ {syscall.FILETYPE_SOCKET_STREAM, "tcp", nil},
+ {syscall.FILETYPE_SOCKET_DGRAM, "", syscall.EOPNOTSUPP},
+ {syscall.FILETYPE_BLOCK_DEVICE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_CHARACTER_DEVICE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_DIRECTORY, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_REGULAR_FILE, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_SYMBOLIC_LINK, "", syscall.ENOTSOCK},
+ {syscall.FILETYPE_UNKNOWN, "", syscall.ENOTSOCK},
+ }
+ for _, test := range tests {
+ net, err := fileListenNet(test.filetype)
+ if net != test.network {
+ t.Errorf("fileListenNet: network mismatch: want=%q got=%q", test.network, net)
+ }
+ if err != test.error {
+ t.Errorf("fileListenNet: error mismatch: want=%v got=%v", test.error, err)
+ }
+ }
+}
+
+func TestWasip1NewFileListener(t *testing.T) {
+ if l, ok := newFileListener(newFD("tcp", -1)).(*TCPListener); !ok {
+ t.Errorf("newFileListener: tcp listener type mismatch: %T", l)
+ } else {
+ testIsTCPAddr(t, "Addr", l.Addr())
+ }
+}
+
+func TestWasip1NewFileConn(t *testing.T) {
+ if c, ok := newFileConn(newFD("tcp", -1)).(*TCPConn); !ok {
+ t.Errorf("newFileConn: tcp conn type mismatch: %T", c)
+ } else {
+ testIsTCPAddr(t, "LocalAddr", c.LocalAddr())
+ testIsTCPAddr(t, "RemoteAddr", c.RemoteAddr())
+ }
+ if c, ok := newFileConn(newFD("udp", -1)).(*UDPConn); !ok {
+ t.Errorf("newFileConn: udp conn type mismatch: %T", c)
+ } else {
+ testIsUDPAddr(t, "LocalAddr", c.LocalAddr())
+ testIsUDPAddr(t, "RemoteAddr", c.RemoteAddr())
+ }
+}
+
+func testIsTCPAddr(t *testing.T, method string, addr Addr) {
+ if _, ok := addr.(*TCPAddr); !ok {
+ t.Errorf("%s: returned address is not a *TCPAddr: %T", method, addr)
+ }
+}
+
+func testIsUDPAddr(t *testing.T, method string, addr Addr) {
+ if _, ok := addr.(*UDPAddr); !ok {
+ t.Errorf("%s: returned address is not a *UDPAddr: %T", method, addr)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/file_windows.go b/platform/dbops/binaries/go/go/src/net/file_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..241fa17617c2bf20073d275c479e01ed288dde58
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/file_windows.go
@@ -0,0 +1,25 @@
+// 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 net
+
+import (
+ "os"
+ "syscall"
+)
+
+func fileConn(f *os.File) (Conn, error) {
+ // TODO: Implement this
+ return nil, syscall.EWINDOWS
+}
+
+func fileListener(f *os.File) (Listener, error) {
+ // TODO: Implement this
+ return nil, syscall.EWINDOWS
+}
+
+func filePacketConn(f *os.File) (PacketConn, error) {
+ // TODO: Implement this
+ return nil, syscall.EWINDOWS
+}
diff --git a/platform/dbops/binaries/go/go/src/net/hook.go b/platform/dbops/binaries/go/go/src/net/hook.go
new file mode 100644
index 0000000000000000000000000000000000000000..eded34d48abe4e8d0f91ed5e133097572423537d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hook.go
@@ -0,0 +1,31 @@
+// 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 net
+
+import (
+ "context"
+ "time"
+)
+
+var (
+ // if non-nil, overrides dialTCP.
+ testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error)
+
+ testHookLookupIP = func(
+ ctx context.Context,
+ fn func(context.Context, string, string) ([]IPAddr, error),
+ network string,
+ host string,
+ ) ([]IPAddr, error) {
+ return fn(ctx, network, host)
+ }
+ testHookSetKeepAlive = func(time.Duration) {}
+
+ // testHookStepTime sleeps until time has moved forward by a nonzero amount.
+ // This helps to avoid flakes in timeout tests by ensuring that an implausibly
+ // short deadline (such as 1ns in the future) is always expired by the time
+ // a relevant system call occurs.
+ testHookStepTime = func() {}
+)
diff --git a/platform/dbops/binaries/go/go/src/net/hook_plan9.go b/platform/dbops/binaries/go/go/src/net/hook_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..6020d329240272e0933034a59fbb03a8f312908e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hook_plan9.go
@@ -0,0 +1,9 @@
+// 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 net
+
+var (
+ hostsFilePath = "/etc/hosts"
+)
diff --git a/platform/dbops/binaries/go/go/src/net/hook_unix.go b/platform/dbops/binaries/go/go/src/net/hook_unix.go
new file mode 100644
index 0000000000000000000000000000000000000000..69b375598dc6adbd4a071681da67c704ef9fa38a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hook_unix.go
@@ -0,0 +1,21 @@
+// 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 unix || js || wasip1
+
+package net
+
+import "syscall"
+
+var (
+ testHookCanceledDial = func() {} // for golang.org/issue/16523
+
+ hostsFilePath = "/etc/hosts"
+
+ // Placeholders for socket system calls.
+ socketFunc func(int, int, int) (int, error) = syscall.Socket
+ connectFunc func(int, syscall.Sockaddr) error = syscall.Connect
+ listenFunc func(int, int) error = syscall.Listen
+ getsockoptIntFunc func(int, int, int) (int, error) = syscall.GetsockoptInt
+)
diff --git a/platform/dbops/binaries/go/go/src/net/hook_windows.go b/platform/dbops/binaries/go/go/src/net/hook_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7c5b5af90fe354f9d4238dade86aa0e08481e35
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hook_windows.go
@@ -0,0 +1,19 @@
+// 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 net
+
+import (
+ "internal/syscall/windows"
+ "syscall"
+)
+
+var (
+ hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
+
+ // Placeholders for socket system calls.
+ wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
+ connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
+ listenFunc func(syscall.Handle, int) error = syscall.Listen
+)
diff --git a/platform/dbops/binaries/go/go/src/net/hosts.go b/platform/dbops/binaries/go/go/src/net/hosts.go
new file mode 100644
index 0000000000000000000000000000000000000000..73e6fcc7a4ae7dfbab02a44d6b4fb0e531beb8c9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hosts.go
@@ -0,0 +1,165 @@
+// 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 net
+
+import (
+ "errors"
+ "internal/bytealg"
+ "io/fs"
+ "net/netip"
+ "sync"
+ "time"
+)
+
+const cacheMaxAge = 5 * time.Second
+
+func parseLiteralIP(addr string) string {
+ ip, err := netip.ParseAddr(addr)
+ if err != nil {
+ return ""
+ }
+ return ip.String()
+}
+
+type byName struct {
+ addrs []string
+ canonicalName string
+}
+
+// hosts contains known host entries.
+var hosts struct {
+ sync.Mutex
+
+ // Key for the list of literal IP addresses must be a host
+ // name. It would be part of DNS labels, a FQDN or an absolute
+ // FQDN.
+ // For now the key is converted to lower case for convenience.
+ byName map[string]byName
+
+ // Key for the list of host names must be a literal IP address
+ // including IPv6 address with zone identifier.
+ // We don't support old-classful IP address notation.
+ byAddr map[string][]string
+
+ expire time.Time
+ path string
+ mtime time.Time
+ size int64
+}
+
+func readHosts() {
+ now := time.Now()
+ hp := hostsFilePath
+
+ if now.Before(hosts.expire) && hosts.path == hp && len(hosts.byName) > 0 {
+ return
+ }
+ mtime, size, err := stat(hp)
+ if err == nil && hosts.path == hp && hosts.mtime.Equal(mtime) && hosts.size == size {
+ hosts.expire = now.Add(cacheMaxAge)
+ return
+ }
+
+ hs := make(map[string]byName)
+ is := make(map[string][]string)
+
+ file, err := open(hp)
+ if err != nil {
+ if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission) {
+ return
+ }
+ }
+
+ if file != nil {
+ defer file.close()
+ for line, ok := file.readLine(); ok; line, ok = file.readLine() {
+ if i := bytealg.IndexByteString(line, '#'); i >= 0 {
+ // Discard comments.
+ line = line[0:i]
+ }
+ f := getFields(line)
+ if len(f) < 2 {
+ continue
+ }
+ addr := parseLiteralIP(f[0])
+ if addr == "" {
+ continue
+ }
+
+ var canonical string
+ for i := 1; i < len(f); i++ {
+ name := absDomainName(f[i])
+ h := []byte(f[i])
+ lowerASCIIBytes(h)
+ key := absDomainName(string(h))
+
+ if i == 1 {
+ canonical = key
+ }
+
+ is[addr] = append(is[addr], name)
+
+ if v, ok := hs[key]; ok {
+ hs[key] = byName{
+ addrs: append(v.addrs, addr),
+ canonicalName: v.canonicalName,
+ }
+ continue
+ }
+
+ hs[key] = byName{
+ addrs: []string{addr},
+ canonicalName: canonical,
+ }
+ }
+ }
+ }
+ // Update the data cache.
+ hosts.expire = now.Add(cacheMaxAge)
+ hosts.path = hp
+ hosts.byName = hs
+ hosts.byAddr = is
+ hosts.mtime = mtime
+ hosts.size = size
+}
+
+// lookupStaticHost looks up the addresses and the canonical name for the given host from /etc/hosts.
+func lookupStaticHost(host string) ([]string, string) {
+ hosts.Lock()
+ defer hosts.Unlock()
+ readHosts()
+ if len(hosts.byName) != 0 {
+ if hasUpperCase(host) {
+ lowerHost := []byte(host)
+ lowerASCIIBytes(lowerHost)
+ host = string(lowerHost)
+ }
+ if byName, ok := hosts.byName[absDomainName(host)]; ok {
+ ipsCp := make([]string, len(byName.addrs))
+ copy(ipsCp, byName.addrs)
+ return ipsCp, byName.canonicalName
+ }
+ }
+ return nil, ""
+}
+
+// lookupStaticAddr looks up the hosts for the given address from /etc/hosts.
+func lookupStaticAddr(addr string) []string {
+ hosts.Lock()
+ defer hosts.Unlock()
+ readHosts()
+ addr = parseLiteralIP(addr)
+ if addr == "" {
+ return nil
+ }
+ if len(hosts.byAddr) != 0 {
+ if hosts, ok := hosts.byAddr[addr]; ok {
+ hostsCp := make([]string, len(hosts))
+ copy(hostsCp, hosts)
+ return hostsCp
+ }
+ }
+ return nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/hosts_test.go b/platform/dbops/binaries/go/go/src/net/hosts_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..5f22920765bd7678c385e84975425500319e4951
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/hosts_test.go
@@ -0,0 +1,214 @@
+// 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 net
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+type staticHostEntry struct {
+ in string
+ out []string
+}
+
+var lookupStaticHostTests = []struct {
+ name string
+ ents []staticHostEntry
+}{
+ {
+ "testdata/hosts",
+ []staticHostEntry{
+ {"odin", []string{"127.0.0.2", "127.0.0.3", "::2"}},
+ {"thor", []string{"127.1.1.1"}},
+ {"ullr", []string{"127.1.1.2"}},
+ {"ullrhost", []string{"127.1.1.2"}},
+ {"localhost", []string{"fe80::1%lo0"}},
+ },
+ },
+ {
+ "testdata/singleline-hosts", // see golang.org/issue/6646
+ []staticHostEntry{
+ {"odin", []string{"127.0.0.2"}},
+ },
+ },
+ {
+ "testdata/ipv4-hosts",
+ []staticHostEntry{
+ {"localhost", []string{"127.0.0.1", "127.0.0.2", "127.0.0.3"}},
+ {"localhost.localdomain", []string{"127.0.0.3"}},
+ },
+ },
+ {
+ "testdata/ipv6-hosts", // see golang.org/issue/8996
+ []staticHostEntry{
+ {"localhost", []string{"::1", "fe80::1", "fe80::2%lo0", "fe80::3%lo0"}},
+ {"localhost.localdomain", []string{"fe80::3%lo0"}},
+ },
+ },
+ {
+ "testdata/case-hosts", // see golang.org/issue/12806
+ []staticHostEntry{
+ {"PreserveMe", []string{"127.0.0.1", "::1"}},
+ {"PreserveMe.local", []string{"127.0.0.1", "::1"}},
+ },
+ },
+}
+
+func TestLookupStaticHost(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+
+ for _, tt := range lookupStaticHostTests {
+ hostsFilePath = tt.name
+ for _, ent := range tt.ents {
+ testStaticHost(t, tt.name, ent)
+ }
+ }
+}
+
+func testStaticHost(t *testing.T, hostsPath string, ent staticHostEntry) {
+ ins := []string{ent.in, absDomainName(ent.in), strings.ToLower(ent.in), strings.ToUpper(ent.in)}
+ for _, in := range ins {
+ addrs, _ := lookupStaticHost(in)
+ if !reflect.DeepEqual(addrs, ent.out) {
+ t.Errorf("%s, lookupStaticHost(%s) = %v; want %v", hostsPath, in, addrs, ent.out)
+ }
+ }
+}
+
+var lookupStaticAddrTests = []struct {
+ name string
+ ents []staticHostEntry
+}{
+ {
+ "testdata/hosts",
+ []staticHostEntry{
+ {"255.255.255.255", []string{"broadcasthost"}},
+ {"127.0.0.2", []string{"odin"}},
+ {"127.0.0.3", []string{"odin"}},
+ {"::2", []string{"odin"}},
+ {"127.1.1.1", []string{"thor"}},
+ {"127.1.1.2", []string{"ullr", "ullrhost"}},
+ {"fe80::1%lo0", []string{"localhost"}},
+ },
+ },
+ {
+ "testdata/singleline-hosts", // see golang.org/issue/6646
+ []staticHostEntry{
+ {"127.0.0.2", []string{"odin"}},
+ },
+ },
+ {
+ "testdata/ipv4-hosts",
+ []staticHostEntry{
+ {"127.0.0.1", []string{"localhost"}},
+ {"127.0.0.2", []string{"localhost"}},
+ {"127.0.0.3", []string{"localhost", "localhost.localdomain"}},
+ },
+ },
+ {
+ "testdata/ipv6-hosts", // see golang.org/issue/8996
+ []staticHostEntry{
+ {"::1", []string{"localhost"}},
+ {"fe80::1", []string{"localhost"}},
+ {"fe80::2%lo0", []string{"localhost"}},
+ {"fe80::3%lo0", []string{"localhost", "localhost.localdomain"}},
+ },
+ },
+ {
+ "testdata/case-hosts", // see golang.org/issue/12806
+ []staticHostEntry{
+ {"127.0.0.1", []string{"PreserveMe", "PreserveMe.local"}},
+ {"::1", []string{"PreserveMe", "PreserveMe.local"}},
+ },
+ },
+}
+
+func TestLookupStaticAddr(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+
+ for _, tt := range lookupStaticAddrTests {
+ hostsFilePath = tt.name
+ for _, ent := range tt.ents {
+ testStaticAddr(t, tt.name, ent)
+ }
+ }
+}
+
+func testStaticAddr(t *testing.T, hostsPath string, ent staticHostEntry) {
+ hosts := lookupStaticAddr(ent.in)
+ for i := range ent.out {
+ ent.out[i] = absDomainName(ent.out[i])
+ }
+ if !reflect.DeepEqual(hosts, ent.out) {
+ t.Errorf("%s, lookupStaticAddr(%s) = %v; want %v", hostsPath, ent.in, hosts, ent.out)
+ }
+}
+
+func TestHostCacheModification(t *testing.T) {
+ // Ensure that programs can't modify the internals of the host cache.
+ // See https://golang.org/issues/14212.
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+
+ hostsFilePath = "testdata/ipv4-hosts"
+ ent := staticHostEntry{"localhost", []string{"127.0.0.1", "127.0.0.2", "127.0.0.3"}}
+ testStaticHost(t, hostsFilePath, ent)
+ // Modify the addresses return by lookupStaticHost.
+ addrs, _ := lookupStaticHost(ent.in)
+ for i := range addrs {
+ addrs[i] += "junk"
+ }
+ testStaticHost(t, hostsFilePath, ent)
+
+ hostsFilePath = "testdata/ipv6-hosts"
+ ent = staticHostEntry{"::1", []string{"localhost"}}
+ testStaticAddr(t, hostsFilePath, ent)
+ // Modify the hosts return by lookupStaticAddr.
+ hosts := lookupStaticAddr(ent.in)
+ for i := range hosts {
+ hosts[i] += "junk"
+ }
+ testStaticAddr(t, hostsFilePath, ent)
+}
+
+var lookupStaticHostAliasesTest = []struct {
+ lookup, res string
+}{
+ // 127.0.0.1
+ {"test", "test"},
+ // 127.0.0.2
+ {"test2.example.com", "test2.example.com"},
+ {"2.test", "test2.example.com"},
+ // 127.0.0.3
+ {"test3.example.com", "3.test"},
+ {"3.test", "3.test"},
+ // 127.0.0.4
+ {"example.com", "example.com"},
+ // 127.0.0.5
+ {"test5.example.com", "test4.example.com"},
+ {"5.test", "test4.example.com"},
+ {"4.test", "test4.example.com"},
+ {"test4.example.com", "test4.example.com"},
+}
+
+func TestLookupStaticHostAliases(t *testing.T) {
+ defer func(orig string) { hostsFilePath = orig }(hostsFilePath)
+
+ hostsFilePath = "testdata/aliases"
+ for _, ent := range lookupStaticHostAliasesTest {
+ testLookupStaticHostAliases(t, ent.lookup, absDomainName(ent.res))
+ }
+}
+
+func testLookupStaticHostAliases(t *testing.T, lookup, lookupRes string) {
+ ins := []string{lookup, absDomainName(lookup), strings.ToLower(lookup), strings.ToUpper(lookup)}
+ for _, in := range ins {
+ _, res := lookupStaticHost(in)
+ if res != lookupRes {
+ t.Errorf("lookupStaticHost(%v): got %v, want %v", in, res, lookupRes)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface.go b/platform/dbops/binaries/go/go/src/net/interface.go
new file mode 100644
index 0000000000000000000000000000000000000000..20ac07d31a4a54caefd75705480141c7e17f3599
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface.go
@@ -0,0 +1,259 @@
+// 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 net
+
+import (
+ "errors"
+ "internal/itoa"
+ "sync"
+ "time"
+)
+
+// BUG(mikio): On JS, methods and functions related to
+// Interface are not implemented.
+
+// BUG(mikio): On AIX, DragonFly BSD, NetBSD, OpenBSD, Plan 9 and
+// Solaris, the MulticastAddrs method of Interface is not implemented.
+
+var (
+ errInvalidInterface = errors.New("invalid network interface")
+ errInvalidInterfaceIndex = errors.New("invalid network interface index")
+ errInvalidInterfaceName = errors.New("invalid network interface name")
+ errNoSuchInterface = errors.New("no such network interface")
+ errNoSuchMulticastInterface = errors.New("no such multicast network interface")
+)
+
+// Interface represents a mapping between network interface name
+// and index. It also represents network interface facility
+// information.
+type Interface struct {
+ Index int // positive integer that starts at one, zero is never used
+ MTU int // maximum transmission unit
+ Name string // e.g., "en0", "lo0", "eth0.100"
+ HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
+ Flags Flags // e.g., FlagUp, FlagLoopback, FlagMulticast
+}
+
+type Flags uint
+
+const (
+ FlagUp Flags = 1 << iota // interface is administratively up
+ FlagBroadcast // interface supports broadcast access capability
+ FlagLoopback // interface is a loopback interface
+ FlagPointToPoint // interface belongs to a point-to-point link
+ FlagMulticast // interface supports multicast access capability
+ FlagRunning // interface is in running state
+)
+
+var flagNames = []string{
+ "up",
+ "broadcast",
+ "loopback",
+ "pointtopoint",
+ "multicast",
+ "running",
+}
+
+func (f Flags) String() string {
+ s := ""
+ for i, name := range flagNames {
+ if f&(1< 0 {
+ ifm := (*syscall.IfMsgHdr)(unsafe.Pointer(&tab[0]))
+ if ifm.Msglen == 0 {
+ break
+ }
+ if ifm.Type == syscall.RTM_IFINFO {
+ if ifindex == 0 || ifindex == int(ifm.Index) {
+ sdl := (*rawSockaddrDatalink)(unsafe.Pointer(&tab[syscall.SizeofIfMsghdr]))
+
+ ifi := &Interface{Index: int(ifm.Index), Flags: linkFlags(ifm.Flags)}
+ ifi.Name = string(sdl.Data[:sdl.Nlen])
+ ifi.HardwareAddr = sdl.Data[sdl.Nlen : sdl.Nlen+sdl.Alen]
+
+ // Retrieve MTU
+ ifr := &ifreq{}
+ copy(ifr.Name[:], ifi.Name)
+ err = unix.Ioctl(sock, syscall.SIOCGIFMTU, unsafe.Pointer(ifr))
+ if err != nil {
+ return nil, err
+ }
+ ifi.MTU = int(ifr.Ifru[0])<<24 | int(ifr.Ifru[1])<<16 | int(ifr.Ifru[2])<<8 | int(ifr.Ifru[3])
+
+ ift = append(ift, *ifi)
+ if ifindex == int(ifm.Index) {
+ break
+ }
+ }
+ }
+ tab = tab[ifm.Msglen:]
+ }
+
+ return ift, nil
+}
+
+func linkFlags(rawFlags int32) Flags {
+ var f Flags
+ if rawFlags&syscall.IFF_UP != 0 {
+ f |= FlagUp
+ }
+ if rawFlags&syscall.IFF_RUNNING != 0 {
+ f |= FlagRunning
+ }
+ if rawFlags&syscall.IFF_BROADCAST != 0 {
+ f |= FlagBroadcast
+ }
+ if rawFlags&syscall.IFF_LOOPBACK != 0 {
+ f |= FlagLoopback
+ }
+ if rawFlags&syscall.IFF_POINTOPOINT != 0 {
+ f |= FlagPointToPoint
+ }
+ if rawFlags&syscall.IFF_MULTICAST != 0 {
+ f |= FlagMulticast
+ }
+ return f
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ tab, err := getIfList()
+ if err != nil {
+ return nil, err
+ }
+
+ var ifat []Addr
+ for len(tab) > 0 {
+ ifm := (*syscall.IfMsgHdr)(unsafe.Pointer(&tab[0]))
+ if ifm.Msglen == 0 {
+ break
+ }
+ if ifm.Type == syscall.RTM_NEWADDR {
+ if ifi == nil || ifi.Index == int(ifm.Index) {
+ mask := ifm.Addrs
+ off := uint(syscall.SizeofIfMsghdr)
+
+ var iprsa, nmrsa *syscall.RawSockaddr
+ for i := uint(0); i < _RTAX_MAX; i++ {
+ if mask&(1< 0 {
+ ift[n].HardwareAddr = make([]byte, len(sa.Addr))
+ copy(ift[n].HardwareAddr, sa.Addr)
+ }
+ for _, sys := range m.Sys() {
+ if imx, ok := sys.(*route.InterfaceMetrics); ok {
+ ift[n].MTU = imx.MTU
+ break
+ }
+ }
+ n++
+ if ifindex == m.Index {
+ return ift[:n], nil
+ }
+ }
+ }
+ return ift[:n], nil
+}
+
+func linkFlags(rawFlags int) Flags {
+ var f Flags
+ if rawFlags&syscall.IFF_UP != 0 {
+ f |= FlagUp
+ }
+ if rawFlags&syscall.IFF_RUNNING != 0 {
+ f |= FlagRunning
+ }
+ if rawFlags&syscall.IFF_BROADCAST != 0 {
+ f |= FlagBroadcast
+ }
+ if rawFlags&syscall.IFF_LOOPBACK != 0 {
+ f |= FlagLoopback
+ }
+ if rawFlags&syscall.IFF_POINTOPOINT != 0 {
+ f |= FlagPointToPoint
+ }
+ if rawFlags&syscall.IFF_MULTICAST != 0 {
+ f |= FlagMulticast
+ }
+ return f
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ index := 0
+ if ifi != nil {
+ index = ifi.Index
+ }
+ msgs, err := interfaceMessages(index)
+ if err != nil {
+ return nil, err
+ }
+ ifat := make([]Addr, 0, len(msgs))
+ for _, m := range msgs {
+ switch m := m.(type) {
+ case *route.InterfaceAddrMessage:
+ if index != 0 && index != m.Index {
+ continue
+ }
+ var mask IPMask
+ switch sa := m.Addrs[syscall.RTAX_NETMASK].(type) {
+ case *route.Inet4Addr:
+ mask = IPv4Mask(sa.IP[0], sa.IP[1], sa.IP[2], sa.IP[3])
+ case *route.Inet6Addr:
+ mask = make(IPMask, IPv6len)
+ copy(mask, sa.IP[:])
+ }
+ var ip IP
+ switch sa := m.Addrs[syscall.RTAX_IFA].(type) {
+ case *route.Inet4Addr:
+ ip = IPv4(sa.IP[0], sa.IP[1], sa.IP[2], sa.IP[3])
+ case *route.Inet6Addr:
+ ip = make(IP, IPv6len)
+ copy(ip, sa.IP[:])
+ }
+ if ip != nil && mask != nil { // NetBSD may contain route.LinkAddr
+ ifat = append(ifat, &IPNet{IP: ip, Mask: mask})
+ }
+ }
+ }
+ return ifat, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_bsd_test.go b/platform/dbops/binaries/go/go/src/net/interface_bsd_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..ce59962f6108f42e50f4f740b368933dbd420b15
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_bsd_test.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.
+
+//go:build darwin || dragonfly || freebsd || netbsd || openbsd
+
+package net
+
+import (
+ "errors"
+ "fmt"
+ "os/exec"
+ "runtime"
+)
+
+func (ti *testInterface) setBroadcast(vid int) error {
+ if runtime.GOOS == "openbsd" {
+ ti.name = fmt.Sprintf("vether%d", vid)
+ } else {
+ ti.name = fmt.Sprintf("vlan%d", vid)
+ }
+ xname, err := exec.LookPath("ifconfig")
+ if err != nil {
+ return err
+ }
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ifconfig", ti.name, "create"},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ifconfig", ti.name, "destroy"},
+ })
+ return nil
+}
+
+func (ti *testInterface) setPointToPoint(suffix int) error {
+ ti.name = fmt.Sprintf("gif%d", suffix)
+ xname, err := exec.LookPath("ifconfig")
+ if err != nil {
+ return err
+ }
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ifconfig", ti.name, "create"},
+ })
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ifconfig", ti.name, "inet", ti.local, ti.remote},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ifconfig", ti.name, "destroy"},
+ })
+ return nil
+}
+
+func (ti *testInterface) setLinkLocal(suffix int) error {
+ return errors.New("not yet implemented for BSD")
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_bsdvar.go b/platform/dbops/binaries/go/go/src/net/interface_bsdvar.go
new file mode 100644
index 0000000000000000000000000000000000000000..e9bea3d3798a0672c4132114a93767e66b3d7f15
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_bsdvar.go
@@ -0,0 +1,28 @@
+// 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.
+
+//go:build dragonfly || netbsd || openbsd
+
+package net
+
+import (
+ "syscall"
+
+ "golang.org/x/net/route"
+)
+
+func interfaceMessages(ifindex int) ([]route.Message, error) {
+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_IFLIST, ifindex)
+ if err != nil {
+ return nil, err
+ }
+ return route.ParseRIB(syscall.NET_RT_IFLIST, rib)
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ // TODO(mikio): Implement this like other platforms.
+ return nil, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_darwin.go b/platform/dbops/binaries/go/go/src/net/interface_darwin.go
new file mode 100644
index 0000000000000000000000000000000000000000..bb4fd73a987670bca842c0783d84c03324c3e41d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_darwin.go
@@ -0,0 +1,53 @@
+// 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 net
+
+import (
+ "syscall"
+
+ "golang.org/x/net/route"
+)
+
+func interfaceMessages(ifindex int) ([]route.Message, error) {
+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_IFLIST, ifindex)
+ if err != nil {
+ return nil, err
+ }
+ return route.ParseRIB(syscall.NET_RT_IFLIST, rib)
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_IFLIST2, ifi.Index)
+ if err != nil {
+ return nil, err
+ }
+ msgs, err := route.ParseRIB(syscall.NET_RT_IFLIST2, rib)
+ if err != nil {
+ return nil, err
+ }
+ ifmat := make([]Addr, 0, len(msgs))
+ for _, m := range msgs {
+ switch m := m.(type) {
+ case *route.InterfaceMulticastAddrMessage:
+ if ifi.Index != m.Index {
+ continue
+ }
+ var ip IP
+ switch sa := m.Addrs[syscall.RTAX_IFA].(type) {
+ case *route.Inet4Addr:
+ ip = IPv4(sa.IP[0], sa.IP[1], sa.IP[2], sa.IP[3])
+ case *route.Inet6Addr:
+ ip = make(IP, IPv6len)
+ copy(ip, sa.IP[:])
+ }
+ if ip != nil {
+ ifmat = append(ifmat, &IPAddr{IP: ip})
+ }
+ }
+ }
+ return ifmat, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_freebsd.go b/platform/dbops/binaries/go/go/src/net/interface_freebsd.go
new file mode 100644
index 0000000000000000000000000000000000000000..8536bd3cf6482bbd46a9934497c1c0705fd3d8bf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_freebsd.go
@@ -0,0 +1,53 @@
+// 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 net
+
+import (
+ "syscall"
+
+ "golang.org/x/net/route"
+)
+
+func interfaceMessages(ifindex int) ([]route.Message, error) {
+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, route.RIBTypeInterface, ifindex)
+ if err != nil {
+ return nil, err
+ }
+ return route.ParseRIB(route.RIBTypeInterface, rib)
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_IFMALIST, ifi.Index)
+ if err != nil {
+ return nil, err
+ }
+ msgs, err := route.ParseRIB(syscall.NET_RT_IFMALIST, rib)
+ if err != nil {
+ return nil, err
+ }
+ ifmat := make([]Addr, 0, len(msgs))
+ for _, m := range msgs {
+ switch m := m.(type) {
+ case *route.InterfaceMulticastAddrMessage:
+ if ifi.Index != m.Index {
+ continue
+ }
+ var ip IP
+ switch sa := m.Addrs[syscall.RTAX_IFA].(type) {
+ case *route.Inet4Addr:
+ ip = IPv4(sa.IP[0], sa.IP[1], sa.IP[2], sa.IP[3])
+ case *route.Inet6Addr:
+ ip = make(IP, IPv6len)
+ copy(ip, sa.IP[:])
+ }
+ if ip != nil {
+ ifmat = append(ifmat, &IPAddr{IP: ip})
+ }
+ }
+ }
+ return ifmat, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_linux.go b/platform/dbops/binaries/go/go/src/net/interface_linux.go
new file mode 100644
index 0000000000000000000000000000000000000000..9112ecc854c74ca4e272c767eb033f899aea949c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_linux.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 net
+
+import (
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// If the ifindex is zero, interfaceTable returns mappings of all
+// network interfaces. Otherwise it returns a mapping of a specific
+// interface.
+func interfaceTable(ifindex int) ([]Interface, error) {
+ tab, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC)
+ if err != nil {
+ return nil, os.NewSyscallError("netlinkrib", err)
+ }
+ msgs, err := syscall.ParseNetlinkMessage(tab)
+ if err != nil {
+ return nil, os.NewSyscallError("parsenetlinkmessage", err)
+ }
+ var ift []Interface
+loop:
+ for _, m := range msgs {
+ switch m.Header.Type {
+ case syscall.NLMSG_DONE:
+ break loop
+ case syscall.RTM_NEWLINK:
+ ifim := (*syscall.IfInfomsg)(unsafe.Pointer(&m.Data[0]))
+ if ifindex == 0 || ifindex == int(ifim.Index) {
+ attrs, err := syscall.ParseNetlinkRouteAttr(&m)
+ if err != nil {
+ return nil, os.NewSyscallError("parsenetlinkrouteattr", err)
+ }
+ ift = append(ift, *newLink(ifim, attrs))
+ if ifindex == int(ifim.Index) {
+ break loop
+ }
+ }
+ }
+ }
+ return ift, nil
+}
+
+const (
+ // See linux/if_arp.h.
+ // Note that Linux doesn't support IPv4 over IPv6 tunneling.
+ sysARPHardwareIPv4IPv4 = 768 // IPv4 over IPv4 tunneling
+ sysARPHardwareIPv6IPv6 = 769 // IPv6 over IPv6 tunneling
+ sysARPHardwareIPv6IPv4 = 776 // IPv6 over IPv4 tunneling
+ sysARPHardwareGREIPv4 = 778 // any over GRE over IPv4 tunneling
+ sysARPHardwareGREIPv6 = 823 // any over GRE over IPv6 tunneling
+)
+
+func newLink(ifim *syscall.IfInfomsg, attrs []syscall.NetlinkRouteAttr) *Interface {
+ ifi := &Interface{Index: int(ifim.Index), Flags: linkFlags(ifim.Flags)}
+ for _, a := range attrs {
+ switch a.Attr.Type {
+ case syscall.IFLA_ADDRESS:
+ // We never return any /32 or /128 IP address
+ // prefix on any IP tunnel interface as the
+ // hardware address.
+ switch len(a.Value) {
+ case IPv4len:
+ switch ifim.Type {
+ case sysARPHardwareIPv4IPv4, sysARPHardwareGREIPv4, sysARPHardwareIPv6IPv4:
+ continue
+ }
+ case IPv6len:
+ switch ifim.Type {
+ case sysARPHardwareIPv6IPv6, sysARPHardwareGREIPv6:
+ continue
+ }
+ }
+ var nonzero bool
+ for _, b := range a.Value {
+ if b != 0 {
+ nonzero = true
+ break
+ }
+ }
+ if nonzero {
+ ifi.HardwareAddr = a.Value[:]
+ }
+ case syscall.IFLA_IFNAME:
+ ifi.Name = string(a.Value[:len(a.Value)-1])
+ case syscall.IFLA_MTU:
+ ifi.MTU = int(*(*uint32)(unsafe.Pointer(&a.Value[:4][0])))
+ }
+ }
+ return ifi
+}
+
+func linkFlags(rawFlags uint32) Flags {
+ var f Flags
+ if rawFlags&syscall.IFF_UP != 0 {
+ f |= FlagUp
+ }
+ if rawFlags&syscall.IFF_RUNNING != 0 {
+ f |= FlagRunning
+ }
+ if rawFlags&syscall.IFF_BROADCAST != 0 {
+ f |= FlagBroadcast
+ }
+ if rawFlags&syscall.IFF_LOOPBACK != 0 {
+ f |= FlagLoopback
+ }
+ if rawFlags&syscall.IFF_POINTOPOINT != 0 {
+ f |= FlagPointToPoint
+ }
+ if rawFlags&syscall.IFF_MULTICAST != 0 {
+ f |= FlagMulticast
+ }
+ return f
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ tab, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, syscall.AF_UNSPEC)
+ if err != nil {
+ return nil, os.NewSyscallError("netlinkrib", err)
+ }
+ msgs, err := syscall.ParseNetlinkMessage(tab)
+ if err != nil {
+ return nil, os.NewSyscallError("parsenetlinkmessage", err)
+ }
+ var ift []Interface
+ if ifi == nil {
+ var err error
+ ift, err = interfaceTable(0)
+ if err != nil {
+ return nil, err
+ }
+ }
+ ifat, err := addrTable(ift, ifi, msgs)
+ if err != nil {
+ return nil, err
+ }
+ return ifat, nil
+}
+
+func addrTable(ift []Interface, ifi *Interface, msgs []syscall.NetlinkMessage) ([]Addr, error) {
+ var ifat []Addr
+loop:
+ for _, m := range msgs {
+ switch m.Header.Type {
+ case syscall.NLMSG_DONE:
+ break loop
+ case syscall.RTM_NEWADDR:
+ ifam := (*syscall.IfAddrmsg)(unsafe.Pointer(&m.Data[0]))
+ if len(ift) != 0 || ifi.Index == int(ifam.Index) {
+ if len(ift) != 0 {
+ var err error
+ ifi, err = interfaceByIndex(ift, int(ifam.Index))
+ if err != nil {
+ return nil, err
+ }
+ }
+ attrs, err := syscall.ParseNetlinkRouteAttr(&m)
+ if err != nil {
+ return nil, os.NewSyscallError("parsenetlinkrouteattr", err)
+ }
+ ifa := newAddr(ifam, attrs)
+ if ifa != nil {
+ ifat = append(ifat, ifa)
+ }
+ }
+ }
+ }
+ return ifat, nil
+}
+
+func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) Addr {
+ var ipPointToPoint bool
+ // Seems like we need to make sure whether the IP interface
+ // stack consists of IP point-to-point numbered or unnumbered
+ // addressing.
+ for _, a := range attrs {
+ if a.Attr.Type == syscall.IFA_LOCAL {
+ ipPointToPoint = true
+ break
+ }
+ }
+ for _, a := range attrs {
+ if ipPointToPoint && a.Attr.Type == syscall.IFA_ADDRESS {
+ continue
+ }
+ switch ifam.Family {
+ case syscall.AF_INET:
+ return &IPNet{IP: IPv4(a.Value[0], a.Value[1], a.Value[2], a.Value[3]), Mask: CIDRMask(int(ifam.Prefixlen), 8*IPv4len)}
+ case syscall.AF_INET6:
+ ifa := &IPNet{IP: make(IP, IPv6len), Mask: CIDRMask(int(ifam.Prefixlen), 8*IPv6len)}
+ copy(ifa.IP, a.Value[:])
+ return ifa
+ }
+ }
+ return nil
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ ifmat4 := parseProcNetIGMP("/proc/net/igmp", ifi)
+ ifmat6 := parseProcNetIGMP6("/proc/net/igmp6", ifi)
+ return append(ifmat4, ifmat6...), nil
+}
+
+func parseProcNetIGMP(path string, ifi *Interface) []Addr {
+ fd, err := open(path)
+ if err != nil {
+ return nil
+ }
+ defer fd.close()
+ var (
+ ifmat []Addr
+ name string
+ )
+ fd.readLine() // skip first line
+ b := make([]byte, IPv4len)
+ for l, ok := fd.readLine(); ok; l, ok = fd.readLine() {
+ f := splitAtBytes(l, " :\r\t\n")
+ if len(f) < 4 {
+ continue
+ }
+ switch {
+ case l[0] != ' ' && l[0] != '\t': // new interface line
+ name = f[1]
+ case len(f[0]) == 8:
+ if ifi == nil || name == ifi.Name {
+ // The Linux kernel puts the IP
+ // address in /proc/net/igmp in native
+ // endianness.
+ for i := 0; i+1 < len(f[0]); i += 2 {
+ b[i/2], _ = xtoi2(f[0][i:i+2], 0)
+ }
+ i := *(*uint32)(unsafe.Pointer(&b[:4][0]))
+ ifma := &IPAddr{IP: IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i))}
+ ifmat = append(ifmat, ifma)
+ }
+ }
+ }
+ return ifmat
+}
+
+func parseProcNetIGMP6(path string, ifi *Interface) []Addr {
+ fd, err := open(path)
+ if err != nil {
+ return nil
+ }
+ defer fd.close()
+ var ifmat []Addr
+ b := make([]byte, IPv6len)
+ for l, ok := fd.readLine(); ok; l, ok = fd.readLine() {
+ f := splitAtBytes(l, " \r\t\n")
+ if len(f) < 6 {
+ continue
+ }
+ if ifi == nil || f[1] == ifi.Name {
+ for i := 0; i+1 < len(f[2]); i += 2 {
+ b[i/2], _ = xtoi2(f[2][i:i+2], 0)
+ }
+ ifma := &IPAddr{IP: IP{b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]}}
+ ifmat = append(ifmat, ifma)
+ }
+ }
+ return ifmat
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_linux_test.go b/platform/dbops/binaries/go/go/src/net/interface_linux_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..0699fec636833f8fe36469012ebb569222e60c1b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_linux_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 net
+
+import (
+ "fmt"
+ "os/exec"
+ "testing"
+)
+
+func (ti *testInterface) setBroadcast(suffix int) error {
+ ti.name = fmt.Sprintf("gotest%d", suffix)
+ xname, err := exec.LookPath("ip")
+ if err != nil {
+ return err
+ }
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "link", "add", ti.name, "type", "dummy"},
+ })
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "add", ti.local, "peer", ti.remote, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "del", ti.local, "peer", ti.remote, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "link", "delete", ti.name, "type", "dummy"},
+ })
+ return nil
+}
+
+func (ti *testInterface) setLinkLocal(suffix int) error {
+ ti.name = fmt.Sprintf("gotest%d", suffix)
+ xname, err := exec.LookPath("ip")
+ if err != nil {
+ return err
+ }
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "link", "add", ti.name, "type", "dummy"},
+ })
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "add", ti.local, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "del", ti.local, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "link", "delete", ti.name, "type", "dummy"},
+ })
+ return nil
+}
+
+func (ti *testInterface) setPointToPoint(suffix int) error {
+ ti.name = fmt.Sprintf("gotest%d", suffix)
+ xname, err := exec.LookPath("ip")
+ if err != nil {
+ return err
+ }
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "tunnel", "add", ti.name, "mode", "gre", "local", ti.local, "remote", ti.remote},
+ })
+ ti.setupCmds = append(ti.setupCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "add", ti.local, "peer", ti.remote, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "address", "del", ti.local, "peer", ti.remote, "dev", ti.name},
+ })
+ ti.teardownCmds = append(ti.teardownCmds, &exec.Cmd{
+ Path: xname,
+ Args: []string{"ip", "tunnel", "del", ti.name, "mode", "gre", "local", ti.local, "remote", ti.remote},
+ })
+ return nil
+}
+
+const (
+ numOfTestIPv4MCAddrs = 14
+ numOfTestIPv6MCAddrs = 18
+)
+
+var (
+ igmpInterfaceTable = []Interface{
+ {Name: "lo"},
+ {Name: "eth0"}, {Name: "eth1"}, {Name: "eth2"},
+ {Name: "eth0.100"}, {Name: "eth0.101"}, {Name: "eth0.102"}, {Name: "eth0.103"},
+ {Name: "device1tap2"},
+ }
+ igmp6InterfaceTable = []Interface{
+ {Name: "lo"},
+ {Name: "eth0"}, {Name: "eth1"}, {Name: "eth2"},
+ {Name: "eth0.100"}, {Name: "eth0.101"}, {Name: "eth0.102"}, {Name: "eth0.103"},
+ {Name: "device1tap2"},
+ {Name: "pan0"},
+ }
+)
+
+func TestParseProcNet(t *testing.T) {
+ defer func() {
+ if p := recover(); p != nil {
+ t.Fatalf("panicked: %v", p)
+ }
+ }()
+
+ var ifmat4 []Addr
+ for _, ifi := range igmpInterfaceTable {
+ ifmat := parseProcNetIGMP("testdata/igmp", &ifi)
+ ifmat4 = append(ifmat4, ifmat...)
+ }
+ if len(ifmat4) != numOfTestIPv4MCAddrs {
+ t.Fatalf("got %d; want %d", len(ifmat4), numOfTestIPv4MCAddrs)
+ }
+
+ var ifmat6 []Addr
+ for _, ifi := range igmp6InterfaceTable {
+ ifmat := parseProcNetIGMP6("testdata/igmp6", &ifi)
+ ifmat6 = append(ifmat6, ifmat...)
+ }
+ if len(ifmat6) != numOfTestIPv6MCAddrs {
+ t.Fatalf("got %d; want %d", len(ifmat6), numOfTestIPv6MCAddrs)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_plan9.go b/platform/dbops/binaries/go/go/src/net/interface_plan9.go
new file mode 100644
index 0000000000000000000000000000000000000000..92b2eed2591bcac7af2f7435514ac3e91aa0ef69
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_plan9.go
@@ -0,0 +1,200 @@
+// 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 net
+
+import (
+ "errors"
+ "internal/itoa"
+ "os"
+)
+
+// If the ifindex is zero, interfaceTable returns mappings of all
+// network interfaces. Otherwise it returns a mapping of a specific
+// interface.
+func interfaceTable(ifindex int) ([]Interface, error) {
+ if ifindex == 0 {
+ n, err := interfaceCount()
+ if err != nil {
+ return nil, err
+ }
+ ifcs := make([]Interface, n)
+ for i := range ifcs {
+ ifc, err := readInterface(i)
+ if err != nil {
+ return nil, err
+ }
+ ifcs[i] = *ifc
+ }
+ return ifcs, nil
+ }
+
+ ifc, err := readInterface(ifindex - 1)
+ if err != nil {
+ return nil, err
+ }
+ return []Interface{*ifc}, nil
+}
+
+func readInterface(i int) (*Interface, error) {
+ ifc := &Interface{
+ Index: i + 1, // Offset the index by one to suit the contract
+ Name: netdir + "/ipifc/" + itoa.Itoa(i), // Name is the full path to the interface path in plan9
+ }
+
+ ifcstat := ifc.Name + "/status"
+ ifcstatf, err := open(ifcstat)
+ if err != nil {
+ return nil, err
+ }
+ defer ifcstatf.close()
+
+ line, ok := ifcstatf.readLine()
+ if !ok {
+ return nil, errors.New("invalid interface status file: " + ifcstat)
+ }
+
+ fields := getFields(line)
+ if len(fields) < 4 {
+ return nil, errors.New("invalid interface status file: " + ifcstat)
+ }
+
+ device := fields[1]
+ mtustr := fields[3]
+
+ mtu, _, ok := dtoi(mtustr)
+ if !ok {
+ return nil, errors.New("invalid status file of interface: " + ifcstat)
+ }
+ ifc.MTU = mtu
+
+ // Not a loopback device ("/dev/null") or packet interface (e.g. "pkt2")
+ if stringsHasPrefix(device, netdir+"/") {
+ deviceaddrf, err := open(device + "/addr")
+ if err != nil {
+ return nil, err
+ }
+ defer deviceaddrf.close()
+
+ line, ok = deviceaddrf.readLine()
+ if !ok {
+ return nil, errors.New("invalid address file for interface: " + device + "/addr")
+ }
+
+ if len(line) > 0 && len(line)%2 == 0 {
+ ifc.HardwareAddr = make([]byte, len(line)/2)
+ var ok bool
+ for i := range ifc.HardwareAddr {
+ j := (i + 1) * 2
+ ifc.HardwareAddr[i], ok = xtoi2(line[i*2:j], 0)
+ if !ok {
+ ifc.HardwareAddr = ifc.HardwareAddr[:i]
+ break
+ }
+ }
+ }
+
+ ifc.Flags = FlagUp | FlagRunning | FlagBroadcast | FlagMulticast
+ } else {
+ ifc.Flags = FlagUp | FlagRunning | FlagMulticast | FlagLoopback
+ }
+
+ return ifc, nil
+}
+
+func interfaceCount() (int, error) {
+ d, err := os.Open(netdir + "/ipifc")
+ if err != nil {
+ return -1, err
+ }
+ defer d.Close()
+
+ names, err := d.Readdirnames(0)
+ if err != nil {
+ return -1, err
+ }
+
+ // Assumes that numbered files in ipifc are strictly
+ // the incrementing numbered directories for the
+ // interfaces
+ c := 0
+ for _, name := range names {
+ if _, _, ok := dtoi(name); !ok {
+ continue
+ }
+ c++
+ }
+
+ return c, nil
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ var ifcs []Interface
+ if ifi == nil {
+ var err error
+ ifcs, err = interfaceTable(0)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ ifcs = []Interface{*ifi}
+ }
+
+ var addrs []Addr
+ for _, ifc := range ifcs {
+ status := ifc.Name + "/status"
+ statusf, err := open(status)
+ if err != nil {
+ return nil, err
+ }
+ defer statusf.close()
+
+ // Read but ignore first line as it only contains the table header.
+ // See https://9p.io/magic/man2html/3/ip
+ if _, ok := statusf.readLine(); !ok {
+ return nil, errors.New("cannot read header line for interface: " + status)
+ }
+
+ for line, ok := statusf.readLine(); ok; line, ok = statusf.readLine() {
+ fields := getFields(line)
+ if len(fields) < 1 {
+ return nil, errors.New("cannot parse IP address for interface: " + status)
+ }
+ addr := fields[0]
+ ip := ParseIP(addr)
+ if ip == nil {
+ return nil, errors.New("cannot parse IP address for interface: " + status)
+ }
+
+ // The mask is represented as CIDR relative to the IPv6 address.
+ // Plan 9 internal representation is always IPv6.
+ maskfld := fields[1]
+ maskfld = maskfld[1:]
+ pfxlen, _, ok := dtoi(maskfld)
+ if !ok {
+ return nil, errors.New("cannot parse network mask for interface: " + status)
+ }
+ var mask IPMask
+ if ip.To4() != nil { // IPv4 or IPv6 IPv4-mapped address
+ mask = CIDRMask(pfxlen-8*len(v4InV6Prefix), 8*IPv4len)
+ }
+ if ip.To16() != nil && ip.To4() == nil { // IPv6 address
+ mask = CIDRMask(pfxlen, 8*IPv6len)
+ }
+
+ addrs = append(addrs, &IPNet{IP: ip, Mask: mask})
+ }
+ }
+
+ return addrs, nil
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ return nil, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_solaris.go b/platform/dbops/binaries/go/go/src/net/interface_solaris.go
new file mode 100644
index 0000000000000000000000000000000000000000..32f503f45b29bac6857cd1e93f142747cc0fed4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_solaris.go
@@ -0,0 +1,92 @@
+// 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 net
+
+import (
+ "syscall"
+
+ "golang.org/x/net/lif"
+)
+
+// If the ifindex is zero, interfaceTable returns mappings of all
+// network interfaces. Otherwise it returns a mapping of a specific
+// interface.
+func interfaceTable(ifindex int) ([]Interface, error) {
+ lls, err := lif.Links(syscall.AF_UNSPEC, "")
+ if err != nil {
+ return nil, err
+ }
+ var ift []Interface
+ for _, ll := range lls {
+ if ifindex != 0 && ifindex != ll.Index {
+ continue
+ }
+ ifi := Interface{Index: ll.Index, MTU: ll.MTU, Name: ll.Name, Flags: linkFlags(ll.Flags)}
+ if len(ll.Addr) > 0 {
+ ifi.HardwareAddr = HardwareAddr(ll.Addr)
+ }
+ ift = append(ift, ifi)
+ }
+ return ift, nil
+}
+
+func linkFlags(rawFlags int) Flags {
+ var f Flags
+ if rawFlags&syscall.IFF_UP != 0 {
+ f |= FlagUp
+ }
+ if rawFlags&syscall.IFF_RUNNING != 0 {
+ f |= FlagRunning
+ }
+ if rawFlags&syscall.IFF_BROADCAST != 0 {
+ f |= FlagBroadcast
+ }
+ if rawFlags&syscall.IFF_LOOPBACK != 0 {
+ f |= FlagLoopback
+ }
+ if rawFlags&syscall.IFF_POINTOPOINT != 0 {
+ f |= FlagPointToPoint
+ }
+ if rawFlags&syscall.IFF_MULTICAST != 0 {
+ f |= FlagMulticast
+ }
+ return f
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ var name string
+ if ifi != nil {
+ name = ifi.Name
+ }
+ as, err := lif.Addrs(syscall.AF_UNSPEC, name)
+ if err != nil {
+ return nil, err
+ }
+ var ifat []Addr
+ for _, a := range as {
+ var ip IP
+ var mask IPMask
+ switch a := a.(type) {
+ case *lif.Inet4Addr:
+ ip = IPv4(a.IP[0], a.IP[1], a.IP[2], a.IP[3])
+ mask = CIDRMask(a.PrefixLen, 8*IPv4len)
+ case *lif.Inet6Addr:
+ ip = make(IP, IPv6len)
+ copy(ip, a.IP[:])
+ mask = CIDRMask(a.PrefixLen, 8*IPv6len)
+ }
+ ifat = append(ifat, &IPNet{IP: ip, Mask: mask})
+ }
+ return ifat, nil
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ return nil, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_stub.go b/platform/dbops/binaries/go/go/src/net/interface_stub.go
new file mode 100644
index 0000000000000000000000000000000000000000..4c280c6ff2efa48250d0a60359165fe32430a616
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_stub.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.
+
+//go:build js || wasip1
+
+package net
+
+// If the ifindex is zero, interfaceTable returns mappings of all
+// network interfaces. Otherwise it returns a mapping of a specific
+// interface.
+func interfaceTable(ifindex int) ([]Interface, error) {
+ return nil, nil
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ return nil, nil
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ return nil, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_test.go b/platform/dbops/binaries/go/go/src/net/interface_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..a97d675e7e0bd6802d3558936a8a1d868c6e4b0b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_test.go
@@ -0,0 +1,380 @@
+// 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 net
+
+import (
+ "fmt"
+ "reflect"
+ "runtime"
+ "testing"
+)
+
+// loopbackInterface returns an available logical network interface
+// for loopback tests. It returns nil if no suitable interface is
+// found.
+func loopbackInterface() *Interface {
+ ift, err := Interfaces()
+ if err != nil {
+ return nil
+ }
+ for _, ifi := range ift {
+ if ifi.Flags&FlagLoopback != 0 && ifi.Flags&FlagUp != 0 {
+ return &ifi
+ }
+ }
+ return nil
+}
+
+// ipv6LinkLocalUnicastAddr returns an IPv6 link-local unicast address
+// on the given network interface for tests. It returns "" if no
+// suitable address is found.
+func ipv6LinkLocalUnicastAddr(ifi *Interface) string {
+ if ifi == nil {
+ return ""
+ }
+ ifat, err := ifi.Addrs()
+ if err != nil {
+ return ""
+ }
+ for _, ifa := range ifat {
+ if ifa, ok := ifa.(*IPNet); ok {
+ if ifa.IP.To4() == nil && ifa.IP.IsLinkLocalUnicast() {
+ return ifa.IP.String()
+ }
+ }
+ }
+ return ""
+}
+
+func TestInterfaces(t *testing.T) {
+ ift, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, ifi := range ift {
+ ifxi, err := InterfaceByIndex(ifi.Index)
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch runtime.GOOS {
+ case "solaris", "illumos":
+ if ifxi.Index != ifi.Index {
+ t.Errorf("got %v; want %v", ifxi, ifi)
+ }
+ default:
+ if !reflect.DeepEqual(ifxi, &ifi) {
+ t.Errorf("got %v; want %v", ifxi, ifi)
+ }
+ }
+ ifxn, err := InterfaceByName(ifi.Name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(ifxn, &ifi) {
+ t.Errorf("got %v; want %v", ifxn, ifi)
+ }
+ t.Logf("%s: flags=%v index=%d mtu=%d hwaddr=%v", ifi.Name, ifi.Flags, ifi.Index, ifi.MTU, ifi.HardwareAddr)
+ }
+}
+
+func TestInterfaceAddrs(t *testing.T) {
+ ift, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ifStats := interfaceStats(ift)
+ ifat, err := InterfaceAddrs()
+ if err != nil {
+ t.Fatal(err)
+ }
+ uniStats, err := validateInterfaceUnicastAddrs(ifat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := checkUnicastStats(ifStats, uniStats); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestInterfaceUnicastAddrs(t *testing.T) {
+ ift, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ifStats := interfaceStats(ift)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var uniStats routeStats
+ for _, ifi := range ift {
+ ifat, err := ifi.Addrs()
+ if err != nil {
+ t.Fatal(ifi, err)
+ }
+ stats, err := validateInterfaceUnicastAddrs(ifat)
+ if err != nil {
+ t.Fatal(ifi, err)
+ }
+ uniStats.ipv4 += stats.ipv4
+ uniStats.ipv6 += stats.ipv6
+ }
+ if err := checkUnicastStats(ifStats, &uniStats); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestInterfaceMulticastAddrs(t *testing.T) {
+ ift, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ifStats := interfaceStats(ift)
+ ifat, err := InterfaceAddrs()
+ if err != nil {
+ t.Fatal(err)
+ }
+ uniStats, err := validateInterfaceUnicastAddrs(ifat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var multiStats routeStats
+ for _, ifi := range ift {
+ ifmat, err := ifi.MulticastAddrs()
+ if err != nil {
+ t.Fatal(ifi, err)
+ }
+ stats, err := validateInterfaceMulticastAddrs(ifmat)
+ if err != nil {
+ t.Fatal(ifi, err)
+ }
+ multiStats.ipv4 += stats.ipv4
+ multiStats.ipv6 += stats.ipv6
+ }
+ if err := checkMulticastStats(ifStats, uniStats, &multiStats); err != nil {
+ t.Fatal(err)
+ }
+}
+
+type ifStats struct {
+ loop int // # of active loopback interfaces
+ other int // # of active other interfaces
+}
+
+func interfaceStats(ift []Interface) *ifStats {
+ var stats ifStats
+ for _, ifi := range ift {
+ if ifi.Flags&FlagUp != 0 {
+ if ifi.Flags&FlagLoopback != 0 {
+ stats.loop++
+ } else {
+ stats.other++
+ }
+ }
+ }
+ return &stats
+}
+
+type routeStats struct {
+ ipv4, ipv6 int // # of active connected unicast, anycast or multicast routes
+}
+
+func validateInterfaceUnicastAddrs(ifat []Addr) (*routeStats, error) {
+ // Note: BSD variants allow assigning any IPv4/IPv6 address
+ // prefix to IP interface. For example,
+ // - 0.0.0.0/0 through 255.255.255.255/32
+ // - ::/0 through ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128
+ // In other words, there is no tightly-coupled combination of
+ // interface address prefixes and connected routes.
+ stats := new(routeStats)
+ for _, ifa := range ifat {
+ switch ifa := ifa.(type) {
+ case *IPNet:
+ if ifa == nil || ifa.IP == nil || ifa.IP.IsMulticast() || ifa.Mask == nil {
+ return nil, fmt.Errorf("unexpected value: %#v", ifa)
+ }
+ if len(ifa.IP) != IPv6len {
+ return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa)
+ }
+ prefixLen, maxPrefixLen := ifa.Mask.Size()
+ if ifa.IP.To4() != nil {
+ if 0 >= prefixLen || prefixLen > 8*IPv4len || maxPrefixLen != 8*IPv4len {
+ return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa)
+ }
+ if ifa.IP.IsLoopback() && prefixLen < 8 { // see RFC 1122
+ return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa)
+ }
+ stats.ipv4++
+ }
+ if ifa.IP.To16() != nil && ifa.IP.To4() == nil {
+ if 0 >= prefixLen || prefixLen > 8*IPv6len || maxPrefixLen != 8*IPv6len {
+ return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa)
+ }
+ if ifa.IP.IsLoopback() && prefixLen != 8*IPv6len { // see RFC 4291
+ return nil, fmt.Errorf("unexpected prefix length: %d/%d for %#v", prefixLen, maxPrefixLen, ifa)
+ }
+ stats.ipv6++
+ }
+ case *IPAddr:
+ if ifa == nil || ifa.IP == nil || ifa.IP.IsMulticast() {
+ return nil, fmt.Errorf("unexpected value: %#v", ifa)
+ }
+ if len(ifa.IP) != IPv6len {
+ return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa)
+ }
+ if ifa.IP.To4() != nil {
+ stats.ipv4++
+ }
+ if ifa.IP.To16() != nil && ifa.IP.To4() == nil {
+ stats.ipv6++
+ }
+ default:
+ return nil, fmt.Errorf("unexpected type: %T", ifa)
+ }
+ }
+ return stats, nil
+}
+
+func validateInterfaceMulticastAddrs(ifat []Addr) (*routeStats, error) {
+ stats := new(routeStats)
+ for _, ifa := range ifat {
+ switch ifa := ifa.(type) {
+ case *IPAddr:
+ if ifa == nil || ifa.IP == nil || ifa.IP.IsUnspecified() || !ifa.IP.IsMulticast() {
+ return nil, fmt.Errorf("unexpected value: %#v", ifa)
+ }
+ if len(ifa.IP) != IPv6len {
+ return nil, fmt.Errorf("should be internal representation either IPv6 or IPv4-mapped IPv6 address: %#v", ifa)
+ }
+ if ifa.IP.To4() != nil {
+ stats.ipv4++
+ }
+ if ifa.IP.To16() != nil && ifa.IP.To4() == nil {
+ stats.ipv6++
+ }
+ default:
+ return nil, fmt.Errorf("unexpected type: %T", ifa)
+ }
+ }
+ return stats, nil
+}
+
+func checkUnicastStats(ifStats *ifStats, uniStats *routeStats) error {
+ // Test the existence of connected unicast routes for IPv4.
+ if supportsIPv4() && ifStats.loop+ifStats.other > 0 && uniStats.ipv4 == 0 {
+ return fmt.Errorf("num IPv4 unicast routes = 0; want >0; summary: %+v, %+v", ifStats, uniStats)
+ }
+ // Test the existence of connected unicast routes for IPv6.
+ // We can assume the existence of ::1/128 when at least one
+ // loopback interface is installed.
+ if supportsIPv6() && ifStats.loop > 0 && uniStats.ipv6 == 0 {
+ return fmt.Errorf("num IPv6 unicast routes = 0; want >0; summary: %+v, %+v", ifStats, uniStats)
+ }
+ return nil
+}
+
+func checkMulticastStats(ifStats *ifStats, uniStats, multiStats *routeStats) error {
+ switch runtime.GOOS {
+ case "aix", "dragonfly", "netbsd", "openbsd", "plan9", "solaris", "illumos":
+ default:
+ // Test the existence of connected multicast route
+ // clones for IPv4. Unlike IPv6, IPv4 multicast
+ // capability is not a mandatory feature, and so IPv4
+ // multicast validation is ignored and we only check
+ // IPv6 below.
+ //
+ // Test the existence of connected multicast route
+ // clones for IPv6. Some platform never uses loopback
+ // interface as the nexthop for multicast routing.
+ // We can assume the existence of connected multicast
+ // route clones when at least two connected unicast
+ // routes, ::1/128 and other, are installed.
+ if supportsIPv6() && ifStats.loop > 0 && uniStats.ipv6 > 1 && multiStats.ipv6 == 0 {
+ return fmt.Errorf("num IPv6 multicast route clones = 0; want >0; summary: %+v, %+v, %+v", ifStats, uniStats, multiStats)
+ }
+ }
+ return nil
+}
+
+func BenchmarkInterfaces(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ for i := 0; i < b.N; i++ {
+ if _, err := Interfaces(); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkInterfaceByIndex(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ ifi := loopbackInterface()
+ if ifi == nil {
+ b.Skip("loopback interface not found")
+ }
+ for i := 0; i < b.N; i++ {
+ if _, err := InterfaceByIndex(ifi.Index); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkInterfaceByName(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ ifi := loopbackInterface()
+ if ifi == nil {
+ b.Skip("loopback interface not found")
+ }
+ for i := 0; i < b.N; i++ {
+ if _, err := InterfaceByName(ifi.Name); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkInterfaceAddrs(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ for i := 0; i < b.N; i++ {
+ if _, err := InterfaceAddrs(); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkInterfacesAndAddrs(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ ifi := loopbackInterface()
+ if ifi == nil {
+ b.Skip("loopback interface not found")
+ }
+ for i := 0; i < b.N; i++ {
+ if _, err := ifi.Addrs(); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkInterfacesAndMulticastAddrs(b *testing.B) {
+ b.ReportAllocs()
+ testHookUninstaller.Do(uninstallTestHooks)
+
+ ifi := loopbackInterface()
+ if ifi == nil {
+ b.Skip("loopback interface not found")
+ }
+ for i := 0; i < b.N; i++ {
+ if _, err := ifi.MulticastAddrs(); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_unix_test.go b/platform/dbops/binaries/go/go/src/net/interface_unix_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..b0a9bcf253d1ce20f7c08c3e976d7f28abf5de62
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_unix_test.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.
+
+//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd
+
+package net
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+type testInterface struct {
+ name string
+ local string
+ remote string
+ setupCmds []*exec.Cmd
+ teardownCmds []*exec.Cmd
+}
+
+func (ti *testInterface) setup() error {
+ for _, cmd := range ti.setupCmds {
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("args=%v out=%q err=%v", cmd.Args, string(out), err)
+ }
+ }
+ return nil
+}
+
+func (ti *testInterface) teardown() error {
+ for _, cmd := range ti.teardownCmds {
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("args=%v out=%q err=%v ", cmd.Args, string(out), err)
+ }
+ }
+ return nil
+}
+
+func TestPointToPointInterface(t *testing.T) {
+ if testing.Short() {
+ t.Skip("avoid external network")
+ }
+ if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
+ t.Skipf("not supported on %s", runtime.GOOS)
+ }
+ if os.Getuid() != 0 {
+ t.Skip("must be root")
+ }
+
+ // We suppose that using IPv4 link-local addresses doesn't
+ // harm anyone.
+ local, remote := "169.254.0.1", "169.254.0.254"
+ ip := ParseIP(remote)
+ for i := 0; i < 3; i++ {
+ ti := &testInterface{local: local, remote: remote}
+ if err := ti.setPointToPoint(5963 + i); err != nil {
+ t.Skipf("test requires external command: %v", err)
+ }
+ if err := ti.setup(); err != nil {
+ if e := err.Error(); strings.Contains(e, "No such device") && strings.Contains(e, "gre0") {
+ t.Skip("skipping test; no gre0 device. likely running in container?")
+ }
+ t.Fatal(err)
+ } else {
+ time.Sleep(3 * time.Millisecond)
+ }
+ ift, err := Interfaces()
+ if err != nil {
+ ti.teardown()
+ t.Fatal(err)
+ }
+ for _, ifi := range ift {
+ if ti.name != ifi.Name {
+ continue
+ }
+ ifat, err := ifi.Addrs()
+ if err != nil {
+ ti.teardown()
+ t.Fatal(err)
+ }
+ for _, ifa := range ifat {
+ if ip.Equal(ifa.(*IPNet).IP) {
+ ti.teardown()
+ t.Fatalf("got %v", ifa)
+ }
+ }
+ }
+ if err := ti.teardown(); err != nil {
+ t.Fatal(err)
+ } else {
+ time.Sleep(3 * time.Millisecond)
+ }
+ }
+}
+
+func TestInterfaceArrivalAndDeparture(t *testing.T) {
+ if testing.Short() {
+ t.Skip("avoid external network")
+ }
+ if os.Getuid() != 0 {
+ t.Skip("must be root")
+ }
+
+ // We suppose that using IPv4 link-local addresses and the
+ // dot1Q ID for Token Ring and FDDI doesn't harm anyone.
+ local, remote := "169.254.0.1", "169.254.0.254"
+ ip := ParseIP(remote)
+ for _, vid := range []int{1002, 1003, 1004, 1005} {
+ ift1, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ti := &testInterface{local: local, remote: remote}
+ if err := ti.setBroadcast(vid); err != nil {
+ t.Skipf("test requires external command: %v", err)
+ }
+ if err := ti.setup(); err != nil {
+ t.Fatal(err)
+ } else {
+ time.Sleep(3 * time.Millisecond)
+ }
+ ift2, err := Interfaces()
+ if err != nil {
+ ti.teardown()
+ t.Fatal(err)
+ }
+ if len(ift2) <= len(ift1) {
+ for _, ifi := range ift1 {
+ t.Logf("before: %v", ifi)
+ }
+ for _, ifi := range ift2 {
+ t.Logf("after: %v", ifi)
+ }
+ ti.teardown()
+ t.Fatalf("got %v; want gt %v", len(ift2), len(ift1))
+ }
+ for _, ifi := range ift2 {
+ if ti.name != ifi.Name {
+ continue
+ }
+ ifat, err := ifi.Addrs()
+ if err != nil {
+ ti.teardown()
+ t.Fatal(err)
+ }
+ for _, ifa := range ifat {
+ if ip.Equal(ifa.(*IPNet).IP) {
+ ti.teardown()
+ t.Fatalf("got %v", ifa)
+ }
+ }
+ }
+ if err := ti.teardown(); err != nil {
+ t.Fatal(err)
+ } else {
+ time.Sleep(3 * time.Millisecond)
+ }
+ ift3, err := Interfaces()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ift3) >= len(ift2) {
+ for _, ifi := range ift2 {
+ t.Logf("before: %v", ifi)
+ }
+ for _, ifi := range ift3 {
+ t.Logf("after: %v", ifi)
+ }
+ t.Fatalf("got %v; want lt %v", len(ift3), len(ift2))
+ }
+ }
+}
+
+func TestInterfaceArrivalAndDepartureZoneCache(t *testing.T) {
+ if testing.Short() {
+ t.Skip("avoid external network")
+ }
+ if os.Getuid() != 0 {
+ t.Skip("must be root")
+ }
+
+ // Ensure zoneCache is filled:
+ _, _ = Listen("tcp", "[fe80::1%nonexistent]:0")
+
+ ti := &testInterface{local: "fe80::1"}
+ if err := ti.setLinkLocal(0); err != nil {
+ t.Skipf("test requires external command: %v", err)
+ }
+ if err := ti.setup(); err != nil {
+ if e := err.Error(); strings.Contains(e, "Permission denied") {
+ t.Skipf("permission denied, skipping test: %v", e)
+ }
+ t.Fatal(err)
+ }
+ defer ti.teardown()
+
+ time.Sleep(3 * time.Millisecond)
+
+ // If Listen fails (on Linux with “bind: invalid argument”), zoneCache was
+ // not updated when encountering a nonexistent interface:
+ ln, err := Listen("tcp", "[fe80::1%"+ti.name+"]:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ln.Close()
+ if err := ti.teardown(); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/src/net/interface_windows.go b/platform/dbops/binaries/go/go/src/net/interface_windows.go
new file mode 100644
index 0000000000000000000000000000000000000000..22a13128499bcf31d8f37ac0741b3a1a3454987c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/interface_windows.go
@@ -0,0 +1,178 @@
+// 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 net
+
+import (
+ "internal/syscall/windows"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// adapterAddresses returns a list of IP adapter and address
+// structures. The structure contains an IP adapter and flattened
+// multiple IP addresses including unicast, anycast and multicast
+// addresses.
+func adapterAddresses() ([]*windows.IpAdapterAddresses, error) {
+ var b []byte
+ l := uint32(15000) // recommended initial size
+ for {
+ b = make([]byte, l)
+ err := windows.GetAdaptersAddresses(syscall.AF_UNSPEC, windows.GAA_FLAG_INCLUDE_PREFIX, 0, (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])), &l)
+ if err == nil {
+ if l == 0 {
+ return nil, nil
+ }
+ break
+ }
+ if err.(syscall.Errno) != syscall.ERROR_BUFFER_OVERFLOW {
+ return nil, os.NewSyscallError("getadaptersaddresses", err)
+ }
+ if l <= uint32(len(b)) {
+ return nil, os.NewSyscallError("getadaptersaddresses", err)
+ }
+ }
+ var aas []*windows.IpAdapterAddresses
+ for aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&b[0])); aa != nil; aa = aa.Next {
+ aas = append(aas, aa)
+ }
+ return aas, nil
+}
+
+// If the ifindex is zero, interfaceTable returns mappings of all
+// network interfaces. Otherwise it returns a mapping of a specific
+// interface.
+func interfaceTable(ifindex int) ([]Interface, error) {
+ aas, err := adapterAddresses()
+ if err != nil {
+ return nil, err
+ }
+ var ift []Interface
+ for _, aa := range aas {
+ index := aa.IfIndex
+ if index == 0 { // ipv6IfIndex is a substitute for ifIndex
+ index = aa.Ipv6IfIndex
+ }
+ if ifindex == 0 || ifindex == int(index) {
+ ifi := Interface{
+ Index: int(index),
+ Name: windows.UTF16PtrToString(aa.FriendlyName),
+ }
+ if aa.OperStatus == windows.IfOperStatusUp {
+ ifi.Flags |= FlagUp
+ ifi.Flags |= FlagRunning
+ }
+ // For now we need to infer link-layer service
+ // capabilities from media types.
+ // TODO: use MIB_IF_ROW2.AccessType now that we no longer support
+ // Windows XP.
+ switch aa.IfType {
+ case windows.IF_TYPE_ETHERNET_CSMACD, windows.IF_TYPE_ISO88025_TOKENRING, windows.IF_TYPE_IEEE80211, windows.IF_TYPE_IEEE1394:
+ ifi.Flags |= FlagBroadcast | FlagMulticast
+ case windows.IF_TYPE_PPP, windows.IF_TYPE_TUNNEL:
+ ifi.Flags |= FlagPointToPoint | FlagMulticast
+ case windows.IF_TYPE_SOFTWARE_LOOPBACK:
+ ifi.Flags |= FlagLoopback | FlagMulticast
+ case windows.IF_TYPE_ATM:
+ ifi.Flags |= FlagBroadcast | FlagPointToPoint | FlagMulticast // assume all services available; LANE, point-to-point and point-to-multipoint
+ }
+ if aa.Mtu == 0xffffffff {
+ ifi.MTU = -1
+ } else {
+ ifi.MTU = int(aa.Mtu)
+ }
+ if aa.PhysicalAddressLength > 0 {
+ ifi.HardwareAddr = make(HardwareAddr, aa.PhysicalAddressLength)
+ copy(ifi.HardwareAddr, aa.PhysicalAddress[:])
+ }
+ ift = append(ift, ifi)
+ if ifindex == ifi.Index {
+ break
+ }
+ }
+ }
+ return ift, nil
+}
+
+// If the ifi is nil, interfaceAddrTable returns addresses for all
+// network interfaces. Otherwise it returns addresses for a specific
+// interface.
+func interfaceAddrTable(ifi *Interface) ([]Addr, error) {
+ aas, err := adapterAddresses()
+ if err != nil {
+ return nil, err
+ }
+ var ifat []Addr
+ for _, aa := range aas {
+ index := aa.IfIndex
+ if index == 0 { // ipv6IfIndex is a substitute for ifIndex
+ index = aa.Ipv6IfIndex
+ }
+ if ifi == nil || ifi.Index == int(index) {
+ for puni := aa.FirstUnicastAddress; puni != nil; puni = puni.Next {
+ sa, err := puni.Address.Sockaddr.Sockaddr()
+ if err != nil {
+ return nil, os.NewSyscallError("sockaddr", err)
+ }
+ switch sa := sa.(type) {
+ case *syscall.SockaddrInet4:
+ ifat = append(ifat, &IPNet{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]), Mask: CIDRMask(int(puni.OnLinkPrefixLength), 8*IPv4len)})
+ case *syscall.SockaddrInet6:
+ ifa := &IPNet{IP: make(IP, IPv6len), Mask: CIDRMask(int(puni.OnLinkPrefixLength), 8*IPv6len)}
+ copy(ifa.IP, sa.Addr[:])
+ ifat = append(ifat, ifa)
+ }
+ }
+ for pany := aa.FirstAnycastAddress; pany != nil; pany = pany.Next {
+ sa, err := pany.Address.Sockaddr.Sockaddr()
+ if err != nil {
+ return nil, os.NewSyscallError("sockaddr", err)
+ }
+ switch sa := sa.(type) {
+ case *syscall.SockaddrInet4:
+ ifat = append(ifat, &IPAddr{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])})
+ case *syscall.SockaddrInet6:
+ ifa := &IPAddr{IP: make(IP, IPv6len)}
+ copy(ifa.IP, sa.Addr[:])
+ ifat = append(ifat, ifa)
+ }
+ }
+ }
+ }
+ return ifat, nil
+}
+
+// interfaceMulticastAddrTable returns addresses for a specific
+// interface.
+func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error) {
+ aas, err := adapterAddresses()
+ if err != nil {
+ return nil, err
+ }
+ var ifat []Addr
+ for _, aa := range aas {
+ index := aa.IfIndex
+ if index == 0 { // ipv6IfIndex is a substitute for ifIndex
+ index = aa.Ipv6IfIndex
+ }
+ if ifi == nil || ifi.Index == int(index) {
+ for pmul := aa.FirstMulticastAddress; pmul != nil; pmul = pmul.Next {
+ sa, err := pmul.Address.Sockaddr.Sockaddr()
+ if err != nil {
+ return nil, os.NewSyscallError("sockaddr", err)
+ }
+ switch sa := sa.(type) {
+ case *syscall.SockaddrInet4:
+ ifat = append(ifat, &IPAddr{IP: IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])})
+ case *syscall.SockaddrInet6:
+ ifa := &IPAddr{IP: make(IP, IPv6len)}
+ copy(ifa.IP, sa.Addr[:])
+ ifat = append(ifat, ifa)
+ }
+ }
+ }
+ }
+ return ifat, nil
+}
diff --git a/platform/dbops/binaries/go/go/src/net/ip.go b/platform/dbops/binaries/go/go/src/net/ip.go
new file mode 100644
index 0000000000000000000000000000000000000000..6083dd8bf9f60455c9e0e225a5e19bf5add09f7f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/src/net/ip.go
@@ -0,0 +1,542 @@
+// 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.
+
+// IP address manipulations
+//
+// IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes.
+// An IPv4 address can be converted to an IPv6 address by
+// adding a canonical prefix (10 zeros, 2 0xFFs).
+// This library accepts either size of byte slice but always
+// returns 16-byte addresses.
+
+package net
+
+import (
+ "internal/bytealg"
+ "internal/itoa"
+ "net/netip"
+)
+
+// IP address lengths (bytes).
+const (
+ IPv4len = 4
+ IPv6len = 16
+)
+
+// An IP is a single IP address, a slice of bytes.
+// Functions in this package accept either 4-byte (IPv4)
+// or 16-byte (IPv6) slices as input.
+//
+// Note that in this documentation, referring to an
+// IP address as an IPv4 address or an IPv6 address
+// is a semantic property of the address, not just the
+// length of the byte slice: a 16-byte slice can still
+// be an IPv4 address.
+type IP []byte
+
+// An IPMask is a bitmask that can be used to manipulate
+// IP addresses for IP addressing and routing.
+//
+// See type [IPNet] and func [ParseCIDR] for details.
+type IPMask []byte
+
+// An IPNet represents an IP network.
+type IPNet struct {
+ IP IP // network number
+ Mask IPMask // network mask
+}
+
+// IPv4 returns the IP address (in 16-byte form) of the
+// IPv4 address a.b.c.d.
+func IPv4(a, b, c, d byte) IP {
+ p := make(IP, IPv6len)
+ copy(p, v4InV6Prefix)
+ p[12] = a
+ p[13] = b
+ p[14] = c
+ p[15] = d
+ return p
+}
+
+var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
+
+// IPv4Mask returns the IP mask (in 4-byte form) of the
+// IPv4 mask a.b.c.d.
+func IPv4Mask(a, b, c, d byte) IPMask {
+ p := make(IPMask, IPv4len)
+ p[0] = a
+ p[1] = b
+ p[2] = c
+ p[3] = d
+ return p
+}
+
+// CIDRMask returns an [IPMask] consisting of 'ones' 1 bits
+// followed by 0s up to a total length of 'bits' bits.
+// For a mask of this form, CIDRMask is the inverse of [IPMask.Size].
+func CIDRMask(ones, bits int) IPMask {
+ if bits != 8*IPv4len && bits != 8*IPv6len {
+ return nil
+ }
+ if ones < 0 || ones > bits {
+ return nil
+ }
+ l := bits / 8
+ m := make(IPMask, l)
+ n := uint(ones)
+ for i := 0; i < l; i++ {
+ if n >= 8 {
+ m[i] = 0xff
+ n -= 8
+ continue
+ }
+ m[i] = ^byte(0xff >> n)
+ n = 0
+ }
+ return m
+}
+
+// Well-known IPv4 addresses
+var (
+ IPv4bcast = IPv4(255, 255, 255, 255) // limited broadcast
+ IPv4allsys = IPv4(224, 0, 0, 1) // all systems
+ IPv4allrouter = IPv4(224, 0, 0, 2) // all routers
+ IPv4zero = IPv4(0, 0, 0, 0) // all zeros
+)
+
+// Well-known IPv6 addresses
+var (
+ IPv6zero = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ IPv6unspecified = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ IPv6loopback = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
+ IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
+ IPv6linklocalallnodes = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
+ IPv6linklocalallrouters = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
+)
+
+// IsUnspecified reports whether ip is an unspecified address, either
+// the IPv4 address "0.0.0.0" or the IPv6 address "::".
+func (ip IP) IsUnspecified() bool {
+ return ip.Equal(IPv4zero) || ip.Equal(IPv6unspecified)
+}
+
+// IsLoopback reports whether ip is a loopback address.
+func (ip IP) IsLoopback() bool {
+ if ip4 := ip.To4(); ip4 != nil {
+ return ip4[0] == 127
+ }
+ return ip.Equal(IPv6loopback)
+}
+
+// IsPrivate reports whether ip is a private address, according to
+// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
+func (ip IP) IsPrivate() bool {
+ if ip4 := ip.To4(); ip4 != nil {
+ // Following RFC 1918, Section 3. Private Address Space which says:
+ // The Internet Assigned Numbers Authority (IANA) has reserved the
+ // following three blocks of the IP address space for private internets:
+ // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
+ // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
+ // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
+ return ip4[0] == 10 ||
+ (ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
+ (ip4[0] == 192 && ip4[1] == 168)
+ }
+ // Following RFC 4193, Section 8. IANA Considerations which says:
+ // The IANA has assigned the FC00::/7 prefix to "Unique Local Unicast".
+ return len(ip) == IPv6len && ip[0]&0xfe == 0xfc
+}
+
+// IsMulticast reports whether ip is a multicast address.
+func (ip IP) IsMulticast() bool {
+ if ip4 := ip.To4(); ip4 != nil {
+ return ip4[0]&0xf0 == 0xe0
+ }
+ return len(ip) == IPv6len && ip[0] == 0xff
+}
+
+// IsInterfaceLocalMulticast reports whether ip is
+// an interface-local multicast address.
+func (ip IP) IsInterfaceLocalMulticast() bool {
+ return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x01
+}
+
+// IsLinkLocalMulticast reports whether ip is a link-local
+// multicast address.
+func (ip IP) IsLinkLocalMulticast() bool {
+ if ip4 := ip.To4(); ip4 != nil {
+ return ip4[0] == 224 && ip4[1] == 0 && ip4[2] == 0
+ }
+ return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x02
+}
+
+// IsLinkLocalUnicast reports whether ip is a link-local
+// unicast address.
+func (ip IP) IsLinkLocalUnicast() bool {
+ if ip4 := ip.To4(); ip4 != nil {
+ return ip4[0] == 169 && ip4[1] == 254
+ }
+ return len(ip) == IPv6len && ip[0] == 0xfe && ip[1]&0xc0 == 0x80
+}
+
+// IsGlobalUnicast reports whether ip is a global unicast
+// address.
+//
+// The identification of global unicast addresses uses address type
+// identification as defined in RFC 1122, RFC 4632 and RFC 4291 with
+// the exception of IPv4 directed broadcast addresses.
+// It returns true even if ip is in IPv4 private address space or
+// local IPv6 unicast address space.
+func (ip IP) IsGlobalUnicast() bool {
+ return (len(ip) == IPv4len || len(ip) == IPv6len) &&
+ !ip.Equal(IPv4bcast) &&
+ !ip.IsUnspecified() &&
+ !ip.IsLoopback() &&
+ !ip.IsMulticast() &&
+ !ip.IsLinkLocalUnicast()
+}
+
+// Is p all zeros?
+func isZeros(p IP) bool {
+ for i := 0; i < len(p); i++ {
+ if p[i] != 0 {
+ return false
+ }
+ }
+ return true
+}
+
+// To4 converts the IPv4 address ip to a 4-byte representation.
+// If ip is not an IPv4 address, To4 returns nil.
+func (ip IP) To4() IP {
+ if len(ip) == IPv4len {
+ return ip
+ }
+ if len(ip) == IPv6len &&
+ isZeros(ip[0:10]) &&
+ ip[10] == 0xff &&
+ ip[11] == 0xff {
+ return ip[12:16]
+ }
+ return nil
+}
+
+// To16 converts the IP address ip to a 16-byte representation.
+// If ip is not an IP address (it is the wrong length), To16 returns nil.
+func (ip IP) To16() IP {
+ if len(ip) == IPv4len {
+ return IPv4(ip[0], ip[1], ip[2], ip[3])
+ }
+ if len(ip) == IPv6len {
+ return ip
+ }
+ return nil
+}
+
+// Default route masks for IPv4.
+var (
+ classAMask = IPv4Mask(0xff, 0, 0, 0)
+ classBMask = IPv4Mask(0xff, 0xff, 0, 0)
+ classCMask = IPv4Mask(0xff, 0xff, 0xff, 0)
+)
+
+// DefaultMask returns the default IP mask for the IP address ip.
+// Only IPv4 addresses have default masks; DefaultMask returns
+// nil if ip is not a valid IPv4 address.
+func (ip IP) DefaultMask() IPMask {
+ if ip = ip.To4(); ip == nil {
+ return nil
+ }
+ switch {
+ case ip[0] < 0x80:
+ return classAMask
+ case ip[0] < 0xC0:
+ return classBMask
+ default:
+ return classCMask
+ }
+}
+
+func allFF(b []byte) bool {
+ for _, c := range b {
+ if c != 0xff {
+ return false
+ }
+ }
+ return true
+}
+
+// Mask returns the result of masking the IP address ip with mask.
+func (ip IP) Mask(mask IPMask) IP {
+ if len(mask) == IPv6len && len(ip) == IPv4len && allFF(mask[:12]) {
+ mask = mask[12:]
+ }
+ if len(mask) == IPv4len && len(ip) == IPv6len && bytealg.Equal(ip[:12], v4InV6Prefix) {
+ ip = ip[12:]
+ }
+ n := len(ip)
+ if n != len(mask) {
+ return nil
+ }
+ out := make(IP, n)
+ for i := 0; i < n; i++ {
+ out[i] = ip[i] & mask[i]
+ }
+ return out
+}
+
+// String returns the string form of the IP address ip.
+// It returns one of 4 forms:
+// - "", if ip has length 0
+// - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address
+// - IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address
+// - the hexadecimal form of ip, without punctuation, if no other cases apply
+func (ip IP) String() string {
+ if len(ip) == 0 {
+ return ""
+ }
+
+ if len(ip) != IPv4len && len(ip) != IPv6len {
+ return "?" + hexString(ip)
+ }
+ // If IPv4, use dotted notation.
+ if p4 := ip.To4(); len(p4) == IPv4len {
+ return netip.AddrFrom4([4]byte(p4)).String()
+ }
+ return netip.AddrFrom16([16]byte(ip)).String()
+}
+
+func hexString(b []byte) string {
+ s := make([]byte, len(b)*2)
+ for i, tn := range b {
+ s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf]
+ }
+ return string(s)
+}
+
+// ipEmptyString is like ip.String except that it returns
+// an empty string when ip is unset.
+func ipEmptyString(ip IP) string {
+ if len(ip) == 0 {
+ return ""
+ }
+ return ip.String()
+}
+
+// MarshalText implements the [encoding.TextMarshaler] interface.
+// The encoding is the same as returned by [IP.String], with one exception:
+// When len(ip) is zero, it returns an empty slice.
+func (ip IP) MarshalText() ([]byte, error) {
+ if len(ip) == 0 {
+ return []byte(""), nil
+ }
+ if len(ip) != IPv4len && len(ip) != IPv6len {
+ return nil, &AddrError{Err: "invalid IP address", Addr: hexString(ip)}
+ }
+ return []byte(ip.String()), nil
+}
+
+// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
+// The IP address is expected in a form accepted by [ParseIP].
+func (ip *IP) UnmarshalText(text []byte) error {
+ if len(text) == 0 {
+ *ip = nil
+ return nil
+ }
+ s := string(text)
+ x := ParseIP(s)
+ if x == nil {
+ return &ParseError{Type: "IP address", Text: s}
+ }
+ *ip = x
+ return nil
+}
+
+// Equal reports whether ip and x are the same IP address.
+// An IPv4 address and that same address in IPv6 form are
+// considered to be equal.
+func (ip IP) Equal(x IP) bool {
+ if len(ip) == len(x) {
+ return bytealg.Equal(ip, x)
+ }
+ if len(ip) == IPv4len && len(x) == IPv6len {
+ return bytealg.Equal(x[0:12], v4InV6Prefix) && bytealg.Equal(ip, x[12:])
+ }
+ if len(ip) == IPv6len && len(x) == IPv4len {
+ return bytealg.Equal(ip[0:12], v4InV6Prefix) && bytealg.Equal(ip[12:], x)
+ }
+ return false
+}
+
+func (ip IP) matchAddrFamily(x IP) bool {
+ return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil
+}
+
+// If mask is a sequence of 1 bits followed by 0 bits,
+// return the number of 1 bits.
+func simpleMaskLength(mask IPMask) int {
+ var n int
+ for i, v := range mask {
+ if v == 0xff {
+ n += 8
+ continue
+ }
+ // found non-ff byte
+ // count 1 bits
+ for v&0x80 != 0 {
+ n++
+ v <<= 1
+ }
+ // rest must be 0 bits
+ if v != 0 {
+ return -1
+ }
+ for i++; i < len(mask); i++ {
+ if mask[i] != 0 {
+ return -1
+ }
+ }
+ break
+ }
+ return n
+}
+
+// Size returns the number of leading ones and total bits in the mask.
+// If the mask is not in the canonical form--ones followed by zeros--then
+// Size returns 0, 0.
+func (m IPMask) Size() (ones, bits int) {
+ ones, bits = simpleMaskLength(m), len(m)*8
+ if ones == -1 {
+ return 0, 0
+ }
+ return
+}
+
+// String returns the hexadecimal form of m, with no punctuation.
+func (m IPMask) String() string {
+ if len(m) == 0 {
+ return ""
+ }
+ return hexString(m)
+}
+
+func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) {
+ if ip = n.IP.To4(); ip == nil {
+ ip = n.IP
+ if len(ip) != IPv6len {
+ return nil, nil
+ }
+ }
+ m = n.Mask
+ switch len(m) {
+ case IPv4len:
+ if len(ip) != IPv4len {
+ return nil, nil
+ }
+ case IPv6len:
+ if len(ip) == IPv4len {
+ m = m[12:]
+ }
+ default:
+ return nil, nil
+ }
+ return
+}
+
+// Contains reports whether the network includes ip.
+func (n *IPNet) Contains(ip IP) bool {
+ nn, m := networkNumberAndMask(n)
+ if x := ip.To4(); x != nil {
+ ip = x
+ }
+ l := len(ip)
+ if l != len(nn) {
+ return false
+ }
+ for i := 0; i < l; i++ {
+ if nn[i]&m[i] != ip[i]&m[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// Network returns the address's network name, "ip+net".
+func (n *IPNet) Network() string { return "ip+net" }
+
+// String returns the CIDR notation of n like "192.0.2.0/24"
+// or "2001:db8::/48" as defined in RFC 4632 and RFC 4291.
+// If the mask is not in the canonical form, it returns the
+// string which consists of an IP address, followed by a slash
+// character and a mask expressed as hexadecimal form with no
+// punctuation like "198.51.100.0/c000ff00".
+func (n *IPNet) String() string {
+ if n == nil {
+ return ""
+ }
+ nn, m := networkNumberAndMask(n)
+ if nn == nil || m == nil {
+ return ""
+ }
+ l := simpleMaskLength(m)
+ if l == -1 {
+ return nn.String() + "/" + m.String()
+ }
+ return nn.String() + "/" + itoa.Uitoa(uint(l))
+}
+
+// ParseIP parses s as an IP address, returning the result.
+// The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6
+// ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form.
+// If s is not a valid textual representation of an IP address,
+// ParseIP returns nil.
+func ParseIP(s string) IP {
+ if addr, valid := parseIP(s); valid {
+ return IP(addr[:])
+ }
+ return nil
+}
+
+func parseIP(s string) ([16]byte, bool) {
+ ip, err := netip.ParseAddr(s)
+ if err != nil || ip.Zone() != "" {
+ return [16]byte{}, false
+ }
+ return ip.As16(), true
+}
+
+// ParseCIDR parses s as a CIDR notation IP address and prefix length,
+// like "192.0.2.0/24" or "2001:db8::/32", as defined in
+// RFC 4632 and RFC 4291.
+//
+// It returns the IP address and the network implied by the IP and
+// prefix length.
+// For example, ParseCIDR("192.0.2.1/24") returns the IP address
+// 192.0.2.1 and the network 192.0.2.0/24.
+func ParseCIDR(s string) (IP, *IPNet, error) {
+ i := bytealg.IndexByteString(s, '/')
+ if i < 0 {
+ return nil, nil, &ParseError{Type: "CIDR address", Text: s}
+ }
+ addr, mask := s[:i], s[i+1:]
+
+ ipAddr, err := netip.ParseAddr(addr)
+ if err != nil || ipAddr.Zone() != "" {
+ return nil, nil, &ParseError{Type: "CIDR address", Text: s}
+ }
+
+ n, i, ok := dtoi(mask)
+ if !ok || i != len(mask) || n < 0 || n > ipAddr.BitLen() {
+ return nil, nil, &ParseError{Type: "CIDR address", Text: s}
+ }
+ m := CIDRMask(n, ipAddr.BitLen())
+ addr16 := ipAddr.As16()
+ return IP(addr16[:]), &IPNet{IP: IP(addr16[:]).Mask(m), Mask: m}, nil
+}
+
+func copyIP(x IP) IP {
+ y := make(IP, len(x))
+ copy(y, x)
+ return y
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_calls.go b/platform/dbops/binaries/go/go/test/escape_calls.go
new file mode 100644
index 0000000000000000000000000000000000000000..5424c006ee4d0d8b2f9bc032f2e7d80a55c8cbdf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_calls.go
@@ -0,0 +1,61 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for function parameters.
+
+// In this test almost everything is BAD except the simplest cases
+// where input directly flows to output.
+
+package foo
+
+func f(buf []byte) []byte { // ERROR "leaking param: buf to result ~r0 level=0$"
+ return buf
+}
+
+func g(*byte) string
+
+func h(e int) {
+ var x [32]byte // ERROR "moved to heap: x$"
+ g(&f(x[:])[0])
+}
+
+type Node struct {
+ s string
+ left, right *Node
+}
+
+func walk(np **Node) int { // ERROR "leaking param content: np"
+ n := *np
+ w := len(n.s)
+ if n == nil {
+ return 0
+ }
+ wl := walk(&n.left)
+ wr := walk(&n.right)
+ if wl < wr {
+ n.left, n.right = n.right, n.left // ERROR "ignoring self-assignment"
+ wl, wr = wr, wl
+ }
+ *np = n
+ return w + wl + wr
+}
+
+// Test for bug where func var f used prototype's escape analysis results.
+func prototype(xyz []string) {} // ERROR "xyz does not escape"
+func bar() {
+ var got [][]string
+ f := prototype
+ f = func(ss []string) { got = append(got, ss) } // ERROR "leaking param: ss" "func literal does not escape"
+ s := "string"
+ f([]string{s}) // ERROR "\[\]string{...} escapes to heap"
+}
+
+func strmin(a, b, c string) string { // ERROR "leaking param: a to result ~r0 level=0" "leaking param: b to result ~r0 level=0" "leaking param: c to result ~r0 level=0"
+ return min(a, b, c)
+}
+func strmax(a, b, c string) string { // ERROR "leaking param: a to result ~r0 level=0" "leaking param: b to result ~r0 level=0" "leaking param: c to result ~r0 level=0"
+ return max(a, b, c)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_closure.go b/platform/dbops/binaries/go/go/test/escape_closure.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b19d6f6e8fc9020bb5549ff80da1db38fcfd23e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_closure.go
@@ -0,0 +1,193 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for closure arguments.
+
+package escape
+
+var sink interface{}
+
+func ClosureCallArgs0() {
+ x := 0
+ func(p *int) { // ERROR "p does not escape" "func literal does not escape"
+ *p = 1
+ }(&x)
+}
+
+func ClosureCallArgs1() {
+ x := 0
+ for {
+ func(p *int) { // ERROR "p does not escape" "func literal does not escape"
+ *p = 1
+ }(&x)
+ }
+}
+
+func ClosureCallArgs2() {
+ for {
+ x := 0
+ func(p *int) { // ERROR "p does not escape" "func literal does not escape"
+ *p = 1
+ }(&x)
+ }
+}
+
+func ClosureCallArgs3() {
+ x := 0 // ERROR "moved to heap: x"
+ func(p *int) { // ERROR "leaking param: p" "func literal does not escape"
+ sink = p
+ }(&x)
+}
+
+func ClosureCallArgs4() {
+ x := 0
+ _ = func(p *int) *int { // ERROR "leaking param: p to result ~r0" "func literal does not escape"
+ return p
+ }(&x)
+}
+
+func ClosureCallArgs5() {
+ x := 0 // ERROR "moved to heap: x"
+ // TODO(mdempsky): We get "leaking param: p" here because the new escape analysis pass
+ // can tell that p flows directly to sink, but it's a little weird. Re-evaluate.
+ sink = func(p *int) *int { // ERROR "leaking param: p" "func literal does not escape"
+ return p
+ }(&x)
+}
+
+func ClosureCallArgs6() {
+ x := 0 // ERROR "moved to heap: x"
+ func(p *int) { // ERROR "moved to heap: p" "func literal does not escape"
+ sink = &p
+ }(&x)
+}
+
+func ClosureCallArgs7() {
+ var pp *int
+ for {
+ x := 0 // ERROR "moved to heap: x"
+ func(p *int) { // ERROR "leaking param: p" "func literal does not escape"
+ pp = p
+ }(&x)
+ }
+ _ = pp
+}
+
+func ClosureCallArgs8() {
+ x := 0
+ defer func(p *int) { // ERROR "p does not escape" "func literal does not escape"
+ *p = 1
+ }(&x)
+}
+
+func ClosureCallArgs9() {
+ // BAD: x should not leak
+ x := 0 // ERROR "moved to heap: x"
+ for {
+ defer func(p *int) { // ERROR "func literal escapes to heap" "p does not escape"
+ *p = 1
+ }(&x)
+ }
+}
+
+func ClosureCallArgs10() {
+ for {
+ x := 0 // ERROR "moved to heap: x"
+ defer func(p *int) { // ERROR "func literal escapes to heap" "p does not escape"
+ *p = 1
+ }(&x)
+ }
+}
+
+func ClosureCallArgs11() {
+ x := 0 // ERROR "moved to heap: x"
+ defer func(p *int) { // ERROR "leaking param: p" "func literal does not escape"
+ sink = p
+ }(&x)
+}
+
+func ClosureCallArgs12() {
+ x := 0
+ defer func(p *int) *int { // ERROR "leaking param: p to result ~r0" "func literal does not escape"
+ return p
+ }(&x)
+}
+
+func ClosureCallArgs13() {
+ x := 0 // ERROR "moved to heap: x"
+ defer func(p *int) { // ERROR "moved to heap: p" "func literal does not escape"
+ sink = &p
+ }(&x)
+}
+
+func ClosureCallArgs14() {
+ x := 0
+ p := &x
+ _ = func(p **int) *int { // ERROR "leaking param: p to result ~r0 level=1" "func literal does not escape"
+ return *p
+ }(&p)
+}
+
+func ClosureCallArgs15() {
+ x := 0 // ERROR "moved to heap: x"
+ p := &x
+ sink = func(p **int) *int { // ERROR "leaking param content: p" "func literal does not escape"
+ return *p
+ }(&p)
+}
+
+func ClosureLeak1(s string) string { // ERROR "s does not escape"
+ t := s + "YYYY" // ERROR "escapes to heap"
+ return ClosureLeak1a(t) // ERROR "... argument does not escape"
+}
+
+// See #14409 -- returning part of captured var leaks it.
+func ClosureLeak1a(a ...string) string { // ERROR "leaking param: a to result ~r0 level=1$"
+ return func() string { // ERROR "func literal does not escape"
+ return a[0]
+ }()
+}
+
+func ClosureLeak2(s string) string { // ERROR "s does not escape"
+ t := s + "YYYY" // ERROR "escapes to heap"
+ c := ClosureLeak2a(t) // ERROR "... argument does not escape"
+ return c
+}
+func ClosureLeak2a(a ...string) string { // ERROR "leaking param content: a"
+ return ClosureLeak2b(func() string { // ERROR "func literal does not escape"
+ return a[0]
+ })
+}
+func ClosureLeak2b(f func() string) string { // ERROR "f does not escape"
+ return f()
+}
+
+func ClosureIndirect() {
+ f := func(p *int) {} // ERROR "p does not escape" "func literal does not escape"
+ f(new(int)) // ERROR "new\(int\) does not escape"
+
+ g := f
+ g(new(int)) // ERROR "new\(int\) does not escape"
+
+ h := nopFunc
+ h(new(int)) // ERROR "new\(int\) does not escape"
+}
+
+func nopFunc(p *int) {} // ERROR "p does not escape"
+
+func ClosureIndirect2() {
+ f := func(p *int) *int { return p } // ERROR "leaking param: p to result ~r0 level=0" "func literal does not escape"
+
+ f(new(int)) // ERROR "new\(int\) does not escape"
+
+ g := f
+ g(new(int)) // ERROR "new\(int\) does not escape"
+
+ h := nopFunc2
+ h(new(int)) // ERROR "new\(int\) does not escape"
+}
+
+func nopFunc2(p *int) *int { return p } // ERROR "leaking param: p to result ~r0 level=0"
diff --git a/platform/dbops/binaries/go/go/test/escape_field.go b/platform/dbops/binaries/go/go/test/escape_field.go
new file mode 100644
index 0000000000000000000000000000000000000000..95d0784d9167cc9cf358dda69914ef9d0a319af0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_field.go
@@ -0,0 +1,174 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis with respect to field assignments.
+
+package escape
+
+var sink interface{}
+
+type X struct {
+ p1 *int
+ p2 *int
+ a [2]*int
+}
+
+type Y struct {
+ x X
+}
+
+func field0() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ x.p1 = &i
+ sink = x.p1
+}
+
+func field1() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ // BAD: &i should not escape
+ x.p1 = &i
+ sink = x.p2
+}
+
+func field3() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ x.p1 = &i
+ sink = x // ERROR "x escapes to heap"
+}
+
+func field4() {
+ i := 0 // ERROR "moved to heap: i$"
+ var y Y
+ y.x.p1 = &i
+ x := y.x
+ sink = x // ERROR "x escapes to heap"
+}
+
+func field5() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ // BAD: &i should not escape here
+ x.a[0] = &i
+ sink = x.a[1]
+}
+
+// BAD: we are not leaking param x, only x.p2
+func field6(x *X) { // ERROR "leaking param content: x$"
+ sink = x.p2
+}
+
+func field6a() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ // BAD: &i should not escape
+ x.p1 = &i
+ field6(&x)
+}
+
+func field7() {
+ i := 0
+ var y Y
+ y.x.p1 = &i
+ x := y.x
+ var y1 Y
+ y1.x = x
+ _ = y1.x.p1
+}
+
+func field8() {
+ i := 0 // ERROR "moved to heap: i$"
+ var y Y
+ y.x.p1 = &i
+ x := y.x
+ var y1 Y
+ y1.x = x
+ sink = y1.x.p1
+}
+
+func field9() {
+ i := 0 // ERROR "moved to heap: i$"
+ var y Y
+ y.x.p1 = &i
+ x := y.x
+ var y1 Y
+ y1.x = x
+ sink = y1.x // ERROR "y1\.x escapes to heap"
+}
+
+func field10() {
+ i := 0 // ERROR "moved to heap: i$"
+ var y Y
+ // BAD: &i should not escape
+ y.x.p1 = &i
+ x := y.x
+ var y1 Y
+ y1.x = x
+ sink = y1.x.p2
+}
+
+func field11() {
+ i := 0 // ERROR "moved to heap: i$"
+ x := X{p1: &i}
+ sink = x.p1
+}
+
+func field12() {
+ i := 0 // ERROR "moved to heap: i$"
+ // BAD: &i should not escape
+ x := X{p1: &i}
+ sink = x.p2
+}
+
+func field13() {
+ i := 0 // ERROR "moved to heap: i$"
+ x := &X{p1: &i} // ERROR "&X{...} does not escape$"
+ sink = x.p1
+}
+
+func field14() {
+ i := 0 // ERROR "moved to heap: i$"
+ // BAD: &i should not escape
+ x := &X{p1: &i} // ERROR "&X{...} does not escape$"
+ sink = x.p2
+}
+
+func field15() {
+ i := 0 // ERROR "moved to heap: i$"
+ x := &X{p1: &i} // ERROR "&X{...} escapes to heap$"
+ sink = x
+}
+
+func field16() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ // BAD: &i should not escape
+ x.p1 = &i
+ var iface interface{} = x // ERROR "x does not escape"
+ x1 := iface.(X)
+ sink = x1.p2
+}
+
+func field17() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ x.p1 = &i
+ var iface interface{} = x // ERROR "x does not escape"
+ x1 := iface.(X)
+ sink = x1.p1
+}
+
+func field18() {
+ i := 0 // ERROR "moved to heap: i$"
+ var x X
+ // BAD: &i should not escape
+ x.p1 = &i
+ var iface interface{} = x // ERROR "x does not escape"
+ y, _ := iface.(Y) // Put X, but extracted Y. The cast will fail, so y is zero initialized.
+ sink = y // ERROR "y escapes to heap"
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_goto.go b/platform/dbops/binaries/go/go/test/escape_goto.go
new file mode 100644
index 0000000000000000000000000000000000000000..90da5a2151297082b9163b998bae1830c0e36db5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_goto.go
@@ -0,0 +1,44 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for goto statements.
+
+package escape
+
+var x bool
+
+func f1() {
+ var p *int
+loop:
+ if x {
+ goto loop
+ }
+ // BAD: We should be able to recognize that there
+ // aren't any more "goto loop" after here.
+ p = new(int) // ERROR "escapes to heap"
+ _ = p
+}
+
+func f2() {
+ var p *int
+ if x {
+ loop:
+ goto loop
+ } else {
+ p = new(int) // ERROR "does not escape"
+ }
+ _ = p
+}
+
+func f3() {
+ var p *int
+ if x {
+ loop:
+ goto loop
+ }
+ p = new(int) // ERROR "does not escape"
+ _ = p
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_hash_maphash.go b/platform/dbops/binaries/go/go/test/escape_hash_maphash.go
new file mode 100644
index 0000000000000000000000000000000000000000..f8dcc5450d021cccb979b03799f7ef5a5316ad96
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_hash_maphash.go
@@ -0,0 +1,19 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for hash/maphash.
+
+package escape
+
+import (
+ "hash/maphash"
+)
+
+func f() {
+ var x maphash.Hash // should be stack allocatable
+ x.WriteString("foo")
+ x.Sum64()
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_iface.go b/platform/dbops/binaries/go/go/test/escape_iface.go
new file mode 100644
index 0000000000000000000000000000000000000000..d822cca2f8485fa6b263cbb2db1599c9fcd4e0e1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_iface.go
@@ -0,0 +1,265 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for interface conversions.
+
+package escape
+
+var sink interface{}
+
+type M interface {
+ M()
+}
+
+func mescapes(m M) { // ERROR "leaking param: m"
+ sink = m
+}
+
+func mdoesnotescape(m M) { // ERROR "m does not escape"
+}
+
+// Tests for type stored directly in iface and with value receiver method.
+type M0 struct {
+ p *int
+}
+
+func (M0) M() {
+}
+
+func efaceEscape0() {
+ {
+ i := 0
+ v := M0{&i}
+ var x M = v
+ _ = x
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M0{&i}
+ var x M = v
+ sink = x
+ }
+ {
+ i := 0
+ v := M0{&i}
+ var x M = v
+ v1 := x.(M0)
+ _ = v1
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M0{&i}
+ // BAD: v does not escape to heap here
+ var x M = v
+ v1 := x.(M0)
+ sink = v1
+ }
+ {
+ i := 0
+ v := M0{&i}
+ var x M = v
+ x.M() // ERROR "devirtualizing x.M"
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M0{&i}
+ var x M = v
+ mescapes(x)
+ }
+ {
+ i := 0
+ v := M0{&i}
+ var x M = v
+ mdoesnotescape(x)
+ }
+}
+
+// Tests for type stored indirectly in iface and with value receiver method.
+type M1 struct {
+ p *int
+ x int
+}
+
+func (M1) M() {
+}
+
+func efaceEscape1() {
+ {
+ i := 0
+ v := M1{&i, 0}
+ var x M = v // ERROR "v does not escape"
+ _ = x
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M1{&i, 0}
+ var x M = v // ERROR "v escapes to heap"
+ sink = x
+ }
+ {
+ i := 0
+ v := M1{&i, 0}
+ var x M = v // ERROR "v does not escape"
+ v1 := x.(M1)
+ _ = v1
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M1{&i, 0}
+ var x M = v // ERROR "v does not escape"
+ v1 := x.(M1)
+ sink = v1 // ERROR "v1 escapes to heap"
+ }
+ {
+ i := 0
+ v := M1{&i, 0}
+ var x M = v // ERROR "v does not escape"
+ x.M() // ERROR "devirtualizing x.M"
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := M1{&i, 0}
+ var x M = v // ERROR "v escapes to heap"
+ mescapes(x)
+ }
+ {
+ i := 0
+ v := M1{&i, 0}
+ var x M = v // ERROR "v does not escape"
+ mdoesnotescape(x)
+ }
+}
+
+// Tests for type stored directly in iface and with pointer receiver method.
+type M2 struct {
+ p *int
+}
+
+func (*M2) M() {
+}
+
+func efaceEscape2() {
+ {
+ i := 0
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ var x M = v
+ _ = x
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := &M2{&i} // ERROR "&M2{...} escapes to heap"
+ var x M = v
+ sink = x
+ }
+ {
+ i := 0
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ var x M = v
+ v1 := x.(*M2)
+ _ = v1
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := &M2{&i} // ERROR "&M2{...} escapes to heap"
+ // BAD: v does not escape to heap here
+ var x M = v
+ v1 := x.(*M2)
+ sink = v1
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ // BAD: v does not escape to heap here
+ var x M = v
+ v1 := x.(*M2)
+ sink = *v1
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ // BAD: v does not escape to heap here
+ var x M = v
+ v1, ok := x.(*M2)
+ sink = *v1
+ _ = ok
+ }
+ {
+ i := 0
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ var x M = v
+ x.M() // ERROR "devirtualizing x.M"
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ v := &M2{&i} // ERROR "&M2{...} escapes to heap"
+ var x M = v
+ mescapes(x)
+ }
+ {
+ i := 0
+ v := &M2{&i} // ERROR "&M2{...} does not escape"
+ var x M = v
+ mdoesnotescape(x)
+ }
+}
+
+type T1 struct {
+ p *int
+}
+
+type T2 struct {
+ T1 T1
+}
+
+func dotTypeEscape() *T2 { // #11931
+ var x interface{}
+ x = &T1{p: new(int)} // ERROR "new\(int\) escapes to heap" "&T1{...} does not escape"
+ return &T2{ // ERROR "&T2{...} escapes to heap"
+ T1: *(x.(*T1)),
+ }
+}
+
+func dotTypeEscape2() { // #13805, #15796
+ {
+ i := 0
+ j := 0
+ var v int
+ var ok bool
+ var x interface{} = i // ERROR "i does not escape"
+ var y interface{} = j // ERROR "j does not escape"
+
+ *(&v) = x.(int)
+ *(&v), *(&ok) = y.(int)
+ }
+ { // #13805, #15796
+ i := 0
+ j := 0
+ var ok bool
+ var x interface{} = i // ERROR "i does not escape"
+ var y interface{} = j // ERROR "j does not escape"
+
+ sink = x.(int) // ERROR "x.\(int\) escapes to heap"
+ sink, *(&ok) = y.(int) // ERROR "autotmp_.* escapes to heap"
+ }
+ {
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ var ok bool
+ var x interface{} = &i
+ var y interface{} = &j
+
+ sink = x.(*int)
+ sink, *(&ok) = y.(*int)
+ }
+}
+
+func issue42279() {
+ type I interface{ M() }
+ type T struct{ I }
+
+ var i I = T{} // ERROR "T\{\} does not escape"
+ i.M() // ERROR "partially devirtualizing i.M to T"
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_indir.go b/platform/dbops/binaries/go/go/test/escape_indir.go
new file mode 100644
index 0000000000000000000000000000000000000000..12005e35f9f12e9a8a559fe83b0dc0f765f33805
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_indir.go
@@ -0,0 +1,160 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis when assigning to indirections.
+
+package escape
+
+var sink interface{}
+
+type ConstPtr struct {
+ p *int
+ c ConstPtr2
+ x **ConstPtr
+}
+
+type ConstPtr2 struct {
+ p *int
+ i int
+}
+
+func constptr0() {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ // BAD: i should not escape here
+ x.p = &i
+ _ = x
+}
+
+func constptr01() *ConstPtr {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap"
+ x.p = &i
+ return x
+}
+
+func constptr02() ConstPtr {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ x.p = &i
+ return *x
+}
+
+func constptr03() **ConstPtr {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap" "moved to heap: x"
+ x.p = &i
+ return &x
+}
+
+func constptr1() {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap"
+ x.p = &i
+ sink = x
+}
+
+func constptr2() {
+ i := 0 // ERROR "moved to heap: i"
+ x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ x.p = &i
+ sink = *x // ERROR "\*x escapes to heap"
+}
+
+func constptr4() *ConstPtr {
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
+ *p = *&ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ return p
+}
+
+func constptr5() *ConstPtr {
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
+ p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ *p = *p1
+ return p
+}
+
+// BAD: p should not escape here
+func constptr6(p *ConstPtr) { // ERROR "leaking param content: p"
+ p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ *p1 = *p
+ _ = p1
+}
+
+func constptr7() **ConstPtr {
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap" "moved to heap: p"
+ var tmp ConstPtr2
+ p1 := &tmp
+ p.c = *p1
+ return &p
+}
+
+func constptr8() *ConstPtr {
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
+ var tmp ConstPtr2
+ p.c = *&tmp
+ return p
+}
+
+func constptr9() ConstPtr {
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) does not escape"
+ var p1 ConstPtr2
+ i := 0 // ERROR "moved to heap: i"
+ p1.p = &i
+ p.c = p1
+ return *p
+}
+
+func constptr10() ConstPtr {
+ x := &ConstPtr{} // ERROR "moved to heap: x" "&ConstPtr{} escapes to heap"
+ i := 0 // ERROR "moved to heap: i"
+ var p *ConstPtr
+ p = &ConstPtr{p: &i, x: &x} // ERROR "&ConstPtr{...} does not escape"
+ var pp **ConstPtr
+ pp = &p
+ return **pp
+}
+
+func constptr11() *ConstPtr {
+ i := 0 // ERROR "moved to heap: i"
+ p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
+ p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
+ p1.p = &i
+ *p = *p1
+ return p
+}
+
+func foo(p **int) { // ERROR "p does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ y := p
+ *y = &i
+}
+
+func foo1(p *int) { // ERROR "p does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ y := &p
+ *y = &i
+}
+
+func foo2() {
+ type Z struct {
+ f **int
+ }
+ x := new(int) // ERROR "moved to heap: x" "new\(int\) escapes to heap"
+ sink = &x
+ var z Z
+ z.f = &x
+ p := z.f
+ i := 0 // ERROR "moved to heap: i"
+ *p = &i
+}
+
+var global *byte
+
+func f() {
+ var x byte // ERROR "moved to heap: x"
+ global = &*&x
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_level.go b/platform/dbops/binaries/go/go/test/escape_level.go
new file mode 100644
index 0000000000000000000000000000000000000000..33ae54053263f784d7c4d6b341e5a308ec40afbf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_level.go
@@ -0,0 +1,108 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test indirection level computation in escape analysis.
+
+package escape
+
+var sink interface{}
+
+func level0() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i // ERROR "moved to heap: p0"
+ p1 := &p0 // ERROR "moved to heap: p1"
+ p2 := &p1 // ERROR "moved to heap: p2"
+ sink = &p2
+}
+
+func level1() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i // ERROR "moved to heap: p0"
+ p1 := &p0 // ERROR "moved to heap: p1"
+ p2 := &p1
+ sink = p2
+}
+
+func level2() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i // ERROR "moved to heap: p0"
+ p1 := &p0
+ p2 := &p1
+ sink = *p2
+}
+
+func level3() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i
+ p1 := &p0
+ p2 := &p1
+ sink = **p2
+}
+
+func level4() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i // ERROR "moved to heap: p0"
+ p1 := &p0
+ p2 := p1 // ERROR "moved to heap: p2"
+ sink = &p2
+}
+
+func level5() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i // ERROR "moved to heap: p0"
+ p1 := &p0
+ p2 := p1
+ sink = p2
+}
+
+func level6() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i
+ p1 := &p0
+ p2 := p1
+ sink = *p2
+}
+
+func level7() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i
+ p1 := &p0
+ // note *p1 == &i
+ p2 := *p1 // ERROR "moved to heap: p2"
+ sink = &p2
+}
+
+func level8() {
+ i := 0 // ERROR "moved to heap: i"
+ p0 := &i
+ p1 := &p0
+ p2 := *p1
+ sink = p2
+}
+
+func level9() {
+ i := 0
+ p0 := &i
+ p1 := &p0
+ p2 := *p1
+ sink = *p2 // ERROR "\*p2 escapes to heap"
+}
+
+func level10() {
+ i := 0
+ p0 := &i
+ p1 := *p0
+ p2 := &p1
+ sink = *p2 // ERROR "\*p2 escapes to heap"
+}
+
+func level11() {
+ i := 0
+ p0 := &i
+ p1 := &p0
+ p2 := **p1 // ERROR "moved to heap: p2"
+ sink = &p2
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_map.go b/platform/dbops/binaries/go/go/test/escape_map.go
new file mode 100644
index 0000000000000000000000000000000000000000..23abaa1e0cc5e91fa1a1ba7c3f66cc31b812f5a5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_map.go
@@ -0,0 +1,107 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for maps.
+
+package escape
+
+var sink interface{}
+
+func map0() {
+ m := make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) does not escape"
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ // BAD: j should not escape
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+ _ = m
+}
+
+func map1() *int {
+ m := make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) does not escape"
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+ return m[&i]
+}
+
+func map2() map[*int]*int {
+ m := make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) escapes to heap"
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+ return m
+}
+
+func map3() []*int {
+ m := make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ // BAD: j should not escape
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+ var r []*int
+ for k := range m {
+ r = append(r, k)
+ }
+ return r
+}
+
+func map4() []*int {
+ m := make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) does not escape"
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+ var r []*int
+ for k, v := range m {
+ // We want to test exactly "for k, v := range m" rather than "for _, v := range m".
+ // The following if is merely to use (but not leak) k.
+ if k != nil {
+ r = append(r, v)
+ }
+ }
+ return r
+}
+
+func map5(m map[*int]*int) { // ERROR "m does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+}
+
+func map6(m map[*int]*int) { // ERROR "m does not escape"
+ if m != nil {
+ m = make(map[*int]*int) // ERROR "make\(map\[\*int\]\*int\) does not escape"
+ }
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m[&i] = &j
+}
+
+func map7() {
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ // BAD: j should not escape
+ j := 0 // ERROR "moved to heap: j"
+ m := map[*int]*int{&i: &j} // ERROR "map\[\*int\]\*int{...} does not escape"
+ _ = m
+}
+
+func map8() {
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m := map[*int]*int{&i: &j} // ERROR "map\[\*int\]\*int{...} escapes to heap"
+ sink = m
+}
+
+func map9() *int {
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ j := 0 // ERROR "moved to heap: j"
+ m := map[*int]*int{&i: &j} // ERROR "map\[\*int\]\*int{...} does not escape"
+ return m[nil]
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_mutations.go b/platform/dbops/binaries/go/go/test/escape_mutations.go
new file mode 100644
index 0000000000000000000000000000000000000000..4365fc1ec33f0646a0ecd580452a6fbadf4b4d08
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_mutations.go
@@ -0,0 +1,77 @@
+// errorcheck -0 -m -d=escapemutationscalls,zerocopy -l
+
+// 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 B struct {
+ x int
+ px *int
+ pb *B
+}
+
+func F1(b *B) { // ERROR "mutates param: b derefs=0"
+ b.x = 1
+}
+
+func F2(b *B) { // ERROR "mutates param: b derefs=1"
+ *b.px = 1
+}
+
+func F2a(b *B) { // ERROR "mutates param: b derefs=0"
+ b.px = nil
+}
+
+func F3(b *B) { // ERROR "leaking param: b"
+ fmt.Println(b) // ERROR "\.\.\. argument does not escape"
+}
+
+func F4(b *B) { // ERROR "leaking param content: b"
+ fmt.Println(*b) // ERROR "\.\.\. argument does not escape" "\*b escapes to heap"
+}
+
+func F4a(b *B) { // ERROR "leaking param content: b" "mutates param: b derefs=0"
+ b.x = 2
+ fmt.Println(*b) // ERROR "\.\.\. argument does not escape" "\*b escapes to heap"
+}
+
+func F5(b *B) { // ERROR "leaking param: b"
+ sink = b
+}
+
+func F6(b *B) int { // ERROR "b does not escape, mutate, or call"
+ return b.x
+}
+
+var sink any
+
+func M() {
+ var b B // ERROR "moved to heap: b"
+ F1(&b)
+ F2(&b)
+ F2a(&b)
+ F3(&b)
+ F4(&b)
+}
+
+func g(s string) { // ERROR "s does not escape, mutate, or call"
+ sink = &([]byte(s))[10] // ERROR "\(\[\]byte\)\(s\) escapes to heap"
+}
+
+func h(out []byte, s string) { // ERROR "mutates param: out derefs=0" "s does not escape, mutate, or call"
+ copy(out, []byte(s)) // ERROR "zero-copy string->\[\]byte conversion" "\(\[\]byte\)\(s\) does not escape"
+}
+
+func i(s string) byte { // ERROR "s does not escape, mutate, or call"
+ p := []byte(s) // ERROR "zero-copy string->\[\]byte conversion" "\(\[\]byte\)\(s\) does not escape"
+ return p[20]
+}
+
+func j(s string, x byte) { // ERROR "s does not escape, mutate, or call"
+ p := []byte(s) // ERROR "\(\[\]byte\)\(s\) does not escape"
+ p[20] = x
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_param.go b/platform/dbops/binaries/go/go/test/escape_param.go
new file mode 100644
index 0000000000000000000000000000000000000000..b630bae88fcd9b357c442609d07d3495aee0aec8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_param.go
@@ -0,0 +1,441 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for function parameters.
+
+// In this test almost everything is BAD except the simplest cases
+// where input directly flows to output.
+
+package escape
+
+func zero() int { return 0 }
+
+var sink interface{}
+
+// in -> out
+func param0(p *int) *int { // ERROR "leaking param: p to result ~r0"
+ return p
+}
+
+func caller0a() {
+ i := 0
+ _ = param0(&i)
+}
+
+func caller0b() {
+ i := 0 // ERROR "moved to heap: i$"
+ sink = param0(&i)
+}
+
+// in, in -> out, out
+func param1(p1, p2 *int) (*int, *int) { // ERROR "leaking param: p1 to result ~r0" "leaking param: p2 to result ~r1"
+ return p1, p2
+}
+
+func caller1() {
+ i := 0 // ERROR "moved to heap: i$"
+ j := 0
+ sink, _ = param1(&i, &j)
+}
+
+// in -> other in
+func param2(p1 *int, p2 **int) { // ERROR "leaking param: p1$" "p2 does not escape$"
+ *p2 = p1
+}
+
+func caller2a() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ param2(&i, &p)
+ _ = p
+}
+
+func caller2b() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ param2(&i, &p)
+ sink = p
+}
+
+func paramArraySelfAssign(p *PairOfPairs) { // ERROR "p does not escape"
+ p.pairs[0] = p.pairs[1] // ERROR "ignoring self-assignment in p.pairs\[0\] = p.pairs\[1\]"
+}
+
+func paramArraySelfAssignUnsafeIndex(p *PairOfPairs) { // ERROR "leaking param content: p"
+ // Function call inside index disables self-assignment case to trigger.
+ p.pairs[zero()] = p.pairs[1]
+ p.pairs[zero()+1] = p.pairs[1]
+}
+
+type PairOfPairs struct {
+ pairs [2]*Pair
+}
+
+type BoxedPair struct {
+ pair *Pair
+}
+
+type WrappedPair struct {
+ pair Pair
+}
+
+func leakParam(x interface{}) { // ERROR "leaking param: x"
+ sink = x
+}
+
+func sinkAfterSelfAssignment1(box *BoxedPair) { // ERROR "leaking param content: box"
+ box.pair.p1 = box.pair.p2 // ERROR "ignoring self-assignment in box.pair.p1 = box.pair.p2"
+ sink = box.pair.p2
+}
+
+func sinkAfterSelfAssignment2(box *BoxedPair) { // ERROR "leaking param content: box"
+ box.pair.p1 = box.pair.p2 // ERROR "ignoring self-assignment in box.pair.p1 = box.pair.p2"
+ sink = box.pair
+}
+
+func sinkAfterSelfAssignment3(box *BoxedPair) { // ERROR "leaking param content: box"
+ box.pair.p1 = box.pair.p2 // ERROR "ignoring self-assignment in box.pair.p1 = box.pair.p2"
+ leakParam(box.pair.p2)
+}
+
+func sinkAfterSelfAssignment4(box *BoxedPair) { // ERROR "leaking param content: box"
+ box.pair.p1 = box.pair.p2 // ERROR "ignoring self-assignment in box.pair.p1 = box.pair.p2"
+ leakParam(box.pair)
+}
+
+func selfAssignmentAndUnrelated(box1, box2 *BoxedPair) { // ERROR "leaking param content: box2" "box1 does not escape"
+ box1.pair.p1 = box1.pair.p2 // ERROR "ignoring self-assignment in box1.pair.p1 = box1.pair.p2"
+ leakParam(box2.pair.p2)
+}
+
+func notSelfAssignment1(box1, box2 *BoxedPair) { // ERROR "leaking param content: box2" "box1 does not escape"
+ box1.pair.p1 = box2.pair.p1
+}
+
+func notSelfAssignment2(p1, p2 *PairOfPairs) { // ERROR "leaking param content: p2" "p1 does not escape"
+ p1.pairs[0] = p2.pairs[1]
+}
+
+func notSelfAssignment3(p1, p2 *PairOfPairs) { // ERROR "leaking param content: p2" "p1 does not escape"
+ p1.pairs[0].p1 = p2.pairs[1].p1
+}
+
+func boxedPairSelfAssign(box *BoxedPair) { // ERROR "box does not escape"
+ box.pair.p1 = box.pair.p2 // ERROR "ignoring self-assignment in box.pair.p1 = box.pair.p2"
+}
+
+func wrappedPairSelfAssign(w *WrappedPair) { // ERROR "w does not escape"
+ w.pair.p1 = w.pair.p2 // ERROR "ignoring self-assignment in w.pair.p1 = w.pair.p2"
+}
+
+// in -> in
+type Pair struct {
+ p1 *int
+ p2 *int
+}
+
+func param3(p *Pair) { // ERROR "p does not escape"
+ p.p1 = p.p2 // ERROR "param3 ignoring self-assignment in p.p1 = p.p2"
+}
+
+func caller3a() {
+ i := 0
+ j := 0
+ p := Pair{&i, &j}
+ param3(&p)
+ _ = p
+}
+
+func caller3b() {
+ i := 0 // ERROR "moved to heap: i$"
+ j := 0 // ERROR "moved to heap: j$"
+ p := Pair{&i, &j}
+ param3(&p)
+ sink = p // ERROR "p escapes to heap$"
+}
+
+// in -> rcvr
+func (p *Pair) param4(i *int) { // ERROR "p does not escape$" "leaking param: i$"
+ p.p1 = i
+}
+
+func caller4a() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := Pair{}
+ p.param4(&i)
+ _ = p
+}
+
+func caller4b() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := Pair{}
+ p.param4(&i)
+ sink = p // ERROR "p escapes to heap$"
+}
+
+// in -> heap
+func param5(i *int) { // ERROR "leaking param: i$"
+ sink = i
+}
+
+func caller5() {
+ i := 0 // ERROR "moved to heap: i$"
+ param5(&i)
+}
+
+// *in -> heap
+func param6(i ***int) { // ERROR "leaking param content: i$"
+ sink = *i
+}
+
+func caller6a() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ p2 := &p
+ param6(&p2)
+}
+
+// **in -> heap
+func param7(i ***int) { // ERROR "leaking param content: i$"
+ sink = **i
+}
+
+func caller7() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i
+ p2 := &p
+ param7(&p2)
+}
+
+// **in -> heap
+func param8(i **int) { // ERROR "i does not escape$"
+ sink = **i // ERROR "\*\(\*i\) escapes to heap"
+}
+
+func caller8() {
+ i := 0
+ p := &i
+ param8(&p)
+}
+
+// *in -> out
+func param9(p ***int) **int { // ERROR "leaking param: p to result ~r0 level=1"
+ return *p
+}
+
+func caller9a() {
+ i := 0
+ p := &i
+ p2 := &p
+ _ = param9(&p2)
+}
+
+func caller9b() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ p2 := &p
+ sink = param9(&p2)
+}
+
+// **in -> out
+func param10(p ***int) *int { // ERROR "leaking param: p to result ~r0 level=2"
+ return **p
+}
+
+func caller10a() {
+ i := 0
+ p := &i
+ p2 := &p
+ _ = param10(&p2)
+}
+
+func caller10b() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i
+ p2 := &p
+ sink = param10(&p2)
+}
+
+// in escapes to heap (address of param taken and returned)
+func param11(i **int) ***int { // ERROR "moved to heap: i$"
+ return &i
+}
+
+func caller11a() {
+ i := 0 // ERROR "moved to heap: i"
+ p := &i // ERROR "moved to heap: p"
+ _ = param11(&p)
+}
+
+func caller11b() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ sink = param11(&p)
+}
+
+func caller11c() { // GOOD
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p"
+ sink = *param11(&p)
+}
+
+func caller11d() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p"
+ p2 := &p
+ sink = param11(p2)
+}
+
+// &in -> rcvr
+type Indir struct {
+ p ***int
+}
+
+func (r *Indir) param12(i **int) { // ERROR "r does not escape$" "moved to heap: i$"
+ r.p = &i
+}
+
+func caller12a() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ var r Indir
+ r.param12(&p)
+ _ = r
+}
+
+func caller12b() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ r := &Indir{} // ERROR "&Indir{} does not escape$"
+ r.param12(&p)
+ _ = r
+}
+
+func caller12c() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ r := Indir{}
+ r.param12(&p)
+ sink = r
+}
+
+func caller12d() {
+ i := 0 // ERROR "moved to heap: i$"
+ p := &i // ERROR "moved to heap: p$"
+ r := Indir{}
+ r.param12(&p)
+ sink = **r.p
+}
+
+// in -> value rcvr
+type Val struct {
+ p **int
+}
+
+func (v Val) param13(i *int) { // ERROR "v does not escape$" "leaking param: i$"
+ *v.p = i
+}
+
+func caller13a() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ var v Val
+ v.p = &p
+ v.param13(&i)
+ _ = v
+}
+
+func caller13b() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ v := Val{&p}
+ v.param13(&i)
+ _ = v
+}
+
+func caller13c() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ v := &Val{&p} // ERROR "&Val{...} does not escape$"
+ v.param13(&i)
+ _ = v
+}
+
+func caller13d() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int // ERROR "moved to heap: p$"
+ var v Val
+ v.p = &p
+ v.param13(&i)
+ sink = v
+}
+
+func caller13e() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int // ERROR "moved to heap: p$"
+ v := Val{&p}
+ v.param13(&i)
+ sink = v
+}
+
+func caller13f() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int // ERROR "moved to heap: p$"
+ v := &Val{&p} // ERROR "&Val{...} escapes to heap$"
+ v.param13(&i)
+ sink = v
+}
+
+func caller13g() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ v := Val{&p}
+ v.param13(&i)
+ sink = *v.p
+}
+
+func caller13h() {
+ i := 0 // ERROR "moved to heap: i$"
+ var p *int
+ v := &Val{&p} // ERROR "&Val{...} does not escape$"
+ v.param13(&i)
+ sink = **v.p // ERROR "\*\(\*v\.p\) escapes to heap"
+}
+
+type Node struct {
+ p *Node
+}
+
+var Sink *Node
+
+func f(x *Node) { // ERROR "leaking param content: x"
+ Sink = &Node{x.p} // ERROR "&Node{...} escapes to heap"
+}
+
+func g(x *Node) *Node { // ERROR "leaking param content: x"
+ return &Node{x.p} // ERROR "&Node{...} escapes to heap"
+}
+
+func h(x *Node) { // ERROR "leaking param: x"
+ y := &Node{x} // ERROR "&Node{...} does not escape"
+ Sink = g(y)
+ f(y)
+}
+
+// interface(in) -> out
+// See also issue 29353.
+
+// Convert to a non-direct interface, require an allocation and
+// copy x to heap (not to result).
+func param14a(x [4]*int) interface{} { // ERROR "leaking param: x$"
+ return x // ERROR "x escapes to heap"
+}
+
+// Convert to a direct interface, does not need an allocation.
+// So x only leaks to result.
+func param14b(x *int) interface{} { // ERROR "leaking param: x to result ~r0 level=0"
+ return x
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_reflect.go b/platform/dbops/binaries/go/go/test/escape_reflect.go
new file mode 100644
index 0000000000000000000000000000000000000000..99fbada9a98eb4641d151dc4059174f10173224b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_reflect.go
@@ -0,0 +1,462 @@
+// errorcheck -0 -m -l
+
+// 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 escape analysis for reflect Value operations.
+
+package escape
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+var sink interface{}
+
+func typ(x int) any {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Type()
+}
+
+func kind(x int) reflect.Kind {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Kind()
+}
+
+func int1(x int) int {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return int(v.Int())
+}
+
+func ptr(x *int) *int { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x)
+ return (*int)(v.UnsafePointer())
+}
+
+func bytes1(x []byte) byte { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Bytes()[0]
+}
+
+// Unfortunate: should only escape content. x (the interface storage) should not escape.
+func bytes2(x []byte) []byte { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Bytes()
+}
+
+func string1(x string) string { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.String()
+}
+
+func string2(x int) string {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.String()
+}
+
+// Unfortunate: should only escape to result.
+func interface1(x any) any { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x)
+ return v.Interface()
+}
+
+func interface2(x int) any {
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Interface()
+}
+
+// Unfortunate: should not escape.
+func interface3(x int) int {
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Interface().(int)
+}
+
+// Unfortunate: should only escape to result.
+func interface4(x *int) any { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x)
+ return v.Interface()
+}
+
+func addr(x *int) reflect.Value { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x).Elem()
+ return v.Addr()
+}
+
+// functions returning pointer as uintptr have to escape.
+func uintptr1(x *int) uintptr { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x)
+ return v.Pointer()
+}
+
+func unsafeaddr(x *int) uintptr { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x).Elem()
+ return v.UnsafeAddr()
+}
+
+func ifacedata(x any) [2]uintptr { // ERROR "moved to heap: x"
+ v := reflect.ValueOf(&x).Elem()
+ return v.InterfaceData()
+}
+
+func can(x int) bool {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.CanAddr() || v.CanInt() || v.CanSet() || v.CanInterface()
+}
+
+func is(x int) bool {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.IsValid() || v.IsNil() || v.IsZero()
+}
+
+func is2(x [2]int) bool {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.IsValid() || v.IsNil() || v.IsZero()
+}
+
+func is3(x struct{ a, b int }) bool {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.IsValid() || v.IsNil() || v.IsZero()
+}
+
+func overflow(x int) bool {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.OverflowInt(1 << 62)
+}
+
+func len1(x []int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Len()
+}
+
+func len2(x [3]int) int {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Len()
+}
+
+func len3(x string) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Len()
+}
+
+func len4(x map[int]int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x)
+ return v.Len()
+}
+
+func len5(x chan int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x)
+ return v.Len()
+}
+
+func cap1(x []int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Cap()
+}
+
+func cap2(x [3]int) int {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Cap()
+}
+
+func cap3(x chan int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x)
+ return v.Cap()
+}
+
+func setlen(x *[]int, n int) { // ERROR "x does not escape"
+ v := reflect.ValueOf(x).Elem()
+ v.SetLen(n)
+}
+
+func setcap(x *[]int, n int) { // ERROR "x does not escape"
+ v := reflect.ValueOf(x).Elem()
+ v.SetCap(n)
+}
+
+// Unfortunate: x doesn't need to escape to heap, just to result.
+func slice1(x []byte) []byte { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Slice(1, 2).Bytes()
+}
+
+// Unfortunate: x doesn't need to escape to heap, just to result.
+func slice2(x string) string { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Slice(1, 2).String()
+}
+
+func slice3(x [10]byte) []byte {
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Slice(1, 2).Bytes()
+}
+
+func elem1(x *int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x)
+ return int(v.Elem().Int())
+}
+
+func elem2(x *string) string { // ERROR "leaking param: x to result ~r0 level=1"
+ v := reflect.ValueOf(x)
+ return string(v.Elem().String())
+}
+
+type S struct {
+ A int
+ B *int
+ C string
+}
+
+func (S) M() {}
+
+func field1(x S) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return int(v.Field(0).Int())
+}
+
+func field2(x S) string { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Field(2).String()
+}
+
+func numfield(x S) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.NumField()
+}
+
+func index1(x []int) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return int(v.Index(0).Int())
+}
+
+// Unfortunate: should only leak content (level=1)
+func index2(x []string) string { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Index(0).String()
+}
+
+func index3(x [3]int) int {
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return int(v.Index(0).Int())
+}
+
+func index4(x [3]string) string { // ERROR "leaking param: x to result ~r0 level=0"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.Index(0).String()
+}
+
+func index5(x string) byte { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return byte(v.Index(0).Uint())
+}
+
+// Unfortunate: x (the interface storage) doesn't need to escape as the function takes a scalar arg.
+func call1(f func(int), x int) { // ERROR "leaking param: f$"
+ fv := reflect.ValueOf(f)
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ fv.Call([]reflect.Value{v}) // ERROR "\[\]reflect\.Value{\.\.\.} does not escape"
+}
+
+func call2(f func(*int), x *int) { // ERROR "leaking param: f$" "leaking param: x$"
+ fv := reflect.ValueOf(f)
+ v := reflect.ValueOf(x)
+ fv.Call([]reflect.Value{v}) // ERROR "\[\]reflect.Value{\.\.\.} does not escape"
+}
+
+func method(x S) reflect.Value { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Method(0)
+}
+
+func nummethod(x S) int { // ERROR "x does not escape"
+ v := reflect.ValueOf(x) // ERROR "x does not escape"
+ return v.NumMethod()
+}
+
+// Unfortunate: k doesn't need to escape.
+func mapindex(m map[string]string, k string) string { // ERROR "m does not escape" "leaking param: k$"
+ mv := reflect.ValueOf(m)
+ kv := reflect.ValueOf(k) // ERROR "k escapes to heap"
+ return mv.MapIndex(kv).String()
+}
+
+func mapkeys(m map[string]string) []reflect.Value { // ERROR "m does not escape"
+ mv := reflect.ValueOf(m)
+ return mv.MapKeys()
+}
+
+func mapiter1(m map[string]string) *reflect.MapIter { // ERROR "leaking param: m$"
+ mv := reflect.ValueOf(m)
+ return mv.MapRange()
+}
+
+func mapiter2(m map[string]string) string { // ERROR "leaking param: m$"
+ mv := reflect.ValueOf(m)
+ it := mv.MapRange()
+ if it.Next() {
+ return it.Key().String()
+ }
+ return ""
+}
+
+func mapiter3(m map[string]string, it *reflect.MapIter) { // ERROR "leaking param: m$" "it does not escape"
+ mv := reflect.ValueOf(m)
+ it.Reset(mv)
+}
+
+func recv1(ch chan string) string { // ERROR "ch does not escape"
+ v := reflect.ValueOf(ch)
+ r, _ := v.Recv()
+ return r.String()
+}
+
+func recv2(ch chan string) string { // ERROR "ch does not escape"
+ v := reflect.ValueOf(ch)
+ r, _ := v.TryRecv()
+ return r.String()
+}
+
+// Unfortunate: x (the interface storage) doesn't need to escape.
+func send1(ch chan string, x string) { // ERROR "ch does not escape" "leaking param: x$"
+ vc := reflect.ValueOf(ch)
+ vx := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ vc.Send(vx)
+}
+
+// Unfortunate: x (the interface storage) doesn't need to escape.
+func send2(ch chan string, x string) bool { // ERROR "ch does not escape" "leaking param: x$"
+ vc := reflect.ValueOf(ch)
+ vx := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return vc.TrySend(vx)
+}
+
+func close1(ch chan string) { // ERROR "ch does not escape"
+ v := reflect.ValueOf(ch)
+ v.Close()
+}
+
+func select1(ch chan string) string { // ERROR "leaking param: ch$"
+ v := reflect.ValueOf(ch)
+ cas := reflect.SelectCase{Dir: reflect.SelectRecv, Chan: v}
+ _, r, _ := reflect.Select([]reflect.SelectCase{cas}) // ERROR "\[\]reflect.SelectCase{...} does not escape"
+ return r.String()
+}
+
+// Unfortunate: x (the interface storage) doesn't need to escape.
+func select2(ch chan string, x string) { // ERROR "leaking param: ch$" "leaking param: x$"
+ vc := reflect.ValueOf(ch)
+ vx := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ cas := reflect.SelectCase{Dir: reflect.SelectSend, Chan: vc, Send: vx}
+ reflect.Select([]reflect.SelectCase{cas}) // ERROR "\[\]reflect.SelectCase{...} does not escape"
+}
+
+var (
+ intTyp = reflect.TypeOf(int(0)) // ERROR "0 does not escape"
+ uintTyp = reflect.TypeOf(uint(0)) // ERROR "uint\(0\) does not escape"
+ stringTyp = reflect.TypeOf(string("")) // ERROR ".. does not escape"
+ bytesTyp = reflect.TypeOf([]byte{}) // ERROR "\[\]byte{} does not escape"
+)
+
+// Unfortunate: should not escape.
+func convert1(x int) uint {
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return uint(v.Convert(uintTyp).Uint())
+}
+
+// Unfortunate: should only escape content to result.
+func convert2(x []byte) string { // ERROR "leaking param: x$"
+ v := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ return v.Convert(stringTyp).String()
+}
+
+// Unfortunate: v doesn't need to leak, x (the interface storage) doesn't need to escape.
+func set1(v reflect.Value, x int) { // ERROR "leaking param: v$"
+ vx := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ v.Set(vx)
+}
+
+// Unfortunate: a can be stack allocated, x (the interface storage) doesn't need to escape.
+func set2(x int) int64 {
+ var a int // ERROR "moved to heap: a"
+ v := reflect.ValueOf(&a).Elem()
+ vx := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ v.Set(vx)
+ return v.Int()
+}
+
+func set3(v reflect.Value, x int) { // ERROR "v does not escape"
+ v.SetInt(int64(x))
+}
+
+func set4(x int) int {
+ var a int
+ v := reflect.ValueOf(&a).Elem() // a should not escape, no error printed
+ v.SetInt(int64(x))
+ return int(v.Int())
+}
+
+func set5(v reflect.Value, x string) { // ERROR "v does not escape" "leaking param: x$"
+ v.SetString(x)
+}
+
+func set6(v reflect.Value, x []byte) { // ERROR "v does not escape" "leaking param: x$"
+ v.SetBytes(x)
+}
+
+func set7(v reflect.Value, x unsafe.Pointer) { // ERROR "v does not escape" "leaking param: x$"
+ v.SetPointer(x)
+}
+
+func setmapindex(m map[string]string, k, e string) { // ERROR "m does not escape" "leaking param: k$" "leaking param: e$"
+ mv := reflect.ValueOf(m)
+ kv := reflect.ValueOf(k) // ERROR "k escapes to heap"
+ ev := reflect.ValueOf(e) // ERROR "e escapes to heap"
+ mv.SetMapIndex(kv, ev)
+}
+
+// Unfortunate: k doesn't need to escape.
+func mapdelete(m map[string]string, k string) { // ERROR "m does not escape" "leaking param: k$"
+ mv := reflect.ValueOf(m)
+ kv := reflect.ValueOf(k) // ERROR "k escapes to heap"
+ mv.SetMapIndex(kv, reflect.Value{})
+}
+
+// Unfortunate: v doesn't need to leak.
+func setiterkey1(v reflect.Value, it *reflect.MapIter) { // ERROR "leaking param: v$" "it does not escape"
+ v.SetIterKey(it)
+}
+
+// Unfortunate: v doesn't need to leak.
+func setiterkey2(v reflect.Value, m map[string]string) { // ERROR "leaking param: v$" "leaking param: m$"
+ it := reflect.ValueOf(m).MapRange()
+ v.SetIterKey(it)
+}
+
+// Unfortunate: v doesn't need to leak.
+func setitervalue1(v reflect.Value, it *reflect.MapIter) { // ERROR "leaking param: v$" "it does not escape"
+ v.SetIterValue(it)
+}
+
+// Unfortunate: v doesn't need to leak.
+func setitervalue2(v reflect.Value, m map[string]string) { // ERROR "leaking param: v$" "leaking param: m$"
+ it := reflect.ValueOf(m).MapRange()
+ v.SetIterValue(it)
+}
+
+// Unfortunate: s doesn't need escape, only leak to result.
+// And x (interface storage) doesn't need to escape.
+func append1(s []int, x int) []int { // ERROR "leaking param: s$"
+ sv := reflect.ValueOf(s) // ERROR "s escapes to heap"
+ xv := reflect.ValueOf(x) // ERROR "x escapes to heap"
+ rv := reflect.Append(sv, xv) // ERROR "... argument does not escape"
+ return rv.Interface().([]int)
+}
+
+// Unfortunate: s doesn't need escape, only leak to result.
+func append2(s, x []int) []int { // ERROR "leaking param: s$" "x does not escape"
+ sv := reflect.ValueOf(s) // ERROR "s escapes to heap"
+ xv := reflect.ValueOf(x) // ERROR "x does not escape"
+ rv := reflect.AppendSlice(sv, xv)
+ return rv.Interface().([]int)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_runtime_atomic.go b/platform/dbops/binaries/go/go/test/escape_runtime_atomic.go
new file mode 100644
index 0000000000000000000000000000000000000000..30d1d0c0c1d89dc572873f037b20a90dd32003c0
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_runtime_atomic.go
@@ -0,0 +1,33 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for runtime/internal/atomic.
+
+package escape
+
+import (
+ "runtime/internal/atomic"
+ "unsafe"
+)
+
+// BAD: should always be "leaking param: addr to result ~r0 level=1$".
+func Loadp(addr unsafe.Pointer) unsafe.Pointer { // ERROR "leaking param: addr( to result ~r0 level=1)?$"
+ return atomic.Loadp(addr)
+}
+
+var ptr unsafe.Pointer
+
+func Storep() {
+ var x int // ERROR "moved to heap: x"
+ atomic.StorepNoWB(unsafe.Pointer(&ptr), unsafe.Pointer(&x))
+}
+
+func Casp1() {
+ // BAD: should always be "does not escape"
+ x := new(int) // ERROR "escapes to heap|does not escape"
+ var y int // ERROR "moved to heap: y"
+ atomic.Casp1(&ptr, unsafe.Pointer(x), unsafe.Pointer(&y))
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_selfassign.go b/platform/dbops/binaries/go/go/test/escape_selfassign.go
new file mode 100644
index 0000000000000000000000000000000000000000..b4fa2084dff706c640c6e16d8dd32dc985c91776
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_selfassign.go
@@ -0,0 +1,32 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for self assignments.
+
+package escape
+
+type S struct {
+ i int
+ pi *int
+}
+
+var sink S
+
+func f(p *S) { // ERROR "leaking param: p"
+ p.pi = &p.i
+ sink = *p
+}
+
+// BAD: "leaking param: p" is too conservative
+func g(p *S) { // ERROR "leaking param: p"
+ p.pi = &p.i
+}
+
+func h() {
+ var s S // ERROR "moved to heap: s"
+ g(&s)
+ sink = s
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_slice.go b/platform/dbops/binaries/go/go/test/escape_slice.go
new file mode 100644
index 0000000000000000000000000000000000000000..65181e57d7edd34559f0eba3a7a46248c3ae7a47
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_slice.go
@@ -0,0 +1,181 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for slices.
+
+package escape
+
+import (
+ "os"
+ "strings"
+)
+
+var sink interface{}
+
+func slice0() {
+ var s []*int
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ s = append(s, &i)
+ _ = s
+}
+
+func slice1() *int {
+ var s []*int
+ i := 0 // ERROR "moved to heap: i"
+ s = append(s, &i)
+ return s[0]
+}
+
+func slice2() []*int {
+ var s []*int
+ i := 0 // ERROR "moved to heap: i"
+ s = append(s, &i)
+ return s
+}
+
+func slice3() *int {
+ var s []*int
+ i := 0 // ERROR "moved to heap: i"
+ s = append(s, &i)
+ for _, p := range s {
+ return p
+ }
+ return nil
+}
+
+func slice4(s []*int) { // ERROR "s does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ s[0] = &i
+}
+
+func slice5(s []*int) { // ERROR "s does not escape"
+ if s != nil {
+ s = make([]*int, 10) // ERROR "make\(\[\]\*int, 10\) does not escape"
+ }
+ i := 0 // ERROR "moved to heap: i"
+ s[0] = &i
+}
+
+func slice6() {
+ s := make([]*int, 10) // ERROR "make\(\[\]\*int, 10\) does not escape"
+ // BAD: i should not escape
+ i := 0 // ERROR "moved to heap: i"
+ s[0] = &i
+ _ = s
+}
+
+func slice7() *int {
+ s := make([]*int, 10) // ERROR "make\(\[\]\*int, 10\) does not escape"
+ i := 0 // ERROR "moved to heap: i"
+ s[0] = &i
+ return s[0]
+}
+
+func slice8() {
+ i := 0
+ s := []*int{&i} // ERROR "\[\]\*int{...} does not escape"
+ _ = s
+}
+
+func slice9() *int {
+ i := 0 // ERROR "moved to heap: i"
+ s := []*int{&i} // ERROR "\[\]\*int{...} does not escape"
+ return s[0]
+}
+
+func slice10() []*int {
+ i := 0 // ERROR "moved to heap: i"
+ s := []*int{&i} // ERROR "\[\]\*int{...} escapes to heap"
+ return s
+}
+
+func slice11() {
+ i := 2
+ s := make([]int, 2, 3) // ERROR "make\(\[\]int, 2, 3\) does not escape"
+ s = make([]int, i, 3) // ERROR "make\(\[\]int, i, 3\) does not escape"
+ s = make([]int, i, 1) // ERROR "make\(\[\]int, i, 1\) does not escape"
+ _ = s
+}
+
+func slice12(x []int) *[1]int { // ERROR "leaking param: x to result ~r0 level=0$"
+ return (*[1]int)(x)
+}
+
+func slice13(x []*int) [1]*int { // ERROR "leaking param: x to result ~r0 level=1$"
+ return [1]*int(x)
+}
+
+func envForDir(dir string) []string { // ERROR "dir does not escape"
+ env := os.Environ()
+ return mergeEnvLists([]string{"PWD=" + dir}, env) // ERROR ".PWD=. \+ dir escapes to heap" "\[\]string{...} does not escape"
+}
+
+func mergeEnvLists(in, out []string) []string { // ERROR "leaking param content: in" "leaking param content: out" "leaking param: out to result ~r0 level=0"
+NextVar:
+ for _, inkv := range in {
+ k := strings.SplitAfterN(inkv, "=", 2)[0]
+ for i, outkv := range out {
+ if strings.HasPrefix(outkv, k) {
+ out[i] = inkv
+ continue NextVar
+ }
+ }
+ out = append(out, inkv)
+ }
+ return out
+}
+
+const (
+ IPv4len = 4
+ IPv6len = 16
+)
+
+var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
+
+func IPv4(a, b, c, d byte) IP {
+ p := make(IP, IPv6len) // ERROR "make\(IP, 16\) escapes to heap"
+ copy(p, v4InV6Prefix)
+ p[12] = a
+ p[13] = b
+ p[14] = c
+ p[15] = d
+ return p
+}
+
+type IP []byte
+
+type IPAddr struct {
+ IP IP
+ Zone string // IPv6 scoped addressing zone
+}
+
+type resolveIPAddrTest struct {
+ network string
+ litAddrOrName string
+ addr *IPAddr
+ err error
+}
+
+var resolveIPAddrTests = []resolveIPAddrTest{
+ {"ip", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
+ {"ip4", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
+ {"ip4:icmp", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
+}
+
+func setupTestData() {
+ resolveIPAddrTests = append(resolveIPAddrTests,
+ []resolveIPAddrTest{ // ERROR "\[\]resolveIPAddrTest{...} does not escape"
+ {"ip",
+ "localhost",
+ &IPAddr{IP: IPv4(127, 0, 0, 1)}, // ERROR "&IPAddr{...} escapes to heap"
+ nil},
+ {"ip4",
+ "localhost",
+ &IPAddr{IP: IPv4(127, 0, 0, 1)}, // ERROR "&IPAddr{...} escapes to heap"
+ nil},
+ }...)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_struct_param1.go b/platform/dbops/binaries/go/go/test/escape_struct_param1.go
new file mode 100644
index 0000000000000000000000000000000000000000..496172c166ac1bc9c5c9cd96f859e342d3ca9afc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_struct_param1.go
@@ -0,0 +1,298 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for *struct function parameters.
+// Note companion strict_param2 checks struct function parameters with similar tests.
+
+package notmain
+
+var Ssink *string
+
+type U struct {
+ _sp *string
+ _spp **string
+}
+
+type V struct {
+ _u U
+ _up *U
+ _upp **U
+}
+
+func (u *U) SP() *string { // ERROR "leaking param: u to result ~r0 level=1$"
+ return u._sp
+}
+
+func (u *U) SPP() **string { // ERROR "leaking param: u to result ~r0 level=1$"
+ return u._spp
+}
+
+func (u *U) SPPi() *string { // ERROR "leaking param: u to result ~r0 level=2$"
+ return *u._spp
+}
+
+func tSPPi() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = pu.SPPi()
+}
+
+func tiSPP() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = *pu.SPP()
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of ps
+func tSP() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s // ERROR "moved to heap: ps$"
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = pu.SP()
+}
+
+func (v *V) u() U { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._u
+}
+
+func (v *V) UP() *U { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._up
+}
+
+func (v *V) UPP() **U { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._upp
+}
+
+func (v *V) UPPia() *U { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v._upp
+}
+
+func (v *V) UPPib() *U { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v.UPP()
+}
+
+func (v *V) USPa() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._u._sp
+}
+
+func (v *V) USPb() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v.u()._sp
+}
+
+func (v *V) USPPia() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v._u._spp
+}
+
+func (v *V) USPPib() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v._u.SPPi()
+}
+
+func (v *V) UPiSPa() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v._up._sp
+}
+
+func (v *V) UPiSPb() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v._up.SP()
+}
+
+func (v *V) UPiSPc() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v.UP()._sp
+}
+
+func (v *V) UPiSPd() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v.UP().SP()
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPa() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPa() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPb() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPb() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPc() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPc() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPd() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPd() // Ssink = &s3 (only &s3 really escapes)
+}
+
+func (v V) UPiSPPia() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v._up._spp
+}
+
+func (v V) UPiSPPib() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v._up.SPPi()
+}
+
+func (v V) UPiSPPic() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v.UP()._spp
+}
+
+func (v V) UPiSPPid() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v.UP().SPPi()
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPia() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPia() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPib() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPib() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPic() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPic() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPid() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPid() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+func (v *V) UPPiSPPia() *string { // ERROR "leaking param: v to result ~r0 level=4$"
+ return *(*v._upp)._spp
+}
+
+// This test isolates the one value that needs to escape, not because
+// it distinguishes fields but because it knows that &s6 is the only
+// value reachable by two indirects from v.
+// The test depends on the level cap in the escape analysis tags
+// being able to encode that fact.
+func tUPPiSPPia() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog"
+ s5 := "emu"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPPiSPPia() // Ssink = *&ps6 = &s6 (only &s6 really escapes)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_struct_param2.go b/platform/dbops/binaries/go/go/test/escape_struct_param2.go
new file mode 100644
index 0000000000000000000000000000000000000000..946397ea9f51a629d3f7051b1d3b5033636a4e30
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_struct_param2.go
@@ -0,0 +1,298 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for struct function parameters.
+// Note companion strict_param1 checks *struct function parameters with similar tests.
+
+package notmain
+
+var Ssink *string
+
+type U struct {
+ _sp *string
+ _spp **string
+}
+
+type V struct {
+ _u U
+ _up *U
+ _upp **U
+}
+
+func (u U) SP() *string { // ERROR "leaking param: u to result ~r0 level=0$"
+ return u._sp
+}
+
+func (u U) SPP() **string { // ERROR "leaking param: u to result ~r0 level=0$"
+ return u._spp
+}
+
+func (u U) SPPi() *string { // ERROR "leaking param: u to result ~r0 level=1$"
+ return *u._spp
+}
+
+func tSPPi() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = pu.SPPi()
+}
+
+func tiSPP() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = *pu.SPP()
+}
+
+// BAD: need fine-grained analysis to avoid spurious escape of ps
+func tSP() {
+ s := "cat" // ERROR "moved to heap: s$"
+ ps := &s // ERROR "moved to heap: ps$"
+ pps := &ps
+ pu := &U{ps, pps} // ERROR "&U{...} does not escape$"
+ Ssink = pu.SP()
+}
+
+func (v V) u() U { // ERROR "leaking param: v to result ~r0 level=0$"
+ return v._u
+}
+
+func (v V) UP() *U { // ERROR "leaking param: v to result ~r0 level=0$"
+ return v._up
+}
+
+func (v V) UPP() **U { // ERROR "leaking param: v to result ~r0 level=0$"
+ return v._upp
+}
+
+func (v V) UPPia() *U { // ERROR "leaking param: v to result ~r0 level=1$"
+ return *v._upp
+}
+
+func (v V) UPPib() *U { // ERROR "leaking param: v to result ~r0 level=1$"
+ return *v.UPP()
+}
+
+func (v V) USPa() *string { // ERROR "leaking param: v to result ~r0 level=0$"
+ return v._u._sp
+}
+
+func (v V) USPb() *string { // ERROR "leaking param: v to result ~r0 level=0$"
+ return v.u()._sp
+}
+
+func (v V) USPPia() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return *v._u._spp
+}
+
+func (v V) USPPib() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._u.SPPi()
+}
+
+func (v V) UPiSPa() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._up._sp
+}
+
+func (v V) UPiSPb() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v._up.SP()
+}
+
+func (v V) UPiSPc() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v.UP()._sp
+}
+
+func (v V) UPiSPd() *string { // ERROR "leaking param: v to result ~r0 level=1$"
+ return v.UP().SP()
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPa() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPa() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPb() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPb() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPc() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPc() // Ssink = &s3 (only &s3 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s3
+func tUPiSPd() {
+ s1 := "ant"
+ s2 := "bat" // ERROR "moved to heap: s2$"
+ s3 := "cat" // ERROR "moved to heap: s3$"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4 // ERROR "moved to heap: ps4$"
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} escapes to heap$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPd() // Ssink = &s3 (only &s3 really escapes)
+}
+
+func (v V) UPiSPPia() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v._up._spp
+}
+
+func (v V) UPiSPPib() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v._up.SPPi()
+}
+
+func (v V) UPiSPPic() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return *v.UP()._spp
+}
+
+func (v V) UPiSPPid() *string { // ERROR "leaking param: v to result ~r0 level=2$"
+ return v.UP().SPPi()
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPia() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPia() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPib() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPib() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPic() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPic() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+// BAD: need fine-grained (field-sensitive) analysis to avoid spurious escape of all but &s4
+func tUPiSPPid() {
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog" // ERROR "moved to heap: s4$"
+ s5 := "emu" // ERROR "moved to heap: s5$"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6 // ERROR "moved to heap: ps6$"
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPiSPPid() // Ssink = *&ps4 = &s4 (only &s4 really escapes)
+}
+
+func (v V) UPPiSPPia() *string { // ERROR "leaking param: v to result ~r0 level=3$"
+ return *(*v._upp)._spp
+}
+
+// This test isolates the one value that needs to escape, not because
+// it distinguishes fields but because it knows that &s6 is the only
+// value reachable by two indirects from v.
+// The test depends on the level cap in the escape analysis tags
+// being able to encode that fact.
+func tUPPiSPPia() { // This test is sensitive to the level cap in function summary results.
+ s1 := "ant"
+ s2 := "bat"
+ s3 := "cat"
+ s4 := "dog"
+ s5 := "emu"
+ s6 := "fox" // ERROR "moved to heap: s6$"
+ ps2 := &s2
+ ps4 := &s4
+ ps6 := &s6
+ u1 := U{&s1, &ps2}
+ u2 := &U{&s3, &ps4} // ERROR "&U{...} does not escape$"
+ u3 := &U{&s5, &ps6} // ERROR "&U{...} does not escape$"
+ v := &V{u1, u2, &u3} // ERROR "&V{...} does not escape$"
+ Ssink = v.UPPiSPPia() // Ssink = *&ps6 = &s6 (only &s6 really escapes)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_struct_return.go b/platform/dbops/binaries/go/go/test/escape_struct_return.go
new file mode 100644
index 0000000000000000000000000000000000000000..a42ae1e8c9b5270e610865554af7477ac95ab6be
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_struct_return.go
@@ -0,0 +1,74 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for function parameters.
+
+package foo
+
+var Ssink *string
+
+type U struct {
+ _sp *string
+ _spp **string
+}
+
+func A(sp *string, spp **string) U { // ERROR "leaking param: sp to result ~r0 level=0$" "leaking param: spp to result ~r0 level=0$"
+ return U{sp, spp}
+}
+
+func B(spp **string) U { // ERROR "leaking param: spp to result ~r0 level=0$"
+ return U{*spp, spp}
+}
+
+func tA1() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := A(sp, spp)
+ _ = u
+ println(s)
+}
+
+func tA2() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := A(sp, spp)
+ println(*u._sp)
+}
+
+func tA3() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := A(sp, spp)
+ println(**u._spp)
+}
+
+func tB1() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := B(spp)
+ _ = u
+ println(s)
+}
+
+func tB2() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := B(spp)
+ println(*u._sp)
+}
+
+func tB3() {
+ s := "cat"
+ sp := &s
+ spp := &sp
+ u := B(spp)
+ println(**u._spp)
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_sync_atomic.go b/platform/dbops/binaries/go/go/test/escape_sync_atomic.go
new file mode 100644
index 0000000000000000000000000000000000000000..e509b3751143cb307af91bc86bb787cbd54fc5e8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_sync_atomic.go
@@ -0,0 +1,38 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for sync/atomic.
+
+package escape
+
+import (
+ "sync/atomic"
+ "unsafe"
+)
+
+// BAD: should be "leaking param: addr to result ~r1 level=1$".
+func LoadPointer(addr *unsafe.Pointer) unsafe.Pointer { // ERROR "leaking param: addr$"
+ return atomic.LoadPointer(addr)
+}
+
+var ptr unsafe.Pointer
+
+func StorePointer() {
+ var x int // ERROR "moved to heap: x"
+ atomic.StorePointer(&ptr, unsafe.Pointer(&x))
+}
+
+func SwapPointer() {
+ var x int // ERROR "moved to heap: x"
+ atomic.SwapPointer(&ptr, unsafe.Pointer(&x))
+}
+
+func CompareAndSwapPointer() {
+ // BAD: x doesn't need to be heap allocated
+ var x int // ERROR "moved to heap: x"
+ var y int // ERROR "moved to heap: y"
+ atomic.CompareAndSwapPointer(&ptr, unsafe.Pointer(&x), unsafe.Pointer(&y))
+}
diff --git a/platform/dbops/binaries/go/go/test/escape_unsafe.go b/platform/dbops/binaries/go/go/test/escape_unsafe.go
new file mode 100644
index 0000000000000000000000000000000000000000..56c536fdfb4c99f320b87e48fbd62c82828cfb72
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/escape_unsafe.go
@@ -0,0 +1,69 @@
+// errorcheck -0 -m -l
+
+// 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.
+
+// Test escape analysis for unsafe.Pointer rules.
+
+package escape
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// (1) Conversion of a *T1 to Pointer to *T2.
+
+func convert(p *float64) *uint64 { // ERROR "leaking param: p to result ~r0 level=0$"
+ return (*uint64)(unsafe.Pointer(p))
+}
+
+// (3) Conversion of a Pointer to a uintptr and back, with arithmetic.
+
+func arithAdd() unsafe.Pointer {
+ var x [2]byte // ERROR "moved to heap: x"
+ return unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) + 1)
+}
+
+func arithSub() unsafe.Pointer {
+ var x [2]byte // ERROR "moved to heap: x"
+ return unsafe.Pointer(uintptr(unsafe.Pointer(&x[1])) - 1)
+}
+
+func arithMask() unsafe.Pointer {
+ var x [2]byte // ERROR "moved to heap: x"
+ return unsafe.Pointer(uintptr(unsafe.Pointer(&x[1])) &^ 1)
+}
+
+// (5) Conversion of the result of reflect.Value.Pointer or
+// reflect.Value.UnsafeAddr from uintptr to Pointer.
+
+// BAD: should be "leaking param: p to result ~r0 level=0$"
+func valuePointer(p *int) unsafe.Pointer { // ERROR "leaking param: p$"
+ return unsafe.Pointer(reflect.ValueOf(p).Pointer())
+}
+
+// BAD: should be "leaking param: p to result ~r0 level=0$"
+func valueUnsafeAddr(p *int) unsafe.Pointer { // ERROR "leaking param: p$"
+ return unsafe.Pointer(reflect.ValueOf(p).Elem().UnsafeAddr())
+}
+
+// (6) Conversion of a reflect.SliceHeader or reflect.StringHeader
+// Data field to or from Pointer.
+
+func fromSliceData(s []int) unsafe.Pointer { // ERROR "leaking param: s to result ~r0 level=0$"
+ return unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s)).Data)
+}
+
+func fromStringData(s string) unsafe.Pointer { // ERROR "leaking param: s to result ~r0 level=0$"
+ return unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)
+}
+
+func toSliceData(s *[]int, p unsafe.Pointer) { // ERROR "s does not escape" "leaking param: p$"
+ (*reflect.SliceHeader)(unsafe.Pointer(s)).Data = uintptr(p)
+}
+
+func toStringData(s *string, p unsafe.Pointer) { // ERROR "s does not escape" "leaking param: p$"
+ (*reflect.StringHeader)(unsafe.Pointer(s)).Data = uintptr(p)
+}
diff --git a/platform/dbops/binaries/go/go/test/fibo.go b/platform/dbops/binaries/go/go/test/fibo.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b816d930dfd3b44a46faead0eefc308028db4ae
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/fibo.go
@@ -0,0 +1,310 @@
+// skip
+
+// 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.
+
+// Usage:
+// fibo compute fibonacci(n), n must be >= 0
+// fibo -bench benchmark fibonacci computation (takes about 1 min)
+//
+// Additional flags:
+// -half add values using two half-digit additions
+// -opt optimize memory allocation through reuse
+// -short only print the first 10 digits of very large fibonacci numbers
+
+// Command fibo is a stand-alone test and benchmark to
+// evaluate the performance of bignum arithmetic written
+// entirely in Go.
+package main
+
+import (
+ "flag"
+ "fmt"
+ "math/big" // only used for printing
+ "os"
+ "strconv"
+ "testing"
+ "text/tabwriter"
+ "time"
+)
+
+var (
+ bench = flag.Bool("bench", false, "run benchmarks")
+ half = flag.Bool("half", false, "use half-digit addition")
+ opt = flag.Bool("opt", false, "optimize memory usage")
+ short = flag.Bool("short", false, "only print first 10 digits of result")
+)
+
+// A large natural number is represented by a nat, each "digit" is
+// a big.Word; the value zero corresponds to the empty nat slice.
+type nat []big.Word
+
+const W = 1 << (5 + ^big.Word(0)>>63) // big.Word size in bits
+
+// The following methods are extracted from math/big to make this a
+// stand-alone program that can easily be run without dependencies
+// and compiled with different compilers.
+
+func (z nat) make(n int) nat {
+ if n <= cap(z) {
+ return z[:n] // reuse z
+ }
+ // 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)
+}
+
+// z = x
+func (z nat) set(x nat) nat {
+ z = z.make(len(x))
+ copy(z, x)
+ return z
+}
+
+// z = x + y
+// (like add, but operating on half-digits at a time)
+func (z nat) halfAdd(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.make(0)
+ case n == 0:
+ // result is x
+ return z.set(x)
+ }
+ // m >= n > 0
+
+ const W2 = W / 2 // half-digit size in bits
+ const M2 = (1 << W2) - 1 // lower half-digit mask
+
+ z = z.make(m + 1)
+ var c big.Word
+ for i := 0; i < n; i++ {
+ // lower half-digit
+ c += x[i]&M2 + y[i]&M2
+ d := c & M2
+ c >>= W2
+ // upper half-digit
+ c += x[i]>>W2 + y[i]>>W2
+ z[i] = c<>= W2
+ }
+ for i := n; i < m; i++ {
+ // lower half-digit
+ c += x[i] & M2
+ d := c & M2
+ c >>= W2
+ // upper half-digit
+ c += x[i] >> W2
+ z[i] = c<>= W2
+ }
+ if c != 0 {
+ z[m] = c
+ m++
+ }
+ return z[:m]
+}
+
+// z = x + y
+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.make(0)
+ case n == 0:
+ // result is x
+ return z.set(x)
+ }
+ // m >= n > 0
+
+ z = z.make(m + 1)
+ var c big.Word
+
+ for i, xi := range x[:n] {
+ yi := y[i]
+ zi := xi + yi + c
+ z[i] = zi
+ // see "Hacker's Delight", section 2-12 (overflow detection)
+ c = ((xi & yi) | ((xi | yi) &^ zi)) >> (W - 1)
+ }
+ for i, xi := range x[n:] {
+ zi := xi + c
+ z[n+i] = zi
+ c = (xi &^ zi) >> (W - 1)
+ if c == 0 {
+ copy(z[n+i+1:], x[i+1:])
+ break
+ }
+ }
+ if c != 0 {
+ z[m] = c
+ m++
+ }
+ return z[:m]
+}
+
+func bitlen(x big.Word) int {
+ n := 0
+ for x > 0 {
+ x >>= 1
+ n++
+ }
+ return n
+}
+
+func (x nat) bitlen() int {
+ if i := len(x); i > 0 {
+ return (i-1)*W + bitlen(x[i-1])
+ }
+ return 0
+}
+
+func (x nat) String() string {
+ const shortLen = 10
+ s := new(big.Int).SetBits(x).String()
+ if *short && len(s) > shortLen {
+ s = s[:shortLen] + "..."
+ }
+ return s
+}
+
+func fibo(n int, half, opt bool) nat {
+ switch n {
+ case 0:
+ return nil
+ case 1:
+ return nat{1}
+ }
+ f0 := nat(nil)
+ f1 := nat{1}
+ if half {
+ if opt {
+ var f2 nat // reuse f2
+ for i := 1; i < n; i++ {
+ f2 = f2.halfAdd(f1, f0)
+ f0, f1, f2 = f1, f2, f0
+ }
+ } else {
+ for i := 1; i < n; i++ {
+ f2 := nat(nil).halfAdd(f1, f0) // allocate a new f2 each time
+ f0, f1 = f1, f2
+ }
+ }
+ } else {
+ if opt {
+ var f2 nat // reuse f2
+ for i := 1; i < n; i++ {
+ f2 = f2.add(f1, f0)
+ f0, f1, f2 = f1, f2, f0
+ }
+ } else {
+ for i := 1; i < n; i++ {
+ f2 := nat(nil).add(f1, f0) // allocate a new f2 each time
+ f0, f1 = f1, f2
+ }
+ }
+ }
+ return f1 // was f2 before shuffle
+}
+
+var tests = []struct {
+ n int
+ want string
+}{
+ {0, "0"},
+ {1, "1"},
+ {2, "1"},
+ {3, "2"},
+ {4, "3"},
+ {5, "5"},
+ {6, "8"},
+ {7, "13"},
+ {8, "21"},
+ {9, "34"},
+ {10, "55"},
+ {100, "354224848179261915075"},
+ {1000, "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875"},
+}
+
+func test(half, opt bool) {
+ for _, test := range tests {
+ got := fibo(test.n, half, opt).String()
+ if got != test.want {
+ fmt.Printf("error: got std fibo(%d) = %s; want %s\n", test.n, got, test.want)
+ os.Exit(1)
+ }
+ }
+}
+
+func selfTest() {
+ if W != 32 && W != 64 {
+ fmt.Printf("error: unexpected wordsize %d", W)
+ os.Exit(1)
+ }
+ for i := 0; i < 4; i++ {
+ test(i&2 == 0, i&1 != 0)
+ }
+}
+
+func doFibo(n int) {
+ start := time.Now()
+ f := fibo(n, *half, *opt)
+ t := time.Since(start)
+ fmt.Printf("fibo(%d) = %s (%d bits, %s)\n", n, f, f.bitlen(), t)
+}
+
+func benchFibo(b *testing.B, n int, half, opt bool) {
+ for i := 0; i < b.N; i++ {
+ fibo(n, half, opt)
+ }
+}
+
+func doBench(half, opt bool) {
+ w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', tabwriter.AlignRight)
+ fmt.Fprintf(w, "wordsize = %d, half = %v, opt = %v\n", W, half, opt)
+ fmt.Fprintf(w, "n\talloc count\talloc bytes\tns/op\ttime/op\t\n")
+ for n := 1; n <= 1e6; n *= 10 {
+ res := testing.Benchmark(func(b *testing.B) { benchFibo(b, n, half, opt) })
+ fmt.Fprintf(w, "%d\t%d\t%d\t%d\t%s\t\n", n, res.AllocsPerOp(), res.AllocedBytesPerOp(), res.NsPerOp(), time.Duration(res.NsPerOp()))
+ }
+ fmt.Fprintln(w)
+ w.Flush()
+}
+
+func main() {
+ selfTest()
+ flag.Parse()
+
+ if args := flag.Args(); len(args) > 0 {
+ // command-line use
+ fmt.Printf("half = %v, opt = %v, wordsize = %d bits\n", *half, *opt, W)
+ for _, arg := range args {
+ n, err := strconv.Atoi(arg)
+ if err != nil || n < 0 {
+ fmt.Println("invalid argument", arg)
+ continue
+ }
+ doFibo(n)
+ }
+ return
+ }
+
+ if *bench {
+ for i := 0; i < 4; i++ {
+ doBench(i&2 == 0, i&1 != 0)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/finprofiled.go b/platform/dbops/binaries/go/go/test/finprofiled.go
new file mode 100644
index 0000000000000000000000000000000000000000..ef8f61c8025115415f97c780abbf9fb037be3289
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/finprofiled.go
@@ -0,0 +1,79 @@
+// run
+
+// 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.
+
+// Test that tiny allocations with finalizers are correctly profiled.
+// Previously profile special records could have been processed prematurely
+// (while the object is still live).
+
+package main
+
+import (
+ "runtime"
+ "time"
+ "unsafe"
+)
+
+func main() {
+ runtime.MemProfileRate = 1
+ // Allocate 1M 4-byte objects and set a finalizer for every third object.
+ // Assuming that tiny block size is 16, some objects get finalizers setup
+ // only for middle bytes. The finalizer resurrects that object.
+ // As the result, all allocated memory must stay alive.
+ const (
+ N = 1 << 20
+ tinyBlockSize = 16 // runtime._TinySize
+ )
+ hold := make([]*int32, 0, N)
+ for i := 0; i < N; i++ {
+ x := new(int32)
+ if i%3 == 0 {
+ runtime.SetFinalizer(x, func(p *int32) {
+ hold = append(hold, p)
+ })
+ }
+ }
+ // Finalize as much as possible.
+ // Note: the sleep only increases probability of bug detection,
+ // it cannot lead to false failure.
+ for i := 0; i < 5; i++ {
+ runtime.GC()
+ time.Sleep(10 * time.Millisecond)
+ }
+ // Read memory profile.
+ var prof []runtime.MemProfileRecord
+ for {
+ if n, ok := runtime.MemProfile(prof, false); ok {
+ prof = prof[:n]
+ break
+ } else {
+ prof = make([]runtime.MemProfileRecord, n+10)
+ }
+ }
+ // See how much memory in tiny objects is profiled.
+ var totalBytes int64
+ for _, p := range prof {
+ bytes := p.AllocBytes - p.FreeBytes
+ nobj := p.AllocObjects - p.FreeObjects
+ if nobj == 0 {
+ // There may be a record that has had all of its objects
+ // freed. That's fine. Avoid a divide-by-zero and skip.
+ continue
+ }
+ size := bytes / nobj
+ if size == tinyBlockSize {
+ totalBytes += bytes
+ }
+ }
+ // 2*tinyBlockSize slack is for any boundary effects.
+ if want := N*int64(unsafe.Sizeof(int32(0))) - 2*tinyBlockSize; totalBytes < want {
+ println("got", totalBytes, "want >=", want)
+ panic("some of the tiny objects are not profiled")
+ }
+ // Just to keep hold alive.
+ if len(hold) != 0 && hold[0] == nil {
+ panic("bad")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/float_lit.go b/platform/dbops/binaries/go/go/test/float_lit.go
new file mode 100644
index 0000000000000000000000000000000000000000..4efae2362da98b9ddbf0e3da70c55f698cbd58bf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/float_lit.go
@@ -0,0 +1,203 @@
+// run
+
+// 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.
+
+// Test floating-point literal syntax.
+
+package main
+
+var bad bool
+
+func pow10(pow int) float64 {
+ if pow < 0 {
+ return 1 / pow10(-pow)
+ }
+ if pow > 0 {
+ return pow10(pow-1) * 10
+ }
+ return 1
+}
+
+func close(da float64, ia, ib int64, pow int) bool {
+ db := float64(ia) / float64(ib)
+ db *= pow10(pow)
+
+ if da == 0 || db == 0 {
+ if da == 0 && db == 0 {
+ return true
+ }
+ return false
+ }
+
+ de := (da - db) / da
+ if de < 0 {
+ de = -de
+ }
+
+ if de < 1e-14 {
+ return true
+ }
+ if !bad {
+ println("BUG")
+ bad = true
+ }
+ return false
+}
+
+func main() {
+ if !close(0., 0, 1, 0) {
+ print("0. is ", 0., "\n")
+ }
+ if !close(+10., 10, 1, 0) {
+ print("+10. is ", +10., "\n")
+ }
+ if !close(-210., -210, 1, 0) {
+ print("-210. is ", -210., "\n")
+ }
+
+ if !close(.0, 0, 1, 0) {
+ print(".0 is ", .0, "\n")
+ }
+ if !close(+.01, 1, 100, 0) {
+ print("+.01 is ", +.01, "\n")
+ }
+ if !close(-.012, -12, 1000, 0) {
+ print("-.012 is ", -.012, "\n")
+ }
+
+ if !close(0.0, 0, 1, 0) {
+ print("0.0 is ", 0.0, "\n")
+ }
+ if !close(+10.01, 1001, 100, 0) {
+ print("+10.01 is ", +10.01, "\n")
+ }
+ if !close(-210.012, -210012, 1000, 0) {
+ print("-210.012 is ", -210.012, "\n")
+ }
+
+ if !close(0E+1, 0, 1, 0) {
+ print("0E+1 is ", 0E+1, "\n")
+ }
+ if !close(+10e2, 10, 1, 2) {
+ print("+10e2 is ", +10e2, "\n")
+ }
+ if !close(-210e3, -210, 1, 3) {
+ print("-210e3 is ", -210e3, "\n")
+ }
+
+ if !close(0E-1, 0, 1, 0) {
+ print("0E-1 is ", 0E-1, "\n")
+ }
+ if !close(+0e23, 0, 1, 1) {
+ print("+0e23 is ", +0e23, "\n")
+ }
+ if !close(-0e345, 0, 1, 1) {
+ print("-0e345 is ", -0e345, "\n")
+ }
+
+ if !close(0E1, 0, 1, 1) {
+ print("0E1 is ", 0E1, "\n")
+ }
+ if !close(+10e23, 10, 1, 23) {
+ print("+10e23 is ", +10e23, "\n")
+ }
+ if !close(-210e34, -210, 1, 34) {
+ print("-210e34 is ", -210e34, "\n")
+ }
+
+ if !close(0.E1, 0, 1, 1) {
+ print("0.E1 is ", 0.E1, "\n")
+ }
+ if !close(+10.e+2, 10, 1, 2) {
+ print("+10.e+2 is ", +10.e+2, "\n")
+ }
+ if !close(-210.e-3, -210, 1, -3) {
+ print("-210.e-3 is ", -210.e-3, "\n")
+ }
+
+ if !close(.0E1, 0, 1, 1) {
+ print(".0E1 is ", .0E1, "\n")
+ }
+ if !close(+.01e2, 1, 100, 2) {
+ print("+.01e2 is ", +.01e2, "\n")
+ }
+ if !close(-.012e3, -12, 1000, 3) {
+ print("-.012e3 is ", -.012e3, "\n")
+ }
+
+ if !close(0.0E1, 0, 1, 0) {
+ print("0.0E1 is ", 0.0E1, "\n")
+ }
+ if !close(+10.01e2, 1001, 100, 2) {
+ print("+10.01e2 is ", +10.01e2, "\n")
+ }
+ if !close(-210.012e3, -210012, 1000, 3) {
+ print("-210.012e3 is ", -210.012e3, "\n")
+ }
+
+ if !close(0.E+12, 0, 1, 0) {
+ print("0.E+12 is ", 0.E+12, "\n")
+ }
+ if !close(+10.e23, 10, 1, 23) {
+ print("+10.e23 is ", +10.e23, "\n")
+ }
+ if !close(-210.e33, -210, 1, 33) {
+ print("-210.e33 is ", -210.e33, "\n")
+ }
+
+ if !close(.0E-12, 0, 1, 0) {
+ print(".0E-12 is ", .0E-12, "\n")
+ }
+ if !close(+.01e23, 1, 100, 23) {
+ print("+.01e23 is ", +.01e23, "\n")
+ }
+ if !close(-.012e34, -12, 1000, 34) {
+ print("-.012e34 is ", -.012e34, "\n")
+ }
+
+ if !close(0.0E12, 0, 1, 12) {
+ print("0.0E12 is ", 0.0E12, "\n")
+ }
+ if !close(+10.01e23, 1001, 100, 23) {
+ print("+10.01e23 is ", +10.01e23, "\n")
+ }
+ if !close(-210.012e33, -210012, 1000, 33) {
+ print("-210.012e33 is ", -210.012e33, "\n")
+ }
+
+ if !close(0.E123, 0, 1, 123) {
+ print("0.E123 is ", 0.E123, "\n")
+ }
+ if !close(+10.e+23, 10, 1, 23) {
+ print("+10.e+234 is ", +10.e+234, "\n")
+ }
+ if !close(-210.e-35, -210, 1, -35) {
+ print("-210.e-35 is ", -210.e-35, "\n")
+ }
+
+ if !close(.0E123, 0, 1, 123) {
+ print(".0E123 is ", .0E123, "\n")
+ }
+ if !close(+.01e29, 1, 100, 29) {
+ print("+.01e29 is ", +.01e29, "\n")
+ }
+ if !close(-.012e29, -12, 1000, 29) {
+ print("-.012e29 is ", -.012e29, "\n")
+ }
+
+ if !close(0.0E123, 0, 1, 123) {
+ print("0.0E123 is ", 0.0E123, "\n")
+ }
+ if !close(+10.01e31, 1001, 100, 31) {
+ print("+10.01e31 is ", +10.01e31, "\n")
+ }
+ if !close(-210.012e19, -210012, 1000, 19) {
+ print("-210.012e19 is ", -210.012e19, "\n")
+ }
+
+ if bad {
+ panic("float_lit")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/float_lit2.go b/platform/dbops/binaries/go/go/test/float_lit2.go
new file mode 100644
index 0000000000000000000000000000000000000000..901698f8a404d16677596a8f80f35b8d0218ca80
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/float_lit2.go
@@ -0,0 +1,164 @@
+// run
+
+// Check conversion of constant to float32/float64 near min/max boundaries.
+
+// 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 main
+
+import (
+ "fmt"
+ "math"
+)
+
+// The largest exact float32 is f₁ = (1+1-1/2²³)×2¹²⁷ = (2-2⁻²³)×2¹²⁷ = 2¹²⁸ - 2¹⁰⁴.
+// The next float32 would be f₂ = (1+1)×2¹²⁷ = 1×2¹²⁸, except that exponent is out of range.
+// Float32 conversion rounds to the nearest float32, rounding to even mantissa:
+// between f₁ and f₂, values closer to f₁ round to f₁ and values closer to f₂ are rejected as out of range.
+// f₁ is an odd mantissa, so the halfway point (f₁+f₂)/2 rounds to f₂ and is rejected.
+// The halfway point is (f₁+f₂)/2 = 2¹²⁸ - 2¹⁰³.
+//
+// The same is true of float64, with different constants: s/24/53/ and s/128/1024/.
+
+const (
+ two24 = 1.0 * (1 << 24)
+ two53 = 1.0 * (1 << 53)
+ two64 = 1.0 * (1 << 64)
+ two128 = two64 * two64
+ two256 = two128 * two128
+ two512 = two256 * two256
+ two768 = two512 * two256
+ two1024 = two512 * two512
+
+ ulp32 = two128 / two24
+ max32 = two128 - ulp32
+
+ ulp64 = two1024 / two53
+ max64 = two1024 - ulp64
+)
+
+var cvt = []struct {
+ bits uint64 // keep us honest
+ exact interface{}
+ approx interface{}
+ text string
+}{
+ // 0
+ {0x7f7ffffe, float32(max32 - ulp32), float32(max32 - ulp32 - ulp32/2), "max32 - ulp32 - ulp32/2"},
+ {0x7f7ffffe, float32(max32 - ulp32), float32(max32 - ulp32), "max32 - ulp32"},
+ {0x7f7ffffe, float32(max32 - ulp32), float32(max32 - ulp32/2), "max32 - ulp32/2"},
+ {0x7f7ffffe, float32(max32 - ulp32), float32(max32 - ulp32 + ulp32/2), "max32 - ulp32 + ulp32/2"},
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32 + ulp32/2 + ulp32/two64), "max32 - ulp32 + ulp32/2 + ulp32/two64"},
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32/2 + ulp32/two64), "max32 - ulp32/2 + ulp32/two64"},
+ {0x7f7fffff, float32(max32), float32(max32), "max32"},
+ {0x7f7fffff, float32(max32), float32(max32 + ulp32/2 - ulp32/two64), "max32 + ulp32/2 - ulp32/two64"},
+
+ {0xff7ffffe, float32(-(max32 - ulp32)), float32(-(max32 - ulp32 - ulp32/2)), "-(max32 - ulp32 - ulp32/2)"},
+ {0xff7ffffe, float32(-(max32 - ulp32)), float32(-(max32 - ulp32)), "-(max32 - ulp32)"},
+ {0xff7ffffe, float32(-(max32 - ulp32)), float32(-(max32 - ulp32/2)), "-(max32 - ulp32/2)"},
+ {0xff7ffffe, float32(-(max32 - ulp32)), float32(-(max32 - ulp32 + ulp32/2)), "-(max32 - ulp32 + ulp32/2)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32 + ulp32/2 + ulp32/two64)), "-(max32 - ulp32 + ulp32/2 + ulp32/two64)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32/2 + ulp32/two64)), "-(max32 - ulp32/2 + ulp32/two64)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32)), "-(max32)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 + ulp32/2 - ulp32/two64)), "-(max32 + ulp32/2 - ulp32/two64)"},
+
+ // These are required to work: according to the Go spec, the internal float mantissa must be at least 256 bits,
+ // and these expressions can be represented exactly with a 256-bit mantissa.
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32 + ulp32/2 + 1), "max32 - ulp32 + ulp32/2 + 1"},
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32/2 + 1), "max32 - ulp32/2 + 1"},
+ {0x7f7fffff, float32(max32), float32(max32 + ulp32/2 - 1), "max32 + ulp32/2 - 1"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32 + ulp32/2 + 1)), "-(max32 - ulp32 + ulp32/2 + 1)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32/2 + 1)), "-(max32 - ulp32/2 + 1)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 + ulp32/2 - 1)), "-(max32 + ulp32/2 - 1)"},
+
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32 + ulp32/2 + 1/two128), "max32 - ulp32 + ulp32/2 + 1/two128"},
+ {0x7f7fffff, float32(max32), float32(max32 - ulp32/2 + 1/two128), "max32 - ulp32/2 + 1/two128"},
+ {0x7f7fffff, float32(max32), float32(max32 + ulp32/2 - 1/two128), "max32 + ulp32/2 - 1/two128"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32 + ulp32/2 + 1/two128)), "-(max32 - ulp32 + ulp32/2 + 1/two128)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 - ulp32/2 + 1/two128)), "-(max32 - ulp32/2 + 1/two128)"},
+ {0xff7fffff, float32(-(max32)), float32(-(max32 + ulp32/2 - 1/two128)), "-(max32 + ulp32/2 - 1/two128)"},
+
+ {0x7feffffffffffffe, float64(max64 - ulp64), float64(max64 - ulp64 - ulp64/2), "max64 - ulp64 - ulp64/2"},
+ {0x7feffffffffffffe, float64(max64 - ulp64), float64(max64 - ulp64), "max64 - ulp64"},
+ {0x7feffffffffffffe, float64(max64 - ulp64), float64(max64 - ulp64/2), "max64 - ulp64/2"},
+ {0x7feffffffffffffe, float64(max64 - ulp64), float64(max64 - ulp64 + ulp64/2), "max64 - ulp64 + ulp64/2"},
+ {0x7fefffffffffffff, float64(max64), float64(max64 - ulp64 + ulp64/2 + ulp64/two64), "max64 - ulp64 + ulp64/2 + ulp64/two64"},
+ {0x7fefffffffffffff, float64(max64), float64(max64 - ulp64/2 + ulp64/two64), "max64 - ulp64/2 + ulp64/two64"},
+ {0x7fefffffffffffff, float64(max64), float64(max64), "max64"},
+ {0x7fefffffffffffff, float64(max64), float64(max64 + ulp64/2 - ulp64/two64), "max64 + ulp64/2 - ulp64/two64"},
+
+ {0xffeffffffffffffe, float64(-(max64 - ulp64)), float64(-(max64 - ulp64 - ulp64/2)), "-(max64 - ulp64 - ulp64/2)"},
+ {0xffeffffffffffffe, float64(-(max64 - ulp64)), float64(-(max64 - ulp64)), "-(max64 - ulp64)"},
+ {0xffeffffffffffffe, float64(-(max64 - ulp64)), float64(-(max64 - ulp64/2)), "-(max64 - ulp64/2)"},
+ {0xffeffffffffffffe, float64(-(max64 - ulp64)), float64(-(max64 - ulp64 + ulp64/2)), "-(max64 - ulp64 + ulp64/2)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 - ulp64 + ulp64/2 + ulp64/two64)), "-(max64 - ulp64 + ulp64/2 + ulp64/two64)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 - ulp64/2 + ulp64/two64)), "-(max64 - ulp64/2 + ulp64/two64)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64)), "-(max64)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 + ulp64/2 - ulp64/two64)), "-(max64 + ulp64/2 - ulp64/two64)"},
+
+ // These are required to work.
+ // The mantissas are exactly 256 bits.
+ // max64 is just below 2¹⁰²⁴ so the bottom bit we can use is 2⁷⁶⁸.
+ {0x7fefffffffffffff, float64(max64), float64(max64 - ulp64 + ulp64/2 + two768), "max64 - ulp64 + ulp64/2 + two768"},
+ {0x7fefffffffffffff, float64(max64), float64(max64 - ulp64/2 + two768), "max64 - ulp64/2 + two768"},
+ {0x7fefffffffffffff, float64(max64), float64(max64 + ulp64/2 - two768), "max64 + ulp64/2 - two768"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 - ulp64 + ulp64/2 + two768)), "-(max64 - ulp64 + ulp64/2 + two768)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 - ulp64/2 + two768)), "-(max64 - ulp64/2 + two768)"},
+ {0xffefffffffffffff, float64(-(max64)), float64(-(max64 + ulp64/2 - two768)), "-(max64 + ulp64/2 - two768)"},
+}
+
+var bugged = false
+
+func bug() {
+ if !bugged {
+ bugged = true
+ fmt.Println("BUG")
+ }
+}
+
+func main() {
+ u64 := math.Float64frombits(0x7fefffffffffffff) - math.Float64frombits(0x7feffffffffffffe)
+ if ulp64 != u64 {
+ bug()
+ fmt.Printf("ulp64=%g, want %g", ulp64, u64)
+ }
+
+ u32 := math.Float32frombits(0x7f7fffff) - math.Float32frombits(0x7f7ffffe)
+ if ulp32 != u32 {
+ bug()
+ fmt.Printf("ulp32=%g, want %g", ulp32, u32)
+ }
+
+ for _, c := range cvt {
+ if bits(c.exact) != c.bits {
+ bug()
+ fmt.Printf("%s: inconsistent table: bits=%#x (%g) but exact=%g (%#x)\n", c.text, c.bits, fromBits(c.bits, c.exact), c.exact, bits(c.exact))
+ }
+ if c.approx != c.exact || bits(c.approx) != c.bits {
+ bug()
+ fmt.Printf("%s: have %g (%#x) want %g (%#x)\n", c.text, c.approx, bits(c.approx), c.exact, c.bits)
+ }
+ }
+}
+
+func bits(x interface{}) interface{} {
+ switch x := x.(type) {
+ case float32:
+ return uint64(math.Float32bits(x))
+ case float64:
+ return math.Float64bits(x)
+ }
+ return 0
+}
+
+func fromBits(b uint64, x interface{}) interface{} {
+ switch x.(type) {
+ case float32:
+ return math.Float32frombits(uint32(b))
+ case float64:
+ return math.Float64frombits(b)
+ }
+ return "?"
+}
diff --git a/platform/dbops/binaries/go/go/test/float_lit3.go b/platform/dbops/binaries/go/go/test/float_lit3.go
new file mode 100644
index 0000000000000000000000000000000000000000..37a1289fb9dd21a22e1b10961e8e94d815e9cbb4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/float_lit3.go
@@ -0,0 +1,47 @@
+// errorcheck
+
+// Check flagging of invalid conversion of constant to float32/float64 near min/max boundaries.
+
+// 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 main
+
+// See float_lit2.go for motivation for these values.
+const (
+ two24 = 1.0 * (1 << 24)
+ two53 = 1.0 * (1 << 53)
+ two64 = 1.0 * (1 << 64)
+ two128 = two64 * two64
+ two256 = two128 * two128
+ two512 = two256 * two256
+ two768 = two512 * two256
+ two1024 = two512 * two512
+
+ ulp32 = two128 / two24
+ max32 = two128 - ulp32
+
+ ulp64 = two1024 / two53
+ max64 = two1024 - ulp64
+)
+
+var x = []interface{}{
+ float32(max32 + ulp32/2 - 1), // ok
+ float32(max32 + ulp32/2 - two128/two256), // ok
+ float32(max32 + ulp32/2), // ERROR "constant 3\.40282e\+38 overflows float32|cannot convert.*to type float32"
+
+ float32(-max32 - ulp32/2 + 1), // ok
+ float32(-max32 - ulp32/2 + two128/two256), // ok
+ float32(-max32 - ulp32/2), // ERROR "constant -3\.40282e\+38 overflows float32|cannot convert.*to type float32"
+
+ // If the compiler's internal floating point representation
+ // is shorter than 1024 bits, it cannot distinguish max64+ulp64/2-1 and max64+ulp64/2.
+ float64(max64 + ulp64/2 - two1024/two256), // ok
+ float64(max64 + ulp64/2 - 1), // ok
+ float64(max64 + ulp64/2), // ERROR "constant 1\.79769e\+308 overflows float64|cannot convert.*to type float64"
+
+ float64(-max64 - ulp64/2 + two1024/two256), // ok
+ float64(-max64 - ulp64/2 + 1), // ok
+ float64(-max64 - ulp64/2), // ERROR "constant -1\.79769e\+308 overflows float64|cannot convert.*to type float64"
+}
diff --git a/platform/dbops/binaries/go/go/test/floatcmp.go b/platform/dbops/binaries/go/go/test/floatcmp.go
new file mode 100644
index 0000000000000000000000000000000000000000..6c424ccd909307f4bd920a3fcbdc59223797f9e8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/floatcmp.go
@@ -0,0 +1,93 @@
+// run
+
+// 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.
+
+// Test floating-point comparison involving NaN.
+
+package main
+
+import "math"
+
+type floatTest struct {
+ name string
+ expr bool
+ want bool
+}
+
+var nan float64 = math.NaN()
+var f float64 = 1
+
+var tests = []floatTest{
+ floatTest{"nan == nan", nan == nan, false},
+ floatTest{"nan != nan", nan != nan, true},
+ floatTest{"nan < nan", nan < nan, false},
+ floatTest{"nan > nan", nan > nan, false},
+ floatTest{"nan <= nan", nan <= nan, false},
+ floatTest{"nan >= nan", nan >= nan, false},
+ floatTest{"f == nan", f == nan, false},
+ floatTest{"f != nan", f != nan, true},
+ floatTest{"f < nan", f < nan, false},
+ floatTest{"f > nan", f > nan, false},
+ floatTest{"f <= nan", f <= nan, false},
+ floatTest{"f >= nan", f >= nan, false},
+ floatTest{"nan == f", nan == f, false},
+ floatTest{"nan != f", nan != f, true},
+ floatTest{"nan < f", nan < f, false},
+ floatTest{"nan > f", nan > f, false},
+ floatTest{"nan <= f", nan <= f, false},
+ floatTest{"nan >= f", nan >= f, false},
+ floatTest{"!(nan == nan)", !(nan == nan), true},
+ floatTest{"!(nan != nan)", !(nan != nan), false},
+ floatTest{"!(nan < nan)", !(nan < nan), true},
+ floatTest{"!(nan > nan)", !(nan > nan), true},
+ floatTest{"!(nan <= nan)", !(nan <= nan), true},
+ floatTest{"!(nan >= nan)", !(nan >= nan), true},
+ floatTest{"!(f == nan)", !(f == nan), true},
+ floatTest{"!(f != nan)", !(f != nan), false},
+ floatTest{"!(f < nan)", !(f < nan), true},
+ floatTest{"!(f > nan)", !(f > nan), true},
+ floatTest{"!(f <= nan)", !(f <= nan), true},
+ floatTest{"!(f >= nan)", !(f >= nan), true},
+ floatTest{"!(nan == f)", !(nan == f), true},
+ floatTest{"!(nan != f)", !(nan != f), false},
+ floatTest{"!(nan < f)", !(nan < f), true},
+ floatTest{"!(nan > f)", !(nan > f), true},
+ floatTest{"!(nan <= f)", !(nan <= f), true},
+ floatTest{"!(nan >= f)", !(nan >= f), true},
+ floatTest{"!!(nan == nan)", !!(nan == nan), false},
+ floatTest{"!!(nan != nan)", !!(nan != nan), true},
+ floatTest{"!!(nan < nan)", !!(nan < nan), false},
+ floatTest{"!!(nan > nan)", !!(nan > nan), false},
+ floatTest{"!!(nan <= nan)", !!(nan <= nan), false},
+ floatTest{"!!(nan >= nan)", !!(nan >= nan), false},
+ floatTest{"!!(f == nan)", !!(f == nan), false},
+ floatTest{"!!(f != nan)", !!(f != nan), true},
+ floatTest{"!!(f < nan)", !!(f < nan), false},
+ floatTest{"!!(f > nan)", !!(f > nan), false},
+ floatTest{"!!(f <= nan)", !!(f <= nan), false},
+ floatTest{"!!(f >= nan)", !!(f >= nan), false},
+ floatTest{"!!(nan == f)", !!(nan == f), false},
+ floatTest{"!!(nan != f)", !!(nan != f), true},
+ floatTest{"!!(nan < f)", !!(nan < f), false},
+ floatTest{"!!(nan > f)", !!(nan > f), false},
+ floatTest{"!!(nan <= f)", !!(nan <= f), false},
+ floatTest{"!!(nan >= f)", !!(nan >= f), false},
+}
+
+func main() {
+ bad := false
+ for _, t := range tests {
+ if t.expr != t.want {
+ if !bad {
+ bad = true
+ println("BUG: floatcmp")
+ }
+ println(t.name, "=", t.expr, "want", t.want)
+ }
+ }
+ if bad {
+ panic("floatcmp failed")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/for.go b/platform/dbops/binaries/go/go/test/for.go
new file mode 100644
index 0000000000000000000000000000000000000000..cfb7f6dad24d5bdd80dca111be9a9ae6806ef1af
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/for.go
@@ -0,0 +1,76 @@
+// run
+
+// 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.
+
+// Test for loops.
+
+package main
+
+func assertequal(is, shouldbe int, msg string) {
+ if is != shouldbe {
+ print("assertion fail", msg, "\n")
+ panic(1)
+ }
+}
+
+func main() {
+ var i, sum int
+
+ i = 0
+ for {
+ i = i + 1
+ if i > 5 {
+ break
+ }
+ }
+ assertequal(i, 6, "break")
+
+ sum = 0
+ for i := 0; i <= 10; i++ {
+ sum = sum + i
+ }
+ assertequal(sum, 55, "all three")
+
+ sum = 0
+ for i := 0; i <= 10; {
+ sum = sum + i
+ i++
+ }
+ assertequal(sum, 55, "only two")
+
+ sum = 0
+ for sum < 100 {
+ sum = sum + 9
+ }
+ assertequal(sum, 99+9, "only one")
+
+ sum = 0
+ for i := 0; i <= 10; i++ {
+ if i%2 == 0 {
+ continue
+ }
+ sum = sum + i
+ }
+ assertequal(sum, 1+3+5+7+9, "continue")
+
+ i = 0
+ for i = range [5]struct{}{} {
+ }
+ assertequal(i, 4, " incorrect index value after range loop")
+
+ i = 0
+ var a1 [5]struct{}
+ for i = range a1 {
+ a1[i] = struct{}{}
+ }
+ assertequal(i, 4, " incorrect index value after array with zero size elem range clear")
+
+ i = 0
+ var a2 [5]int
+ for i = range a2 {
+ a2[i] = 0
+ }
+ assertequal(i, 4, " incorrect index value after array range clear")
+}
diff --git a/platform/dbops/binaries/go/go/test/func.go b/platform/dbops/binaries/go/go/test/func.go
new file mode 100644
index 0000000000000000000000000000000000000000..246cb56fd95c398ef2f973cee4599814dd19b1bb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func.go
@@ -0,0 +1,90 @@
+// run
+
+// 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.
+
+// Test simple functions.
+
+package main
+
+func assertequal(is, shouldbe int, msg string) {
+ if is != shouldbe {
+ print("assertion fail", msg, "\n")
+ panic(1)
+ }
+}
+
+func f1() {
+}
+
+func f2(a int) {
+}
+
+func f3(a, b int) int {
+ return a + b
+}
+
+func f4(a, b int, c float32) int {
+ return (a+b)/2 + int(c)
+}
+
+func f5(a int) int {
+ return 5
+}
+
+func f6(a int) (r int) {
+ return 6
+}
+
+func f7(a int) (x int, y float32) {
+ return 7, 7.0
+}
+
+
+func f8(a int) (x int, y float32) {
+ return 8, 8.0
+}
+
+type T struct {
+ x, y int
+}
+
+func (t *T) m10(a int, b float32) int {
+ return (t.x + a) * (t.y + int(b))
+}
+
+
+func f9(a int) (i int, f float32) {
+ i = 9
+ f = 9.0
+ return
+}
+
+
+func main() {
+ f1()
+ f2(1)
+ r3 := f3(1, 2)
+ assertequal(r3, 3, "3")
+ r4 := f4(0, 2, 3.0)
+ assertequal(r4, 4, "4")
+ r5 := f5(1)
+ assertequal(r5, 5, "5")
+ r6 := f6(1)
+ assertequal(r6, 6, "6")
+ r7, s7 := f7(1)
+ assertequal(r7, 7, "r7")
+ assertequal(int(s7), 7, "s7")
+ r8, s8 := f8(1)
+ assertequal(r8, 8, "r8")
+ assertequal(int(s8), 8, "s8")
+ r9, s9 := f9(1)
+ assertequal(r9, 9, "r9")
+ assertequal(int(s9), 9, "s9")
+ var t *T = new(T)
+ t.x = 1
+ t.y = 2
+ r10 := t.m10(1, 3.0)
+ assertequal(r10, 10, "10")
+}
diff --git a/platform/dbops/binaries/go/go/test/func1.go b/platform/dbops/binaries/go/go/test/func1.go
new file mode 100644
index 0000000000000000000000000000000000000000..ec25161d13c675c61bb6b21ffc8310a262a80c5f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func1.go
@@ -0,0 +1,19 @@
+// errorcheck
+
+// 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.
+
+// Test that result parameters are in the same scope as regular parameters.
+// Does not compile.
+
+package main
+
+func f1(a int) (int, float32) {
+ return 7, 7.0
+}
+
+
+func f2(a int) (a int, b float32) { // ERROR "duplicate argument a|definition|redeclared"
+ return 8, 8.0
+}
diff --git a/platform/dbops/binaries/go/go/test/func2.go b/platform/dbops/binaries/go/go/test/func2.go
new file mode 100644
index 0000000000000000000000000000000000000000..b5966a91f6065e58030908746c5b996615635a4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func2.go
@@ -0,0 +1,33 @@
+// compile
+
+// 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.
+
+// Test function signatures.
+// Compiled but not run.
+
+package main
+
+type t1 int
+type t2 int
+type t3 int
+
+func f1(t1, t2, t3)
+func f2(t1, t2, t3 bool)
+func f3(t1, t2, x t3)
+func f4(t1, *t3)
+func (x *t1) f5(y []t2) (t1, *t3)
+func f6() (int, *string)
+func f7(*t2, t3)
+func f8(os int) int
+
+func f9(os int) int {
+ return os
+}
+func f10(err error) error {
+ return err
+}
+func f11(t1 string) string {
+ return t1
+}
diff --git a/platform/dbops/binaries/go/go/test/func3.go b/platform/dbops/binaries/go/go/test/func3.go
new file mode 100644
index 0000000000000000000000000000000000000000..6be3bf0184d386f436fd3d7a1044b26da8084613
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func3.go
@@ -0,0 +1,20 @@
+// errorcheck
+
+// 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.
+
+// Verify that illegal function signatures are detected.
+// Does not compile.
+
+package main
+
+type t1 int
+type t2 int
+type t3 int
+
+func f1(*t2, x t3) // ERROR "named"
+func f2(t1, *t2, x t3) // ERROR "named"
+func f3() (x int, *string) // ERROR "named"
+
+func f4() (t1 t1) // legal - scope of parameter named t1 starts in body of f4.
diff --git a/platform/dbops/binaries/go/go/test/func4.go b/platform/dbops/binaries/go/go/test/func4.go
new file mode 100644
index 0000000000000000000000000000000000000000..85f1e4b81e91fea4c9b3dee5851d5025140aab69
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func4.go
@@ -0,0 +1,18 @@
+// errorcheck
+
+// 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.
+
+// Verify that it is illegal to take the address of a function.
+// Does not compile.
+
+package main
+
+var notmain func()
+
+func main() {
+ var x = &main // ERROR "address of|invalid"
+ main = notmain // ERROR "assign to|invalid"
+ _ = x
+}
diff --git a/platform/dbops/binaries/go/go/test/func5.go b/platform/dbops/binaries/go/go/test/func5.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e058be7e6e19526fb24502964b5466d6e3fa86a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func5.go
@@ -0,0 +1,91 @@
+// run
+
+// 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.
+
+// Test functions and goroutines.
+
+package main
+
+func caller(f func(int, int) int, a, b int, c chan int) {
+ c <- f(a, b)
+}
+
+func gocall(f func(int, int) int, a, b int) int {
+ c := make(chan int)
+ go caller(f, a, b, c)
+ return <-c
+}
+
+func call(f func(int, int) int, a, b int) int {
+ return f(a, b)
+}
+
+func call1(f func(int, int) int, a, b int) int {
+ return call(f, a, b)
+}
+
+var f func(int, int) int
+
+func add(x, y int) int {
+ return x + y
+}
+
+func fn() func(int, int) int {
+ return f
+}
+
+var fc func(int, int, chan int)
+
+func addc(x, y int, c chan int) {
+ c <- x+y
+}
+
+func fnc() func(int, int, chan int) {
+ return fc
+}
+
+func three(x int) {
+ if x != 3 {
+ println("wrong val", x)
+ panic("fail")
+ }
+}
+
+var notmain func()
+
+func emptyresults() {}
+func noresults() {}
+
+var nothing func()
+
+func main() {
+ three(call(add, 1, 2))
+ three(call1(add, 1, 2))
+ f = add
+ three(call(f, 1, 2))
+ three(call1(f, 1, 2))
+ three(call(fn(), 1, 2))
+ three(call1(fn(), 1, 2))
+ three(call(func(a, b int) int { return a + b }, 1, 2))
+ three(call1(func(a, b int) int { return a + b }, 1, 2))
+
+ fc = addc
+ c := make(chan int)
+ go addc(1, 2, c)
+ three(<-c)
+ go fc(1, 2, c)
+ three(<-c)
+ go fnc()(1, 2, c)
+ three(<-c)
+ go func(a, b int, c chan int) { c <- a+b }(1, 2, c)
+ three(<-c)
+
+ emptyresults()
+ noresults()
+ nothing = emptyresults
+ nothing()
+ nothing = noresults
+ nothing()
+}
diff --git a/platform/dbops/binaries/go/go/test/func6.go b/platform/dbops/binaries/go/go/test/func6.go
new file mode 100644
index 0000000000000000000000000000000000000000..5b2f9f273ec88a7f72a1eb4090dc3eb1426eda71
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func6.go
@@ -0,0 +1,16 @@
+// run
+
+// 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.
+
+// Test closures in if conditions.
+
+package main
+
+func main() {
+ if func() bool { return true }() {} // gc used to say this was a syntax error
+ if (func() bool { return true })() {}
+ if (func() bool { return true }()) {}
+}
+
diff --git a/platform/dbops/binaries/go/go/test/func7.go b/platform/dbops/binaries/go/go/test/func7.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b22199f7e3b7515a058d0557268f1cccb8414f3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func7.go
@@ -0,0 +1,30 @@
+// run
+
+// 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.
+
+// Test evaluation order in if condition.
+
+package main
+
+var calledf = false
+
+func f() int {
+ calledf = true
+ return 1
+}
+
+func g() int {
+ if !calledf {
+ panic("BUG: func7 - called g before f")
+ }
+ return 0
+}
+
+func main() {
+ // gc used to evaluate g() before f().
+ if f() < g() {
+ panic("wrong answer")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/func8.go b/platform/dbops/binaries/go/go/test/func8.go
new file mode 100644
index 0000000000000000000000000000000000000000..9de01d43ea5e86a9885071b9fd441185762c17a3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/func8.go
@@ -0,0 +1,47 @@
+// run
+
+// 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.
+
+// Test evaluation order.
+
+package main
+
+var calledf int
+
+func f() int {
+ calledf++
+ return 0
+}
+
+func g() int {
+ return calledf
+}
+
+var xy string
+
+//go:noinline
+func x() bool {
+ xy += "x"
+ return false
+}
+
+//go:noinline
+func y() string {
+ xy += "y"
+ return "abc"
+}
+
+func main() {
+ if f() == g() {
+ panic("wrong f,g order")
+ }
+
+ if x() == (y() == "abc") {
+ panic("wrong compare")
+ }
+ if xy != "xy" {
+ panic("wrong x,y order")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/funcdup.go b/platform/dbops/binaries/go/go/test/funcdup.go
new file mode 100644
index 0000000000000000000000000000000000000000..3dbb15b0d4949167e65b0bdda0daea83825c62d7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/funcdup.go
@@ -0,0 +1,27 @@
+// errorcheck
+
+// 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 T interface {
+ F1(i int) (i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+ F2(i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+ F3() (i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+}
+
+type T1 func(i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+type T2 func(i int) (i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+type T3 func() (i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+
+type R struct{}
+
+func (i *R) F1(i int) {} // ERROR "duplicate argument i|redefinition|previous|redeclared"
+func (i *R) F2() (i int) {return 0} // ERROR "duplicate argument i|redefinition|previous|redeclared"
+func (i *R) F3(j int) (j int) {return 0} // ERROR "duplicate argument j|redefinition|previous|redeclared"
+
+func F1(i, i int) {} // ERROR "duplicate argument i|redefinition|previous|redeclared"
+func F2(i int) (i int) {return 0} // ERROR "duplicate argument i|redefinition|previous|redeclared"
+func F3() (i, i int) {return 0, 0} // ERROR "duplicate argument i|redefinition|previous|redeclared"
diff --git a/platform/dbops/binaries/go/go/test/funcdup2.go b/platform/dbops/binaries/go/go/test/funcdup2.go
new file mode 100644
index 0000000000000000000000000000000000000000..2ee3024e5ccd91fc0b4abc3242c102eecc63fd58
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/funcdup2.go
@@ -0,0 +1,17 @@
+// errorcheck
+
+// 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
+
+var T interface {
+ F1(i int) (i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+ F2(i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+ F3() (i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+}
+
+var T1 func(i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+var T2 func(i int) (i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
+var T3 func() (i, i int) // ERROR "duplicate argument i|redefinition|previous|redeclared"
diff --git a/platform/dbops/binaries/go/go/test/fuse.go b/platform/dbops/binaries/go/go/test/fuse.go
new file mode 100644
index 0000000000000000000000000000000000000000..f64a087965ae096346e2e7e985794f38380023fa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/fuse.go
@@ -0,0 +1,191 @@
+// errorcheck -0 -d=ssa/late_fuse/debug=1
+
+//go:build (amd64 && !gcflags_noopt) || (arm64 && !gcflags_noopt)
+
+// 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 "strings"
+
+const Cf2 = 2.0
+
+func fEqEq(a int, f float64) bool {
+ return a == 0 && f > Cf2 || a == 0 && f < -Cf2 // ERROR "Redirect Eq64 based on Eq64$"
+}
+
+func fEqNeq(a int32, f float64) bool {
+ return a == 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq32 based on Eq32$"
+}
+
+func fEqLess(a int8, f float64) bool {
+ return a == 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fEqLeq(a float64, f float64) bool {
+ return a == 0 && f > Cf2 || a <= 0 && f < -Cf2
+}
+
+func fEqLessU(a uint, f float64) bool {
+ return a == 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fEqLeqU(a uint64, f float64) bool {
+ return a == 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq64U based on Eq64$"
+}
+
+func fNeqEq(a int, f float64) bool {
+ return a != 0 && f > Cf2 || a == 0 && f < -Cf2 // ERROR "Redirect Eq64 based on Neq64$"
+}
+
+func fNeqNeq(a int32, f float64) bool {
+ return a != 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq32 based on Neq32$"
+}
+
+func fNeqLess(a float32, f float64) bool {
+ // TODO: Add support for floating point numbers in prove
+ return a != 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fNeqLeq(a int16, f float64) bool {
+ return a != 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq16 based on Neq16$"
+}
+
+func fNeqLessU(a uint, f float64) bool {
+ return a != 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fNeqLeqU(a uint32, f float64) bool {
+ return a != 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq32U based on Neq32$"
+}
+
+func fLessEq(a int, f float64) bool {
+ return a < 0 && f > Cf2 || a == 0 && f < -Cf2
+}
+
+func fLessNeq(a int32, f float64) bool {
+ return a < 0 && f > Cf2 || a != 0 && f < -Cf2
+}
+
+func fLessLess(a float32, f float64) bool {
+ return a < 0 && f > Cf2 || a < 0 && f < -Cf2 // ERROR "Redirect Less32F based on Less32F$"
+}
+
+func fLessLeq(a float64, f float64) bool {
+ return a < 0 && f > Cf2 || a <= 0 && f < -Cf2
+}
+
+func fLeqEq(a float64, f float64) bool {
+ return a <= 0 && f > Cf2 || a == 0 && f < -Cf2
+}
+
+func fLeqNeq(a int16, f float64) bool {
+ return a <= 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq16 based on Leq16$"
+}
+
+func fLeqLess(a float32, f float64) bool {
+ return a <= 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fLeqLeq(a int8, f float64) bool {
+ return a <= 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq8 based on Leq8$"
+}
+
+func fLessUEq(a uint8, f float64) bool {
+ return a < 0 && f > Cf2 || a == 0 && f < -Cf2
+}
+
+func fLessUNeq(a uint16, f float64) bool {
+ return a < 0 && f > Cf2 || a != 0 && f < -Cf2
+}
+
+func fLessULessU(a uint32, f float64) bool {
+ return a < 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fLessULeqU(a uint64, f float64) bool {
+ return a < 0 && f > Cf2 || a <= 0 && f < -Cf2
+}
+
+func fLeqUEq(a uint8, f float64) bool {
+ return a <= 0 && f > Cf2 || a == 0 && f < -Cf2 // ERROR "Redirect Eq8 based on Leq8U$"
+}
+
+func fLeqUNeq(a uint16, f float64) bool {
+ return a <= 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq16 based on Leq16U$"
+}
+
+func fLeqLessU(a uint32, f float64) bool {
+ return a <= 0 && f > Cf2 || a < 0 && f < -Cf2
+}
+
+func fLeqLeqU(a uint64, f float64) bool {
+ return a <= 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq64U based on Leq64U$"
+}
+
+// Arg tests are disabled because the op name is different on amd64 and arm64.
+
+func fEqPtrEqPtr(a, b *int, f float64) bool {
+ return a == b && f > Cf2 || a == b && f < -Cf2 // ERROR "Redirect EqPtr based on EqPtr$"
+}
+
+func fEqPtrNeqPtr(a, b *int, f float64) bool {
+ return a == b && f > Cf2 || a != b && f < -Cf2 // ERROR "Redirect NeqPtr based on EqPtr$"
+}
+
+func fNeqPtrEqPtr(a, b *int, f float64) bool {
+ return a != b && f > Cf2 || a == b && f < -Cf2 // ERROR "Redirect EqPtr based on NeqPtr$"
+}
+
+func fNeqPtrNeqPtr(a, b *int, f float64) bool {
+ return a != b && f > Cf2 || a != b && f < -Cf2 // ERROR "Redirect NeqPtr based on NeqPtr$"
+}
+
+func fEqInterEqInter(a interface{}, f float64) bool {
+ return a == nil && f > Cf2 || a == nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
+}
+
+func fEqInterNeqInter(a interface{}, f float64) bool {
+ return a == nil && f > Cf2 || a != nil && f < -Cf2
+}
+
+func fNeqInterEqInter(a interface{}, f float64) bool {
+ return a != nil && f > Cf2 || a == nil && f < -Cf2
+}
+
+func fNeqInterNeqInter(a interface{}, f float64) bool {
+ return a != nil && f > Cf2 || a != nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
+}
+
+func fEqSliceEqSlice(a []int, f float64) bool {
+ return a == nil && f > Cf2 || a == nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
+}
+
+func fEqSliceNeqSlice(a []int, f float64) bool {
+ return a == nil && f > Cf2 || a != nil && f < -Cf2
+}
+
+func fNeqSliceEqSlice(a []int, f float64) bool {
+ return a != nil && f > Cf2 || a == nil && f < -Cf2
+}
+
+func fNeqSliceNeqSlice(a []int, f float64) bool {
+ return a != nil && f > Cf2 || a != nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
+}
+
+func fPhi(a, b string) string {
+ aslash := strings.HasSuffix(a, "/") // ERROR "Redirect Phi based on Phi$"
+ bslash := strings.HasPrefix(b, "/")
+ switch {
+ case aslash && bslash:
+ return a + b[1:]
+ case !aslash && !bslash:
+ return a + "/" + b
+ }
+ return a + b
+}
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/gc.go b/platform/dbops/binaries/go/go/test/gc.go
new file mode 100644
index 0000000000000000000000000000000000000000..6688f9fbddb9148c60ff0719e45cfc367cff35dc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/gc.go
@@ -0,0 +1,26 @@
+// run
+
+// 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.
+
+// Simple test of the garbage collector.
+
+package main
+
+import "runtime"
+
+func mk2() {
+ b := new([10000]byte)
+ _ = b
+ // println(b, "stored at", &b)
+}
+
+func mk1() { mk2() }
+
+func main() {
+ for i := 0; i < 10; i++ {
+ mk1()
+ runtime.GC()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/gc1.go b/platform/dbops/binaries/go/go/test/gc1.go
new file mode 100644
index 0000000000000000000000000000000000000000..6049ea14e9bfa9a3a4ab26ccb4169c34968f1552
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/gc1.go
@@ -0,0 +1,16 @@
+// run
+
+// 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 simple test of the garbage collector.
+
+package main
+
+func main() {
+ for i := 0; i < 1e5; i++ {
+ x := new([100]byte)
+ _ = x
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/gc2.go b/platform/dbops/binaries/go/go/test/gc2.go
new file mode 100644
index 0000000000000000000000000000000000000000..954a021a144599a43922a34ffc3a6574b2cabf97
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/gc2.go
@@ -0,0 +1,46 @@
+// run
+
+//go:build !nacl && !js
+
+// 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.
+
+// Test that buffered channels are garbage collected properly.
+// An interesting case because they have finalizers and used to
+// have self loops that kept them from being collected.
+// (Cyclic data with finalizers is never finalized, nor collected.)
+
+package main
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+)
+
+func main() {
+ const N = 10000
+ st := new(runtime.MemStats)
+ memstats := new(runtime.MemStats)
+ runtime.ReadMemStats(st)
+ for i := 0; i < N; i++ {
+ c := make(chan int, 10)
+ _ = c
+ if i%100 == 0 {
+ for j := 0; j < 4; j++ {
+ runtime.GC()
+ runtime.Gosched()
+ runtime.GC()
+ runtime.Gosched()
+ }
+ }
+ }
+
+ runtime.ReadMemStats(memstats)
+ obj := int64(memstats.HeapObjects - st.HeapObjects)
+ if obj > N/5 {
+ fmt.Println("too many objects left:", obj)
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/gcgort.go b/platform/dbops/binaries/go/go/test/gcgort.go
new file mode 100644
index 0000000000000000000000000000000000000000..973e7965952caac4984e8aa195189cc7b8032e15
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/gcgort.go
@@ -0,0 +1,1850 @@
+// run
+
+// 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.
+
+// Test independent goroutines modifying a comprehensive
+// variety of vars during aggressive garbage collection.
+
+// The point is to catch GC regressions like fixedbugs/issue22781.go
+
+package main
+
+import (
+ "errors"
+ "runtime"
+ "runtime/debug"
+ "sync"
+)
+
+const (
+ goroutines = 8
+ allocs = 8
+ mods = 8
+
+ length = 9
+)
+
+func main() {
+ debug.SetGCPercent(1)
+ var wg sync.WaitGroup
+ for i := 0; i < goroutines; i++ {
+ for _, t := range types {
+ err := t.valid()
+ if err != nil {
+ panic(err)
+ }
+ wg.Add(1)
+ go func(f modifier) {
+ var wg2 sync.WaitGroup
+ for j := 0; j < allocs; j++ {
+ wg2.Add(1)
+ go func() {
+ f.t()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.pointerT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.arrayT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.sliceT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.mapT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.mapPointerKeyT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.chanT()
+ wg2.Done()
+ }()
+ wg2.Add(1)
+ go func() {
+ f.interfaceT()
+ wg2.Done()
+ }()
+ }
+ wg2.Wait()
+ wg.Done()
+ }(t)
+ }
+ }
+ wg.Wait()
+}
+
+type modifier struct {
+ name string
+ t func()
+ pointerT func()
+ arrayT func()
+ sliceT func()
+ mapT func()
+ mapPointerKeyT func()
+ chanT func()
+ interfaceT func()
+}
+
+func (a modifier) valid() error {
+ switch {
+ case a.name == "":
+ return errors.New("modifier without name")
+ case a.t == nil:
+ return errors.New(a.name + " missing t")
+ case a.pointerT == nil:
+ return errors.New(a.name + " missing pointerT")
+ case a.arrayT == nil:
+ return errors.New(a.name + " missing arrayT")
+ case a.sliceT == nil:
+ return errors.New(a.name + " missing sliceT")
+ case a.mapT == nil:
+ return errors.New(a.name + " missing mapT")
+ case a.mapPointerKeyT == nil:
+ return errors.New(a.name + " missing mapPointerKeyT")
+ case a.chanT == nil:
+ return errors.New(a.name + " missing chanT")
+ case a.interfaceT == nil:
+ return errors.New(a.name + " missing interfaceT")
+ default:
+ return nil
+ }
+}
+
+var types = []modifier{
+ modifier{
+ name: "bool",
+ t: func() {
+ var a bool
+ for i := 0; i < mods; i++ {
+ a = !a
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *bool { return new(bool) }()
+ for i := 0; i < mods; i++ {
+ *a = !*a
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]bool{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] = !a[j]
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]bool, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] = !a[j]
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[bool]bool)
+ for i := 0; i < mods; i++ {
+ a[false] = !a[false]
+ a[true] = !a[true]
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*bool]bool)
+ for i := 0; i < length; i++ {
+ a[new(bool)] = false
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, v := range a {
+ a[k] = !v
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan bool)
+ for i := 0; i < mods; i++ {
+ go func() { a <- false }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(bool(false))
+ for i := 0; i < mods; i++ {
+ a = !a.(bool)
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uint8",
+ t: func() {
+ var u uint8
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uint8 { return new(uint8) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uint8{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uint8, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uint8]uint8)
+ for i := 0; i < length; i++ {
+ a[uint8(i)] = uint8(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uint8]uint8)
+ for i := 0; i < length; i++ {
+ a[new(uint8)] = uint8(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uint8)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uint8(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uint8(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uint8) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uint16",
+ t: func() {
+ var u uint16
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uint16 { return new(uint16) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uint16{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uint16, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uint16]uint16)
+ for i := 0; i < length; i++ {
+ a[uint16(i)] = uint16(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uint16]uint16)
+ for i := 0; i < length; i++ {
+ a[new(uint16)] = uint16(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uint16)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uint16(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uint16(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uint16) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uint32",
+ t: func() {
+ var u uint32
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uint32 { return new(uint32) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uint32{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uint32, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uint32]uint32)
+ for i := 0; i < length; i++ {
+ a[uint32(i)] = uint32(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uint32]uint32)
+ for i := 0; i < length; i++ {
+ a[new(uint32)] = uint32(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uint32)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uint32(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uint32(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uint32) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uint64",
+ t: func() {
+ var u uint64
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uint64 { return new(uint64) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uint64{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uint64, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uint64]uint64)
+ for i := 0; i < length; i++ {
+ a[uint64(i)] = uint64(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uint64]uint64)
+ for i := 0; i < length; i++ {
+ a[new(uint64)] = uint64(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uint64)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uint64(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uint64(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uint64) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "int8",
+ t: func() {
+ var u int8
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *int8 { return new(int8) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]int8{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]int8, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[int8]int8)
+ for i := 0; i < length; i++ {
+ a[int8(i)] = int8(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*int8]int8)
+ for i := 0; i < length; i++ {
+ a[new(int8)] = int8(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan int8)
+ for i := 0; i < mods; i++ {
+ go func() { a <- int8(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(int8(0))
+ for i := 0; i < mods; i++ {
+ a = a.(int8) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "int16",
+ t: func() {
+ var u int16
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *int16 { return new(int16) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]int16{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]int16, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[int16]int16)
+ for i := 0; i < length; i++ {
+ a[int16(i)] = int16(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*int16]int16)
+ for i := 0; i < length; i++ {
+ a[new(int16)] = int16(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan int16)
+ for i := 0; i < mods; i++ {
+ go func() { a <- int16(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(int16(0))
+ for i := 0; i < mods; i++ {
+ a = a.(int16) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "int32",
+ t: func() {
+ var u int32
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *int32 { return new(int32) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]int32{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]int32, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[int32]int32)
+ for i := 0; i < length; i++ {
+ a[int32(i)] = int32(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*int32]int32)
+ for i := 0; i < length; i++ {
+ a[new(int32)] = int32(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan int32)
+ for i := 0; i < mods; i++ {
+ go func() { a <- int32(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(int32(0))
+ for i := 0; i < mods; i++ {
+ a = a.(int32) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "int64",
+ t: func() {
+ var u int64
+ for i := 0; i < mods; i++ {
+ u++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *int64 { return new(int64) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]int64{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]int64, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[int64]int64)
+ for i := 0; i < length; i++ {
+ a[int64(i)] = int64(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*int64]int64)
+ for i := 0; i < length; i++ {
+ a[new(int64)] = int64(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan int64)
+ for i := 0; i < mods; i++ {
+ go func() { a <- int64(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(int64(0))
+ for i := 0; i < mods; i++ {
+ a = a.(int64) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "float32",
+ t: func() {
+ u := float32(1.01)
+ for i := 0; i < mods; i++ {
+ u *= 1.01
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *float32 { return new(float32) }()
+ *a = 1.01
+ for i := 0; i < mods; i++ {
+ *a *= 1.01
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]float32{}
+ for i := 0; i < length; i++ {
+ a[i] = float32(1.01)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]float32, length)
+ for i := 0; i < length; i++ {
+ a[i] = float32(1.01)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[float32]float32)
+ for i := 0; i < length; i++ {
+ a[float32(i)] = float32(i) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= 1.01
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*float32]float32)
+ for i := 0; i < length; i++ {
+ a[new(float32)] = float32(i) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan float32)
+ for i := 0; i < mods; i++ {
+ go func() { a <- float32(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(float32(0))
+ for i := 0; i < mods; i++ {
+ a = a.(float32) * 1.01
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "float64",
+ t: func() {
+ u := float64(1.01)
+ for i := 0; i < mods; i++ {
+ u *= 1.01
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *float64 { return new(float64) }()
+ *a = 1.01
+ for i := 0; i < mods; i++ {
+ *a *= 1.01
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]float64{}
+ for i := 0; i < length; i++ {
+ a[i] = float64(1.01)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]float64, length)
+ for i := 0; i < length; i++ {
+ a[i] = float64(1.01)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[float64]float64)
+ for i := 0; i < length; i++ {
+ a[float64(i)] = float64(i) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= 1.01
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*float64]float64)
+ for i := 0; i < length; i++ {
+ a[new(float64)] = float64(i) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= 1.01
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan float64)
+ for i := 0; i < mods; i++ {
+ go func() { a <- float64(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(float64(0))
+ for i := 0; i < mods; i++ {
+ a = a.(float64) * 1.01
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "complex64",
+ t: func() {
+ c := complex64(complex(float32(1.01), float32(1.01)))
+ for i := 0; i < mods; i++ {
+ c = complex(real(c)*1.01, imag(c)*1.01)
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *complex64 { return new(complex64) }()
+ *a = complex64(complex(float32(1.01), float32(1.01)))
+ for i := 0; i < mods; i++ {
+ *a *= complex(real(*a)*1.01, imag(*a)*1.01)
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]complex64{}
+ for i := 0; i < length; i++ {
+ a[i] = complex64(complex(float32(1.01), float32(1.01)))
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= complex(real(a[j])*1.01, imag(a[j])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]complex64, length)
+ for i := 0; i < length; i++ {
+ a[i] = complex64(complex(float32(1.01), float32(1.01)))
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= complex(real(a[j])*1.01, imag(a[j])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[complex64]complex64)
+ for i := 0; i < length; i++ {
+ a[complex64(complex(float32(i), float32(i)))] = complex64(complex(float32(i), float32(i))) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= complex(real(a[k])*1.01, imag(a[k])*1.01)
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*complex64]complex64)
+ for i := 0; i < length; i++ {
+ a[new(complex64)] = complex64(complex(float32(i), float32(i))) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= complex(real(a[k])*1.01, imag(a[k])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan complex64)
+ for i := 0; i < mods; i++ {
+ go func() { a <- complex64(complex(float32(i), float32(i))) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(complex64(complex(float32(1.01), float32(1.01))))
+ for i := 0; i < mods; i++ {
+ a = a.(complex64) * complex(real(a.(complex64))*1.01, imag(a.(complex64))*1.01)
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "complex128",
+ t: func() {
+ c := complex128(complex(float64(1.01), float64(1.01)))
+ for i := 0; i < mods; i++ {
+ c = complex(real(c)*1.01, imag(c)*1.01)
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *complex128 { return new(complex128) }()
+ *a = complex128(complex(float64(1.01), float64(1.01)))
+ for i := 0; i < mods; i++ {
+ *a *= complex(real(*a)*1.01, imag(*a)*1.01)
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]complex128{}
+ for i := 0; i < length; i++ {
+ a[i] = complex128(complex(float64(1.01), float64(1.01)))
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= complex(real(a[j])*1.01, imag(a[j])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]complex128, length)
+ for i := 0; i < length; i++ {
+ a[i] = complex128(complex(float64(1.01), float64(1.01)))
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] *= complex(real(a[j])*1.01, imag(a[j])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[complex128]complex128)
+ for i := 0; i < length; i++ {
+ a[complex128(complex(float64(i), float64(i)))] = complex128(complex(float64(i), float64(i))) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= complex(real(a[k])*1.01, imag(a[k])*1.01)
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*complex128]complex128)
+ for i := 0; i < length; i++ {
+ a[new(complex128)] = complex128(complex(float64(i), float64(i))) + 0.01
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] *= complex(real(a[k])*1.01, imag(a[k])*1.01)
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan complex128)
+ for i := 0; i < mods; i++ {
+ go func() { a <- complex128(complex(float64(i), float64(i))) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(complex128(complex(float64(1.01), float64(1.01))))
+ for i := 0; i < mods; i++ {
+ a = a.(complex128) * complex(real(a.(complex128))*1.01, imag(a.(complex128))*1.01)
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "byte",
+ t: func() {
+ var a byte
+ for i := 0; i < mods; i++ {
+ a++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *byte { return new(byte) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]byte{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]byte, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[byte]byte)
+ for i := 0; i < length; i++ {
+ a[byte(i)] = byte(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*byte]byte)
+ for i := 0; i < length; i++ {
+ a[new(byte)] = byte(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan byte)
+ for i := 0; i < mods; i++ {
+ go func() { a <- byte(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(byte(0))
+ for i := 0; i < mods; i++ {
+ a = a.(byte) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "rune",
+ t: func() {
+ var a rune
+ for i := 0; i < mods; i++ {
+ a++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *rune { return new(rune) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]rune{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]rune, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[rune]rune)
+ for i := 0; i < length; i++ {
+ a[rune(i)] = rune(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*rune]rune)
+ for i := 0; i < length; i++ {
+ a[new(rune)] = rune(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan rune)
+ for i := 0; i < mods; i++ {
+ go func() { a <- rune(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(rune(0))
+ for i := 0; i < mods; i++ {
+ a = a.(rune) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uint",
+ t: func() {
+ var a uint
+ for i := 0; i < mods; i++ {
+ a++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uint { return new(uint) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uint{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uint, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uint]uint)
+ for i := 0; i < length; i++ {
+ a[uint(i)] = uint(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uint]uint)
+ for i := 0; i < length; i++ {
+ a[new(uint)] = uint(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uint)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uint(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uint(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uint) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "int",
+ t: func() {
+ var a int
+ for i := 0; i < mods; i++ {
+ a++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *int { return new(int) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]int{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]int, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[int]int)
+ for i := 0; i < length; i++ {
+ a[int(i)] = int(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*int]int)
+ for i := 0; i < length; i++ {
+ a[new(int)] = int(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan int)
+ for i := 0; i < mods; i++ {
+ go func() { a <- int(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(int(0))
+ for i := 0; i < mods; i++ {
+ a = a.(int) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "uintptr",
+ t: func() {
+ var a uintptr
+ for i := 0; i < mods; i++ {
+ a++
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ a := func() *uintptr { return new(uintptr) }()
+ for i := 0; i < mods; i++ {
+ *a++
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]uintptr{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]uintptr, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j]++
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[uintptr]uintptr)
+ for i := 0; i < length; i++ {
+ a[uintptr(i)] = uintptr(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*uintptr]uintptr)
+ for i := 0; i < length; i++ {
+ a[new(uintptr)] = uintptr(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k]++
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan uintptr)
+ for i := 0; i < mods; i++ {
+ go func() { a <- uintptr(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(uintptr(0))
+ for i := 0; i < mods; i++ {
+ a = a.(uintptr) + 1
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "string",
+ t: func() {
+ var s string
+ f := func(a string) string { return a }
+ for i := 0; i < mods; i++ {
+ s = str(i)
+ s = f(s)
+ }
+ },
+ pointerT: func() {
+ a := func() *string { return new(string) }()
+ for i := 0; i < mods; i++ {
+ *a = str(i)
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]string{}
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] = str(i)
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]string, length)
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j] = str(i)
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[string]string)
+ for i := 0; i < length; i++ {
+ a[string(i)] = str(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] = str(i)
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*string]string)
+ for i := 0; i < length; i++ {
+ a[new(string)] = str(i)
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for k, _ := range a {
+ a[k] = str(i)
+ runtime.Gosched()
+ }
+ }
+ },
+ chanT: func() {
+ a := make(chan string)
+ for i := 0; i < mods; i++ {
+ go func() { a <- str(i) }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(str(0))
+ f := func(a string) string { return a }
+ for i := 0; i < mods; i++ {
+ a = str(i)
+ a = f(a.(string))
+ runtime.Gosched()
+ }
+ },
+ },
+ modifier{
+ name: "structT",
+ t: func() {
+ s := newStructT()
+ for i := 0; i < mods; i++ {
+ s.u8++
+ s.u16++
+ s.u32++
+ s.u64++
+ s.i8++
+ s.i16++
+ s.i32++
+ s.i64++
+ s.f32 *= 1.01
+ s.f64 *= 1.01
+ s.c64 = complex(real(s.c64)*1.01, imag(s.c64)*1.01)
+ s.c128 = complex(real(s.c128)*1.01, imag(s.c128)*1.01)
+ s.b++
+ s.r++
+ s.u++
+ s.in++
+ s.uip++
+ s.s = str(i)
+ runtime.Gosched()
+ }
+ },
+ pointerT: func() {
+ s := func() *structT {
+ t := newStructT()
+ return &t
+ }()
+ for i := 0; i < mods; i++ {
+ s.u8++
+ s.u16++
+ s.u32++
+ s.u64++
+ s.i8++
+ s.i16++
+ s.i32++
+ s.i64++
+ s.f32 *= 1.01
+ s.f64 *= 1.01
+ s.c64 = complex(real(s.c64)*1.01, imag(s.c64)*1.01)
+ s.c128 = complex(real(s.c128)*1.01, imag(s.c128)*1.01)
+ s.b++
+ s.r++
+ s.u++
+ s.in++
+ s.uip++
+ s.s = str(i)
+ runtime.Gosched()
+ }
+ },
+ arrayT: func() {
+ a := [length]structT{}
+ for i := 0; i < len(a); i++ {
+ a[i] = newStructT()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j].u8++
+ a[j].u16++
+ a[j].u32++
+ a[j].u64++
+ a[j].i8++
+ a[j].i16++
+ a[j].i32++
+ a[j].i64++
+ a[j].f32 *= 1.01
+ a[j].f64 *= 1.01
+ a[j].c64 = complex(real(a[j].c64)*1.01, imag(a[j].c64)*1.01)
+ a[j].c128 = complex(real(a[j].c128)*1.01, imag(a[j].c128)*1.01)
+ a[j].b++
+ a[j].r++
+ a[j].u++
+ a[j].in++
+ a[j].uip++
+ a[j].s = str(i)
+ runtime.Gosched()
+ }
+ }
+ },
+ sliceT: func() {
+ a := make([]structT, length)
+ for i := 0; i < len(a); i++ {
+ a[i] = newStructT()
+ }
+ for i := 0; i < mods; i++ {
+ for j := 0; j < len(a); j++ {
+ a[j].u8++
+ a[j].u16++
+ a[j].u32++
+ a[j].u64++
+ a[j].i8++
+ a[j].i16++
+ a[j].i32++
+ a[j].i64++
+ a[j].f32 *= 1.01
+ a[j].f64 *= 1.01
+ a[j].c64 = complex(real(a[j].c64)*1.01, imag(a[j].c64)*1.01)
+ a[j].c128 = complex(real(a[j].c128)*1.01, imag(a[j].c128)*1.01)
+ a[j].b++
+ a[j].r++
+ a[j].u++
+ a[j].in++
+ a[j].uip++
+ a[j].s = str(i)
+ runtime.Gosched()
+ }
+ }
+ },
+ mapT: func() {
+ a := make(map[structT]structT)
+ for i := 0; i < length; i++ {
+ m := newStructT()
+ m.in = i
+ a[m] = newStructT()
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j, _ := range a {
+ m := a[j]
+ m.u8++
+ m.u16++
+ m.u32++
+ m.u64++
+ m.i8++
+ m.i16++
+ m.i32++
+ m.i64++
+ m.f32 *= 1.01
+ m.f64 *= 1.01
+ m.c64 = complex(real(a[j].c64)*1.01, imag(a[j].c64)*1.01)
+ m.c128 = complex(real(a[j].c128)*1.01, imag(a[j].c128)*1.01)
+ m.b++
+ m.r++
+ m.u++
+ m.in++
+ m.uip++
+ m.s = str(i)
+ a[j] = m
+ runtime.Gosched()
+ }
+ runtime.Gosched()
+ }
+ },
+ mapPointerKeyT: func() {
+ a := make(map[*structT]structT)
+ f := func() *structT {
+ m := newStructT()
+ return &m
+ }
+ for i := 0; i < length; i++ {
+ m := f()
+ m.in = i
+ a[m] = newStructT()
+ runtime.Gosched()
+ }
+ for i := 0; i < mods; i++ {
+ for j, _ := range a {
+ m := a[j]
+ m.u8++
+ m.u16++
+ m.u32++
+ m.u64++
+ m.i8++
+ m.i16++
+ m.i32++
+ m.i64++
+ m.f32 *= 1.01
+ m.f64 *= 1.01
+ m.c64 = complex(real(a[j].c64)*1.01, imag(a[j].c64)*1.01)
+ m.c128 = complex(real(a[j].c128)*1.01, imag(a[j].c128)*1.01)
+ m.b++
+ m.r++
+ m.u++
+ m.in++
+ m.uip++
+ m.s = str(i)
+ a[j] = m
+ runtime.Gosched()
+ }
+ runtime.Gosched()
+ }
+ },
+ chanT: func() {
+ a := make(chan structT)
+ for i := 0; i < mods; i++ {
+ go func() { a <- newStructT() }()
+ <-a
+ runtime.Gosched()
+ }
+ },
+ interfaceT: func() {
+ a := interface{}(newStructT())
+ for i := 0; i < mods; i++ {
+ a = a.(structT)
+ runtime.Gosched()
+ }
+ },
+ },
+}
+
+type structT struct {
+ u8 uint8
+ u16 uint16
+ u32 uint32
+ u64 uint64
+ i8 int8
+ i16 int16
+ i32 int32
+ i64 int64
+ f32 float32
+ f64 float64
+ c64 complex64
+ c128 complex128
+ b byte
+ r rune
+ u uint
+ in int
+ uip uintptr
+ s string
+}
+
+func newStructT() structT {
+ return structT{
+ f32: 1.01,
+ f64: 1.01,
+ c64: complex(float32(1.01), float32(1.01)),
+ c128: complex(float64(1.01), float64(1.01)),
+ }
+}
+
+func str(in int) string {
+ switch in % 3 {
+ case 0:
+ return "Hello"
+ case 1:
+ return "world"
+ case 2:
+ return "!"
+ }
+ return "?"
+}
diff --git a/platform/dbops/binaries/go/go/test/gcstring.go b/platform/dbops/binaries/go/go/test/gcstring.go
new file mode 100644
index 0000000000000000000000000000000000000000..7633d5da55e31d738c3f327fd290f11fa2d466d1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/gcstring.go
@@ -0,0 +1,48 @@
+// run
+
+// 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 s[len(s):] - which can point past the end of the allocated block -
+// does not confuse the garbage collector.
+
+package main
+
+import (
+ "runtime"
+ "time"
+)
+
+type T struct {
+ ptr **int
+ pad [120]byte
+}
+
+var things []interface{}
+
+func main() {
+ setup()
+ runtime.GC()
+ runtime.GC()
+ time.Sleep(10*time.Millisecond)
+ runtime.GC()
+ runtime.GC()
+ time.Sleep(10*time.Millisecond)
+}
+
+func setup() {
+ var Ts []interface{}
+ buf := make([]byte, 128)
+
+ for i := 0; i < 10000; i++ {
+ s := string(buf)
+ t := &T{ptr: new(*int)}
+ runtime.SetFinalizer(t.ptr, func(**int) { panic("*int freed too early") })
+ Ts = append(Ts, t)
+ things = append(things, s[len(s):])
+ }
+
+ things = append(things, Ts...)
+}
+
diff --git a/platform/dbops/binaries/go/go/test/goprint.go b/platform/dbops/binaries/go/go/test/goprint.go
new file mode 100644
index 0000000000000000000000000000000000000000..d44b259081e6801fe4d40b88697e5e5b94d6aa15
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/goprint.go
@@ -0,0 +1,32 @@
+// run
+
+// 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.
+
+// Test that println can be the target of a go statement.
+
+package main
+
+import (
+ "log"
+ "runtime"
+ "time"
+)
+
+func main() {
+ numg0 := runtime.NumGoroutine()
+ deadline := time.Now().Add(10 * time.Second)
+ go println(42, true, false, true, 1.5, "world", (chan int)(nil), []int(nil), (map[string]int)(nil), (func())(nil), byte(255))
+ for {
+ numg := runtime.NumGoroutine()
+ if numg > numg0 {
+ if time.Now().After(deadline) {
+ log.Fatalf("%d goroutines > initial %d after deadline", numg, numg0)
+ }
+ runtime.Gosched()
+ continue
+ }
+ break
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/goprint.out b/platform/dbops/binaries/go/go/test/goprint.out
new file mode 100644
index 0000000000000000000000000000000000000000..da3919ed64f50a8db50657eb11ebd7629fe26758
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/goprint.out
@@ -0,0 +1 @@
+42 true false true +1.500000e+000 world 0x0 [0/0]0x0 0x0 0x0 255
diff --git a/platform/dbops/binaries/go/go/test/goto.go b/platform/dbops/binaries/go/go/test/goto.go
new file mode 100644
index 0000000000000000000000000000000000000000..d660c9ce624aaa69c3e355940c9e891b4643c561
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/goto.go
@@ -0,0 +1,538 @@
+// errorcheck
+
+// 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.
+
+// Verify goto semantics.
+// Does not compile.
+//
+// Each test is in a separate function just so that if the
+// compiler stops processing after one error, we don't
+// lose other ones.
+
+package main
+
+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 declaration of x at LINE+1|goto jumps over declaration"
+ x := 1 // GCCGO_ERROR "defined here"
+ _ = 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 declaration of x at LINE+5|goto jumps over declaration"
+ {
+ x := 1
+ _ = x
+ }
+ x := 1 // GCCGO_ERROR "defined here"
+ _ = x
+L:
+}
+
+// goto across declaration in reverse okay
+func _() {
+L:
+ x := 1
+ _ = x
+ goto L
+}
+
+// error shows first offending variable
+func _() {
+ goto L // ERROR "goto L jumps over declaration of y at LINE+3|goto jumps over declaration"
+ x := 1 // GCCGO_ERROR "defined here"
+ _ = x
+ y := 1
+ _ = y
+L:
+}
+
+// goto not okay even if code path is dead
+func _() {
+ goto L // ERROR "goto L jumps over declaration of y at LINE+3|goto jumps over declaration"
+ x := 1 // GCCGO_ERROR "defined here"
+ _ = x
+ y := 1
+ _ = y
+ return
+L:
+}
+
+// goto into outer block okay
+func _() {
+ {
+ goto L
+ }
+L:
+}
+
+// goto backward into outer block okay
+func _() {
+L:
+ {
+ goto L
+ }
+}
+
+// goto into inner block not okay
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+// goto backward into inner block still not okay
+func _() {
+ { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+// error shows first (outermost) offending block
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+3|goto jumps into block"
+ {
+ {
+ { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ }
+ }
+}
+
+// error prefers block diagnostic over declaration diagnostic
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+3|goto jumps into block"
+ x := 1
+ _ = x
+ { // GCCGO_ERROR "block starts here"
+ 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 starting at LINE+1|goto jumps into block"
+ if true { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ if true { // GCCGO_ERROR "block starts here"
+ L:
+ } else {
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+2|goto jumps into block"
+ if true {
+ } else { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+func _() {
+ if false { // GCCGO_ERROR "block starts here"
+ L:
+ } else {
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+ }
+}
+
+func _() {
+ if true {
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ } else { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+func _() {
+ if true {
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ } else if false { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+func _() {
+ if true {
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ } else if false { // GCCGO_ERROR "block starts here"
+ L:
+ } else {
+ }
+}
+
+func _() {
+ // This one is tricky. There is an implicit scope
+ // starting at the second if statement, and it contains
+ // the final else, so the outermost offending scope
+ // really is LINE+1 (like in the previous test),
+ // even though it looks like it might be LINE+3 instead.
+ if true {
+ goto L // ERROR "goto L jumps into block starting at LINE+2|goto jumps into block"
+ } else if false {
+ } else { // GCCGO_ERROR "block starts here"
+ L:
+ }
+}
+
+/* Want to enable these tests but gofmt mangles them. Issue 1972.
+
+func _() {
+ // This one is okay, because the else is in the
+ // implicit whole-if block and has no inner block
+ // (no { }) around it.
+ if true {
+ goto L
+ } else
+ L:
+}
+
+func _() {
+ // Still not okay.
+ if true { //// GCCGO_ERROR "block starts here"
+ L:
+ } else
+ goto L //// ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+*/
+
+// for
+
+func _() {
+ for {
+ goto L
+ }
+L:
+}
+
+func _() {
+ for {
+ goto L
+ L:
+ }
+}
+
+func _() {
+ for { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for { // GCCGO_ERROR "block starts here"
+ goto L
+ L1:
+ }
+L:
+ goto L1 // ERROR "goto L1 jumps into block starting at LINE-5|goto jumps into block"
+}
+
+func _() {
+ for i < n { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for i = 0; i < n; i++ { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for i = range x { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for i = range c { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for i = range m { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto jumps into block"
+}
+
+func _() {
+ for i = range s { // GCCGO_ERROR "block starts here"
+ L:
+ }
+ goto L // ERROR "goto L jumps into block starting at LINE-3|goto 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 starting at LINE+2|goto jumps into block"
+ switch i {
+ case 0:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+2|goto jumps into block"
+ switch i {
+ case 0:
+ L: // GCCGO_ERROR "block starts here"
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+3|goto jumps into block"
+ switch i {
+ case 0:
+ default:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ switch i {
+ default:
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ case 0:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ switch i {
+ case 0:
+ L: // GCCGO_ERROR "block starts here"
+ ;
+ default:
+ goto L // ERROR "goto L jumps into block starting at LINE-4|goto 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 starting at LINE+2|goto jumps into block"
+ select {
+ case c <- 1:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+2|goto jumps into block"
+ select {
+ case c <- 1:
+ L: // GCCGO_ERROR "block starts here"
+ ;
+ default:
+ }
+}
+
+func _() {
+ goto L // ERROR "goto L jumps into block starting at LINE+3|goto jumps into block"
+ select {
+ case <-c:
+ default:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ select {
+ default:
+ goto L // ERROR "goto L jumps into block starting at LINE+1|goto jumps into block"
+ case <-c:
+ L: // GCCGO_ERROR "block starts here"
+ }
+}
+
+func _() {
+ select {
+ case <-c:
+ L: // GCCGO_ERROR "block starts here"
+ ;
+ default:
+ goto L // ERROR "goto L jumps into block starting at LINE-4|goto jumps into block"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/heapsampling.go b/platform/dbops/binaries/go/go/test/heapsampling.go
new file mode 100644
index 0000000000000000000000000000000000000000..741db74f894d454227e869baa6e8c82e66b470d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/heapsampling.go
@@ -0,0 +1,314 @@
+// run
+
+// 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.
+
+// Test heap sampling logic.
+
+package main
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+)
+
+var a16 *[16]byte
+var a512 *[512]byte
+var a256 *[256]byte
+var a1k *[1024]byte
+var a16k *[16 * 1024]byte
+var a17k *[17 * 1024]byte
+var a18k *[18 * 1024]byte
+
+// This test checks that heap sampling produces reasonable results.
+// Note that heap sampling uses randomization, so the results vary for
+// run to run. To avoid flakes, this test performs multiple
+// experiments and only complains if all of them consistently fail.
+func main() {
+ // Sample at 16K instead of default 512K to exercise sampling more heavily.
+ runtime.MemProfileRate = 16 * 1024
+
+ if err := testInterleavedAllocations(); err != nil {
+ panic(err.Error())
+ }
+ if err := testSmallAllocations(); err != nil {
+ panic(err.Error())
+ }
+}
+
+// Repeatedly exercise a set of allocations and check that the heap
+// profile collected by the runtime unsamples to a reasonable
+// value. Because sampling is based on randomization, there can be
+// significant variability on the unsampled data. To account for that,
+// the testcase allows for a 10% margin of error, but only fails if it
+// consistently fails across three experiments, avoiding flakes.
+func testInterleavedAllocations() error {
+ const iters = 50000
+ // Sizes of the allocations performed by each experiment.
+ frames := []string{"main.allocInterleaved1", "main.allocInterleaved2", "main.allocInterleaved3"}
+
+ // Pass if at least one of three experiments has no errors. Use a separate
+ // function for each experiment to identify each experiment in the profile.
+ allocInterleaved1(iters)
+ if checkAllocations(getMemProfileRecords(), frames[0:1], iters, allocInterleavedSizes) == nil {
+ // Passed on first try, report no error.
+ return nil
+ }
+ allocInterleaved2(iters)
+ if checkAllocations(getMemProfileRecords(), frames[0:2], iters, allocInterleavedSizes) == nil {
+ // Passed on second try, report no error.
+ return nil
+ }
+ allocInterleaved3(iters)
+ // If it fails a third time, we may be onto something.
+ return checkAllocations(getMemProfileRecords(), frames[0:3], iters, allocInterleavedSizes)
+}
+
+var allocInterleavedSizes = []int64{17 * 1024, 1024, 18 * 1024, 512, 16 * 1024, 256}
+
+// allocInterleaved stress-tests the heap sampling logic by interleaving large and small allocations.
+func allocInterleaved(n int) {
+ for i := 0; i < n; i++ {
+ // Test verification depends on these lines being contiguous.
+ a17k = new([17 * 1024]byte)
+ a1k = new([1024]byte)
+ a18k = new([18 * 1024]byte)
+ a512 = new([512]byte)
+ a16k = new([16 * 1024]byte)
+ a256 = new([256]byte)
+ // Test verification depends on these lines being contiguous.
+
+ // Slow down the allocation rate to avoid #52433.
+ runtime.Gosched()
+ }
+}
+
+func allocInterleaved1(n int) {
+ allocInterleaved(n)
+}
+
+func allocInterleaved2(n int) {
+ allocInterleaved(n)
+}
+
+func allocInterleaved3(n int) {
+ allocInterleaved(n)
+}
+
+// Repeatedly exercise a set of allocations and check that the heap
+// profile collected by the runtime unsamples to a reasonable
+// value. Because sampling is based on randomization, there can be
+// significant variability on the unsampled data. To account for that,
+// the testcase allows for a 10% margin of error, but only fails if it
+// consistently fails across three experiments, avoiding flakes.
+func testSmallAllocations() error {
+ const iters = 50000
+ // Sizes of the allocations performed by each experiment.
+ sizes := []int64{1024, 512, 256}
+ frames := []string{"main.allocSmall1", "main.allocSmall2", "main.allocSmall3"}
+
+ // Pass if at least one of three experiments has no errors. Use a separate
+ // function for each experiment to identify each experiment in the profile.
+ allocSmall1(iters)
+ if checkAllocations(getMemProfileRecords(), frames[0:1], iters, sizes) == nil {
+ // Passed on first try, report no error.
+ return nil
+ }
+ allocSmall2(iters)
+ if checkAllocations(getMemProfileRecords(), frames[0:2], iters, sizes) == nil {
+ // Passed on second try, report no error.
+ return nil
+ }
+ allocSmall3(iters)
+ // If it fails a third time, we may be onto something.
+ return checkAllocations(getMemProfileRecords(), frames[0:3], iters, sizes)
+}
+
+// allocSmall performs only small allocations for sanity testing.
+func allocSmall(n int) {
+ for i := 0; i < n; i++ {
+ // Test verification depends on these lines being contiguous.
+ a1k = new([1024]byte)
+ a512 = new([512]byte)
+ a256 = new([256]byte)
+
+ // Slow down the allocation rate to avoid #52433.
+ runtime.Gosched()
+ }
+}
+
+// Three separate instances of testing to avoid flakes. Will report an error
+// only if they all consistently report failures.
+func allocSmall1(n int) {
+ allocSmall(n)
+}
+
+func allocSmall2(n int) {
+ allocSmall(n)
+}
+
+func allocSmall3(n int) {
+ allocSmall(n)
+}
+
+// checkAllocations validates that the profile records collected for
+// the named function are consistent with count contiguous allocations
+// of the specified sizes.
+// Check multiple functions and only report consistent failures across
+// multiple tests.
+// Look only at samples that include the named frames, and group the
+// allocations by their line number. All these allocations are done from
+// the same leaf function, so their line numbers are the same.
+func checkAllocations(records []runtime.MemProfileRecord, frames []string, count int64, size []int64) error {
+ objectsPerLine := map[int][]int64{}
+ bytesPerLine := map[int][]int64{}
+ totalCount := []int64{}
+ // Compute the line number of the first allocation. All the
+ // allocations are from the same leaf, so pick the first one.
+ var firstLine int
+ for ln := range allocObjects(records, frames[0]) {
+ if firstLine == 0 || firstLine > ln {
+ firstLine = ln
+ }
+ }
+ for _, frame := range frames {
+ var objectCount int64
+ a := allocObjects(records, frame)
+ for s := range size {
+ // Allocations of size size[s] should be on line firstLine + s.
+ ln := firstLine + s
+ objectsPerLine[ln] = append(objectsPerLine[ln], a[ln].objects)
+ bytesPerLine[ln] = append(bytesPerLine[ln], a[ln].bytes)
+ objectCount += a[ln].objects
+ }
+ totalCount = append(totalCount, objectCount)
+ }
+ for i, w := range size {
+ ln := firstLine + i
+ if err := checkValue(frames[0], ln, "objects", count, objectsPerLine[ln]); err != nil {
+ return err
+ }
+ if err := checkValue(frames[0], ln, "bytes", count*w, bytesPerLine[ln]); err != nil {
+ return err
+ }
+ }
+ return checkValue(frames[0], 0, "total", count*int64(len(size)), totalCount)
+}
+
+// checkValue checks an unsampled value against its expected value.
+// Given that this is a sampled value, it will be unexact and will change
+// from run to run. Only report it as a failure if all the values land
+// consistently far from the expected value.
+func checkValue(fname string, ln int, testName string, want int64, got []int64) error {
+ if got == nil {
+ return fmt.Errorf("Unexpected empty result")
+ }
+ min, max := got[0], got[0]
+ for _, g := range got[1:] {
+ if g < min {
+ min = g
+ }
+ if g > max {
+ max = g
+ }
+ }
+ margin := want / 10 // 10% margin.
+ if min > want+margin || max < want-margin {
+ return fmt.Errorf("%s:%d want %s in [%d: %d], got %v", fname, ln, testName, want-margin, want+margin, got)
+ }
+ return nil
+}
+
+func getMemProfileRecords() []runtime.MemProfileRecord {
+ // Force the runtime to update the object and byte counts.
+ // This can take up to two GC cycles to get a complete
+ // snapshot of the current point in time.
+ runtime.GC()
+ runtime.GC()
+
+ // Find out how many records there are (MemProfile(nil, true)),
+ // allocate that many records, and get the data.
+ // There's a race—more records might be added between
+ // the two calls—so allocate a few extra records for safety
+ // and also try again if we're very unlucky.
+ // The loop should only execute one iteration in the common case.
+ var p []runtime.MemProfileRecord
+ n, ok := runtime.MemProfile(nil, true)
+ for {
+ // Allocate room for a slightly bigger profile,
+ // in case a few more entries have been added
+ // since the call to MemProfile.
+ p = make([]runtime.MemProfileRecord, n+50)
+ n, ok = runtime.MemProfile(p, true)
+ if ok {
+ p = p[0:n]
+ break
+ }
+ // Profile grew; try again.
+ }
+ return p
+}
+
+type allocStat struct {
+ bytes, objects int64
+}
+
+// allocObjects examines the profile records for samples including the
+// named function and returns the allocation stats aggregated by
+// source line number of the allocation (at the leaf frame).
+func allocObjects(records []runtime.MemProfileRecord, function string) map[int]allocStat {
+ a := make(map[int]allocStat)
+ for _, r := range records {
+ var pcs []uintptr
+ for _, s := range r.Stack0 {
+ if s == 0 {
+ break
+ }
+ pcs = append(pcs, s)
+ }
+ frames := runtime.CallersFrames(pcs)
+ line := 0
+ for {
+ frame, more := frames.Next()
+ name := frame.Function
+ if line == 0 {
+ line = frame.Line
+ }
+ if name == function {
+ allocStat := a[line]
+ allocStat.bytes += r.AllocBytes
+ allocStat.objects += r.AllocObjects
+ a[line] = allocStat
+ }
+ if !more {
+ break
+ }
+ }
+ }
+ for line, stats := range a {
+ objects, bytes := scaleHeapSample(stats.objects, stats.bytes, int64(runtime.MemProfileRate))
+ a[line] = allocStat{bytes, objects}
+ }
+ return a
+}
+
+// scaleHeapSample unsamples heap allocations.
+// Taken from src/cmd/pprof/internal/profile/legacy_profile.go
+func scaleHeapSample(count, size, rate int64) (int64, int64) {
+ if count == 0 || size == 0 {
+ return 0, 0
+ }
+
+ if rate <= 1 {
+ // if rate==1 all samples were collected so no adjustment is needed.
+ // if rate<1 treat as unknown and skip scaling.
+ return count, size
+ }
+
+ avgSize := float64(size) / float64(count)
+ scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
+
+ return int64(float64(count) * scale), int64(float64(size) * scale)
+}
diff --git a/platform/dbops/binaries/go/go/test/helloworld.go b/platform/dbops/binaries/go/go/test/helloworld.go
new file mode 100644
index 0000000000000000000000000000000000000000..06851d13b3aa7b66c0438bdd2c5ea00ad4f4d1c1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/helloworld.go
@@ -0,0 +1,13 @@
+// run
+
+// 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.
+
+// Test that we can do page 1 of the C book.
+
+package main
+
+func main() {
+ print("hello, world\n")
+}
diff --git a/platform/dbops/binaries/go/go/test/helloworld.out b/platform/dbops/binaries/go/go/test/helloworld.out
new file mode 100644
index 0000000000000000000000000000000000000000..4b5fa63702dd96796042e92787f464e28f09f17d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/helloworld.out
@@ -0,0 +1 @@
+hello, world
diff --git a/platform/dbops/binaries/go/go/test/if.go b/platform/dbops/binaries/go/go/test/if.go
new file mode 100644
index 0000000000000000000000000000000000000000..25cc141648b9a65b7555075ad947b1035ad3111d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/if.go
@@ -0,0 +1,93 @@
+// run
+
+// 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.
+
+// Test if statements in various forms.
+
+package main
+
+func assertequal(is, shouldbe int, msg string) {
+ if is != shouldbe {
+ print("assertion fail", msg, "\n")
+ panic(1)
+ }
+}
+
+func main() {
+ i5 := 5
+ i7 := 7
+
+ var count int
+
+ count = 0
+ if true {
+ count = count + 1
+ }
+ assertequal(count, 1, "if true")
+
+ count = 0
+ if false {
+ count = count + 1
+ }
+ assertequal(count, 0, "if false")
+
+ count = 0
+ if one := 1; true {
+ count = count + one
+ }
+ assertequal(count, 1, "if true one")
+
+ count = 0
+ if one := 1; false {
+ count = count + 1
+ _ = one
+ }
+ assertequal(count, 0, "if false one")
+
+ count = 0
+ if i5 < i7 {
+ count = count + 1
+ }
+ assertequal(count, 1, "if cond")
+
+ count = 0
+ if true {
+ count = count + 1
+ } else {
+ count = count - 1
+ }
+ assertequal(count, 1, "if else true")
+
+ count = 0
+ if false {
+ count = count + 1
+ } else {
+ count = count - 1
+ }
+ assertequal(count, -1, "if else false")
+
+ count = 0
+ if t := 1; false {
+ count = count + 1
+ _ = t
+ t := 7
+ _ = t
+ } else {
+ count = count - t
+ }
+ assertequal(count, -1, "if else false var")
+
+ count = 0
+ t := 1
+ if false {
+ count = count + 1
+ t := 7
+ _ = t
+ } else {
+ count = count - t
+ }
+ _ = t
+ assertequal(count, -1, "if else false var outside")
+}
diff --git a/platform/dbops/binaries/go/go/test/import.go b/platform/dbops/binaries/go/go/test/import.go
new file mode 100644
index 0000000000000000000000000000000000000000..d135cd284517fb540e2ff43fb2b6892b72f800ba
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import.go
@@ -0,0 +1,24 @@
+// compile
+
+// 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.
+
+// Test that when import gives multiple names
+// to a single type, they still all refer to the same type.
+
+package main
+
+import _os_ "os"
+import "os"
+import . "os"
+
+func f(e *os.File)
+
+func main() {
+ var _e_ *_os_.File
+ var dot *File
+
+ f(_e_)
+ f(dot)
+}
diff --git a/platform/dbops/binaries/go/go/test/import1.go b/platform/dbops/binaries/go/go/test/import1.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a4534bbfeef1f39175da36dea0b8410742226dd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import1.go
@@ -0,0 +1,19 @@
+// errorcheck
+
+// 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.
+
+// Verify that import conflicts are detected by the compiler.
+// Does not compile.
+
+package main
+
+import "bufio" // ERROR "previous|not used"
+import bufio "os" // ERROR "redeclared|redefinition|incompatible" "imported and not used|imported as bufio and not used"
+
+import (
+ "fmt" // ERROR "previous|not used"
+ fmt "math" // ERROR "redeclared|redefinition|incompatible" "imported and not used: \x22math\x22 as fmt|imported as fmt and not used"
+ . "math" // GC_ERROR "imported and not used: \x22math\x22$|imported and not used"
+)
diff --git a/platform/dbops/binaries/go/go/test/import2.go b/platform/dbops/binaries/go/go/test/import2.go
new file mode 100644
index 0000000000000000000000000000000000000000..1ef1dd4a187f50a90ab1197e8d78ccd0d36f4c09
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import2.go
@@ -0,0 +1,8 @@
+// compiledir
+
+// 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.
+
+// Tests that export data does not corrupt type syntax.
+package ignored
diff --git a/platform/dbops/binaries/go/go/test/import4.go b/platform/dbops/binaries/go/go/test/import4.go
new file mode 100644
index 0000000000000000000000000000000000000000..875bf894302e1e176a5676106b4a1cee98bdf705
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import4.go
@@ -0,0 +1,11 @@
+// errorcheckdir
+
+// 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.
+
+// Verify that various kinds of "imported and not used"
+// errors are caught by the compiler.
+// Does not compile.
+
+package ignored
diff --git a/platform/dbops/binaries/go/go/test/import5.go b/platform/dbops/binaries/go/go/test/import5.go
new file mode 100644
index 0000000000000000000000000000000000000000..8fdc8c3757409f416156ac68a7f893ae712df836
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import5.go
@@ -0,0 +1,27 @@
+// errorcheck
+
+// 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.
+
+// Verify that invalid imports are rejected by the compiler.
+// Does not compile.
+
+package main
+
+// Correct import paths.
+import _ "fmt"
+import _ `time`
+import _ "m\x61th"
+import _ "go/parser"
+
+// Correct import paths, but the packages don't exist.
+// Don't test.
+//import "a.b"
+//import "greek/αβ"
+
+// Import paths must be strings.
+import 42 // ERROR "import path must be a string"
+import 'a' // ERROR "import path must be a string"
+import 3.14 // ERROR "import path must be a string"
+import 0.25i // ERROR "import path must be a string"
diff --git a/platform/dbops/binaries/go/go/test/import6.go b/platform/dbops/binaries/go/go/test/import6.go
new file mode 100644
index 0000000000000000000000000000000000000000..17c7dd4817388a5ba655542463fdc2234cb12823
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/import6.go
@@ -0,0 +1,39 @@
+// errorcheck
+
+// 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.
+
+// Verify that invalid imports are rejected by the compiler.
+// Does not compile.
+
+package main
+
+// Each of these pairs tests both `` vs "" strings
+// and also use of invalid characters spelled out as
+// escape sequences and written directly.
+// For example `"\x00"` tests import "\x00"
+// while "`\x00`" tests import ``.
+import "" // ERROR "import path"
+import `` // ERROR "import path"
+import "\x00" // ERROR "import path"
+import `\x00` // ERROR "import path"
+import "\x7f" // ERROR "import path"
+import `\x7f` // ERROR "import path"
+import "a!" // ERROR "import path"
+import `a!` // ERROR "import path"
+import "a b" // ERROR "import path"
+import `a b` // ERROR "import path"
+import "a\\b" // ERROR "import path"
+import `a\\b` // ERROR "import path"
+import "\"`a`\"" // ERROR "import path"
+import `\"a\"` // ERROR "import path"
+import "\x80\x80" // ERROR "import path"
+import `\x80\x80` // ERROR "import path"
+import "\xFFFD" // ERROR "import path"
+import `\xFFFD` // ERROR "import path"
+
+// Invalid local imports.
+// types2 adds extra "not used" error.
+import "/foo" // ERROR "import path cannot be absolute path|not used"
+import "c:/foo" // ERROR "import path contains invalid character|invalid character"
diff --git a/platform/dbops/binaries/go/go/test/index.go b/platform/dbops/binaries/go/go/test/index.go
new file mode 100644
index 0000000000000000000000000000000000000000..91195ad632bea77a97f4f69457b89e74c4eea7e5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/index.go
@@ -0,0 +1,299 @@
+// skip
+
+// 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.
+
+// Generate test of index and slice bounds checks.
+// The actual tests are index0.go, index1.go, index2.go.
+
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "unsafe"
+)
+
+const prolog = `
+
+package main
+
+import (
+ "runtime"
+)
+
+type quad struct { x, y, z, w int }
+
+const (
+ cj = 100011
+ ci int = 100012
+ ci8 int8 = 115
+ ci16 int16 = 10016
+ ci32 int32 = 100013
+ ci64 int64 = 100014
+ ci64big int64 = 1<<31
+ ci64bigger int64 = 1<<32
+ chuge = 1<<100
+ cfgood = 2.0
+ cfbad = 2.1
+
+ cnj = -2
+ cni int = -3
+ cni8 int8 = -6
+ cni16 int16 = -7
+ cni32 int32 = -4
+ cni64 int64 = -5
+ cni64big int64 = -1<<31
+ cni64bigger int64 = -1<<32
+ cnhuge = -1<<100
+ cnfgood = -2.0
+ cnfbad = -2.1
+)
+
+var j int = 100020
+var i int = 100021
+var i8 int8 = 126
+var i16 int16 = 10025
+var i32 int32 = 100022
+var i64 int64 = 100023
+var i64big int64 = 1<<31
+var i64bigger int64 = 1<<32
+var huge uint64 = 1<<64 - 1
+var fgood float64 = 2.0
+var fbad float64 = 2.1
+
+var nj int = -10
+var ni int = -11
+var ni8 int8 = -14
+var ni16 int16 = -15
+var ni32 int32 = -12
+var ni64 int64 = -13
+var ni64big int64 = -1<<31
+var ni64bigger int64 = -1<<32
+var nhuge int64 = -1<<63
+var nfgood float64 = -2.0
+var nfbad float64 = -2.1
+
+var si []int = make([]int, 10)
+var ai [10]int
+var pai *[10]int = &ai
+
+var sq []quad = make([]quad, 10)
+var aq [10]quad
+var paq *[10]quad = &aq
+
+var sib []int = make([]int, 100000)
+var aib [100000]int
+var paib *[100000]int = &aib
+
+var sqb []quad = make([]quad, 100000)
+var aqb [100000]quad
+var paqb *[100000]quad = &aqb
+
+type T struct {
+ si []int
+ ai [10]int
+ pai *[10]int
+ sq []quad
+ aq [10]quad
+ paq *[10]quad
+
+ sib []int
+ aib [100000]int
+ paib *[100000]int
+ sqb []quad
+ aqb [100000]quad
+ paqb *[100000]quad
+}
+
+var t = T{si, ai, pai, sq, aq, paq, sib, aib, paib, sqb, aqb, paqb}
+
+var pt = &T{si, ai, pai, sq, aq, paq, sib, aib, paib, sqb, aqb, paqb}
+
+// test that f panics
+func test(f func(), s string) {
+ defer func() {
+ if err := recover(); err == nil {
+ _, file, line, _ := runtime.Caller(2)
+ bug()
+ print(file, ":", line, ": ", s, " did not panic\n")
+ } else if !contains(err.(error).Error(), "out of range") {
+ _, file, line, _ := runtime.Caller(2)
+ bug()
+ print(file, ":", line, ": ", s, " unexpected panic: ", err.(error).Error(), "\n")
+ }
+ }()
+ f()
+}
+
+func contains(x, y string) bool {
+ for i := 0; i+len(y) <= len(x); i++ {
+ if x[i:i+len(y)] == y {
+ return true
+ }
+ }
+ return false
+}
+
+
+var X interface{}
+func use(y interface{}) {
+ X = y
+}
+
+var didBug = false
+
+func bug() {
+ if !didBug {
+ didBug = true
+ println("BUG")
+ }
+}
+
+func main() {
+`
+
+// pass variable set in index[012].go
+// 0 - dynamic checks
+// 1 - static checks of invalid constants (cannot assign to types)
+// 2 - static checks of array bounds
+
+func testExpr(b *bufio.Writer, expr string) {
+ if pass == 0 {
+ fmt.Fprintf(b, "\ttest(func(){use(%s)}, %q)\n", expr, expr)
+ } else {
+ fmt.Fprintf(b, "\tuse(%s) // ERROR \"index|overflow|truncated|must be integer\"\n", expr)
+ }
+}
+
+func main() {
+ b := bufio.NewWriter(os.Stdout)
+
+ if pass == 0 {
+ fmt.Fprint(b, "// run\n\n")
+ } else {
+ fmt.Fprint(b, "// errorcheck\n\n")
+ }
+ fmt.Fprint(b, prolog)
+
+ var choices = [][]string{
+ // Direct value, fetch from struct, fetch from struct pointer.
+ // The last two cases get us to oindex_const_sudo in gsubr.c.
+ []string{"", "t.", "pt."},
+
+ // Array, pointer to array, slice.
+ []string{"a", "pa", "s"},
+
+ // Element is int, element is quad (struct).
+ // This controls whether we end up in gsubr.c (i) or cgen.c (q).
+ []string{"i", "q"},
+
+ // Small or big len.
+ []string{"", "b"},
+
+ // Variable or constant.
+ []string{"", "c"},
+
+ // Positive or negative.
+ []string{"", "n"},
+
+ // Size of index.
+ []string{"j", "i", "i8", "i16", "i32", "i64", "i64big", "i64bigger", "huge", "fgood", "fbad"},
+ }
+
+ forall(choices, func(x []string) {
+ p, a, e, big, c, n, i := x[0], x[1], x[2], x[3], x[4], x[5], x[6]
+
+ // Pass: dynamic=0, static=1, 2.
+ // Which cases should be caught statically?
+ // Only constants, obviously.
+ // Beyond that, must be one of these:
+ // indexing into array or pointer to array
+ // negative constant
+ // large constant
+ thisPass := 0
+ if c == "c" && (a == "a" || a == "pa" || n == "n" || i == "i64big" || i == "i64bigger" || i == "huge" || i == "fbad") {
+ if i == "huge" {
+ // Due to a detail of gc's internals,
+ // the huge constant errors happen in an
+ // earlier pass than the others and inhibits
+ // the next pass from running.
+ // So run it as a separate check.
+ thisPass = 1
+ } else if a == "s" && n == "" && (i == "i64big" || i == "i64bigger") && unsafe.Sizeof(int(0)) > 4 {
+ // If int is 64 bits, these huge
+ // numbers do fit in an int, so they
+ // are not rejected at compile time.
+ thisPass = 0
+ } else {
+ thisPass = 2
+ }
+ }
+
+ pae := p + a + e + big
+ cni := c + n + i
+
+ // If we're using the big-len data, positive int8 and int16 cannot overflow.
+ if big == "b" && n == "" && (i == "i8" || i == "i16") {
+ if pass == 0 {
+ fmt.Fprintf(b, "\tuse(%s[%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[0:%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[1:%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[%s:])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[%s:%s])\n", pae, cni, cni)
+ }
+ return
+ }
+
+ // Float variables cannot be used as indices.
+ if c == "" && (i == "fgood" || i == "fbad") {
+ return
+ }
+ // Integral float constant is ok.
+ if c == "c" && n == "" && i == "fgood" {
+ if pass == 0 {
+ fmt.Fprintf(b, "\tuse(%s[%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[0:%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[1:%s])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[%s:])\n", pae, cni)
+ fmt.Fprintf(b, "\tuse(%s[%s:%s])\n", pae, cni, cni)
+ }
+ return
+ }
+
+ // Only print the test case if it is appropriate for this pass.
+ if thisPass == pass {
+ // Index operation
+ testExpr(b, pae+"["+cni+"]")
+
+ // Slice operation.
+ // Low index 0 is a special case in ggen.c
+ // so test both 0 and 1.
+ testExpr(b, pae+"[0:"+cni+"]")
+ testExpr(b, pae+"[1:"+cni+"]")
+ testExpr(b, pae+"["+cni+":]")
+ testExpr(b, pae+"["+cni+":"+cni+"]")
+ }
+ })
+
+ fmt.Fprintln(b, "}")
+ b.Flush()
+}
+
+func forall(choices [][]string, f func([]string)) {
+ x := make([]string, len(choices))
+
+ var recurse func(d int)
+ recurse = func(d int) {
+ if d >= len(choices) {
+ f(x)
+ return
+ }
+ for _, x[d] = range choices[d] {
+ recurse(d + 1)
+ }
+ }
+ recurse(0)
+}
diff --git a/platform/dbops/binaries/go/go/test/index0.go b/platform/dbops/binaries/go/go/test/index0.go
new file mode 100644
index 0000000000000000000000000000000000000000..62f339277b935261122daf8b3c98f550913ccd6e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/index0.go
@@ -0,0 +1,12 @@
+// runoutput ./index.go
+
+// 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.
+
+// Generate test of index and slice bounds checks.
+// The output is compiled and run.
+
+package main
+
+const pass = 0
diff --git a/platform/dbops/binaries/go/go/test/index1.go b/platform/dbops/binaries/go/go/test/index1.go
new file mode 100644
index 0000000000000000000000000000000000000000..40efc54eff61e3990c84b25e9c3cf505b504f6ab
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/index1.go
@@ -0,0 +1,12 @@
+// errorcheckoutput ./index.go
+
+// 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.
+
+// Generate test of index and slice bounds checks.
+// The output is error checked.
+
+package main
+
+const pass = 1
diff --git a/platform/dbops/binaries/go/go/test/index2.go b/platform/dbops/binaries/go/go/test/index2.go
new file mode 100644
index 0000000000000000000000000000000000000000..2a210cc981883c293d5ffec9aea5f298d3301680
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/index2.go
@@ -0,0 +1,12 @@
+// errorcheckoutput ./index.go
+
+// 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.
+
+// Generate test of index and slice bounds checks.
+// The output is error checked.
+
+package main
+
+const pass = 2
diff --git a/platform/dbops/binaries/go/go/test/indirect.go b/platform/dbops/binaries/go/go/test/indirect.go
new file mode 100644
index 0000000000000000000000000000000000000000..bb20f3009bfdd010b6806c0e36ddb178d50062c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/indirect.go
@@ -0,0 +1,87 @@
+// run
+
+// 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.
+
+// Test various safe uses of indirection.
+
+package main
+
+var m0 map[string]int
+var m1 *map[string]int
+var m2 *map[string]int = &m0
+var m3 map[string]int = map[string]int{"a": 1}
+var m4 *map[string]int = &m3
+
+var s0 string
+var s1 *string
+var s2 *string = &s0
+var s3 string = "a"
+var s4 *string = &s3
+
+var a0 [10]int
+var a1 *[10]int
+var a2 *[10]int = &a0
+
+var b0 []int
+var b1 *[]int
+var b2 *[]int = &b0
+var b3 []int = []int{1, 2, 3}
+var b4 *[]int = &b3
+
+func crash() {
+ // these uses of nil pointers
+ // would crash but should type check
+ println("crash",
+ len(a1)+cap(a1))
+}
+
+func nocrash() {
+ // this is spaced funny so that
+ // the compiler will print a different
+ // line number for each len call if
+ // it decides there are type errors.
+ // it might also help in the traceback.
+ x :=
+ len(m0) +
+ len(m3)
+ if x != 1 {
+ println("wrong maplen")
+ panic("fail")
+ }
+
+ x =
+ len(s0) +
+ len(s3)
+ if x != 1 {
+ println("wrong stringlen")
+ panic("fail")
+ }
+
+ x =
+ len(a0) +
+ len(a2)
+ if x != 20 {
+ println("wrong arraylen")
+ panic("fail")
+ }
+
+ x =
+ len(b0) +
+ len(b3)
+ if x != 3 {
+ println("wrong slicelen")
+ panic("fail")
+ }
+
+ x =
+ cap(b0) +
+ cap(b3)
+ if x != 3 {
+ println("wrong slicecap")
+ panic("fail")
+ }
+}
+
+func main() { nocrash() }
diff --git a/platform/dbops/binaries/go/go/test/indirect1.go b/platform/dbops/binaries/go/go/test/indirect1.go
new file mode 100644
index 0000000000000000000000000000000000000000..51da4cc7c4586b82f0121318f6ec545f01591a2c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/indirect1.go
@@ -0,0 +1,72 @@
+// errorcheck
+
+// 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.
+
+// Verify that illegal uses of indirection are caught by the compiler.
+// Does not compile.
+
+package main
+
+var m0 map[string]int
+var m1 *map[string]int
+var m2 *map[string]int = &m0
+var m3 map[string]int = map[string]int{"a": 1}
+var m4 *map[string]int = &m3
+
+var s0 string
+var s1 *string
+var s2 *string = &s0
+var s3 string = "a"
+var s4 *string = &s3
+
+var a0 [10]int
+var a1 *[10]int
+var a2 *[10]int = &a0
+
+var b0 []int
+var b1 *[]int
+var b2 *[]int = &b0
+var b3 []int = []int{1, 2, 3}
+var b4 *[]int = &b3
+
+func f() {
+ // this is spaced funny so that
+ // the compiler will print a different
+ // line number for each len call when
+ // it decides there are type errors.
+ x :=
+ len(m0)+
+ len(m1)+ // ERROR "illegal|invalid|must be"
+ len(m2)+ // ERROR "illegal|invalid|must be"
+ len(m3)+
+ len(m4)+ // ERROR "illegal|invalid|must be"
+
+ len(s0)+
+ len(s1)+ // ERROR "illegal|invalid|must be"
+ len(s2)+ // ERROR "illegal|invalid|must be"
+ len(s3)+
+ len(s4)+ // ERROR "illegal|invalid|must be"
+
+ len(a0)+
+ len(a1)+
+ len(a2)+
+
+ cap(a0)+
+ cap(a1)+
+ cap(a2)+
+
+ len(b0)+
+ len(b1)+ // ERROR "illegal|invalid|must be"
+ len(b2)+ // ERROR "illegal|invalid|must be"
+ len(b3)+
+ len(b4)+ // ERROR "illegal|invalid|must be"
+
+ cap(b0)+
+ cap(b1)+ // ERROR "illegal|invalid|must be"
+ cap(b2)+ // ERROR "illegal|invalid|must be"
+ cap(b3)+
+ cap(b4) // ERROR "illegal|invalid|must be"
+ _ = x
+}
diff --git a/platform/dbops/binaries/go/go/test/init.go b/platform/dbops/binaries/go/go/test/init.go
new file mode 100644
index 0000000000000000000000000000000000000000..43bb3c6503e99294480a0bbbce847e47e0372bc6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/init.go
@@ -0,0 +1,19 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous use of init is detected.
+// Does not compile.
+
+package main
+
+func init() {
+}
+
+func main() {
+ init() // ERROR "undefined.*init"
+ runtime.init() // ERROR "undefined.*runtime\.init|reference to undefined name|undefined: runtime"
+ var _ = init // ERROR "undefined.*init"
+}
diff --git a/platform/dbops/binaries/go/go/test/init1.go b/platform/dbops/binaries/go/go/test/init1.go
new file mode 100644
index 0000000000000000000000000000000000000000..0803dced1c4c6b4f1b1b0e8aa500a3e0830ff383
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/init1.go
@@ -0,0 +1,53 @@
+// run
+
+// 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.
+
+// Test that goroutines and garbage collection run during init.
+
+package main
+
+import "runtime"
+
+var x []byte
+
+func init() {
+ c := make(chan int)
+ go send(c)
+ <-c
+
+ const N = 1000
+ const MB = 1 << 20
+ b := make([]byte, MB)
+ for i := range b {
+ b[i] = byte(i%10 + '0')
+ }
+ s := string(b)
+
+ memstats := new(runtime.MemStats)
+ runtime.ReadMemStats(memstats)
+ sys, numGC := memstats.Sys, memstats.NumGC
+
+ // Generate 1,000 MB of garbage, only retaining 1 MB total.
+ for i := 0; i < N; i++ {
+ x = []byte(s)
+ }
+
+ // Verify that the garbage collector ran by seeing if we
+ // allocated fewer than N*MB bytes from the system.
+ runtime.ReadMemStats(memstats)
+ sys1, numGC1 := memstats.Sys, memstats.NumGC
+ if sys1-sys >= N*MB || numGC1 == numGC {
+ println("allocated 1000 chunks of", MB, "and used ", sys1-sys, "memory")
+ println("numGC went", numGC, "to", numGC1)
+ panic("init1")
+ }
+}
+
+func send(c chan int) {
+ c <- 1
+}
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/initcomma.go b/platform/dbops/binaries/go/go/test/initcomma.go
new file mode 100644
index 0000000000000000000000000000000000000000..a54fce4280236a164459681347ee274902ddd039
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/initcomma.go
@@ -0,0 +1,81 @@
+// run
+
+// 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.
+
+// Test trailing commas. DO NOT gofmt THIS FILE.
+
+package main
+
+var a = []int{1, 2, }
+var b = [5]int{1, 2, 3, }
+var c = []int{1, }
+var d = [...]int{1, 2, 3, }
+
+func main() {
+ if len(a) != 2 {
+ println("len a", len(a))
+ panic("fail")
+ }
+ if len(b) != 5 {
+ println("len b", len(b))
+ panic("fail")
+ }
+ if len(c) != 1 {
+ println("len d", len(c))
+ panic("fail")
+ }
+ if len(d) != 3 {
+ println("len c", len(d))
+ panic("fail")
+ }
+
+ if a[0] != 1 {
+ println("a[0]", a[0])
+ panic("fail")
+ }
+ if a[1] != 2 {
+ println("a[1]", a[1])
+ panic("fail")
+ }
+
+ if b[0] != 1 {
+ println("b[0]", b[0])
+ panic("fail")
+ }
+ if b[1] != 2 {
+ println("b[1]", b[1])
+ panic("fail")
+ }
+ if b[2] != 3 {
+ println("b[2]", b[2])
+ panic("fail")
+ }
+ if b[3] != 0 {
+ println("b[3]", b[3])
+ panic("fail")
+ }
+ if b[4] != 0 {
+ println("b[4]", b[4])
+ panic("fail")
+ }
+
+ if c[0] != 1 {
+ println("c[0]", c[0])
+ panic("fail")
+ }
+
+ if d[0] != 1 {
+ println("d[0]", d[0])
+ panic("fail")
+ }
+ if d[1] != 2 {
+ println("d[1]", d[1])
+ panic("fail")
+ }
+ if d[2] != 3 {
+ println("d[2]", d[2])
+ panic("fail")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/initexp.go b/platform/dbops/binaries/go/go/test/initexp.go
new file mode 100644
index 0000000000000000000000000000000000000000..b4d4701aab7707ca56dbc9daf78eda76ce3d7044
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/initexp.go
@@ -0,0 +1,36 @@
+// errorcheck -t 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
+
+// The init cycle diagnosis used to take exponential time
+// to traverse the call graph paths. This test case takes
+// at least two minutes on a modern laptop with the bug
+// and runs in a fraction of a second without it.
+// 10 seconds (-t 10 above) should be plenty if the code is working.
+
+var x = f() + z() // ERROR "initialization cycle"
+
+func f() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func z() int { return x }
+
+func a1() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a2() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a3() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a4() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a5() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a6() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a7() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+func a8() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
+
+func b1() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b2() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b3() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b4() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b5() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b6() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b7() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
+func b8() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
diff --git a/platform/dbops/binaries/go/go/test/initialize.go b/platform/dbops/binaries/go/go/test/initialize.go
new file mode 100644
index 0000000000000000000000000000000000000000..bbf73d9464e96154baa8e7a3ef802b2b50b73ae1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/initialize.go
@@ -0,0 +1,105 @@
+// run
+
+// 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.
+
+// Test initialization of package-level variables.
+
+package main
+
+import (
+ "fmt"
+ "reflect"
+)
+
+type S struct {
+ A, B, C, X, Y, Z int
+}
+
+type T struct {
+ S
+}
+
+var a1 = S{0, 0, 0, 1, 2, 3}
+var b1 = S{X: 1, Z: 3, Y: 2}
+
+var a2 = S{0, 0, 0, 0, 0, 0}
+var b2 = S{}
+
+var a3 = T{S{1, 2, 3, 0, 0, 0}}
+var b3 = T{S: S{A: 1, B: 2, C: 3}}
+
+var a4 = &[16]byte{0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0}
+var b4 = &[16]byte{4: 1, 1, 1, 1, 12: 1, 1}
+
+var a5 = &[16]byte{1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0}
+var b5 = &[16]byte{1, 4: 1, 1, 1, 1, 12: 1, 1}
+
+var a6 = &[16]byte{1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0}
+var b6 = &[...]byte{1, 4: 1, 1, 1, 1, 12: 1, 1, 0, 0}
+
+func f7(ch chan int) [2]chan int { return [2]chan int{ch, ch} }
+
+var a7 = f7(make(chan int))
+
+func f8(m map[string]string) [2]map[string]string { return [2]map[string]string{m, m} }
+func m8(m [2]map[string]string) string {
+ m[0]["def"] = "ghi"
+ return m[1]["def"]
+}
+
+var a8 = f8(make(map[string]string))
+var a9 = f8(map[string]string{"abc": "def"})
+
+func f10(s *S) [2]*S { return [2]*S{s, s} }
+
+var a10 = f10(new(S))
+var a11 = f10(&S{X: 1})
+
+func f12(b []byte) [2][]byte { return [2][]byte{b, b} }
+
+var a12 = f12([]byte("hello"))
+var a13 = f12([]byte{1, 2, 3})
+var a14 = f12(make([]byte, 1))
+
+func f15(b []rune) [2][]rune { return [2][]rune{b, b} }
+
+var a15 = f15([]rune("hello"))
+var a16 = f15([]rune{1, 2, 3})
+
+type Same struct {
+ a, b interface{}
+}
+
+var same = []Same{
+ {a1, b1},
+ {a2, b2},
+ {a3, b3},
+ {a4, b4},
+ {a5, b5},
+ {a6, b6},
+ {a7[0] == a7[1], true},
+ {m8(a8) == "ghi", true},
+ {m8(a9) == "ghi", true},
+ {a10[0] == a10[1], true},
+ {a11[0] == a11[1], true},
+ {&a12[0][0] == &a12[1][0], true},
+ {&a13[0][0] == &a13[1][0], true},
+ {&a14[0][0] == &a14[1][0], true},
+ {&a15[0][0] == &a15[1][0], true},
+ {&a16[0][0] == &a16[1][0], true},
+}
+
+func main() {
+ ok := true
+ for i, s := range same {
+ if !reflect.DeepEqual(s.a, s.b) {
+ ok = false
+ fmt.Printf("#%d not same: %v and %v\n", i+1, s.a, s.b)
+ }
+ }
+ if !ok {
+ fmt.Println("BUG: test/initialize")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/initializerr.go b/platform/dbops/binaries/go/go/test/initializerr.go
new file mode 100644
index 0000000000000000000000000000000000000000..aae740da38ffe6838ddf5a85d318aec23a77e111
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/initializerr.go
@@ -0,0 +1,41 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous initialization expressions are caught by the compiler
+// Does not compile.
+
+package main
+
+type S struct {
+ A, B, C, X, Y, Z int
+}
+
+type T struct {
+ S
+}
+
+var x = 1
+var a1 = S{0, X: 1} // ERROR "mixture|undefined" "too few values"
+var a2 = S{Y: 3, Z: 2, Y: 3} // ERROR "duplicate"
+var a3 = T{S{}, 2, 3, 4, 5, 6} // ERROR "convert|too many"
+var a4 = [5]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // ERROR "index|too many"
+var a5 = []byte{x: 2} // ERROR "index"
+var a6 = []byte{1: 1, 2: 2, 1: 3} // ERROR "duplicate"
+
+var ok1 = S{} // should be ok
+var ok2 = T{S: ok1} // should be ok
+
+// These keys can be computed at compile time but they are
+// not constants as defined by the spec, so they do not trigger
+// compile-time errors about duplicate key values.
+// See issue 4555.
+
+type Key struct{ X, Y int }
+
+var _ = map[Key]string{
+ Key{1, 2}: "hello",
+ Key{1, 2}: "world",
+}
diff --git a/platform/dbops/binaries/go/go/test/initloop.go b/platform/dbops/binaries/go/go/test/initloop.go
new file mode 100644
index 0000000000000000000000000000000000000000..b1a8470b3a0b15b3824375f24b34509def075fbe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/initloop.go
@@ -0,0 +1,17 @@
+// errorcheck
+
+// 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.
+
+// Verify that initialization loops are caught
+// and that the errors print correctly.
+
+package main
+
+var (
+ x int = a
+ a int = b // ERROR "a refers to\n.*b refers to\n.*c refers to\n.*a|initialization loop"
+ b int = c
+ c int = a
+)
diff --git a/platform/dbops/binaries/go/go/test/inline.go b/platform/dbops/binaries/go/go/test/inline.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd14f25983355597230030735903f98b6a890268
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline.go
@@ -0,0 +1,427 @@
+// errorcheckwithauto -0 -m -d=inlfuncswithclosures=1
+
+//go:build !goexperiment.newinliner
+
+// 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.
+
+// Test, using compiler diagnostic flags, that inlining is working.
+// Compiles but does not run.
+
+package foo
+
+import (
+ "errors"
+ "runtime"
+ "unsafe"
+)
+
+func add2(p *byte, n uintptr) *byte { // ERROR "can inline add2" "leaking param: p to result"
+ return (*byte)(add1(unsafe.Pointer(p), n)) // ERROR "inlining call to add1"
+}
+
+func add1(p unsafe.Pointer, x uintptr) unsafe.Pointer { // ERROR "can inline add1" "leaking param: p to result"
+ return unsafe.Pointer(uintptr(p) + x)
+}
+
+func f(x *byte) *byte { // ERROR "can inline f" "leaking param: x to result"
+ return add2(x, 1) // ERROR "inlining call to add2" "inlining call to add1"
+}
+
+//go:noinline
+func g(x int) int {
+ return x + 1
+}
+
+func h(x int) int { // ERROR "can inline h"
+ return x + 2
+}
+
+func i(x int) int { // ERROR "can inline i"
+ const y = 2
+ return x + y
+}
+
+func j(x int) int { // ERROR "can inline j"
+ switch {
+ case x > 0:
+ return x + 2
+ default:
+ return x + 1
+ }
+}
+
+func f2() int { // ERROR "can inline f2"
+ tmp1 := h
+ tmp2 := tmp1
+ return tmp2(0) // ERROR "inlining call to h"
+}
+
+var abc = errors.New("abc") // ERROR "inlining call to errors.New"
+
+var somethingWrong error
+
+// local closures can be inlined
+func l(x, y int) (int, int, error) { // ERROR "can inline l"
+ e := func(err error) (int, int, error) { // ERROR "can inline l.func1" "func literal does not escape" "leaking param: err to result"
+ return 0, 0, err
+ }
+ if x == y {
+ e(somethingWrong) // ERROR "inlining call to l.func1"
+ } else {
+ f := e
+ f(nil) // ERROR "inlining call to l.func1"
+ }
+ return y, x, nil
+}
+
+// any re-assignment prevents closure inlining
+func m() int {
+ foo := func() int { return 1 } // ERROR "can inline m.func1" "func literal does not escape"
+ x := foo()
+ foo = func() int { return 2 } // ERROR "can inline m.func2" "func literal does not escape"
+ return x + foo()
+}
+
+// address taking prevents closure inlining
+func n() int {
+ foo := func() int { return 1 } // ERROR "can inline n.func1" "func literal does not escape"
+ bar := &foo
+ x := (*bar)() + foo()
+ return x
+}
+
+// make sure assignment inside closure is detected
+func o() int {
+ foo := func() int { return 1 } // ERROR "can inline o.func1" "func literal does not escape"
+ func(x int) { // ERROR "can inline o.func2"
+ if x > 10 {
+ foo = func() int { return 2 } // ERROR "can inline o.func2"
+ }
+ }(11) // ERROR "func literal does not escape" "inlining call to o.func2"
+ return foo()
+}
+
+func p() int { // ERROR "can inline p"
+ return func() int { return 42 }() // ERROR "can inline p.func1" "inlining call to p.func1"
+}
+
+func q(x int) int { // ERROR "can inline q"
+ foo := func() int { return x * 2 } // ERROR "can inline q.func1" "func literal does not escape"
+ return foo() // ERROR "inlining call to q.func1"
+}
+
+func r(z int) int {
+ foo := func(x int) int { // ERROR "can inline r.func1" "func literal does not escape"
+ return x + z
+ }
+ bar := func(x int) int { // ERROR "func literal does not escape" "can inline r.func2"
+ return x + func(y int) int { // ERROR "can inline r.func2.1" "can inline r.r.func2.func3"
+ return 2*y + x*z
+ }(x) // ERROR "inlining call to r.func2.1"
+ }
+ return foo(42) + bar(42) // ERROR "inlining call to r.func1" "inlining call to r.func2" "inlining call to r.r.func2.func3"
+}
+
+func s0(x int) int { // ERROR "can inline s0"
+ foo := func() { // ERROR "can inline s0.func1" "func literal does not escape"
+ x = x + 1
+ }
+ foo() // ERROR "inlining call to s0.func1"
+ return x
+}
+
+func s1(x int) int { // ERROR "can inline s1"
+ foo := func() int { // ERROR "can inline s1.func1" "func literal does not escape"
+ return x
+ }
+ x = x + 1
+ return foo() // ERROR "inlining call to s1.func1"
+}
+
+func switchBreak(x, y int) int { // ERROR "can inline switchBreak"
+ var n int
+ switch x {
+ case 0:
+ n = 1
+ Done:
+ switch y {
+ case 0:
+ n += 10
+ break Done
+ }
+ n = 2
+ }
+ return n
+}
+
+func switchType(x interface{}) int { // ERROR "can inline switchType" "x does not escape"
+ switch x.(type) {
+ case int:
+ return x.(int)
+ default:
+ return 0
+ }
+}
+
+// Test that switches on constant things, with constant cases, only cost anything for
+// the case that matches. See issue 50253.
+func switchConst1(p func(string)) { // ERROR "can inline switchConst" "p does not escape"
+ const c = 1
+ switch c {
+ case 0:
+ p("zero")
+ case 1:
+ p("one")
+ case 2:
+ p("two")
+ default:
+ p("other")
+ }
+}
+
+func switchConst2() string { // ERROR "can inline switchConst2"
+ switch runtime.GOOS {
+ case "linux":
+ return "Leenooks"
+ case "windows":
+ return "Windoze"
+ case "darwin":
+ return "MackBone"
+ case "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100":
+ return "Numbers"
+ default:
+ return "oh nose!"
+ }
+}
+func switchConst3() string { // ERROR "can inline switchConst3"
+ switch runtime.GOOS {
+ case "Linux":
+ panic("Linux")
+ case "Windows":
+ panic("Windows")
+ case "Darwin":
+ panic("Darwin")
+ case "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100":
+ panic("Numbers")
+ default:
+ return "oh nose!"
+ }
+}
+func switchConst4() { // ERROR "can inline switchConst4"
+ const intSize = 32 << (^uint(0) >> 63)
+ want := func() string { // ERROR "can inline switchConst4.func1"
+ switch intSize {
+ case 32:
+ return "32"
+ case 64:
+ return "64"
+ default:
+ panic("unreachable")
+ }
+ }() // ERROR "inlining call to switchConst4.func1"
+ _ = want
+}
+
+func inlineRangeIntoMe(data []int) { // ERROR "can inline inlineRangeIntoMe" "data does not escape"
+ rangeFunc(data, 12) // ERROR "inlining call to rangeFunc"
+}
+
+func rangeFunc(xs []int, b int) int { // ERROR "can inline rangeFunc" "xs does not escape"
+ for i, x := range xs {
+ if x == b {
+ return i
+ }
+ }
+ return -1
+}
+
+type T struct{}
+
+func (T) meth(int, int) {} // ERROR "can inline T.meth"
+
+func k() (T, int, int) { return T{}, 0, 0 } // ERROR "can inline k"
+
+func f3() { // ERROR "can inline f3"
+ T.meth(k()) // ERROR "inlining call to k" "inlining call to T.meth"
+ // ERRORAUTO "inlining call to T.meth"
+}
+
+func small1() { // ERROR "can inline small1"
+ runtime.GC()
+}
+func small2() int { // ERROR "can inline small2"
+ return runtime.GOMAXPROCS(0)
+}
+func small3(t T) { // ERROR "can inline small3"
+ t.meth2(3, 5)
+}
+func small4(t T) { // not inlineable - has 2 calls.
+ t.meth2(runtime.GOMAXPROCS(0), 5)
+}
+func (T) meth2(int, int) { // not inlineable - has 2 calls.
+ runtime.GC()
+ runtime.GC()
+}
+
+// Issue #29737 - make sure we can do inlining for a chain of recursive functions
+func ee() { // ERROR "can inline ee"
+ ff(100) // ERROR "inlining call to ff" "inlining call to gg" "inlining call to hh"
+}
+
+func ff(x int) { // ERROR "can inline ff"
+ if x < 0 {
+ return
+ }
+ gg(x - 1) // ERROR "inlining call to gg" "inlining call to hh"
+}
+func gg(x int) { // ERROR "can inline gg"
+ hh(x - 1) // ERROR "inlining call to hh" "inlining call to ff"
+}
+func hh(x int) { // ERROR "can inline hh"
+ ff(x - 1) // ERROR "inlining call to ff" "inlining call to gg"
+}
+
+// Issue #14768 - make sure we can inline for loops.
+func for1(fn func() bool) { // ERROR "can inline for1" "fn does not escape"
+ for {
+ if fn() {
+ break
+ } else {
+ continue
+ }
+ }
+}
+
+func for2(fn func() bool) { // ERROR "can inline for2" "fn does not escape"
+Loop:
+ for {
+ if fn() {
+ break Loop
+ } else {
+ continue Loop
+ }
+ }
+}
+
+// Issue #18493 - make sure we can do inlining of functions with a method value
+type T1 struct{}
+
+func (a T1) meth(val int) int { // ERROR "can inline T1.meth"
+ return val + 5
+}
+
+func getMeth(t1 T1) func(int) int { // ERROR "can inline getMeth"
+ return t1.meth // ERROR "t1.meth escapes to heap"
+ // ERRORAUTO "inlining call to T1.meth"
+}
+
+func ii() { // ERROR "can inline ii"
+ var t1 T1
+ f := getMeth(t1) // ERROR "inlining call to getMeth" "t1.meth does not escape"
+ _ = f(3)
+}
+
+// Issue #42194 - make sure that functions evaluated in
+// go and defer statements can be inlined.
+func gd1(int) {
+ defer gd1(gd2()) // ERROR "inlining call to gd2"
+ defer gd3()() // ERROR "inlining call to gd3"
+ go gd1(gd2()) // ERROR "inlining call to gd2"
+ go gd3()() // ERROR "inlining call to gd3"
+}
+
+func gd2() int { // ERROR "can inline gd2"
+ return 1
+}
+
+func gd3() func() { // ERROR "can inline gd3"
+ return ii
+}
+
+// Issue #42788 - ensure ODEREF OCONVNOP* OADDR is low cost.
+func EncodeQuad(d []uint32, x [6]float32) { // ERROR "can inline EncodeQuad" "d does not escape"
+ _ = d[:6]
+ d[0] = float32bits(x[0]) // ERROR "inlining call to float32bits"
+ d[1] = float32bits(x[1]) // ERROR "inlining call to float32bits"
+ d[2] = float32bits(x[2]) // ERROR "inlining call to float32bits"
+ d[3] = float32bits(x[3]) // ERROR "inlining call to float32bits"
+ d[4] = float32bits(x[4]) // ERROR "inlining call to float32bits"
+ d[5] = float32bits(x[5]) // ERROR "inlining call to float32bits"
+}
+
+// float32bits is a copy of math.Float32bits to ensure that
+// these tests pass with `-gcflags=-l`.
+func float32bits(f float32) uint32 { // ERROR "can inline float32bits"
+ return *(*uint32)(unsafe.Pointer(&f))
+}
+
+// Ensure OCONVNOP is zero cost.
+func Conv(v uint64) uint64 { // ERROR "can inline Conv"
+ return conv2(conv2(conv2(v))) // ERROR "inlining call to (conv1|conv2)"
+}
+func conv2(v uint64) uint64 { // ERROR "can inline conv2"
+ return conv1(conv1(conv1(conv1(v)))) // ERROR "inlining call to conv1"
+}
+func conv1(v uint64) uint64 { // ERROR "can inline conv1"
+ return uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(v)))))))))))
+}
+
+func select1(x, y chan bool) int { // ERROR "can inline select1" "x does not escape" "y does not escape"
+ select {
+ case <-x:
+ return 1
+ case <-y:
+ return 2
+ }
+}
+
+func select2(x, y chan bool) { // ERROR "can inline select2" "x does not escape" "y does not escape"
+loop: // test that labeled select can be inlined.
+ select {
+ case <-x:
+ break loop
+ case <-y:
+ }
+}
+
+func inlineSelect2(x, y chan bool) { // ERROR "can inline inlineSelect2" ERROR "x does not escape" "y does not escape"
+loop:
+ for i := 0; i < 5; i++ {
+ if i == 3 {
+ break loop
+ }
+ select2(x, y) // ERROR "inlining call to select2"
+ }
+}
+
+// Issue #62211: inlining a function with unreachable "return"
+// statements could trip up phi insertion.
+func issue62211(x bool) { // ERROR "can inline issue62211"
+ if issue62211F(x) { // ERROR "inlining call to issue62211F"
+ }
+ if issue62211G(x) { // ERROR "inlining call to issue62211G"
+ }
+
+ // Initial fix CL caused a "non-monotonic scope positions" failure
+ // on code like this.
+ if z := 0; false {
+ panic(z)
+ }
+}
+
+func issue62211F(x bool) bool { // ERROR "can inline issue62211F"
+ if x || true {
+ return true
+ }
+ return true
+}
+
+func issue62211G(x bool) bool { // ERROR "can inline issue62211G"
+ if x || true {
+ return true
+ } else {
+ return true
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_big.go b/platform/dbops/binaries/go/go/test/inline_big.go
new file mode 100644
index 0000000000000000000000000000000000000000..7dd1abdb6ae18b53a74659c66cf38318c13cd243
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_big.go
@@ -0,0 +1,1029 @@
+// errorcheck -0 -m=2
+
+// 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.
+
+// Test that we restrict inlining into very large functions.
+// See issue #26546.
+
+package foo
+
+func small(a []int) int { // ERROR "can inline small with cost .* as:.*" "a does not escape"
+ // Cost 16 body (need cost < 20).
+ // See cmd/compile/internal/gc/inl.go:inlineBigFunction*
+ return a[0] + a[1] + a[2] + a[3]
+}
+func medium(a []int) int { // ERROR "can inline medium with cost .* as:.*" "a does not escape"
+ // Cost 32 body (need cost > 20 and cost < 80).
+ // See cmd/compile/internal/gc/inl.go:inlineBigFunction*
+ return a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6] + a[7]
+}
+
+func f(a []int) int { // ERROR "cannot inline f:.*" "a does not escape" "function f considered 'big'"
+ // Add lots of nodes to f's body. We need >5000.
+ // See cmd/compile/internal/gc/inl.go:inlineBigFunction*
+ a[0] = 0
+ a[1] = 0
+ a[2] = 0
+ a[3] = 0
+ a[4] = 0
+ a[5] = 0
+ a[6] = 0
+ a[7] = 0
+ a[8] = 0
+ a[9] = 0
+ a[10] = 0
+ a[11] = 0
+ a[12] = 0
+ a[13] = 0
+ a[14] = 0
+ a[15] = 0
+ a[16] = 0
+ a[17] = 0
+ a[18] = 0
+ a[19] = 0
+ a[20] = 0
+ a[21] = 0
+ a[22] = 0
+ a[23] = 0
+ a[24] = 0
+ a[25] = 0
+ a[26] = 0
+ a[27] = 0
+ a[28] = 0
+ a[29] = 0
+ a[30] = 0
+ a[31] = 0
+ a[32] = 0
+ a[33] = 0
+ a[34] = 0
+ a[35] = 0
+ a[36] = 0
+ a[37] = 0
+ a[38] = 0
+ a[39] = 0
+ a[40] = 0
+ a[41] = 0
+ a[42] = 0
+ a[43] = 0
+ a[44] = 0
+ a[45] = 0
+ a[46] = 0
+ a[47] = 0
+ a[48] = 0
+ a[49] = 0
+ a[50] = 0
+ a[51] = 0
+ a[52] = 0
+ a[53] = 0
+ a[54] = 0
+ a[55] = 0
+ a[56] = 0
+ a[57] = 0
+ a[58] = 0
+ a[59] = 0
+ a[60] = 0
+ a[61] = 0
+ a[62] = 0
+ a[63] = 0
+ a[64] = 0
+ a[65] = 0
+ a[66] = 0
+ a[67] = 0
+ a[68] = 0
+ a[69] = 0
+ a[70] = 0
+ a[71] = 0
+ a[72] = 0
+ a[73] = 0
+ a[74] = 0
+ a[75] = 0
+ a[76] = 0
+ a[77] = 0
+ a[78] = 0
+ a[79] = 0
+ a[80] = 0
+ a[81] = 0
+ a[82] = 0
+ a[83] = 0
+ a[84] = 0
+ a[85] = 0
+ a[86] = 0
+ a[87] = 0
+ a[88] = 0
+ a[89] = 0
+ a[90] = 0
+ a[91] = 0
+ a[92] = 0
+ a[93] = 0
+ a[94] = 0
+ a[95] = 0
+ a[96] = 0
+ a[97] = 0
+ a[98] = 0
+ a[99] = 0
+ a[100] = 0
+ a[101] = 0
+ a[102] = 0
+ a[103] = 0
+ a[104] = 0
+ a[105] = 0
+ a[106] = 0
+ a[107] = 0
+ a[108] = 0
+ a[109] = 0
+ a[110] = 0
+ a[111] = 0
+ a[112] = 0
+ a[113] = 0
+ a[114] = 0
+ a[115] = 0
+ a[116] = 0
+ a[117] = 0
+ a[118] = 0
+ a[119] = 0
+ a[120] = 0
+ a[121] = 0
+ a[122] = 0
+ a[123] = 0
+ a[124] = 0
+ a[125] = 0
+ a[126] = 0
+ a[127] = 0
+ a[128] = 0
+ a[129] = 0
+ a[130] = 0
+ a[131] = 0
+ a[132] = 0
+ a[133] = 0
+ a[134] = 0
+ a[135] = 0
+ a[136] = 0
+ a[137] = 0
+ a[138] = 0
+ a[139] = 0
+ a[140] = 0
+ a[141] = 0
+ a[142] = 0
+ a[143] = 0
+ a[144] = 0
+ a[145] = 0
+ a[146] = 0
+ a[147] = 0
+ a[148] = 0
+ a[149] = 0
+ a[150] = 0
+ a[151] = 0
+ a[152] = 0
+ a[153] = 0
+ a[154] = 0
+ a[155] = 0
+ a[156] = 0
+ a[157] = 0
+ a[158] = 0
+ a[159] = 0
+ a[160] = 0
+ a[161] = 0
+ a[162] = 0
+ a[163] = 0
+ a[164] = 0
+ a[165] = 0
+ a[166] = 0
+ a[167] = 0
+ a[168] = 0
+ a[169] = 0
+ a[170] = 0
+ a[171] = 0
+ a[172] = 0
+ a[173] = 0
+ a[174] = 0
+ a[175] = 0
+ a[176] = 0
+ a[177] = 0
+ a[178] = 0
+ a[179] = 0
+ a[180] = 0
+ a[181] = 0
+ a[182] = 0
+ a[183] = 0
+ a[184] = 0
+ a[185] = 0
+ a[186] = 0
+ a[187] = 0
+ a[188] = 0
+ a[189] = 0
+ a[190] = 0
+ a[191] = 0
+ a[192] = 0
+ a[193] = 0
+ a[194] = 0
+ a[195] = 0
+ a[196] = 0
+ a[197] = 0
+ a[198] = 0
+ a[199] = 0
+ a[200] = 0
+ a[201] = 0
+ a[202] = 0
+ a[203] = 0
+ a[204] = 0
+ a[205] = 0
+ a[206] = 0
+ a[207] = 0
+ a[208] = 0
+ a[209] = 0
+ a[210] = 0
+ a[211] = 0
+ a[212] = 0
+ a[213] = 0
+ a[214] = 0
+ a[215] = 0
+ a[216] = 0
+ a[217] = 0
+ a[218] = 0
+ a[219] = 0
+ a[220] = 0
+ a[221] = 0
+ a[222] = 0
+ a[223] = 0
+ a[224] = 0
+ a[225] = 0
+ a[226] = 0
+ a[227] = 0
+ a[228] = 0
+ a[229] = 0
+ a[230] = 0
+ a[231] = 0
+ a[232] = 0
+ a[233] = 0
+ a[234] = 0
+ a[235] = 0
+ a[236] = 0
+ a[237] = 0
+ a[238] = 0
+ a[239] = 0
+ a[240] = 0
+ a[241] = 0
+ a[242] = 0
+ a[243] = 0
+ a[244] = 0
+ a[245] = 0
+ a[246] = 0
+ a[247] = 0
+ a[248] = 0
+ a[249] = 0
+ a[250] = 0
+ a[251] = 0
+ a[252] = 0
+ a[253] = 0
+ a[254] = 0
+ a[255] = 0
+ a[256] = 0
+ a[257] = 0
+ a[258] = 0
+ a[259] = 0
+ a[260] = 0
+ a[261] = 0
+ a[262] = 0
+ a[263] = 0
+ a[264] = 0
+ a[265] = 0
+ a[266] = 0
+ a[267] = 0
+ a[268] = 0
+ a[269] = 0
+ a[270] = 0
+ a[271] = 0
+ a[272] = 0
+ a[273] = 0
+ a[274] = 0
+ a[275] = 0
+ a[276] = 0
+ a[277] = 0
+ a[278] = 0
+ a[279] = 0
+ a[280] = 0
+ a[281] = 0
+ a[282] = 0
+ a[283] = 0
+ a[284] = 0
+ a[285] = 0
+ a[286] = 0
+ a[287] = 0
+ a[288] = 0
+ a[289] = 0
+ a[290] = 0
+ a[291] = 0
+ a[292] = 0
+ a[293] = 0
+ a[294] = 0
+ a[295] = 0
+ a[296] = 0
+ a[297] = 0
+ a[298] = 0
+ a[299] = 0
+ a[300] = 0
+ a[301] = 0
+ a[302] = 0
+ a[303] = 0
+ a[304] = 0
+ a[305] = 0
+ a[306] = 0
+ a[307] = 0
+ a[308] = 0
+ a[309] = 0
+ a[310] = 0
+ a[311] = 0
+ a[312] = 0
+ a[313] = 0
+ a[314] = 0
+ a[315] = 0
+ a[316] = 0
+ a[317] = 0
+ a[318] = 0
+ a[319] = 0
+ a[320] = 0
+ a[321] = 0
+ a[322] = 0
+ a[323] = 0
+ a[324] = 0
+ a[325] = 0
+ a[326] = 0
+ a[327] = 0
+ a[328] = 0
+ a[329] = 0
+ a[330] = 0
+ a[331] = 0
+ a[332] = 0
+ a[333] = 0
+ a[334] = 0
+ a[335] = 0
+ a[336] = 0
+ a[337] = 0
+ a[338] = 0
+ a[339] = 0
+ a[340] = 0
+ a[341] = 0
+ a[342] = 0
+ a[343] = 0
+ a[344] = 0
+ a[345] = 0
+ a[346] = 0
+ a[347] = 0
+ a[348] = 0
+ a[349] = 0
+ a[350] = 0
+ a[351] = 0
+ a[352] = 0
+ a[353] = 0
+ a[354] = 0
+ a[355] = 0
+ a[356] = 0
+ a[357] = 0
+ a[358] = 0
+ a[359] = 0
+ a[360] = 0
+ a[361] = 0
+ a[362] = 0
+ a[363] = 0
+ a[364] = 0
+ a[365] = 0
+ a[366] = 0
+ a[367] = 0
+ a[368] = 0
+ a[369] = 0
+ a[370] = 0
+ a[371] = 0
+ a[372] = 0
+ a[373] = 0
+ a[374] = 0
+ a[375] = 0
+ a[376] = 0
+ a[377] = 0
+ a[378] = 0
+ a[379] = 0
+ a[380] = 0
+ a[381] = 0
+ a[382] = 0
+ a[383] = 0
+ a[384] = 0
+ a[385] = 0
+ a[386] = 0
+ a[387] = 0
+ a[388] = 0
+ a[389] = 0
+ a[390] = 0
+ a[391] = 0
+ a[392] = 0
+ a[393] = 0
+ a[394] = 0
+ a[395] = 0
+ a[396] = 0
+ a[397] = 0
+ a[398] = 0
+ a[399] = 0
+ a[400] = 0
+ a[401] = 0
+ a[402] = 0
+ a[403] = 0
+ a[404] = 0
+ a[405] = 0
+ a[406] = 0
+ a[407] = 0
+ a[408] = 0
+ a[409] = 0
+ a[410] = 0
+ a[411] = 0
+ a[412] = 0
+ a[413] = 0
+ a[414] = 0
+ a[415] = 0
+ a[416] = 0
+ a[417] = 0
+ a[418] = 0
+ a[419] = 0
+ a[420] = 0
+ a[421] = 0
+ a[422] = 0
+ a[423] = 0
+ a[424] = 0
+ a[425] = 0
+ a[426] = 0
+ a[427] = 0
+ a[428] = 0
+ a[429] = 0
+ a[430] = 0
+ a[431] = 0
+ a[432] = 0
+ a[433] = 0
+ a[434] = 0
+ a[435] = 0
+ a[436] = 0
+ a[437] = 0
+ a[438] = 0
+ a[439] = 0
+ a[440] = 0
+ a[441] = 0
+ a[442] = 0
+ a[443] = 0
+ a[444] = 0
+ a[445] = 0
+ a[446] = 0
+ a[447] = 0
+ a[448] = 0
+ a[449] = 0
+ a[450] = 0
+ a[451] = 0
+ a[452] = 0
+ a[453] = 0
+ a[454] = 0
+ a[455] = 0
+ a[456] = 0
+ a[457] = 0
+ a[458] = 0
+ a[459] = 0
+ a[460] = 0
+ a[461] = 0
+ a[462] = 0
+ a[463] = 0
+ a[464] = 0
+ a[465] = 0
+ a[466] = 0
+ a[467] = 0
+ a[468] = 0
+ a[469] = 0
+ a[470] = 0
+ a[471] = 0
+ a[472] = 0
+ a[473] = 0
+ a[474] = 0
+ a[475] = 0
+ a[476] = 0
+ a[477] = 0
+ a[478] = 0
+ a[479] = 0
+ a[480] = 0
+ a[481] = 0
+ a[482] = 0
+ a[483] = 0
+ a[484] = 0
+ a[485] = 0
+ a[486] = 0
+ a[487] = 0
+ a[488] = 0
+ a[489] = 0
+ a[490] = 0
+ a[491] = 0
+ a[492] = 0
+ a[493] = 0
+ a[494] = 0
+ a[495] = 0
+ a[496] = 0
+ a[497] = 0
+ a[498] = 0
+ a[499] = 0
+ a[500] = 0
+ a[501] = 0
+ a[502] = 0
+ a[503] = 0
+ a[504] = 0
+ a[505] = 0
+ a[506] = 0
+ a[507] = 0
+ a[508] = 0
+ a[509] = 0
+ a[510] = 0
+ a[511] = 0
+ a[512] = 0
+ a[513] = 0
+ a[514] = 0
+ a[515] = 0
+ a[516] = 0
+ a[517] = 0
+ a[518] = 0
+ a[519] = 0
+ a[520] = 0
+ a[521] = 0
+ a[522] = 0
+ a[523] = 0
+ a[524] = 0
+ a[525] = 0
+ a[526] = 0
+ a[527] = 0
+ a[528] = 0
+ a[529] = 0
+ a[530] = 0
+ a[531] = 0
+ a[532] = 0
+ a[533] = 0
+ a[534] = 0
+ a[535] = 0
+ a[536] = 0
+ a[537] = 0
+ a[538] = 0
+ a[539] = 0
+ a[540] = 0
+ a[541] = 0
+ a[542] = 0
+ a[543] = 0
+ a[544] = 0
+ a[545] = 0
+ a[546] = 0
+ a[547] = 0
+ a[548] = 0
+ a[549] = 0
+ a[550] = 0
+ a[551] = 0
+ a[552] = 0
+ a[553] = 0
+ a[554] = 0
+ a[555] = 0
+ a[556] = 0
+ a[557] = 0
+ a[558] = 0
+ a[559] = 0
+ a[560] = 0
+ a[561] = 0
+ a[562] = 0
+ a[563] = 0
+ a[564] = 0
+ a[565] = 0
+ a[566] = 0
+ a[567] = 0
+ a[568] = 0
+ a[569] = 0
+ a[570] = 0
+ a[571] = 0
+ a[572] = 0
+ a[573] = 0
+ a[574] = 0
+ a[575] = 0
+ a[576] = 0
+ a[577] = 0
+ a[578] = 0
+ a[579] = 0
+ a[580] = 0
+ a[581] = 0
+ a[582] = 0
+ a[583] = 0
+ a[584] = 0
+ a[585] = 0
+ a[586] = 0
+ a[587] = 0
+ a[588] = 0
+ a[589] = 0
+ a[590] = 0
+ a[591] = 0
+ a[592] = 0
+ a[593] = 0
+ a[594] = 0
+ a[595] = 0
+ a[596] = 0
+ a[597] = 0
+ a[598] = 0
+ a[599] = 0
+ a[600] = 0
+ a[601] = 0
+ a[602] = 0
+ a[603] = 0
+ a[604] = 0
+ a[605] = 0
+ a[606] = 0
+ a[607] = 0
+ a[608] = 0
+ a[609] = 0
+ a[610] = 0
+ a[611] = 0
+ a[612] = 0
+ a[613] = 0
+ a[614] = 0
+ a[615] = 0
+ a[616] = 0
+ a[617] = 0
+ a[618] = 0
+ a[619] = 0
+ a[620] = 0
+ a[621] = 0
+ a[622] = 0
+ a[623] = 0
+ a[624] = 0
+ a[625] = 0
+ a[626] = 0
+ a[627] = 0
+ a[628] = 0
+ a[629] = 0
+ a[630] = 0
+ a[631] = 0
+ a[632] = 0
+ a[633] = 0
+ a[634] = 0
+ a[635] = 0
+ a[636] = 0
+ a[637] = 0
+ a[638] = 0
+ a[639] = 0
+ a[640] = 0
+ a[641] = 0
+ a[642] = 0
+ a[643] = 0
+ a[644] = 0
+ a[645] = 0
+ a[646] = 0
+ a[647] = 0
+ a[648] = 0
+ a[649] = 0
+ a[650] = 0
+ a[651] = 0
+ a[652] = 0
+ a[653] = 0
+ a[654] = 0
+ a[655] = 0
+ a[656] = 0
+ a[657] = 0
+ a[658] = 0
+ a[659] = 0
+ a[660] = 0
+ a[661] = 0
+ a[662] = 0
+ a[663] = 0
+ a[664] = 0
+ a[665] = 0
+ a[666] = 0
+ a[667] = 0
+ a[668] = 0
+ a[669] = 0
+ a[670] = 0
+ a[671] = 0
+ a[672] = 0
+ a[673] = 0
+ a[674] = 0
+ a[675] = 0
+ a[676] = 0
+ a[677] = 0
+ a[678] = 0
+ a[679] = 0
+ a[680] = 0
+ a[681] = 0
+ a[682] = 0
+ a[683] = 0
+ a[684] = 0
+ a[685] = 0
+ a[686] = 0
+ a[687] = 0
+ a[688] = 0
+ a[689] = 0
+ a[690] = 0
+ a[691] = 0
+ a[692] = 0
+ a[693] = 0
+ a[694] = 0
+ a[695] = 0
+ a[696] = 0
+ a[697] = 0
+ a[698] = 0
+ a[699] = 0
+ a[700] = 0
+ a[701] = 0
+ a[702] = 0
+ a[703] = 0
+ a[704] = 0
+ a[705] = 0
+ a[706] = 0
+ a[707] = 0
+ a[708] = 0
+ a[709] = 0
+ a[710] = 0
+ a[711] = 0
+ a[712] = 0
+ a[713] = 0
+ a[714] = 0
+ a[715] = 0
+ a[716] = 0
+ a[717] = 0
+ a[718] = 0
+ a[719] = 0
+ a[720] = 0
+ a[721] = 0
+ a[722] = 0
+ a[723] = 0
+ a[724] = 0
+ a[725] = 0
+ a[726] = 0
+ a[727] = 0
+ a[728] = 0
+ a[729] = 0
+ a[730] = 0
+ a[731] = 0
+ a[732] = 0
+ a[733] = 0
+ a[734] = 0
+ a[735] = 0
+ a[736] = 0
+ a[737] = 0
+ a[738] = 0
+ a[739] = 0
+ a[740] = 0
+ a[741] = 0
+ a[742] = 0
+ a[743] = 0
+ a[744] = 0
+ a[745] = 0
+ a[746] = 0
+ a[747] = 0
+ a[748] = 0
+ a[749] = 0
+ a[750] = 0
+ a[751] = 0
+ a[752] = 0
+ a[753] = 0
+ a[754] = 0
+ a[755] = 0
+ a[756] = 0
+ a[757] = 0
+ a[758] = 0
+ a[759] = 0
+ a[760] = 0
+ a[761] = 0
+ a[762] = 0
+ a[763] = 0
+ a[764] = 0
+ a[765] = 0
+ a[766] = 0
+ a[767] = 0
+ a[768] = 0
+ a[769] = 0
+ a[770] = 0
+ a[771] = 0
+ a[772] = 0
+ a[773] = 0
+ a[774] = 0
+ a[775] = 0
+ a[776] = 0
+ a[777] = 0
+ a[778] = 0
+ a[779] = 0
+ a[780] = 0
+ a[781] = 0
+ a[782] = 0
+ a[783] = 0
+ a[784] = 0
+ a[785] = 0
+ a[786] = 0
+ a[787] = 0
+ a[788] = 0
+ a[789] = 0
+ a[790] = 0
+ a[791] = 0
+ a[792] = 0
+ a[793] = 0
+ a[794] = 0
+ a[795] = 0
+ a[796] = 0
+ a[797] = 0
+ a[798] = 0
+ a[799] = 0
+ a[800] = 0
+ a[801] = 0
+ a[802] = 0
+ a[803] = 0
+ a[804] = 0
+ a[805] = 0
+ a[806] = 0
+ a[807] = 0
+ a[808] = 0
+ a[809] = 0
+ a[810] = 0
+ a[811] = 0
+ a[812] = 0
+ a[813] = 0
+ a[814] = 0
+ a[815] = 0
+ a[816] = 0
+ a[817] = 0
+ a[818] = 0
+ a[819] = 0
+ a[820] = 0
+ a[821] = 0
+ a[822] = 0
+ a[823] = 0
+ a[824] = 0
+ a[825] = 0
+ a[826] = 0
+ a[827] = 0
+ a[828] = 0
+ a[829] = 0
+ a[830] = 0
+ a[831] = 0
+ a[832] = 0
+ a[833] = 0
+ a[834] = 0
+ a[835] = 0
+ a[836] = 0
+ a[837] = 0
+ a[838] = 0
+ a[839] = 0
+ a[840] = 0
+ a[841] = 0
+ a[842] = 0
+ a[843] = 0
+ a[844] = 0
+ a[845] = 0
+ a[846] = 0
+ a[847] = 0
+ a[848] = 0
+ a[849] = 0
+ a[850] = 0
+ a[851] = 0
+ a[852] = 0
+ a[853] = 0
+ a[854] = 0
+ a[855] = 0
+ a[856] = 0
+ a[857] = 0
+ a[858] = 0
+ a[859] = 0
+ a[860] = 0
+ a[861] = 0
+ a[862] = 0
+ a[863] = 0
+ a[864] = 0
+ a[865] = 0
+ a[866] = 0
+ a[867] = 0
+ a[868] = 0
+ a[869] = 0
+ a[870] = 0
+ a[871] = 0
+ a[872] = 0
+ a[873] = 0
+ a[874] = 0
+ a[875] = 0
+ a[876] = 0
+ a[877] = 0
+ a[878] = 0
+ a[879] = 0
+ a[880] = 0
+ a[881] = 0
+ a[882] = 0
+ a[883] = 0
+ a[884] = 0
+ a[885] = 0
+ a[886] = 0
+ a[887] = 0
+ a[888] = 0
+ a[889] = 0
+ a[890] = 0
+ a[891] = 0
+ a[892] = 0
+ a[893] = 0
+ a[894] = 0
+ a[895] = 0
+ a[896] = 0
+ a[897] = 0
+ a[898] = 0
+ a[899] = 0
+ a[900] = 0
+ a[901] = 0
+ a[902] = 0
+ a[903] = 0
+ a[904] = 0
+ a[905] = 0
+ a[906] = 0
+ a[907] = 0
+ a[908] = 0
+ a[909] = 0
+ a[910] = 0
+ a[911] = 0
+ a[912] = 0
+ a[913] = 0
+ a[914] = 0
+ a[915] = 0
+ a[916] = 0
+ a[917] = 0
+ a[918] = 0
+ a[919] = 0
+ a[920] = 0
+ a[921] = 0
+ a[922] = 0
+ a[923] = 0
+ a[924] = 0
+ a[925] = 0
+ a[926] = 0
+ a[927] = 0
+ a[928] = 0
+ a[929] = 0
+ a[930] = 0
+ a[931] = 0
+ a[932] = 0
+ a[933] = 0
+ a[934] = 0
+ a[935] = 0
+ a[936] = 0
+ a[937] = 0
+ a[938] = 0
+ a[939] = 0
+ a[940] = 0
+ a[941] = 0
+ a[942] = 0
+ a[943] = 0
+ a[944] = 0
+ a[945] = 0
+ a[946] = 0
+ a[947] = 0
+ a[948] = 0
+ a[949] = 0
+ a[950] = 0
+ a[951] = 0
+ a[952] = 0
+ a[953] = 0
+ a[954] = 0
+ a[955] = 0
+ a[956] = 0
+ a[957] = 0
+ a[958] = 0
+ a[959] = 0
+ a[960] = 0
+ a[961] = 0
+ a[962] = 0
+ a[963] = 0
+ a[964] = 0
+ a[965] = 0
+ a[966] = 0
+ a[967] = 0
+ a[968] = 0
+ a[969] = 0
+ a[970] = 0
+ a[971] = 0
+ a[972] = 0
+ a[973] = 0
+ a[974] = 0
+ a[975] = 0
+ a[976] = 0
+ a[977] = 0
+ a[978] = 0
+ a[979] = 0
+ a[980] = 0
+ a[981] = 0
+ a[982] = 0
+ a[983] = 0
+ a[984] = 0
+ a[985] = 0
+ a[986] = 0
+ a[987] = 0
+ a[988] = 0
+ a[989] = 0
+ a[990] = 0
+ a[991] = 0
+ a[992] = 0
+ a[993] = 0
+ a[994] = 0
+ a[995] = 0
+ a[996] = 0
+ a[997] = 0
+ a[998] = 0
+ a[999] = 0
+ x := small(a) // ERROR "inlining call to small"
+ y := medium(a) // The crux of this test: medium is not inlined.
+ return x + y
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_caller.go b/platform/dbops/binaries/go/go/test/inline_caller.go
new file mode 100644
index 0000000000000000000000000000000000000000..daff145a9229fec989afeb146ca1bbf69d37df9b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_caller.go
@@ -0,0 +1,77 @@
+// run -gcflags -l=4
+
+// 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
+
+import (
+ "fmt"
+ "runtime"
+)
+
+type frame struct {
+ pc uintptr
+ file string
+ line int
+ ok bool
+}
+
+var (
+ skip int
+ globalFrame frame
+)
+
+func f() {
+ g() // line 27
+}
+
+func g() {
+ h() // line 31
+}
+
+func h() {
+ x := &globalFrame
+ x.pc, x.file, x.line, x.ok = runtime.Caller(skip) // line 36
+}
+
+//go:noinline
+func testCaller(skp int) frame {
+ skip = skp
+ f() // line 42
+ frame := globalFrame
+ if !frame.ok {
+ panic(fmt.Sprintf("skip=%d runtime.Caller failed", skp))
+ }
+ return frame
+}
+
+type wantFrame struct {
+ funcName string
+ line int
+}
+
+// -1 means don't care
+var expected = []wantFrame{
+ 0: {"main.h", 36},
+ 1: {"main.g", 31},
+ 2: {"main.f", 27},
+ 3: {"main.testCaller", 42},
+ 4: {"main.main", 68},
+ 5: {"runtime.main", -1},
+ 6: {"runtime.goexit", -1},
+}
+
+func main() {
+ for i := 0; i <= 6; i++ {
+ frame := testCaller(i) // line 68
+ fn := runtime.FuncForPC(frame.pc)
+ if expected[i].line >= 0 && frame.line != expected[i].line {
+ panic(fmt.Sprintf("skip=%d expected line %d, got line %d", i, expected[i].line, frame.line))
+ }
+ if fn.Name() != expected[i].funcName {
+ panic(fmt.Sprintf("skip=%d expected function %s, got %s", i, expected[i].funcName, fn.Name()))
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_callers.go b/platform/dbops/binaries/go/go/test/inline_callers.go
new file mode 100644
index 0000000000000000000000000000000000000000..ee7d6470728cb916c34f3c4e2f73cfa9a1edb31c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_callers.go
@@ -0,0 +1,95 @@
+// run -gcflags=-l=4
+
+// 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
+
+import (
+ "fmt"
+ "runtime"
+)
+
+var skip int
+var npcs int
+var pcs = make([]uintptr, 32)
+
+func f() {
+ g()
+}
+
+func g() {
+ h()
+}
+
+func h() {
+ npcs = runtime.Callers(skip, pcs)
+}
+
+func testCallers(skp int) (frames []string) {
+ skip = skp
+ f()
+ for i := 0; i < npcs; i++ {
+ fn := runtime.FuncForPC(pcs[i] - 1)
+ frames = append(frames, fn.Name())
+ if fn.Name() == "main.main" {
+ break
+ }
+ }
+ return
+}
+
+func testCallersFrames(skp int) (frames []string) {
+ skip = skp
+ f()
+ callers := pcs[:npcs]
+ ci := runtime.CallersFrames(callers)
+ for {
+ frame, more := ci.Next()
+ frames = append(frames, frame.Function)
+ if !more || frame.Function == "main.main" {
+ break
+ }
+ }
+ return
+}
+
+var expectedFrames [][]string = [][]string{
+ 0: {"runtime.Callers", "main.h", "main.g", "main.f", "main.testCallers", "main.main"},
+ 1: {"main.h", "main.g", "main.f", "main.testCallers", "main.main"},
+ 2: {"main.g", "main.f", "main.testCallers", "main.main"},
+ 3: {"main.f", "main.testCallers", "main.main"},
+ 4: {"main.testCallers", "main.main"},
+ 5: {"main.main"},
+}
+
+var allFrames = []string{"runtime.Callers", "main.h", "main.g", "main.f", "main.testCallersFrames", "main.main"}
+
+func same(xs, ys []string) bool {
+ if len(xs) != len(ys) {
+ return false
+ }
+ for i := range xs {
+ if xs[i] != ys[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func main() {
+ for i := 0; i <= 5; i++ {
+ frames := testCallers(i)
+ expected := expectedFrames[i]
+ if !same(frames, expected) {
+ fmt.Printf("testCallers(%d):\n got %v\n want %v\n", i, frames, expected)
+ }
+
+ frames = testCallersFrames(i)
+ expected = allFrames[i:]
+ if !same(frames, expected) {
+ fmt.Printf("testCallersFrames(%d):\n got %v\n want %v\n", i, frames, expected)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_endian.go b/platform/dbops/binaries/go/go/test/inline_endian.go
new file mode 100644
index 0000000000000000000000000000000000000000..fc94321de03b94beefb7440244f1484ac7170a1e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_endian.go
@@ -0,0 +1,35 @@
+// errorcheckwithauto -0 -m -d=inlfuncswithclosures=1
+
+//go:build (386 || amd64 || arm64 || ppc64le || s390x) && !gcflags_noopt
+
+// 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.
+
+// Similar to inline.go, but only for architectures that can merge loads.
+
+package foo
+
+import (
+ "encoding/binary"
+)
+
+// Ensure that simple encoding/binary functions are cheap enough
+// that functions using them can also be inlined (issue 42958).
+func endian(b []byte) uint64 { // ERROR "can inline endian" "b does not escape"
+ return binary.LittleEndian.Uint64(b) + binary.BigEndian.Uint64(b) // ERROR "inlining call to binary.littleEndian.Uint64" "inlining call to binary.bigEndian.Uint64"
+}
+
+func appendLittleEndian(b []byte) []byte { // ERROR "can inline appendLittleEndian" "leaking param: b to result ~r0 level=0"
+ b = binary.LittleEndian.AppendUint64(b, 64) // ERROR "inlining call to binary.littleEndian.AppendUint64"
+ b = binary.LittleEndian.AppendUint32(b, 32) // ERROR "inlining call to binary.littleEndian.AppendUint32"
+ b = binary.LittleEndian.AppendUint16(b, 16) // ERROR "inlining call to binary.littleEndian.AppendUint16"
+ return b
+}
+
+func appendBigEndian(b []byte) []byte { // ERROR "can inline appendBigEndian" "leaking param: b to result ~r0 level=0"
+ b = binary.BigEndian.AppendUint64(b, 64) // ERROR "inlining call to binary.bigEndian.AppendUint64"
+ b = binary.BigEndian.AppendUint32(b, 32) // ERROR "inlining call to binary.bigEndian.AppendUint32"
+ b = binary.BigEndian.AppendUint16(b, 16) // ERROR "inlining call to binary.bigEndian.AppendUint16"
+ return b
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_literal.go b/platform/dbops/binaries/go/go/test/inline_literal.go
new file mode 100644
index 0000000000000000000000000000000000000000..53c6c05b180145d5876da043576a0b738635a278
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_literal.go
@@ -0,0 +1,50 @@
+// run
+
+// 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
+
+import (
+ "log"
+ "reflect"
+ "runtime"
+)
+
+func hello() string {
+ return "Hello World" // line 16
+}
+
+func foo() string { // line 19
+ x := hello() // line 20
+ y := hello() // line 21
+ return x + y // line 22
+}
+
+func bar() string {
+ x := hello() // line 26
+ return x
+}
+
+// funcPC returns the PC for the func value f.
+func funcPC(f interface{}) uintptr {
+ return reflect.ValueOf(f).Pointer()
+}
+
+// Test for issue #15453. Previously, line 26 would appear in foo().
+func main() {
+ pc := funcPC(foo)
+ f := runtime.FuncForPC(pc)
+ for ; runtime.FuncForPC(pc) == f; pc++ {
+ file, line := f.FileLine(pc)
+ if line == 0 {
+ continue
+ }
+ // Line 16 can appear inside foo() because PC-line table has
+ // innermost line numbers after inlining.
+ if line != 16 && !(line >= 19 && line <= 22) {
+ log.Fatalf("unexpected line at PC=%d: %s:%d\n", pc, file, line)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_math_bits_rotate.go b/platform/dbops/binaries/go/go/test/inline_math_bits_rotate.go
new file mode 100644
index 0000000000000000000000000000000000000000..ad15d60e0807f04251d9b99c0e0d06f09959b429
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_math_bits_rotate.go
@@ -0,0 +1,29 @@
+// errorcheck -0 -m
+
+//go:build amd64
+
+// 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.
+
+// Test that inlining of math/bits.RotateLeft* treats those calls as intrinsics.
+
+package p
+
+import "math/bits"
+
+var (
+ x8 uint8
+ x16 uint16
+ x32 uint32
+ x64 uint64
+ x uint
+)
+
+func f() { // ERROR "can inline f"
+ x8 = bits.RotateLeft8(x8, 1)
+ x16 = bits.RotateLeft16(x16, 1)
+ x32 = bits.RotateLeft32(x32, 1)
+ x64 = bits.RotateLeft64(x64, 1)
+ x = bits.RotateLeft(x, 1)
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_sync.go b/platform/dbops/binaries/go/go/test/inline_sync.go
new file mode 100644
index 0000000000000000000000000000000000000000..eaa2176d5fdc3dfeaa8c67182533ce4a0bb7854b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_sync.go
@@ -0,0 +1,53 @@
+// errorcheck -0 -m
+
+//go:build !nacl && !386 && !wasm && !arm && !gcflags_noopt
+
+// 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.
+
+// Test, using compiler diagnostic flags, that inlining of functions
+// imported from the sync package is working.
+// Compiles but does not run.
+
+// FIXME: This test is disabled on architectures where atomic operations
+// are function calls rather than intrinsics, since this prevents inlining
+// of the sync fast paths. This test should be re-enabled once the problem
+// is solved.
+
+package foo
+
+import (
+ "sync"
+)
+
+var mutex *sync.Mutex
+
+func small5() { // ERROR "can inline small5"
+ // the Unlock fast path should be inlined
+ mutex.Unlock() // ERROR "inlining call to sync\.\(\*Mutex\)\.Unlock"
+}
+
+func small6() { // ERROR "can inline small6"
+ // the Lock fast path should be inlined
+ mutex.Lock() // ERROR "inlining call to sync\.\(\*Mutex\)\.Lock"
+}
+
+var once *sync.Once
+
+func small7() { // ERROR "can inline small7"
+ // the Do fast path should be inlined
+ once.Do(small5) // ERROR "inlining call to sync\.\(\*Once\)\.Do" "inlining call to atomic\.\(\*Uint32\)\.Load"
+}
+
+var rwmutex *sync.RWMutex
+
+func small8() { // ERROR "can inline small8"
+ // the RUnlock fast path should be inlined
+ rwmutex.RUnlock() // ERROR "inlining call to sync\.\(\*RWMutex\)\.RUnlock" "inlining call to atomic\.\(\*Int32\)\.Add"
+}
+
+func small9() { // ERROR "can inline small9"
+ // the RLock fast path should be inlined
+ rwmutex.RLock() // ERROR "inlining call to sync\.\(\*RWMutex\)\.RLock" "inlining call to atomic\.\(\*Int32\)\.Add"
+}
diff --git a/platform/dbops/binaries/go/go/test/inline_variadic.go b/platform/dbops/binaries/go/go/test/inline_variadic.go
new file mode 100644
index 0000000000000000000000000000000000000000..49483d77f79934b9f4011da0705daba3faeb2a7b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/inline_variadic.go
@@ -0,0 +1,19 @@
+// errorcheck -0 -m
+
+// 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 inlining of variadic functions.
+// See issue #18116.
+
+package foo
+
+func head(xs ...string) string { // ERROR "can inline head" "leaking param: xs to result"
+ return xs[0]
+}
+
+func f() string { // ERROR "can inline f"
+ x := head("hello", "world") // ERROR "inlining call to head" "\.\.\. argument does not escape"
+ return x
+}
diff --git a/platform/dbops/binaries/go/go/test/int_lit.go b/platform/dbops/binaries/go/go/test/int_lit.go
new file mode 100644
index 0000000000000000000000000000000000000000..78deaea13020557993bbec27e6547c67428bb418
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/int_lit.go
@@ -0,0 +1,26 @@
+// run
+
+// 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.
+
+// Test integer literal syntax.
+
+package main
+
+import "os"
+
+func main() {
+ s := 0 +
+ 123 +
+ 0123 +
+ 0000 +
+ 0x0 +
+ 0x123 +
+ 0X0 +
+ 0X123
+ if s != 788 {
+ print("s is ", s, "; should be 788\n")
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/intcvt.go b/platform/dbops/binaries/go/go/test/intcvt.go
new file mode 100644
index 0000000000000000000000000000000000000000..3920528a403bfad15b4f5faee8c63ceab3356846
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/intcvt.go
@@ -0,0 +1,181 @@
+// run
+
+// 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.
+
+// Test implicit and explicit conversions of constants.
+
+package main
+
+const (
+ ci8 = -1 << 7
+ ci16 = -1<<15 + 100
+ ci32 = -1<<31 + 100000
+ ci64 = -1<<63 + 10000000001
+
+ cu8 = 1<<8 - 1
+ cu16 = 1<<16 - 1234
+ cu32 = 1<<32 - 1234567
+ cu64 = 1<<64 - 1234567890123
+
+ cf32 = 1e8 + 0.5
+ cf64 = -1e8 + 0.5
+)
+
+var (
+ i8 int8 = ci8
+ i16 int16 = ci16
+ i32 int32 = ci32
+ i64 int64 = ci64
+
+ u8 uint8 = cu8
+ u16 uint16 = cu16
+ u32 uint32 = cu32
+ u64 uint64 = cu64
+
+ // f32 float32 = 1e8 + 0.5
+ // f64 float64 = -1e8 + 0.5
+)
+
+func chki8(i, v int8) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chki16(i, v int16) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chki32(i, v int32) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chki64(i, v int64) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chku8(i, v uint8) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chku16(i, v uint16) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chku32(i, v uint32) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+func chku64(i, v uint64) {
+ if i != v {
+ println(i, "!=", v)
+ panic("fail")
+ }
+}
+//func chkf32(f, v float32) { if f != v { println(f, "!=", v); panic("fail") } }
+//func chkf64(f, v float64) { if f != v { println(f, "!=", v); panic("fail") } }
+
+func main() {
+ chki8(int8(i8), ci8&0xff-1<<8)
+ chki8(int8(i16), ci16&0xff)
+ chki8(int8(i32), ci32&0xff-1<<8)
+ chki8(int8(i64), ci64&0xff)
+ chki8(int8(u8), cu8&0xff-1<<8)
+ chki8(int8(u16), cu16&0xff)
+ chki8(int8(u32), cu32&0xff)
+ chki8(int8(u64), cu64&0xff)
+ // chki8(int8(f32), 0)
+ // chki8(int8(f64), 0)
+
+ chki16(int16(i8), ci8&0xffff-1<<16)
+ chki16(int16(i16), ci16&0xffff-1<<16)
+ chki16(int16(i32), ci32&0xffff-1<<16)
+ chki16(int16(i64), ci64&0xffff-1<<16)
+ chki16(int16(u8), cu8&0xffff)
+ chki16(int16(u16), cu16&0xffff-1<<16)
+ chki16(int16(u32), cu32&0xffff)
+ chki16(int16(u64), cu64&0xffff-1<<16)
+ // chki16(int16(f32), 0)
+ // chki16(int16(f64), 0)
+
+ chki32(int32(i8), ci8&0xffffffff-1<<32)
+ chki32(int32(i16), ci16&0xffffffff-1<<32)
+ chki32(int32(i32), ci32&0xffffffff-1<<32)
+ chki32(int32(i64), ci64&0xffffffff)
+ chki32(int32(u8), cu8&0xffffffff)
+ chki32(int32(u16), cu16&0xffffffff)
+ chki32(int32(u32), cu32&0xffffffff-1<<32)
+ chki32(int32(u64), cu64&0xffffffff-1<<32)
+ // chki32(int32(f32), 0)
+ // chki32(int32(f64), 0)
+
+ chki64(int64(i8), ci8&0xffffffffffffffff-1<<64)
+ chki64(int64(i16), ci16&0xffffffffffffffff-1<<64)
+ chki64(int64(i32), ci32&0xffffffffffffffff-1<<64)
+ chki64(int64(i64), ci64&0xffffffffffffffff-1<<64)
+ chki64(int64(u8), cu8&0xffffffffffffffff)
+ chki64(int64(u16), cu16&0xffffffffffffffff)
+ chki64(int64(u32), cu32&0xffffffffffffffff)
+ chki64(int64(u64), cu64&0xffffffffffffffff-1<<64)
+ // chki64(int64(f32), 0)
+ // chki64(int64(f64), 0)
+
+
+ chku8(uint8(i8), ci8&0xff)
+ chku8(uint8(i16), ci16&0xff)
+ chku8(uint8(i32), ci32&0xff)
+ chku8(uint8(i64), ci64&0xff)
+ chku8(uint8(u8), cu8&0xff)
+ chku8(uint8(u16), cu16&0xff)
+ chku8(uint8(u32), cu32&0xff)
+ chku8(uint8(u64), cu64&0xff)
+ // chku8(uint8(f32), 0)
+ // chku8(uint8(f64), 0)
+
+ chku16(uint16(i8), ci8&0xffff)
+ chku16(uint16(i16), ci16&0xffff)
+ chku16(uint16(i32), ci32&0xffff)
+ chku16(uint16(i64), ci64&0xffff)
+ chku16(uint16(u8), cu8&0xffff)
+ chku16(uint16(u16), cu16&0xffff)
+ chku16(uint16(u32), cu32&0xffff)
+ chku16(uint16(u64), cu64&0xffff)
+ // chku16(uint16(f32), 0)
+ // chku16(uint16(f64), 0)
+
+ chku32(uint32(i8), ci8&0xffffffff)
+ chku32(uint32(i16), ci16&0xffffffff)
+ chku32(uint32(i32), ci32&0xffffffff)
+ chku32(uint32(i64), ci64&0xffffffff)
+ chku32(uint32(u8), cu8&0xffffffff)
+ chku32(uint32(u16), cu16&0xffffffff)
+ chku32(uint32(u32), cu32&0xffffffff)
+ chku32(uint32(u64), cu64&0xffffffff)
+ // chku32(uint32(f32), 0)
+ // chku32(uint32(f64), 0)
+
+ chku64(uint64(i8), ci8&0xffffffffffffffff)
+ chku64(uint64(i16), ci16&0xffffffffffffffff)
+ chku64(uint64(i32), ci32&0xffffffffffffffff)
+ chku64(uint64(i64), ci64&0xffffffffffffffff)
+ chku64(uint64(u8), cu8&0xffffffffffffffff)
+ chku64(uint64(u16), cu16&0xffffffffffffffff)
+ chku64(uint64(u32), cu32&0xffffffffffffffff)
+ chku64(uint64(u64), cu64&0xffffffffffffffff)
+ // chku64(uint64(f32), 0)
+ // chku64(uint64(f64), 0)
+}
diff --git a/platform/dbops/binaries/go/go/test/intrinsic.go b/platform/dbops/binaries/go/go/test/intrinsic.go
new file mode 100644
index 0000000000000000000000000000000000000000..702b6acaf86ccda1fb16aa30ca36c28f4d19ff6b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/intrinsic.go
@@ -0,0 +1,9 @@
+// errorcheckandrundir -0 -d=ssa/intrinsics/debug
+
+//go:build amd64 || arm64 || arm || s390x
+
+// 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 ignored
diff --git a/platform/dbops/binaries/go/go/test/intrinsic_atomic.go b/platform/dbops/binaries/go/go/test/intrinsic_atomic.go
new file mode 100644
index 0000000000000000000000000000000000000000..72038e676a7951cfcf4a3bdd363c512d984172ff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/intrinsic_atomic.go
@@ -0,0 +1,21 @@
+// errorcheck -0 -d=ssa/intrinsics/debug
+
+//go:build amd64 || arm64 || loong64 || mips || mipsle || mips64 || mips64le || ppc64 || ppc64le || riscv64 || s390x
+
+// 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 main
+
+import "sync/atomic"
+
+var x uint32
+
+func atomics() {
+ _ = atomic.LoadUint32(&x) // ERROR "intrinsic substitution for LoadUint32"
+ atomic.StoreUint32(&x, 1) // ERROR "intrinsic substitution for StoreUint32"
+ atomic.AddUint32(&x, 1) // ERROR "intrinsic substitution for AddUint32"
+ atomic.SwapUint32(&x, 1) // ERROR "intrinsic substitution for SwapUint32"
+ atomic.CompareAndSwapUint32(&x, 1, 2) // ERROR "intrinsic substitution for CompareAndSwapUint32"
+}
diff --git a/platform/dbops/binaries/go/go/test/iota.go b/platform/dbops/binaries/go/go/test/iota.go
new file mode 100644
index 0000000000000000000000000000000000000000..7187dbe335ea42f03ea44942782398b49d45027b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/iota.go
@@ -0,0 +1,122 @@
+// run
+
+// 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.
+
+// Test iota.
+
+package main
+
+func assert(cond bool, msg string) {
+ if !cond {
+ print("assertion fail: ", msg, "\n")
+ panic(1)
+ }
+}
+
+const (
+ x int = iota
+ y = iota
+ z = 1 << iota
+ f float32 = 2 * iota
+ g float32 = 4.5 * float32(iota)
+)
+
+const (
+ X = 0
+ Y
+ Z
+)
+
+const (
+ A = 1 << iota
+ B
+ C
+ D
+ E = iota * iota
+ F
+ G
+)
+
+const (
+ a = 1
+ b = iota << a
+ c = iota << b
+ d
+)
+
+const (
+ i = (a << iota) + (b * iota)
+ j
+ k
+ l
+)
+
+const (
+ m = iota == 0
+ n
+)
+
+const (
+ p = float32(iota)
+ q
+ r
+)
+
+const (
+ s = string(iota + 'a')
+ t
+)
+
+const (
+ abit, amask = 1 << iota, 1< 10:
+ if x == 11 {
+ break L3
+ }
+ if x == 12 {
+ continue L3 // ERROR "invalid continue label .*L3|continue is not in a loop$"
+ }
+ 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|continue is not in a loop$"
+ }
+ if x == 15 {
+ goto L4
+ }
+ }
+
+L5:
+ f2()
+ if x == 16 {
+ break L5 // ERROR "invalid break label .*L5"
+ }
+ if x == 17 {
+ continue L5 // ERROR "invalid continue label .*L5|continue is not in a loop$"
+ }
+ 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
+ }
+ }
+
+ continue // ERROR "continue is not in a loop$|continue statement not within for"
+ for {
+ continue on // ERROR "continue label not defined: on|invalid continue label .*on"
+ }
+
+ break // ERROR "break is not in a loop, switch, or select|break statement not within for or switch or select"
+ for {
+ break dance // ERROR "break label not defined: dance|invalid break label .*dance"
+ }
+
+ for {
+ switch x {
+ case 1:
+ continue
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/linkmain.go b/platform/dbops/binaries/go/go/test/linkmain.go
new file mode 100644
index 0000000000000000000000000000000000000000..18962a9848b46143698f0ff252837de37324565f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkmain.go
@@ -0,0 +1,12 @@
+//go:build ignore
+
+// 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.
+
+// For linkmain_run.go.
+
+package notmain
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/linkmain_run.go b/platform/dbops/binaries/go/go/test/linkmain_run.go
new file mode 100644
index 0000000000000000000000000000000000000000..55aa65267303daeca1f5df739a142a72f66b03b3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkmain_run.go
@@ -0,0 +1,84 @@
+// run
+
+//go:build !nacl && !js && !wasip1
+
+// 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.
+
+// Run the sinit test.
+
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+var tmpDir string
+
+func cleanup() {
+ os.RemoveAll(tmpDir)
+}
+
+func run(cmdline ...string) {
+ args := strings.Fields(strings.Join(cmdline, " "))
+ cmd := exec.Command(args[0], args[1:]...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ fmt.Printf("$ %s\n", cmdline)
+ fmt.Println(string(out))
+ fmt.Println(err)
+ cleanup()
+ os.Exit(1)
+ }
+}
+
+func runFail(cmdline ...string) {
+ args := strings.Fields(strings.Join(cmdline, " "))
+ cmd := exec.Command(args[0], args[1:]...)
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ fmt.Printf("$ %s\n", cmdline)
+ fmt.Println(string(out))
+ fmt.Println("SHOULD HAVE FAILED!")
+ cleanup()
+ os.Exit(1)
+ }
+}
+
+func main() {
+ var err error
+ tmpDir, err = ioutil.TempDir("", "")
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ tmp := func(name string) string {
+ return filepath.Join(tmpDir, name)
+ }
+
+ importcfg, err := exec.Command("go", "list", "-export", "-f", "{{if .Export}}packagefile {{.ImportPath}}={{.Export}}{{end}}", "std").Output()
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ os.WriteFile(tmp("importcfg"), importcfg, 0644)
+
+ // helloworld.go is package main
+ run("go tool compile -p=main -importcfg", tmp("importcfg"), "-o", tmp("linkmain.o"), "helloworld.go")
+ run("go tool compile -p=main -importcfg", tmp("importcfg"), " -pack -o", tmp("linkmain.a"), "helloworld.go")
+ run("go tool link -importcfg", tmp("importcfg"), "-o", tmp("linkmain.exe"), tmp("linkmain.o"))
+ run("go tool link -importcfg", tmp("importcfg"), "-o", tmp("linkmain.exe"), tmp("linkmain.a"))
+
+ // linkmain.go is not
+ run("go tool compile -importcfg", tmp("importcfg"), "-p=notmain -o", tmp("linkmain1.o"), "linkmain.go")
+ run("go tool compile -importcfg", tmp("importcfg"), "-p=notmain -pack -o", tmp("linkmain1.a"), "linkmain.go")
+ runFail("go tool link -importcfg", tmp("importcfg"), "-o", tmp("linkmain.exe"), tmp("linkmain1.o"))
+ runFail("go tool link -importcfg", tmp("importcfg"), "-o", tmp("linkmain.exe"), tmp("linkmain1.a"))
+ cleanup()
+}
diff --git a/platform/dbops/binaries/go/go/test/linkname.go b/platform/dbops/binaries/go/go/test/linkname.go
new file mode 100644
index 0000000000000000000000000000000000000000..c94a113c90f79b11df1e6da6fb70d4affe1c0050
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkname.go
@@ -0,0 +1,15 @@
+// errorcheckandrundir -0 -m -l=4
+
+// 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.
+
+// Tests that linknames are included in export data (issue 18167).
+package ignored
+
+/*
+Without CL 33911, this test would fail with the following error:
+
+main.main: relocation target linkname2.byteIndex not defined
+main.main: undefined: "linkname2.byteIndex"
+*/
diff --git a/platform/dbops/binaries/go/go/test/linkname3.go b/platform/dbops/binaries/go/go/test/linkname3.go
new file mode 100644
index 0000000000000000000000000000000000000000..df110cd064d151e4e7a2eee26fa842adda28436c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkname3.go
@@ -0,0 +1,25 @@
+// errorcheck
+
+// 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.
+
+// Tests that errors are reported for misuse of linkname.
+package p
+
+import _ "unsafe"
+
+type t int
+
+var x, y int
+
+//go:linkname x ok
+
+// ERROR "//go:linkname must refer to declared function or variable"
+// ERROR "//go:linkname must refer to declared function or variable"
+// ERROR "duplicate //go:linkname for x"
+
+//line linkname3.go:18
+//go:linkname nonexist nonexist
+//go:linkname t notvarfunc
+//go:linkname x duplicate
diff --git a/platform/dbops/binaries/go/go/test/linkobj.go b/platform/dbops/binaries/go/go/test/linkobj.go
new file mode 100644
index 0000000000000000000000000000000000000000..85570269eb5c5ee7e075e04838c5e309530be0e1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkobj.go
@@ -0,0 +1,164 @@
+// run
+
+//go:build !nacl && !js && gc && !wasip1
+
+// 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 the compiler -linkobj flag.
+
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+var pwd, tmpdir string
+
+func main() {
+ dir, err := ioutil.TempDir("", "go-test-linkobj-")
+ if err != nil {
+ log.Fatal(err)
+ }
+ pwd, err = os.Getwd()
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := os.Chdir(dir); err != nil {
+ os.RemoveAll(dir)
+ log.Fatal(err)
+ }
+ tmpdir = dir
+
+ writeFile("p1.go", `
+ package p1
+
+ func F() {
+ println("hello from p1")
+ }
+ `)
+ writeFile("p2.go", `
+ package p2
+
+ import "./p1"
+
+ func F() {
+ p1.F()
+ println("hello from p2")
+ }
+
+ func main() {}
+ `)
+ writeFile("p3.go", `
+ package main
+
+ import "./p2"
+
+ func main() {
+ p2.F()
+ println("hello from main")
+ }
+ `)
+
+ stdlibimportcfg, err := os.ReadFile(os.Getenv("STDLIB_IMPORTCFG"))
+ if err != nil {
+ fatalf("listing stdlib export files: %v", err)
+ }
+
+ // two rounds: once using normal objects, again using .a files (compile -pack).
+ for round := 0; round < 2; round++ {
+ pkg := "-pack=" + fmt.Sprint(round)
+
+ // The compiler expects the files being read to have the right suffix.
+ o := "o"
+ if round == 1 {
+ o = "a"
+ }
+
+ importcfg := string(stdlibimportcfg) + "\npackagefile p1=p1." + o + "\npackagefile p2=p2." + o
+ os.WriteFile("importcfg", []byte(importcfg), 0644)
+
+ // inlining is disabled to make sure that the link objects contain needed code.
+ run("go", "tool", "compile", "-p=p1", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p1."+o, "-linkobj", "p1.lo", "p1.go")
+ run("go", "tool", "compile", "-p=p2", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p2."+o, "-linkobj", "p2.lo", "p2.go")
+ run("go", "tool", "compile", "-p=main", pkg, "-D", ".", "-importcfg=importcfg", "-l", "-o", "p3."+o, "-linkobj", "p3.lo", "p3.go")
+
+ cp("p1."+o, "p1.oo")
+ cp("p2."+o, "p2.oo")
+ cp("p3."+o, "p3.oo")
+ cp("p1.lo", "p1."+o)
+ cp("p2.lo", "p2."+o)
+ cp("p3.lo", "p3."+o)
+ out := runFail("go", "tool", "link", "p2."+o)
+ if !strings.Contains(out, "not package main") {
+ fatalf("link p2.o failed but not for package main:\n%s", out)
+ }
+
+ run("go", "tool", "link", "-importcfg=importcfg", "-o", "a.out.exe", "p3."+o)
+ out = run("./a.out.exe")
+ if !strings.Contains(out, "hello from p1\nhello from p2\nhello from main\n") {
+ fatalf("running main, incorrect output:\n%s", out)
+ }
+
+ // ensure that mistaken future round can't use these
+ os.Remove("p1.o")
+ os.Remove("a.out.exe")
+ }
+
+ cleanup()
+}
+
+func run(args ...string) string {
+ out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
+ if err != nil {
+ fatalf("run %v: %s\n%s", args, err, out)
+ }
+ return string(out)
+}
+
+func runFail(args ...string) string {
+ out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
+ if err == nil {
+ fatalf("runFail %v: unexpected success!\n%s", args, err, out)
+ }
+ return string(out)
+}
+
+func cp(src, dst string) {
+ data, err := ioutil.ReadFile(src)
+ if err != nil {
+ fatalf("%v", err)
+ }
+ err = ioutil.WriteFile(dst, data, 0666)
+ if err != nil {
+ fatalf("%v", err)
+ }
+}
+
+func writeFile(name, data string) {
+ err := ioutil.WriteFile(name, []byte(data), 0666)
+ if err != nil {
+ fatalf("%v", err)
+ }
+}
+
+func cleanup() {
+ const debug = false
+ if debug {
+ println("TMPDIR:", tmpdir)
+ return
+ }
+ os.Chdir(pwd) // get out of tmpdir before removing it
+ os.RemoveAll(tmpdir)
+}
+
+func fatalf(format string, args ...interface{}) {
+ cleanup()
+ log.Fatalf(format, args...)
+}
diff --git a/platform/dbops/binaries/go/go/test/linkx.go b/platform/dbops/binaries/go/go/test/linkx.go
new file mode 100644
index 0000000000000000000000000000000000000000..4f85b241a96d586ffe646e9bd53d4a3bc4213e80
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkx.go
@@ -0,0 +1,38 @@
+// skip
+
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Test the -X facility of the gc linker (6l etc.).
+// This test is run by linkx_run.go.
+
+package main
+
+import "fmt"
+
+var tbd string
+var overwrite string = "dibs"
+
+var tbdcopy = tbd
+var overwritecopy = overwrite
+var arraycopy = [2]string{tbd, overwrite}
+
+var b bool
+var x int
+
+func main() {
+ fmt.Println(tbd)
+ fmt.Println(tbdcopy)
+ fmt.Println(arraycopy[0])
+
+ fmt.Println(overwrite)
+ fmt.Println(overwritecopy)
+ fmt.Println(arraycopy[1])
+
+ // Check non-string symbols are not overwritten.
+ // This also make them used.
+ if b || x != 0 {
+ panic("b or x overwritten")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/linkx_run.go b/platform/dbops/binaries/go/go/test/linkx_run.go
new file mode 100644
index 0000000000000000000000000000000000000000..15f7c9ab4f93451dad9100b2bdef1bd9b62a7b40
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/linkx_run.go
@@ -0,0 +1,71 @@
+// run
+
+//go:build !nacl && !js && !wasip1 && gc
+
+// 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.
+
+// Run the linkx test.
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+func main() {
+ // test(" ") // old deprecated & removed syntax
+ test("=") // new syntax
+}
+
+func test(sep string) {
+ // Successful run
+ cmd := exec.Command("go", "run", "-ldflags=-X main.tbd"+sep+"hello -X main.overwrite"+sep+"trumped -X main.nosuchsymbol"+sep+"neverseen", "linkx.go")
+ var out, errbuf bytes.Buffer
+ cmd.Stdout = &out
+ cmd.Stderr = &errbuf
+ err := cmd.Run()
+ if err != nil {
+ fmt.Println(errbuf.String())
+ fmt.Println(out.String())
+ fmt.Println(err)
+ os.Exit(1)
+ }
+
+ want := "hello\nhello\nhello\ntrumped\ntrumped\ntrumped\n"
+ got := out.String()
+ if got != want {
+ fmt.Printf("got %q want %q\n", got, want)
+ os.Exit(1)
+ }
+
+ // Issue 8810
+ cmd = exec.Command("go", "run", "-ldflags=-X main.tbd", "linkx.go")
+ _, err = cmd.CombinedOutput()
+ if err == nil {
+ fmt.Println("-X linker flag should not accept keys without values")
+ os.Exit(1)
+ }
+
+ // Issue 9621
+ cmd = exec.Command("go", "run", "-ldflags=-X main.b=false -X main.x=42", "linkx.go")
+ outx, err := cmd.CombinedOutput()
+ if err == nil {
+ fmt.Println("-X linker flag should not overwrite non-strings")
+ os.Exit(1)
+ }
+ outstr := string(outx)
+ if !strings.Contains(outstr, "main.b") {
+ fmt.Printf("-X linker flag did not diagnose overwrite of main.b:\n%s\n", outstr)
+ os.Exit(1)
+ }
+ if !strings.Contains(outstr, "main.x") {
+ fmt.Printf("-X linker flag did not diagnose overwrite of main.x:\n%s\n", outstr)
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/literal.go b/platform/dbops/binaries/go/go/test/literal.go
new file mode 100644
index 0000000000000000000000000000000000000000..c3d6bc123a6b0c9997ac8ee3816d1ed6640cef61
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/literal.go
@@ -0,0 +1,229 @@
+// run
+
+// 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.
+
+// Test literal syntax for basic types.
+
+package main
+
+var nbad int
+
+func assert(cond bool, msg string) {
+ if !cond {
+ if nbad == 0 {
+ print("BUG")
+ }
+ nbad++
+ print(" ", msg)
+ }
+}
+
+func equal(a, b float32) bool {
+ return a == b
+}
+
+func main() {
+ // bool
+ var t bool = true
+ var f bool = false
+ assert(t == !f, "bool")
+
+ // int8
+ var i00 int8 = 0
+ var i01 int8 = 1
+ var i02 int8 = -1
+ var i03 int8 = 127
+ var i04 int8 = -127
+ var i05 int8 = -128
+ var i06 int8 = +127
+ assert(i01 == i00+1, "i01")
+ assert(i02 == -i01, "i02")
+ assert(i03 == -i04, "i03")
+ assert(-(i05+1) == i06, "i05")
+
+ // int16
+ var i10 int16 = 0
+ var i11 int16 = 1
+ var i12 int16 = -1
+ var i13 int16 = 32767
+ var i14 int16 = -32767
+ var i15 int16 = -32768
+ var i16 int16 = +32767
+ assert(i11 == i10+1, "i11")
+ assert(i12 == -i11, "i12")
+ assert(i13 == -i14, "i13")
+ assert(-(i15+1) == i16, "i15")
+
+ // int32
+ var i20 int32 = 0
+ var i21 int32 = 1
+ var i22 int32 = -1
+ var i23 int32 = 2147483647
+ var i24 int32 = -2147483647
+ var i25 int32 = -2147483648
+ var i26 int32 = +2147483647
+ assert(i21 == i20+1, "i21")
+ assert(i22 == -i21, "i22")
+ assert(i23 == -i24, "i23")
+ assert(-(i25+1) == i26, "i25")
+ assert(i23 == (1<<31)-1, "i23 size")
+
+ // int64
+ var i30 int64 = 0
+ var i31 int64 = 1
+ var i32 int64 = -1
+ var i33 int64 = 9223372036854775807
+ var i34 int64 = -9223372036854775807
+ var i35 int64 = -9223372036854775808
+ var i36 int64 = +9223372036854775807
+ assert(i31 == i30+1, "i31")
+ assert(i32 == -i31, "i32")
+ assert(i33 == -i34, "i33")
+ assert(-(i35+1) == i36, "i35")
+ assert(i33 == (1<<63)-1, "i33 size")
+
+ // uint8
+ var u00 uint8 = 0
+ var u01 uint8 = 1
+ var u02 uint8 = 255
+ var u03 uint8 = +255
+ assert(u01 == u00+1, "u01")
+ assert(u02 == u03, "u02")
+ assert(u03 == (1<<8)-1, "u03 size")
+
+ // uint16
+ var u10 uint16 = 0
+ var u11 uint16 = 1
+ var u12 uint16 = 65535
+ var u13 uint16 = +65535
+ assert(u11 == u10+1, "u11")
+ assert(u12 == u13, "u12")
+
+ // uint32
+ var u20 uint32 = 0
+ var u21 uint32 = 1
+ var u22 uint32 = 4294967295
+ var u23 uint32 = +4294967295
+ assert(u21 == u20+1, "u21")
+ assert(u22 == u23, "u22")
+
+ // uint64
+ var u30 uint64 = 0
+ var u31 uint64 = 1
+ var u32 uint64 = 18446744073709551615
+ var u33 uint64 = +18446744073709551615
+ _, _, _, _ = u30, u31, u32, u33
+
+ // float
+ var f00 float32 = 3.14159
+ var f01 float32 = -3.14159
+ var f02 float32 = +3.14159
+ var f03 float32 = 0.0
+ var f04 float32 = .0
+ var f05 float32 = 0.
+ var f06 float32 = -0.0
+ var f07 float32 = 1e10
+ var f08 float32 = -1e10
+ var f09 float32 = 1e-10
+ var f10 float32 = 1e+10
+ var f11 float32 = 1.e-10
+ var f12 float32 = 1.e+10
+ var f13 float32 = .1e-10
+ var f14 float32 = .1e+10
+ var f15 float32 = 1.1e-10
+ var f16 float32 = 1.1e+10
+ assert(f01 == -f00, "f01")
+ assert(f02 == -f01, "f02")
+ assert(f03 == f04, "f03")
+ assert(f04 == f05, "f04")
+ assert(f05 == f06, "f05")
+ assert(f07 == -f08, "f07")
+ assert(equal(f09, 1/f10), "f09")
+ assert(f11 == f09, "f11")
+ assert(f12 == f10, "f12")
+ assert(equal(f13, f09/10.0), "f13")
+ assert(equal(f14, f12/10.0), "f14")
+ assert(equal(f15, f16/1e20), "f15")
+
+ // character
+ var c0 uint8 = 'a'
+ var c1 uint8 = 'ä'
+ var c2 uint8 = '\a'
+ var c3 uint8 = '\b'
+ var c4 uint8 = '\f'
+ var c5 uint8 = '\n'
+ var c6 uint8 = '\r'
+ var c7 uint8 = '\t'
+ var c8 uint8 = '\v'
+ // var c9 uint8 = '本' // correctly caught as error
+ var c9 uint16 = '本'
+ assert(c0 == 0x61, "c0")
+ assert(c1 == 0xe4, "c1")
+ assert(c2 == 0x07, "c2")
+ assert(c3 == 0x08, "c3")
+ assert(c4 == 0x0c, "c4")
+ assert(c5 == 0x0a, "c4")
+ assert(c6 == 0x0d, "c6")
+ assert(c7 == 0x09, "c7")
+ assert(c8 == 0x0b, "c8")
+ assert(c9 == 0x672c, "c9")
+
+ var c00 uint8 = '\000'
+ var c01 uint8 = '\007'
+ var c02 uint8 = '\177'
+ var c03 uint8 = '\377'
+ assert(c00 == 0, "c00")
+ assert(c01 == 7, "c01")
+ assert(c02 == 127, "c02")
+ assert(c03 == 255, "c03")
+
+ var cx0 uint8 = '\x00'
+ var cx1 uint8 = '\x0f'
+ var cx2 uint8 = '\xff'
+ assert(cx0 == 0, "cx0")
+ assert(cx1 == 15, "cx1")
+ assert(cx2 == 255, "cx2")
+
+ var cu0 uint16 = '\u1234'
+ var cu1 uint32 = '\U00101234'
+ assert(cu0 == 0x1234, "cu0")
+ assert(cu1 == 0x101234, "cu1")
+
+ // string
+ var s0 string = ""
+ var s1 string = "hellô"
+ assert(s1[0] == 'h', "s1-0")
+ assert(s1[4] == 0xc3, "s1-4")
+ assert(s1[5] == 0xb4, "s1-5")
+ var s2 string = "\a\b\f\n\r\t\v"
+ _, _ = s0, s2
+
+ var s00 string = "\000"
+ var s01 string = "\007"
+ var s02 string = "\377"
+ assert(s00[0] == 0, "s00")
+ assert(s01[0] == 7, "s01")
+ assert(s02[0] == 255, "s02")
+
+ var x00 string = "\x00"
+ var x01 string = "\x0f"
+ var x02 string = "\xff"
+ assert(x00[0] == 0, "x00")
+ assert(x01[0] == 15, "x01")
+ assert(x02[0] == 255, "x02")
+
+ // these are all the same string
+ var sj0 string = "日本語"
+ var sj1 string = "\u65e5\u672c\u8a9e"
+ var sj2 string = "\U000065e5\U0000672c\U00008a9e"
+ var sj3 string = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"
+ assert(sj0 == sj1, "sj1")
+ assert(sj0 == sj2, "sj2")
+ assert(sj0 == sj3, "sj3")
+
+ if nbad > 0 {
+ panic("literal failed")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/literal2.go b/platform/dbops/binaries/go/go/test/literal2.go
new file mode 100644
index 0000000000000000000000000000000000000000..f552e33adaffeb7254e2efb1b1ef6b6434fd38ff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/literal2.go
@@ -0,0 +1,90 @@
+// run
+
+// 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.
+
+// Test Go2 literal syntax for basic types.
+// Avoid running gofmt on this file to preserve the
+// test cases with upper-case prefixes (0B, 0O, 0X).
+
+package main
+
+import "fmt"
+
+func assert(cond bool) {
+ if !cond {
+ panic("assertion failed")
+ }
+}
+
+func equal(x, y interface{}) bool {
+ if x != y {
+ fmt.Printf("%g != %g\n", x, y)
+ return false
+ }
+ return true
+}
+
+func main() {
+ // 0-octals
+ assert(0_1 == 01)
+ assert(012 == 012)
+ assert(0_1_2 == 012)
+ assert(0_1_2i == complex(0, 12)) // decimal digits despite leading 0 for backward-compatibility
+ assert(00089i == complex(0, 89)) // decimal digits despite leading 0 for backward-compatibility
+
+ // decimals
+ assert(1_000_000 == 1000000)
+ assert(1_000i == complex(0, 1000))
+
+ // hexadecimals
+ assert(0x_1 == 0x1)
+ assert(0x1_2 == 0x12)
+ assert(0x_cafe_f00d == 0xcafef00d)
+ assert(0x_cafei == complex(0, 0xcafe))
+
+ // octals
+ assert(0o_1 == 01)
+ assert(0o12 == 012)
+ assert(0o_1_2 == 012)
+ assert(0o_1_2i == complex(0, 0o12))
+
+ // binaries
+ assert(0b_1 == 1)
+ assert(0b10 == 2)
+ assert(0b_1_0 == 2)
+ assert(0b_1_0i == complex(0, 2))
+
+ // decimal floats
+ assert(0. == 0.0)
+ assert(.0 == 0.0)
+ assert(1_0. == 10.0)
+ assert(.0_1 == 0.01)
+ assert(1_0.0_1 == 10.01)
+ assert(1_0.0_1i == complex(0, 10.01))
+
+ assert(0.e1_0 == 0.0e10)
+ assert(.0e1_0 == 0.0e10)
+ assert(1_0.e1_0 == 10.0e10)
+ assert(.0_1e1_0 == 0.01e10)
+ assert(1_0.0_1e1_0 == 10.01e10)
+ assert(1_0.0_1e1_0i == complex(0, 10.01e10))
+
+ // hexadecimal floats
+ assert(equal(0x1p-2, 0.25))
+ assert(equal(0x2.p10, 2048.0))
+ assert(equal(0x1.Fp+0, 1.9375))
+ assert(equal(0x.8p-0, 0.5))
+ assert(equal(0x1FFFp-16, 0.1249847412109375))
+ assert(equal(0x1.fffffffffffffp1023, 1.7976931348623157e308))
+ assert(equal(0x1.fffffffffffffp1023i, complex(0, 1.7976931348623157e308)))
+
+ assert(equal(0x_1p-2, 0.25))
+ assert(equal(0x2.p1_0, 2048.0))
+ assert(equal(0x1_0.Fp+0, 16.9375))
+ assert(equal(0x_0.8p-0, 0.5))
+ assert(equal(0x_1FF_Fp-16, 0.1249847412109375))
+ assert(equal(0x1.f_ffff_ffff_ffffp1_023, 1.7976931348623157e308))
+ assert(equal(0x1.f_ffff_ffff_ffffp1_023i, complex(0, 1.7976931348623157e308)))
+}
diff --git a/platform/dbops/binaries/go/go/test/live.go b/platform/dbops/binaries/go/go/test/live.go
new file mode 100644
index 0000000000000000000000000000000000000000..5658c8ba06763ec1568a5391c7047c3e609fbfbe
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/live.go
@@ -0,0 +1,725 @@
+// errorcheckwithauto -0 -l -live -wb=0 -d=ssa/insert_resched_checks/off
+
+//go:build !ppc64 && !ppc64le && !goexperiment.regabiargs
+
+// ppc64 needs a better tighten pass to make f18 pass
+// rescheduling checks need to be turned off because there are some live variables across the inserted check call
+//
+// For register ABI, liveness info changes slightly. See live_regabi.go.
+
+// 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.
+
+// liveness tests with inlining disabled.
+// see also live2.go.
+
+package main
+
+func printnl()
+
+//go:noescape
+func printpointer(**int)
+
+//go:noescape
+func printintpointer(*int)
+
+//go:noescape
+func printstringpointer(*string)
+
+//go:noescape
+func printstring(string)
+
+//go:noescape
+func printbytepointer(*byte)
+
+func printint(int)
+
+func f1() {
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+}
+
+func f2(b bool) {
+ if b {
+ printint(0) // nothing live here
+ return
+ }
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+}
+
+func f3(b1, b2 bool) {
+ // Here x and y are ambiguously live. In previous go versions they
+ // were marked as live throughout the function to avoid being
+ // poisoned in GODEBUG=gcdead=1 mode; this is now no longer the
+ // case.
+
+ printint(0)
+ if b1 == false {
+ printint(0)
+ return
+ }
+
+ if b2 {
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+ } else {
+ var y *int // ERROR "stack object y \*int$"
+ printpointer(&y) // ERROR "live at call to printpointer: y$"
+ printpointer(&y)
+ }
+ printint(0) // nothing is live here
+}
+
+// The old algorithm treated x as live on all code that
+// could flow to a return statement, so it included the
+// function entry and code above the declaration of x
+// but would not include an indirect use of x in an infinite loop.
+// Check that these cases are handled correctly.
+
+func f4(b1, b2 bool) { // x not live here
+ if b2 {
+ printint(0) // x not live here
+ return
+ }
+ var z **int
+ x := new(int) // ERROR "stack object x \*int$"
+ *x = 42
+ z = &x
+ printint(**z) // ERROR "live at call to printint: x$"
+ if b2 {
+ printint(1) // x not live here
+ return
+ }
+ for {
+ printint(**z) // ERROR "live at call to printint: x$"
+ }
+}
+
+func f5(b1 bool) {
+ var z **int
+ if b1 {
+ x := new(int) // ERROR "stack object x \*int$"
+ *x = 42
+ z = &x
+ } else {
+ y := new(int) // ERROR "stack object y \*int$"
+ *y = 54
+ z = &y
+ }
+ printint(**z) // nothing live here
+}
+
+// confusion about the _ result used to cause spurious "live at entry to f6: _".
+
+func f6() (_, y string) {
+ y = "hello"
+ return
+}
+
+// confusion about addressed results used to cause "live at entry to f7: x".
+
+func f7() (x string) { // ERROR "stack object x string"
+ _ = &x
+ x = "hello"
+ return
+}
+
+// ignoring block returns used to cause "live at entry to f8: x, y".
+
+func f8() (x, y string) {
+ return g8()
+}
+
+func g8() (string, string)
+
+// ignoring block assignments used to cause "live at entry to f9: x"
+// issue 7205
+
+var i9 interface{}
+
+func f9() bool {
+ g8()
+ x := i9
+ y := interface{}(g18()) // ERROR "live at call to convT: x.data$" "live at call to g18: x.data$" "stack object .autotmp_[0-9]+ \[2\]string$"
+ i9 = y // make y escape so the line above has to call convT
+ return x != y
+}
+
+// liveness formerly confused by UNDEF followed by RET,
+// leading to "live at entry to f10: ~r1" (unnamed result).
+
+func f10() string {
+ panic(1)
+}
+
+// liveness formerly confused by select, thinking runtime.selectgo
+// can return to next instruction; it always jumps elsewhere.
+// note that you have to use at least two cases in the select
+// to get a true select; smaller selects compile to optimized helper functions.
+
+var c chan *int
+var b bool
+
+// this used to have a spurious "live at entry to f11a: ~r0"
+func f11a() *int {
+ select { // ERROR "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ return nil
+ case <-c:
+ return nil
+ }
+}
+
+func f11b() *int {
+ p := new(int)
+ if b {
+ // At this point p is dead: the code here cannot
+ // get to the bottom of the function.
+ // This used to have a spurious "live at call to printint: p".
+ printint(1) // nothing live here!
+ select { // ERROR "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ return nil
+ case <-c:
+ return nil
+ }
+ }
+ println(*p)
+ return nil
+}
+
+var sink *int
+
+func f11c() *int {
+ p := new(int)
+ sink = p // prevent stack allocation, otherwise p is rematerializeable
+ if b {
+ // Unlike previous, the cases in this select fall through,
+ // so we can get to the println, so p is not dead.
+ printint(1) // ERROR "live at call to printint: p$"
+ select { // ERROR "live at call to selectgo: p$" "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ case <-c:
+ }
+ }
+ println(*p)
+ return nil
+}
+
+// similarly, select{} does not fall through.
+// this used to have a spurious "live at entry to f12: ~r0".
+
+func f12() *int {
+ if b {
+ select {}
+ } else {
+ return nil
+ }
+}
+
+// incorrectly placed VARDEF annotations can cause missing liveness annotations.
+// this used to be missing the fact that s is live during the call to g13 (because it is
+// needed for the call to h13).
+
+func f13() {
+ s := g14()
+ s = h13(s, g13(s)) // ERROR "live at call to g13: s.ptr$"
+}
+
+func g13(string) string
+func h13(string, string) string
+
+// more incorrectly placed VARDEF.
+
+func f14() {
+ x := g14() // ERROR "stack object x string$"
+ printstringpointer(&x)
+}
+
+func g14() string
+
+// Checking that various temporaries do not persist or cause
+// ambiguously live values that must be zeroed.
+// The exact temporary names are inconsequential but we are
+// trying to check that there is only one at any given site,
+// and also that none show up in "ambiguously live" messages.
+
+var m map[string]int
+var mi map[interface{}]int
+
+// str and iface are used to ensure that a temp is required for runtime calls below.
+func str() string
+func iface() interface{}
+
+func f16() {
+ if b {
+ delete(mi, iface()) // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ }
+ delete(mi, iface())
+ delete(mi, iface())
+}
+
+var m2s map[string]*byte
+var m2 map[[2]string]*byte
+var x2 [2]string
+var bp *byte
+
+func f17a(p *byte) { // ERROR "live at entry to f17a: p$"
+ if b {
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+ }
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+}
+
+func f17b(p *byte) { // ERROR "live at entry to f17b: p$"
+ // key temporary
+ if b {
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+ }
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+}
+
+func f17c() {
+ // key and value temporaries
+ if b {
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+ }
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+}
+
+func f17d() *byte
+
+func g18() [2]string
+
+func f18() {
+ // key temporary for mapaccess.
+ // temporary introduced by orderexpr.
+ var z *byte
+ if b {
+ z = m2[g18()] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z = m2[g18()]
+ z = m2[g18()]
+ printbytepointer(z)
+}
+
+var ch chan *byte
+
+// byteptr is used to ensure that a temp is required for runtime calls below.
+func byteptr() *byte
+
+func f19() {
+ // dest temporary for channel receive.
+ var z *byte
+
+ if b {
+ z = <-ch // ERROR "stack object .autotmp_[0-9]+ \*byte$"
+ }
+ z = <-ch
+ z = <-ch // ERROR "live at call to chanrecv1: .autotmp_[0-9]+$"
+ printbytepointer(z)
+}
+
+func f20() {
+ // src temporary for channel send
+ if b {
+ ch <- byteptr() // ERROR "stack object .autotmp_[0-9]+ \*byte$"
+ }
+ ch <- byteptr()
+ ch <- byteptr()
+}
+
+func f21() {
+ // key temporary for mapaccess using array literal key.
+ var z *byte
+ if b {
+ z = m2[[2]string{"x", "y"}] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z = m2[[2]string{"x", "y"}]
+ z = m2[[2]string{"x", "y"}]
+ printbytepointer(z)
+}
+
+func f23() {
+ // key temporary for two-result map access using array literal key.
+ var z *byte
+ var ok bool
+ if b {
+ z, ok = m2[[2]string{"x", "y"}] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z, ok = m2[[2]string{"x", "y"}]
+ z, ok = m2[[2]string{"x", "y"}]
+ printbytepointer(z)
+ print(ok)
+}
+
+func f24() {
+ // key temporary for map access using array literal key.
+ // value temporary too.
+ if b {
+ m2[[2]string{"x", "y"}] = nil // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ m2[[2]string{"x", "y"}] = nil
+ m2[[2]string{"x", "y"}] = nil
+}
+
+// Non-open-coded defers should not cause autotmps. (Open-coded defers do create extra autotmps).
+func f25(b bool) {
+ for i := 0; i < 2; i++ {
+ // Put in loop to make sure defer is not open-coded
+ defer g25()
+ }
+ if b {
+ return
+ }
+ var x string
+ x = g14()
+ printstring(x)
+ return
+}
+
+func g25()
+
+// non-escaping ... slices passed to function call should die on return,
+// so that the temporaries do not stack and do not cause ambiguously
+// live variables.
+
+func f26(b bool) {
+ if b {
+ print26((*int)(nil), (*int)(nil), (*int)(nil)) // ERROR "stack object .autotmp_[0-9]+ \[3\]interface \{\}$"
+ }
+ print26((*int)(nil), (*int)(nil), (*int)(nil))
+ print26((*int)(nil), (*int)(nil), (*int)(nil))
+ printnl()
+}
+
+//go:noescape
+func print26(...interface{})
+
+// non-escaping closures passed to function call should die on return
+
+func f27(b bool) {
+ x := 0
+ if b {
+ call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ call27(func() { x++ })
+ call27(func() { x++ })
+ printnl()
+}
+
+// but defer does escape to later execution in the function
+
+func f27defer(b bool) {
+ x := 0
+ if b {
+ defer call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ defer call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+ .autotmp_[0-9]+"
+ return // ERROR "live at indirect call: .autotmp_[0-9]+"
+}
+
+// and newproc (go) escapes to the heap
+
+func f27go(b bool) {
+ x := 0
+ if b {
+ go call27(func() { x++ }) // ERROR "live at call to newobject: &x$" "live at call to newobject: &x .autotmp_[0-9]+$" "live at call to newproc: &x$" // allocate two closures, the func literal, and the wrapper for go
+ }
+ go call27(func() { x++ }) // ERROR "live at call to newobject: &x$" "live at call to newobject: .autotmp_[0-9]+$" // allocate two closures, the func literal, and the wrapper for go
+ printnl()
+}
+
+//go:noescape
+func call27(func())
+
+// concatstring slice should die on return
+
+var s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 string
+
+func f28(b bool) {
+ if b {
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10) // ERROR "stack object .autotmp_[0-9]+ \[10\]string$"
+ }
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10)
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10)
+}
+
+// map iterator should die on end of range loop
+
+func f29(b bool) {
+ if b {
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$" "stack object .autotmp_[0-9]+ runtime.hiter$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+ }
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+}
+
+// copy of array of pointers should die at end of range loop
+var pstructarr [10]pstruct
+
+// Struct size chosen to make pointer to element in pstructarr
+// not computable by strength reduction.
+type pstruct struct {
+ intp *int
+ _ [8]byte
+}
+
+func f30(b bool) {
+ // live temp during printintpointer(p):
+ // the internal iterator pointer if a pointer to pstruct in pstructarr
+ // can not be easily computed by strength reduction.
+ if b {
+ for _, p := range pstructarr { // ERROR "stack object .autotmp_[0-9]+ \[10\]pstruct$"
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+ }
+ for _, p := range pstructarr {
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+ for _, p := range pstructarr {
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+}
+
+// conversion to interface should not leave temporary behind
+
+func f31(b1, b2, b3 bool) {
+ if b1 {
+ g31(g18()) // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ if b2 {
+ h31(g18()) // ERROR "live at call to convT: .autotmp_[0-9]+$" "live at call to newobject: .autotmp_[0-9]+$"
+ }
+ if b3 {
+ panic(g18())
+ }
+ print(b3)
+}
+
+func g31(interface{})
+func h31(...interface{})
+
+// non-escaping partial functions passed to function call should die on return
+
+type T32 int
+
+func (t *T32) Inc() { // ERROR "live at entry to \(\*T32\).Inc: t$"
+ *t++
+}
+
+var t32 T32
+
+func f32(b bool) {
+ if b {
+ call32(t32.Inc) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ call32(t32.Inc)
+ call32(t32.Inc)
+}
+
+//go:noescape
+func call32(func())
+
+// temporaries introduced during if conditions and && || expressions
+// should die once the condition has been acted upon.
+
+var m33 map[interface{}]int
+
+func f33() {
+ if m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ printnl()
+ return
+ } else {
+ printnl()
+ }
+ printnl()
+}
+
+func f34() {
+ if m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f35() {
+ if m33[byteptr()] == 0 && // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f36() {
+ if m33[byteptr()] == 0 || // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f37() {
+ if (m33[byteptr()] == 0 || // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0) && // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 {
+ printnl()
+ return
+ }
+ printnl()
+}
+
+// select temps should disappear in the case bodies
+
+var c38 chan string
+
+func fc38() chan string
+func fi38(int) *string
+func fb38() *bool
+
+func f38(b bool) {
+ // we don't care what temps are printed on the lines with output.
+ // we care that the println lines have no live variables
+ // and therefore no output.
+ if b {
+ select { // ERROR "live at call to selectgo:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ \[4\]runtime.scase$"
+ case <-fc38():
+ printnl()
+ case fc38() <- *fi38(1): // ERROR "live at call to fc38:( .autotmp_[0-9]+)+$" "live at call to fi38:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ string$"
+ printnl()
+ case *fi38(2) = <-fc38(): // ERROR "live at call to fc38:( .autotmp_[0-9]+)+$" "live at call to fi38:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ string$"
+ printnl()
+ case *fi38(3), *fb38() = <-fc38(): // ERROR "stack object .autotmp_[0-9]+ string$" "live at call to f[ibc]38:( .autotmp_[0-9]+)+$"
+ printnl()
+ }
+ printnl()
+ }
+ printnl()
+}
+
+// issue 8097: mishandling of x = x during return.
+
+func f39() (x []int) {
+ x = []int{1}
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+$"
+ return x
+}
+
+func f39a() (x []int) {
+ x = []int{1}
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+$"
+ return
+}
+
+func f39b() (x [10]*int) {
+ x = [10]*int{}
+ x[0] = new(int) // ERROR "live at call to newobject: x$"
+ printnl() // ERROR "live at call to printnl: x$"
+ return x
+}
+
+func f39c() (x [10]*int) {
+ x = [10]*int{}
+ x[0] = new(int) // ERROR "live at call to newobject: x$"
+ printnl() // ERROR "live at call to printnl: x$"
+ return
+}
+
+// issue 8142: lost 'addrtaken' bit on inlined variables.
+// no inlining in this test, so just checking that non-inlined works.
+
+type T40 struct {
+ m map[int]int
+}
+
+//go:noescape
+func useT40(*T40)
+
+func newT40() *T40 {
+ ret := T40{}
+ ret.m = make(map[int]int, 42) // ERROR "live at call to makemap: &ret$"
+ return &ret
+}
+
+func bad40() {
+ t := newT40()
+ _ = t
+ printnl()
+}
+
+func good40() {
+ ret := T40{} // ERROR "stack object ret T40$"
+ ret.m = make(map[int]int) // ERROR "live at call to rand32: .autotmp_[0-9]+$" "stack object .autotmp_[0-9]+ runtime.hmap$"
+ t := &ret
+ printnl() // ERROR "live at call to printnl: ret$"
+ // Note: ret is live at the printnl because the compiler moves &ret
+ // from before the printnl to after.
+ useT40(t)
+}
+
+func ddd1(x, y *int) { // ERROR "live at entry to ddd1: x y$"
+ ddd2(x, y) // ERROR "stack object .autotmp_[0-9]+ \[2\]\*int$"
+ printnl()
+ // Note: no .?autotmp live at printnl. See issue 16996.
+}
+func ddd2(a ...*int) { // ERROR "live at entry to ddd2: a$"
+ sink = a[0]
+}
+
+// issue 16016: autogenerated wrapper should have arguments live
+type T struct{}
+
+func (*T) Foo(ptr *int) {}
+
+type R struct{ *T }
+
+// issue 18860: output arguments must be live all the time if there is a defer.
+// In particular, at printint r must be live.
+func f41(p, q *int) (r *int) { // ERROR "live at entry to f41: p q$"
+ r = p
+ defer func() {
+ recover()
+ }()
+ printint(0) // ERROR "live at call to printint: .autotmp_[0-9]+ q r$"
+ r = q
+ return // ERROR "live at call to f41.func1: .autotmp_[0-9]+ r$"
+}
+
+func f42() {
+ var p, q, r int
+ f43([]*int{&p, &q, &r}) // ERROR "stack object .autotmp_[0-9]+ \[3\]\*int$"
+ f43([]*int{&p, &r, &q})
+ f43([]*int{&q, &p, &r})
+}
+
+//go:noescape
+func f43(a []*int)
+
+// Assigning to a sub-element that makes up an entire local variable
+// should clobber that variable.
+func f44(f func() [2]*int) interface{} { // ERROR "live at entry to f44: f"
+ type T struct {
+ s [1][2]*int
+ }
+ ret := T{} // ERROR "stack object ret T"
+ ret.s[0] = f()
+ return ret
+}
diff --git a/platform/dbops/binaries/go/go/test/live1.go b/platform/dbops/binaries/go/go/test/live1.go
new file mode 100644
index 0000000000000000000000000000000000000000..87c8c97c41cb1897320819ebd3207e1902be1381
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/live1.go
@@ -0,0 +1,46 @@
+// compile
+
+// 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 code compiles without
+// "internal error: ... recorded as live on entry" errors
+// from the liveness code.
+//
+// This code contains methods or other construct that
+// trigger the generation of wrapper functions with no
+// clear line number (they end up using line 1), and those
+// would have annotations printed if we used -live=1,
+// like the live.go test does.
+// Instead, this test relies on the fact that the liveness
+// analysis turns any non-live parameter on entry into
+// a compile error. Compiling successfully means that bug
+// has been avoided.
+
+package main
+
+// The liveness analysis used to get confused by the tail return
+// instruction in the wrapper methods generated for T1.M and (*T1).M,
+// causing a spurious "live at entry: ~r1" for the return result.
+
+type T struct {
+}
+
+func (t *T) M() *int
+
+type T1 struct {
+ *T
+}
+
+// Liveness analysis used to have the VARDEFs in the wrong place,
+// causing a temporary to appear live on entry.
+
+func f1(pkg, typ, meth string) {
+ panic("value method " + pkg + "." + typ + "." + meth + " called using nil *" + typ + " pointer")
+}
+
+func f2() interface{} {
+ return new(int)
+}
+
diff --git a/platform/dbops/binaries/go/go/test/live2.go b/platform/dbops/binaries/go/go/test/live2.go
new file mode 100644
index 0000000000000000000000000000000000000000..2beac4f8d2bbe4e70711c209383dc198a47829d5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/live2.go
@@ -0,0 +1,41 @@
+// errorcheck -0 -live -wb=0
+
+// 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.
+
+// liveness tests with inlining ENABLED
+// see also live.go.
+
+package main
+
+// issue 8142: lost 'addrtaken' bit on inlined variables.
+
+func printnl()
+
+//go:noescape
+func useT40(*T40)
+
+type T40 struct {
+ m map[int]int
+}
+
+func newT40() *T40 {
+ ret := T40{}
+ ret.m = make(map[int]int, 42) // ERROR "live at call to makemap: &ret$"
+ return &ret
+}
+
+func bad40() {
+ t := newT40() // ERROR "stack object ret T40$" "stack object .autotmp_[0-9]+ runtime.hmap$"
+ printnl() // ERROR "live at call to printnl: ret$"
+ useT40(t)
+}
+
+func good40() {
+ ret := T40{} // ERROR "stack object ret T40$"
+ ret.m = make(map[int]int, 42) // ERROR "stack object .autotmp_[0-9]+ runtime.hmap$"
+ t := &ret
+ printnl() // ERROR "live at call to printnl: ret$"
+ useT40(t)
+}
diff --git a/platform/dbops/binaries/go/go/test/live_regabi.go b/platform/dbops/binaries/go/go/test/live_regabi.go
new file mode 100644
index 0000000000000000000000000000000000000000..a335126b3f558f1f700f4371f936a666be181338
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/live_regabi.go
@@ -0,0 +1,742 @@
+// errorcheckwithauto -0 -l -live -wb=0 -d=ssa/insert_resched_checks/off
+
+//go:build (amd64 && goexperiment.regabiargs) || (arm64 && goexperiment.regabiargs)
+
+// 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.
+
+// liveness tests with inlining disabled.
+// see also live2.go.
+
+package main
+
+import "runtime"
+
+func printnl()
+
+//go:noescape
+func printpointer(**int)
+
+//go:noescape
+func printintpointer(*int)
+
+//go:noescape
+func printstringpointer(*string)
+
+//go:noescape
+func printstring(string)
+
+//go:noescape
+func printbytepointer(*byte)
+
+func printint(int)
+
+func f1() {
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+}
+
+func f2(b bool) {
+ if b {
+ printint(0) // nothing live here
+ return
+ }
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+}
+
+func f3(b1, b2 bool) {
+ // Here x and y are ambiguously live. In previous go versions they
+ // were marked as live throughout the function to avoid being
+ // poisoned in GODEBUG=gcdead=1 mode; this is now no longer the
+ // case.
+
+ printint(0)
+ if b1 == false {
+ printint(0)
+ return
+ }
+
+ if b2 {
+ var x *int // ERROR "stack object x \*int$"
+ printpointer(&x) // ERROR "live at call to printpointer: x$"
+ printpointer(&x)
+ } else {
+ var y *int // ERROR "stack object y \*int$"
+ printpointer(&y) // ERROR "live at call to printpointer: y$"
+ printpointer(&y)
+ }
+ printint(0) // nothing is live here
+}
+
+// The old algorithm treated x as live on all code that
+// could flow to a return statement, so it included the
+// function entry and code above the declaration of x
+// but would not include an indirect use of x in an infinite loop.
+// Check that these cases are handled correctly.
+
+func f4(b1, b2 bool) { // x not live here
+ if b2 {
+ printint(0) // x not live here
+ return
+ }
+ var z **int
+ x := new(int) // ERROR "stack object x \*int$"
+ *x = 42
+ z = &x
+ printint(**z) // ERROR "live at call to printint: x$"
+ if b2 {
+ printint(1) // x not live here
+ return
+ }
+ for {
+ printint(**z) // ERROR "live at call to printint: x$"
+ }
+}
+
+func f5(b1 bool) {
+ var z **int
+ if b1 {
+ x := new(int) // ERROR "stack object x \*int$"
+ *x = 42
+ z = &x
+ } else {
+ y := new(int) // ERROR "stack object y \*int$"
+ *y = 54
+ z = &y
+ }
+ printint(**z) // nothing live here
+}
+
+// confusion about the _ result used to cause spurious "live at entry to f6: _".
+
+func f6() (_, y string) {
+ y = "hello"
+ return
+}
+
+// confusion about addressed results used to cause "live at entry to f7: x".
+
+func f7() (x string) { // ERROR "stack object x string"
+ _ = &x
+ x = "hello"
+ return
+}
+
+// ignoring block returns used to cause "live at entry to f8: x, y".
+
+func f8() (x, y string) {
+ return g8()
+}
+
+func g8() (string, string)
+
+// ignoring block assignments used to cause "live at entry to f9: x"
+// issue 7205
+
+var i9 interface{}
+
+func f9() bool {
+ g8()
+ x := i9
+ y := interface{}(g18()) // ERROR "live at call to convT: x.data$" "live at call to g18: x.data$" "stack object .autotmp_[0-9]+ \[2\]string$"
+ i9 = y // make y escape so the line above has to call convT
+ return x != y
+}
+
+// liveness formerly confused by UNDEF followed by RET,
+// leading to "live at entry to f10: ~r1" (unnamed result).
+
+func f10() string {
+ panic(1)
+}
+
+// liveness formerly confused by select, thinking runtime.selectgo
+// can return to next instruction; it always jumps elsewhere.
+// note that you have to use at least two cases in the select
+// to get a true select; smaller selects compile to optimized helper functions.
+
+var c chan *int
+var b bool
+
+// this used to have a spurious "live at entry to f11a: ~r0"
+func f11a() *int {
+ select { // ERROR "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ return nil
+ case <-c:
+ return nil
+ }
+}
+
+func f11b() *int {
+ p := new(int)
+ if b {
+ // At this point p is dead: the code here cannot
+ // get to the bottom of the function.
+ // This used to have a spurious "live at call to printint: p".
+ printint(1) // nothing live here!
+ select { // ERROR "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ return nil
+ case <-c:
+ return nil
+ }
+ }
+ println(*p)
+ return nil
+}
+
+var sink *int
+
+func f11c() *int {
+ p := new(int)
+ sink = p // prevent stack allocation, otherwise p is rematerializeable
+ if b {
+ // Unlike previous, the cases in this select fall through,
+ // so we can get to the println, so p is not dead.
+ printint(1) // ERROR "live at call to printint: p$"
+ select { // ERROR "live at call to selectgo: p$" "stack object .autotmp_[0-9]+ \[2\]runtime.scase$"
+ case <-c:
+ case <-c:
+ }
+ }
+ println(*p)
+ return nil
+}
+
+// similarly, select{} does not fall through.
+// this used to have a spurious "live at entry to f12: ~r0".
+
+func f12() *int {
+ if b {
+ select {}
+ } else {
+ return nil
+ }
+}
+
+// incorrectly placed VARDEF annotations can cause missing liveness annotations.
+// this used to be missing the fact that s is live during the call to g13 (because it is
+// needed for the call to h13).
+
+func f13() {
+ s := g14()
+ s = h13(s, g13(s)) // ERROR "live at call to g13: s.ptr$"
+}
+
+func g13(string) string
+func h13(string, string) string
+
+// more incorrectly placed VARDEF.
+
+func f14() {
+ x := g14() // ERROR "stack object x string$"
+ printstringpointer(&x)
+}
+
+func g14() string
+
+// Checking that various temporaries do not persist or cause
+// ambiguously live values that must be zeroed.
+// The exact temporary names are inconsequential but we are
+// trying to check that there is only one at any given site,
+// and also that none show up in "ambiguously live" messages.
+
+var m map[string]int
+var mi map[interface{}]int
+
+// str and iface are used to ensure that a temp is required for runtime calls below.
+func str() string
+func iface() interface{}
+
+func f16() {
+ if b {
+ delete(mi, iface()) // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ }
+ delete(mi, iface())
+ delete(mi, iface())
+}
+
+var m2s map[string]*byte
+var m2 map[[2]string]*byte
+var x2 [2]string
+var bp *byte
+
+func f17a(p *byte) { // ERROR "live at entry to f17a: p$"
+ if b {
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+ }
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+ m2[x2] = p // ERROR "live at call to mapassign: p$"
+}
+
+func f17b(p *byte) { // ERROR "live at entry to f17b: p$"
+ // key temporary
+ if b {
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+ }
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+ m2s[str()] = p // ERROR "live at call to mapassign_faststr: p$" "live at call to str: p$"
+}
+
+func f17c() {
+ // key and value temporaries
+ if b {
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+ }
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+ m2s[str()] = f17d() // ERROR "live at call to f17d: .autotmp_[0-9]+$" "live at call to mapassign_faststr: .autotmp_[0-9]+$"
+}
+
+func f17d() *byte
+
+func g18() [2]string
+
+func f18() {
+ // key temporary for mapaccess.
+ // temporary introduced by orderexpr.
+ var z *byte
+ if b {
+ z = m2[g18()] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z = m2[g18()]
+ z = m2[g18()]
+ printbytepointer(z)
+}
+
+var ch chan *byte
+
+// byteptr is used to ensure that a temp is required for runtime calls below.
+func byteptr() *byte
+
+func f19() {
+ // dest temporary for channel receive.
+ var z *byte
+
+ if b {
+ z = <-ch // ERROR "stack object .autotmp_[0-9]+ \*byte$"
+ }
+ z = <-ch
+ z = <-ch // ERROR "live at call to chanrecv1: .autotmp_[0-9]+$"
+ printbytepointer(z)
+}
+
+func f20() {
+ // src temporary for channel send
+ if b {
+ ch <- byteptr() // ERROR "stack object .autotmp_[0-9]+ \*byte$"
+ }
+ ch <- byteptr()
+ ch <- byteptr()
+}
+
+func f21() {
+ // key temporary for mapaccess using array literal key.
+ var z *byte
+ if b {
+ z = m2[[2]string{"x", "y"}] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z = m2[[2]string{"x", "y"}]
+ z = m2[[2]string{"x", "y"}]
+ printbytepointer(z)
+}
+
+func f23() {
+ // key temporary for two-result map access using array literal key.
+ var z *byte
+ var ok bool
+ if b {
+ z, ok = m2[[2]string{"x", "y"}] // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ z, ok = m2[[2]string{"x", "y"}]
+ z, ok = m2[[2]string{"x", "y"}]
+ printbytepointer(z)
+ print(ok)
+}
+
+func f24() {
+ // key temporary for map access using array literal key.
+ // value temporary too.
+ if b {
+ m2[[2]string{"x", "y"}] = nil // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ m2[[2]string{"x", "y"}] = nil
+ m2[[2]string{"x", "y"}] = nil
+}
+
+// Non-open-coded defers should not cause autotmps. (Open-coded defers do create extra autotmps).
+func f25(b bool) {
+ for i := 0; i < 2; i++ {
+ // Put in loop to make sure defer is not open-coded
+ defer g25()
+ }
+ if b {
+ return
+ }
+ var x string
+ x = g14()
+ printstring(x)
+ return
+}
+
+func g25()
+
+// non-escaping ... slices passed to function call should die on return,
+// so that the temporaries do not stack and do not cause ambiguously
+// live variables.
+
+func f26(b bool) {
+ if b {
+ print26((*int)(nil), (*int)(nil), (*int)(nil)) // ERROR "stack object .autotmp_[0-9]+ \[3\]interface \{\}$"
+ }
+ print26((*int)(nil), (*int)(nil), (*int)(nil))
+ print26((*int)(nil), (*int)(nil), (*int)(nil))
+ printnl()
+}
+
+//go:noescape
+func print26(...interface{})
+
+// non-escaping closures passed to function call should die on return
+
+func f27(b bool) {
+ x := 0
+ if b {
+ call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ call27(func() { x++ })
+ call27(func() { x++ })
+ printnl()
+}
+
+// but defer does escape to later execution in the function
+
+func f27defer(b bool) {
+ x := 0
+ if b {
+ defer call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ defer call27(func() { x++ }) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+ .autotmp_[0-9]+"
+ return // ERROR "live at indirect call: .autotmp_[0-9]+"
+}
+
+// and newproc (go) escapes to the heap
+
+func f27go(b bool) {
+ x := 0
+ if b {
+ go call27(func() { x++ }) // ERROR "live at call to newobject: &x$" "live at call to newobject: &x .autotmp_[0-9]+$" "live at call to newproc: &x$" // allocate two closures, the func literal, and the wrapper for go
+ }
+ go call27(func() { x++ }) // ERROR "live at call to newobject: &x$" "live at call to newobject: .autotmp_[0-9]+$" // allocate two closures, the func literal, and the wrapper for go
+ printnl()
+}
+
+//go:noescape
+func call27(func())
+
+// concatstring slice should die on return
+
+var s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 string
+
+func f28(b bool) {
+ if b {
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10) // ERROR "stack object .autotmp_[0-9]+ \[10\]string$"
+ }
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10)
+ printstring(s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10)
+}
+
+// map iterator should die on end of range loop
+
+func f29(b bool) {
+ if b {
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$" "stack object .autotmp_[0-9]+ runtime.hiter$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+ }
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+ for k := range m { // ERROR "live at call to mapiterinit: .autotmp_[0-9]+$" "live at call to mapiternext: .autotmp_[0-9]+$"
+ printstring(k) // ERROR "live at call to printstring: .autotmp_[0-9]+$"
+ }
+}
+
+// copy of array of pointers should die at end of range loop
+var pstructarr [10]pstruct
+
+// Struct size chosen to make pointer to element in pstructarr
+// not computable by strength reduction.
+type pstruct struct {
+ intp *int
+ _ [8]byte
+}
+
+func f30(b bool) {
+ // live temp during printintpointer(p):
+ // the internal iterator pointer if a pointer to pstruct in pstructarr
+ // can not be easily computed by strength reduction.
+ if b {
+ for _, p := range pstructarr { // ERROR "stack object .autotmp_[0-9]+ \[10\]pstruct$"
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+ }
+ for _, p := range pstructarr {
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+ for _, p := range pstructarr {
+ printintpointer(p.intp) // ERROR "live at call to printintpointer: .autotmp_[0-9]+$"
+ }
+}
+
+// conversion to interface should not leave temporary behind
+
+func f31(b1, b2, b3 bool) {
+ if b1 {
+ g31(g18()) // ERROR "stack object .autotmp_[0-9]+ \[2\]string$"
+ }
+ if b2 {
+ h31(g18()) // ERROR "live at call to convT: .autotmp_[0-9]+$" "live at call to newobject: .autotmp_[0-9]+$"
+ }
+ if b3 {
+ panic(g18())
+ }
+ print(b3)
+}
+
+func g31(interface{})
+func h31(...interface{})
+
+// non-escaping partial functions passed to function call should die on return
+
+type T32 int
+
+func (t *T32) Inc() { // ERROR "live at entry to \(\*T32\).Inc: t$"
+ *t++
+}
+
+var t32 T32
+
+func f32(b bool) {
+ if b {
+ call32(t32.Inc) // ERROR "stack object .autotmp_[0-9]+ struct \{"
+ }
+ call32(t32.Inc)
+ call32(t32.Inc)
+}
+
+//go:noescape
+func call32(func())
+
+// temporaries introduced during if conditions and && || expressions
+// should die once the condition has been acted upon.
+
+var m33 map[interface{}]int
+
+func f33() {
+ if m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ printnl()
+ return
+ } else {
+ printnl()
+ }
+ printnl()
+}
+
+func f34() {
+ if m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}$"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f35() {
+ if m33[byteptr()] == 0 && // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f36() {
+ if m33[byteptr()] == 0 || // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 { // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ printnl()
+ return
+ }
+ printnl()
+}
+
+func f37() {
+ if (m33[byteptr()] == 0 || // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0) && // ERROR "stack object .autotmp_[0-9]+ interface \{\}"
+ m33[byteptr()] == 0 {
+ printnl()
+ return
+ }
+ printnl()
+}
+
+// select temps should disappear in the case bodies
+
+var c38 chan string
+
+func fc38() chan string
+func fi38(int) *string
+func fb38() *bool
+
+func f38(b bool) {
+ // we don't care what temps are printed on the lines with output.
+ // we care that the println lines have no live variables
+ // and therefore no output.
+ if b {
+ select { // ERROR "live at call to selectgo:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ \[4\]runtime.scase$"
+ case <-fc38():
+ printnl()
+ case fc38() <- *fi38(1): // ERROR "live at call to fc38:( .autotmp_[0-9]+)+$" "live at call to fi38:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ string$"
+ printnl()
+ case *fi38(2) = <-fc38(): // ERROR "live at call to fc38:( .autotmp_[0-9]+)+$" "live at call to fi38:( .autotmp_[0-9]+)+$" "stack object .autotmp_[0-9]+ string$"
+ printnl()
+ case *fi38(3), *fb38() = <-fc38(): // ERROR "stack object .autotmp_[0-9]+ string$" "live at call to f[ibc]38:( .autotmp_[0-9]+)+$"
+ printnl()
+ }
+ printnl()
+ }
+ printnl()
+}
+
+// issue 8097: mishandling of x = x during return.
+
+func f39() (x []int) {
+ x = []int{1}
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+$"
+ return x
+}
+
+func f39a() (x []int) {
+ x = []int{1}
+ printnl() // ERROR "live at call to printnl: .autotmp_[0-9]+$"
+ return
+}
+
+func f39b() (x [10]*int) {
+ x = [10]*int{}
+ x[0] = new(int) // ERROR "live at call to newobject: x$"
+ printnl() // ERROR "live at call to printnl: x$"
+ return x
+}
+
+func f39c() (x [10]*int) {
+ x = [10]*int{}
+ x[0] = new(int) // ERROR "live at call to newobject: x$"
+ printnl() // ERROR "live at call to printnl: x$"
+ return
+}
+
+// issue 8142: lost 'addrtaken' bit on inlined variables.
+// no inlining in this test, so just checking that non-inlined works.
+
+type T40 struct {
+ m map[int]int
+}
+
+//go:noescape
+func useT40(*T40)
+
+func newT40() *T40 {
+ ret := T40{}
+ ret.m = make(map[int]int, 42) // ERROR "live at call to makemap: &ret$"
+ return &ret
+}
+
+func bad40() {
+ t := newT40()
+ _ = t
+ printnl()
+}
+
+func good40() {
+ ret := T40{} // ERROR "stack object ret T40$"
+ ret.m = make(map[int]int) // ERROR "live at call to rand32: .autotmp_[0-9]+$" "stack object .autotmp_[0-9]+ runtime.hmap$"
+ t := &ret
+ printnl() // ERROR "live at call to printnl: ret$"
+ // Note: ret is live at the printnl because the compiler moves &ret
+ // from before the printnl to after.
+ useT40(t)
+}
+
+func ddd1(x, y *int) { // ERROR "live at entry to ddd1: x y$"
+ ddd2(x, y) // ERROR "stack object .autotmp_[0-9]+ \[2\]\*int$"
+ printnl()
+ // Note: no .?autotmp live at printnl. See issue 16996.
+}
+func ddd2(a ...*int) { // ERROR "live at entry to ddd2: a$"
+ sink = a[0]
+}
+
+// issue 16016: autogenerated wrapper should have arguments live
+type T struct{}
+
+func (*T) Foo(ptr *int) {}
+
+type R struct{ *T }
+
+// issue 18860: output arguments must be live all the time if there is a defer.
+// In particular, at printint r must be live.
+func f41(p, q *int) (r *int) { // ERROR "live at entry to f41: p q$"
+ r = p
+ defer func() {
+ recover()
+ }()
+ printint(0) // ERROR "live at call to printint: .autotmp_[0-9]+ q r$"
+ r = q
+ return // ERROR "live at call to f41.func1: .autotmp_[0-9]+ r$"
+}
+
+func f42() {
+ var p, q, r int
+ f43([]*int{&p, &q, &r}) // ERROR "stack object .autotmp_[0-9]+ \[3\]\*int$"
+ f43([]*int{&p, &r, &q})
+ f43([]*int{&q, &p, &r})
+}
+
+//go:noescape
+func f43(a []*int)
+
+// Assigning to a sub-element that makes up an entire local variable
+// should clobber that variable.
+func f44(f func() [2]*int) interface{} { // ERROR "live at entry to f44: f"
+ type T struct {
+ s [1][2]*int
+ }
+ ret := T{} // ERROR "stack object ret T"
+ ret.s[0] = f()
+ return ret
+}
+
+func f45(a, b, c, d, e, f, g, h, i, j, k, l *byte) { // ERROR "live at entry to f45: a b c d e f g h i j k l"
+ f46(a, b, c, d, e, f, g, h, i, j, k, l) // ERROR "live at call to f46: a b c d e f g h i j k l"
+ runtime.KeepAlive(a)
+ runtime.KeepAlive(b)
+ runtime.KeepAlive(c)
+ runtime.KeepAlive(d)
+ runtime.KeepAlive(e)
+ runtime.KeepAlive(f)
+ runtime.KeepAlive(g)
+ runtime.KeepAlive(h)
+ runtime.KeepAlive(i)
+ runtime.KeepAlive(j)
+ runtime.KeepAlive(k)
+ runtime.KeepAlive(l)
+}
+
+//go:noinline
+func f46(a, b, c, d, e, f, g, h, i, j, k, l *byte) {
+}
diff --git a/platform/dbops/binaries/go/go/test/live_uintptrkeepalive.go b/platform/dbops/binaries/go/go/test/live_uintptrkeepalive.go
new file mode 100644
index 0000000000000000000000000000000000000000..ae41101954b7d3b41b9ea7f3f3757ca0cb1032cf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/live_uintptrkeepalive.go
@@ -0,0 +1,63 @@
+// errorcheck -0 -m -live -std
+
+//go:build !windows && !js && !wasip1
+
+// 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.
+
+// Test escape analysis and liveness inferred for uintptrkeepalive functions.
+//
+// This behavior is enabled automatically for function declarations with no
+// bodies (assembly, linkname), as well as explicitly on complete functions
+// with //go:uintptrkeepalive.
+//
+// This is most important for syscall.Syscall (and similar functions), so we
+// test it explicitly.
+
+package p
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func implicit(uintptr) // ERROR "assuming ~p0 is unsafe uintptr"
+
+//go:uintptrkeepalive
+//go:nosplit
+func explicit(uintptr) {
+}
+
+func autotmpImplicit() { // ERROR "can inline autotmpImplicit"
+ var t int
+ implicit(uintptr(unsafe.Pointer(&t))) // ERROR "live at call to implicit: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func autotmpExplicit() { // ERROR "can inline autotmpExplicit"
+ var t int
+ explicit(uintptr(unsafe.Pointer(&t))) // ERROR "live at call to explicit: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func autotmpSyscall() { // ERROR "can inline autotmpSyscall"
+ var v int
+ syscall.Syscall(0, 1, uintptr(unsafe.Pointer(&v)), 2) // ERROR "live at call to Syscall: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func localImplicit() { // ERROR "can inline localImplicit"
+ var t int
+ p := unsafe.Pointer(&t)
+ implicit(uintptr(p)) // ERROR "live at call to implicit: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func localExplicit() { // ERROR "can inline localExplicit"
+ var t int
+ p := unsafe.Pointer(&t)
+ explicit(uintptr(p)) // ERROR "live at call to explicit: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func localSyscall() { // ERROR "can inline localSyscall"
+ var v int
+ p := unsafe.Pointer(&v)
+ syscall.Syscall(0, 1, uintptr(p), 2) // ERROR "live at call to Syscall: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
diff --git a/platform/dbops/binaries/go/go/test/loopbce.go b/platform/dbops/binaries/go/go/test/loopbce.go
new file mode 100644
index 0000000000000000000000000000000000000000..04c186be0eb194d52db47beb6955c0b4e7f5003e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/loopbce.go
@@ -0,0 +1,478 @@
+// errorcheck -0 -d=ssa/prove/debug=1
+
+//go:build amd64
+
+package main
+
+import "math"
+
+func f0a(a []int) int {
+ x := 0
+ for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func f0b(a []int) int {
+ x := 0
+ for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ b := a[i:] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ x += b[0]
+ }
+ return x
+}
+
+func f0c(a []int) int {
+ x := 0
+ for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ b := a[:i+1] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ x += b[0]
+ }
+ return x
+}
+
+func f1(a []int) int {
+ x := 0
+ for _, i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ x += i
+ }
+ return x
+}
+
+func f2(a []int) int {
+ x := 0
+ for i := 1; i < len(a); i++ { // ERROR "Induction variable: limits \[1,\?\), increment 1$"
+ x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func f4(a [10]int) int {
+ x := 0
+ for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
+ x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func f5(a [10]int) int {
+ x := 0
+ for i := -10; i < len(a); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
+ x += a[i+10]
+ }
+ return x
+}
+
+func f5_int32(a [10]int) int {
+ x := 0
+ for i := int32(-10); i < int32(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
+ x += a[i+10]
+ }
+ return x
+}
+
+func f5_int16(a [10]int) int {
+ x := 0
+ for i := int16(-10); i < int16(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
+ x += a[i+10]
+ }
+ return x
+}
+
+func f5_int8(a [10]int) int {
+ x := 0
+ for i := int8(-10); i < int8(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
+ x += a[i+10]
+ }
+ return x
+}
+
+func f6(a []int) {
+ for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ b := a[0:i] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ f6(b)
+ }
+}
+
+func g0a(a string) int {
+ x := 0
+ for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g0b(a string) int {
+ x := 0
+ for i := 0; len(a) > i; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g0c(a string) int {
+ x := 0
+ for i := len(a); i > 0; i-- { // ERROR "Induction variable: limits \(0,\?\], increment 1$"
+ x += int(a[i-1]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g0d(a string) int {
+ x := 0
+ for i := len(a); 0 < i; i-- { // ERROR "Induction variable: limits \(0,\?\], increment 1$"
+ x += int(a[i-1]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g0e(a string) int {
+ x := 0
+ for i := len(a) - 1; i >= 0; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1$"
+ x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g0f(a string) int {
+ x := 0
+ for i := len(a) - 1; 0 <= i; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1$"
+ x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g1() int {
+ a := "evenlength"
+ x := 0
+ for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
+ x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return x
+}
+
+func g2() int {
+ a := "evenlength"
+ x := 0
+ for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
+ j := i
+ if a[i] == 'e' { // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ j = j + 1
+ }
+ x += int(a[j])
+ }
+ return x
+}
+
+func g3a() {
+ a := "this string has length 25"
+ for i := 0; i < len(a); i += 5 { // ERROR "Induction variable: limits \[0,20\], increment 5$"
+ useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useString(a[:i+3]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useString(a[:i+5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useString(a[:i+6])
+ }
+}
+
+func g3b(a string) {
+ for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[i+1:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+}
+
+func g3c(a string) {
+ for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[:i+1]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+}
+
+func h1(a []byte) {
+ c := a[:128]
+ for i := range c { // ERROR "Induction variable: limits \[0,128\), increment 1$"
+ c[i] = byte(i) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+}
+
+func h2(a []byte) {
+ for i := range a[:128] { // ERROR "Induction variable: limits \[0,128\), increment 1$"
+ a[i] = byte(i)
+ }
+}
+
+func k0(a [100]int) [100]int {
+ for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ a[i-11] = i
+ a[i-10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i-5] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+5] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+11] = i
+ }
+ return a
+}
+
+func k1(a [100]int) [100]int {
+ for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ useSlice(a[:i-11])
+ useSlice(a[:i-10]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i-5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i+5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i+10]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i+11]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[:i+12])
+
+ }
+ return a
+}
+
+func k2(a [100]int) [100]int {
+ for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ useSlice(a[i-11:])
+ useSlice(a[i-10:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i-5:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i+5:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i+10:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i+11:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ useSlice(a[i+12:])
+ }
+ return a
+}
+
+func k3(a [100]int) [100]int {
+ for i := -10; i < 90; i++ { // ERROR "Induction variable: limits \[-10,90\), increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ a[i+9] = i
+ a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+11] = i
+ }
+ return a
+}
+
+func k3neg(a [100]int) [100]int {
+ for i := 89; i > -11; i-- { // ERROR "Induction variable: limits \(-11,89\], increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ a[i+9] = i
+ a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+11] = i
+ }
+ return a
+}
+
+func k3neg2(a [100]int) [100]int {
+ for i := 89; i >= -10; i-- { // ERROR "Induction variable: limits \[-10,89\], increment 1$"
+ if a[0] == 0xdeadbeef {
+ // This is a trick to prohibit sccp to optimize out the following out of bound check
+ continue
+ }
+ a[i+9] = i
+ a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i+11] = i
+ }
+ return a
+}
+
+func k4(a [100]int) [100]int {
+ min := (-1) << 63
+ for i := min; i < min+50; i++ { // ERROR "Induction variable: limits \[-9223372036854775808,-9223372036854775758\), increment 1$"
+ a[i-min] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return a
+}
+
+func k5(a [100]int) [100]int {
+ max := (1 << 63) - 1
+ for i := max - 50; i < max; i++ { // ERROR "Induction variable: limits \[9223372036854775757,9223372036854775807\), increment 1$"
+ a[i-max+50] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ a[i-(max-70)] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
+ }
+ return a
+}
+
+func d1(a [100]int) [100]int {
+ for i := 0; i < 100; i++ { // ERROR "Induction variable: limits \[0,100\), increment 1$"
+ for j := 0; j < i; j++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ a[j] = 0 // ERROR "Proved IsInBounds$"
+ a[j+1] = 0 // FIXME: this boundcheck should be eliminated
+ a[j+2] = 0
+ }
+ }
+ return a
+}
+
+func d2(a [100]int) [100]int {
+ for i := 0; i < 100; i++ { // ERROR "Induction variable: limits \[0,100\), increment 1$"
+ for j := 0; i > j; j++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ a[j] = 0 // ERROR "Proved IsInBounds$"
+ a[j+1] = 0 // FIXME: this boundcheck should be eliminated
+ a[j+2] = 0
+ }
+ }
+ return a
+}
+
+func d3(a [100]int) [100]int {
+ for i := 0; i <= 99; i++ { // ERROR "Induction variable: limits \[0,99\], increment 1$"
+ for j := 0; j <= i-1; j++ {
+ a[j] = 0
+ a[j+1] = 0 // ERROR "Proved IsInBounds$"
+ a[j+2] = 0
+ }
+ }
+ return a
+}
+
+func d4() {
+ for i := int64(math.MaxInt64 - 9); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775798,9223372036854775802\], increment 4$"
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 8); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775799,9223372036854775803\], increment 4$"
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 7); i < math.MaxInt64-2; i += 4 {
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 6); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775801,9223372036854775801\], increment 4$"
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 9); i <= math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775798,9223372036854775802\], increment 4$"
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 8); i <= math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775799,9223372036854775803\], increment 4$"
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 7); i <= math.MaxInt64-2; i += 4 {
+ useString("foo")
+ }
+ for i := int64(math.MaxInt64 - 6); i <= math.MaxInt64-2; i += 4 {
+ useString("foo")
+ }
+}
+
+func d5() {
+ for i := int64(math.MinInt64 + 9); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775803,-9223372036854775799\], increment 4"
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 8); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775804,-9223372036854775800\], increment 4"
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 7); i > math.MinInt64+2; i -= 4 {
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 6); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775802,-9223372036854775802\], increment 4"
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 9); i >= math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775803,-9223372036854775799\], increment 4"
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 8); i >= math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775804,-9223372036854775800\], increment 4"
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 7); i >= math.MinInt64+2; i -= 4 {
+ useString("foo")
+ }
+ for i := int64(math.MinInt64 + 6); i >= math.MinInt64+2; i -= 4 {
+ useString("foo")
+ }
+}
+
+func bce1() {
+ // tests overflow of max-min
+ a := int64(9223372036854774057)
+ b := int64(-1547)
+ z := int64(1337)
+
+ if a%z == b%z {
+ panic("invalid test: modulos should differ")
+ }
+
+ for i := b; i < a; i += z { // ERROR "Induction variable: limits \[-1547,9223372036854772720\], increment 1337"
+ useString("foobar")
+ }
+}
+
+func nobce2(a string) {
+ for i := int64(0); i < int64(len(a)); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+ for i := int64(0); i < int64(len(a))-31337; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+ for i := int64(0); i < int64(len(a))+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+ j := int64(len(a)) - 123
+ for i := int64(0); i < j+123+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
+ }
+ for i := int64(0); i < j+122+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ // len(a)-123+122+MinInt overflows when len(a) == 0, so a bound check is needed here
+ useString(a[i:])
+ }
+}
+
+func nobce3(a [100]int64) [100]int64 {
+ min := int64((-1) << 63)
+ max := int64((1 << 63) - 1)
+ for i := min; i < max; i++ { // ERROR "Induction variable: limits \[-9223372036854775808,9223372036854775807\), increment 1$"
+ }
+ return a
+}
+
+func issue26116a(a []int) {
+ // There is no induction variable here. The comparison is in the wrong direction.
+ for i := 3; i > 6; i++ {
+ a[i] = 0
+ }
+ for i := 7; i < 3; i-- {
+ a[i] = 1
+ }
+}
+
+func stride1(x *[7]int) int {
+ s := 0
+ for i := 0; i <= 8; i += 3 { // ERROR "Induction variable: limits \[0,6\], increment 3"
+ s += x[i] // ERROR "Proved IsInBounds"
+ }
+ return s
+}
+
+func stride2(x *[7]int) int {
+ s := 0
+ for i := 0; i < 9; i += 3 { // ERROR "Induction variable: limits \[0,6\], increment 3"
+ s += x[i] // ERROR "Proved IsInBounds"
+ }
+ return s
+}
+
+//go:noinline
+func useString(a string) {
+}
+
+//go:noinline
+func useSlice(a []int) {
+}
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/mainsig.go b/platform/dbops/binaries/go/go/test/mainsig.go
new file mode 100644
index 0000000000000000000000000000000000000000..d006d9cda3142affd3a3c34aa584263964a75854
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/mainsig.go
@@ -0,0 +1,13 @@
+// errorcheck
+
+// 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(int) {} // ERROR "func main must have no arguments and no return values"
+func main() int { return 1 } // ERROR "func main must have no arguments and no return values" "main redeclared in this block"
+
+func init(int) {} // ERROR "func init must have no arguments and no return values"
+func init() int { return 1 } // ERROR "func init must have no arguments and no return values"
diff --git a/platform/dbops/binaries/go/go/test/makechan.go b/platform/dbops/binaries/go/go/test/makechan.go
new file mode 100644
index 0000000000000000000000000000000000000000..9fabd1701f9cbd326f75987ee1a772f6d8268654
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/makechan.go
@@ -0,0 +1,28 @@
+// errorcheck
+
+// 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.
+
+// Ensure that typed non-integer, negative and to large
+// values are not accepted as size argument in make for
+// channels.
+
+package main
+
+type T chan byte
+
+var sink T
+
+func main() {
+ sink = make(T, -1) // ERROR "negative buffer argument in make.*|must not be negative"
+ sink = make(T, uint64(1<<63)) // ERROR "buffer argument too large in make.*|overflows int"
+
+ sink = make(T, 0.5) // ERROR "constant 0.5 truncated to integer|truncated to int"
+ sink = make(T, 1.0)
+ sink = make(T, float32(1.0)) // ERROR "non-integer buffer argument in make.*|must be integer"
+ sink = make(T, float64(1.0)) // ERROR "non-integer buffer argument in make.*|must be integer"
+ sink = make(T, 1+0i)
+ sink = make(T, complex64(1+0i)) // ERROR "non-integer buffer argument in make.*|must be integer"
+ sink = make(T, complex128(1+0i)) // ERROR "non-integer buffer argument in make.*|must be integer"
+}
diff --git a/platform/dbops/binaries/go/go/test/makemap.go b/platform/dbops/binaries/go/go/test/makemap.go
new file mode 100644
index 0000000000000000000000000000000000000000..f63e5b4b6ace97dc2f21c600188bb8fde78d36bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/makemap.go
@@ -0,0 +1,34 @@
+// errorcheck
+
+// 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.
+
+// Ensure that typed non-integer, negative and too large
+// values are not accepted as size argument in make for
+// maps.
+
+package main
+
+type T map[int]int
+
+var sink T
+
+func main() {
+ sink = make(T, -1) // ERROR "negative size argument in make.*|must not be negative"
+ sink = make(T, uint64(1<<63)) // ERROR "size argument too large in make.*|overflows int"
+
+ // Test that errors are emitted at call sites, not const declarations
+ const x = -1
+ sink = make(T, x) // ERROR "negative size argument in make.*|must not be negative"
+ const y = uint64(1 << 63)
+ sink = make(T, y) // ERROR "size argument too large in make.*|overflows int"
+
+ sink = make(T, 0.5) // ERROR "constant 0.5 truncated to integer|truncated to int"
+ sink = make(T, 1.0)
+ sink = make(T, float32(1.0)) // ERROR "non-integer size argument in make.*|must be integer"
+ sink = make(T, float64(1.0)) // ERROR "non-integer size argument in make.*|must be integer"
+ sink = make(T, 1+0i)
+ sink = make(T, complex64(1+0i)) // ERROR "non-integer size argument in make.*|must be integer"
+ sink = make(T, complex128(1+0i)) // ERROR "non-integer size argument in make.*|must be integer"
+}
diff --git a/platform/dbops/binaries/go/go/test/makenew.go b/platform/dbops/binaries/go/go/test/makenew.go
new file mode 100644
index 0000000000000000000000000000000000000000..14854dcf0c8fe70e4ae766cbdf74b9ee3a612d4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/makenew.go
@@ -0,0 +1,19 @@
+// errorcheck
+
+// 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.
+
+// Verify that make and new arguments requirements are enforced by the
+// compiler.
+
+package main
+
+func main() {
+ _ = make() // ERROR "missing argument|not enough arguments"
+ _ = make(int) // ERROR "cannot make type|cannot make int"
+ _ = make([]int) // ERROR "missing len argument|expects 2 or 3 arguments"
+
+ _ = new() // ERROR "missing argument|not enough arguments"
+ _ = new(int, 2) // ERROR "too many arguments"
+}
diff --git a/platform/dbops/binaries/go/go/test/makeslice.go b/platform/dbops/binaries/go/go/test/makeslice.go
new file mode 100644
index 0000000000000000000000000000000000000000..0ffecd7c4367dc4d6f8303c9ddee30bd3c96b59c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/makeslice.go
@@ -0,0 +1,149 @@
+// run
+
+// 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 main
+
+import (
+ "strings"
+ "unsafe"
+)
+
+func main() {
+ n := -1
+ testInts(uint64(n))
+ testBytes(uint64(n))
+
+ var t *byte
+ if unsafe.Sizeof(t) == 8 {
+ // Test mem > maxAlloc
+ testInts(1 << 59)
+
+ // Test elem.size*cap overflow
+ testInts(1<<63 - 1)
+
+ testInts(1<<64 - 1)
+ testBytes(1<<64 - 1)
+ } else {
+ testInts(1<<31 - 1)
+
+ // Test elem.size*cap overflow
+ testInts(1<<32 - 1)
+ testBytes(1<<32 - 1)
+ }
+}
+
+func shouldPanic(str string, f func()) {
+ defer func() {
+ err := recover()
+ if err == nil {
+ panic("did not panic")
+ }
+ s := err.(error).Error()
+ if !strings.Contains(s, str) {
+ panic("got panic " + s + ", want " + str)
+ }
+ }()
+
+ f()
+}
+
+func testInts(n uint64) {
+ testMakeInts(n)
+ testMakeCopyInts(n)
+ testMakeInAppendInts(n)
+}
+
+func testBytes(n uint64) {
+ testMakeBytes(n)
+ testMakeCopyBytes(n)
+ testMakeInAppendBytes(n)
+}
+
+// Test make panics for given length or capacity n.
+func testMakeInts(n uint64) {
+ type T []int
+ shouldPanic("len out of range", func() { _ = make(T, int(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, int(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, uint(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, uint(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, int64(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, int64(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, uint64(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, uint64(n)) })
+}
+
+func testMakeBytes(n uint64) {
+ type T []byte
+ shouldPanic("len out of range", func() { _ = make(T, int(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, int(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, uint(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, uint(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, int64(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, int64(n)) })
+ shouldPanic("len out of range", func() { _ = make(T, uint64(n)) })
+ shouldPanic("cap out of range", func() { _ = make(T, 0, uint64(n)) })
+}
+
+// Test make+copy panics since the gc compiler optimizes these
+// to runtime.makeslicecopy calls.
+func testMakeCopyInts(n uint64) {
+ type T []int
+ var c = make(T, 8)
+ shouldPanic("len out of range", func() { x := make(T, int(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, int(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, uint(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, uint(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, int64(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, int64(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, uint64(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, uint64(n)); copy(x, c) })
+}
+
+func testMakeCopyBytes(n uint64) {
+ type T []byte
+ var c = make(T, 8)
+ shouldPanic("len out of range", func() { x := make(T, int(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, int(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, uint(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, uint(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, int64(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, int64(n)); copy(x, c) })
+ shouldPanic("len out of range", func() { x := make(T, uint64(n)); copy(x, c) })
+ shouldPanic("cap out of range", func() { x := make(T, 0, uint64(n)); copy(x, c) })
+}
+
+// Test make in append panics for int slices since the gc compiler optimizes makes in appends.
+func testMakeInAppendInts(n uint64) {
+ type T []int
+ for _, length := range []int{0, 1} {
+ t := make(T, length)
+ shouldPanic("len out of range", func() { _ = append(t, make(T, int(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, int(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, int64(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, int64(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, uint64(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, uint64(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, int(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, int(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, uint(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, uint(n))...) })
+ }
+}
+
+func testMakeInAppendBytes(n uint64) {
+ type T []byte
+ for _, length := range []int{0, 1} {
+ t := make(T, length)
+ shouldPanic("len out of range", func() { _ = append(t, make(T, int(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, int(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, uint(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, uint(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, int64(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, int64(n))...) })
+ shouldPanic("len out of range", func() { _ = append(t, make(T, uint64(n))...) })
+ shouldPanic("cap out of range", func() { _ = append(t, make(T, 0, uint64(n))...) })
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/mallocfin.go b/platform/dbops/binaries/go/go/test/mallocfin.go
new file mode 100644
index 0000000000000000000000000000000000000000..be6d79b2b8e09ed623639972ac9e9f7ff9a411bb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/mallocfin.go
@@ -0,0 +1,77 @@
+// run
+
+// 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.
+
+// Test basic operation of finalizers.
+
+package main
+
+import (
+ "runtime"
+ "time"
+)
+
+const N = 250
+
+type A struct {
+ b *B
+ n int
+}
+
+type B struct {
+ n int
+}
+
+var i int
+var nfinal int
+var final [N]int
+
+// the unused return is to test finalizers with return values
+func finalA(a *A) (unused [N]int) {
+ if final[a.n] != 0 {
+ println("finalA", a.n, final[a.n])
+ panic("fail")
+ }
+ final[a.n] = 1
+ return
+}
+
+func finalB(b *B) {
+ if final[b.n] != 1 {
+ println("finalB", b.n, final[b.n])
+ panic("fail")
+ }
+ final[b.n] = 2
+ nfinal++
+}
+
+func nofinalB(b *B) {
+ panic("nofinalB run")
+}
+
+func main() {
+ runtime.GOMAXPROCS(4)
+ for i = 0; i < N; i++ {
+ b := &B{i}
+ a := &A{b, i}
+ c := new(B)
+ runtime.SetFinalizer(c, nofinalB)
+ runtime.SetFinalizer(b, finalB)
+ runtime.SetFinalizer(a, finalA)
+ runtime.SetFinalizer(c, nil)
+ }
+ for i := 0; i < N; i++ {
+ runtime.GC()
+ runtime.Gosched()
+ time.Sleep(1e6)
+ if nfinal >= N*8/10 {
+ break
+ }
+ }
+ if nfinal < N*8/10 {
+ println("not enough finalizing:", nfinal, "/", N)
+ panic("fail")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/map.go b/platform/dbops/binaries/go/go/test/map.go
new file mode 100644
index 0000000000000000000000000000000000000000..2c1cf8a14038259d1453a57e3d4e7a7d27da7ea6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/map.go
@@ -0,0 +1,684 @@
+// run
+
+// 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.
+
+// Test maps, almost exhaustively.
+// Complexity (linearity) test is in maplinear.go.
+
+package main
+
+import (
+ "fmt"
+ "math"
+ "strconv"
+)
+
+const count = 100
+
+func P(a []string) string {
+ s := "{"
+ for i := 0; i < len(a); i++ {
+ if i > 0 {
+ s += ","
+ }
+ s += `"` + a[i] + `"`
+ }
+ s += "}"
+ return s
+}
+
+func main() {
+ testbasic()
+ testfloat()
+ testnan()
+}
+
+func testbasic() {
+ // Test a map literal.
+ mlit := map[string]int{"0": 0, "1": 1, "2": 2, "3": 3, "4": 4}
+ for i := 0; i < len(mlit); i++ {
+ s := string([]byte{byte(i) + '0'})
+ if mlit[s] != i {
+ panic(fmt.Sprintf("mlit[%s] = %d\n", s, mlit[s]))
+ }
+ }
+
+ mib := make(map[int]bool)
+ mii := make(map[int]int)
+ mfi := make(map[float32]int)
+ mif := make(map[int]float32)
+ msi := make(map[string]int)
+ mis := make(map[int]string)
+ mss := make(map[string]string)
+ mspa := make(map[string][]string)
+ // BUG need an interface map both ways too
+
+ type T struct {
+ i int64 // can't use string here; struct values are only compared at the top level
+ f float32
+ }
+ mipT := make(map[int]*T)
+ mpTi := make(map[*T]int)
+ mit := make(map[int]T)
+ // mti := make(map[T] int)
+
+ type M map[int]int
+ mipM := make(map[int]M)
+
+ var apT [2 * count]*T
+
+ for i := 0; i < count; i++ {
+ s := strconv.Itoa(i)
+ s10 := strconv.Itoa(i * 10)
+ f := float32(i)
+ t := T{int64(i), f}
+ apT[i] = new(T)
+ apT[i].i = int64(i)
+ apT[i].f = f
+ apT[2*i] = new(T) // need twice as many entries as we use, for the nonexistence check
+ apT[2*i].i = int64(i)
+ apT[2*i].f = f
+ m := M{i: i + 1}
+ mib[i] = (i != 0)
+ mii[i] = 10 * i
+ mfi[float32(i)] = 10 * i
+ mif[i] = 10.0 * f
+ mis[i] = s
+ msi[s] = i
+ mss[s] = s10
+ mss[s] = s10
+ as := make([]string, 2)
+ as[0] = s10
+ as[1] = s10
+ mspa[s] = as
+ mipT[i] = apT[i]
+ mpTi[apT[i]] = i
+ mipM[i] = m
+ mit[i] = t
+ // mti[t] = i
+ }
+
+ // test len
+ if len(mib) != count {
+ panic(fmt.Sprintf("len(mib) = %d\n", len(mib)))
+ }
+ if len(mii) != count {
+ panic(fmt.Sprintf("len(mii) = %d\n", len(mii)))
+ }
+ if len(mfi) != count {
+ panic(fmt.Sprintf("len(mfi) = %d\n", len(mfi)))
+ }
+ if len(mif) != count {
+ panic(fmt.Sprintf("len(mif) = %d\n", len(mif)))
+ }
+ if len(msi) != count {
+ panic(fmt.Sprintf("len(msi) = %d\n", len(msi)))
+ }
+ if len(mis) != count {
+ panic(fmt.Sprintf("len(mis) = %d\n", len(mis)))
+ }
+ if len(mss) != count {
+ panic(fmt.Sprintf("len(mss) = %d\n", len(mss)))
+ }
+ if len(mspa) != count {
+ panic(fmt.Sprintf("len(mspa) = %d\n", len(mspa)))
+ }
+ if len(mipT) != count {
+ panic(fmt.Sprintf("len(mipT) = %d\n", len(mipT)))
+ }
+ if len(mpTi) != count {
+ panic(fmt.Sprintf("len(mpTi) = %d\n", len(mpTi)))
+ }
+ // if len(mti) != count {
+ // panic(fmt.Sprintf("len(mti) = %d\n", len(mti)))
+ // }
+ if len(mipM) != count {
+ panic(fmt.Sprintf("len(mipM) = %d\n", len(mipM)))
+ }
+ // if len(mti) != count {
+ // panic(fmt.Sprintf("len(mti) = %d\n", len(mti)))
+ // }
+ if len(mit) != count {
+ panic(fmt.Sprintf("len(mit) = %d\n", len(mit)))
+ }
+
+ // test construction directly
+ for i := 0; i < count; i++ {
+ s := strconv.Itoa(i)
+ s10 := strconv.Itoa(i * 10)
+ f := float32(i)
+ // BUG m := M(i, i+1)
+ if mib[i] != (i != 0) {
+ panic(fmt.Sprintf("mib[%d] = %t\n", i, mib[i]))
+ }
+ if mii[i] != 10*i {
+ panic(fmt.Sprintf("mii[%d] = %d\n", i, mii[i]))
+ }
+ if mfi[f] != 10*i {
+ panic(fmt.Sprintf("mfi[%d] = %d\n", i, mfi[f]))
+ }
+ if mif[i] != 10.0*f {
+ panic(fmt.Sprintf("mif[%d] = %g\n", i, mif[i]))
+ }
+ if mis[i] != s {
+ panic(fmt.Sprintf("mis[%d] = %s\n", i, mis[i]))
+ }
+ if msi[s] != i {
+ panic(fmt.Sprintf("msi[%s] = %d\n", s, msi[s]))
+ }
+ if mss[s] != s10 {
+ panic(fmt.Sprintf("mss[%s] = %g\n", s, mss[s]))
+ }
+ for j := 0; j < len(mspa[s]); j++ {
+ if mspa[s][j] != s10 {
+ panic(fmt.Sprintf("mspa[%s][%d] = %s\n", s, j, mspa[s][j]))
+ }
+ }
+ if mipT[i].i != int64(i) || mipT[i].f != f {
+ panic(fmt.Sprintf("mipT[%d] = %v\n", i, mipT[i]))
+ }
+ if mpTi[apT[i]] != i {
+ panic(fmt.Sprintf("mpTi[apT[%d]] = %d\n", i, mpTi[apT[i]]))
+ }
+ // if(mti[t] != i) {
+ // panic(fmt.Sprintf("mti[%s] = %s\n", s, mti[t]))
+ // }
+ if mipM[i][i] != i+1 {
+ panic(fmt.Sprintf("mipM[%d][%d] = %d\n", i, i, mipM[i][i]))
+ }
+ // if(mti[t] != i) {
+ // panic(fmt.Sprintf("mti[%v] = %d\n", t, mti[t]))
+ // }
+ if mit[i].i != int64(i) || mit[i].f != f {
+ panic(fmt.Sprintf("mit[%d] = {%d %g}\n", i, mit[i].i, mit[i].f))
+ }
+ }
+
+ // test existence with tuple check
+ // failed lookups yield a false value for the boolean.
+ for i := 0; i < count; i++ {
+ s := strconv.Itoa(i)
+ f := float32(i)
+ {
+ _, b := mib[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mib[%d]\n", i))
+ }
+ _, b = mib[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mib[%d]\n", i))
+ }
+ }
+ {
+ _, b := mii[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mii[%d]\n", i))
+ }
+ _, b = mii[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mii[%d]\n", i))
+ }
+ }
+ {
+ _, b := mfi[f]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mfi[%d]\n", i))
+ }
+ _, b = mfi[f]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mfi[%d]\n", i))
+ }
+ }
+ {
+ _, b := mif[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mif[%d]\n", i))
+ }
+ _, b = mif[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mif[%d]\n", i))
+ }
+ }
+ {
+ _, b := mis[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mis[%d]\n", i))
+ }
+ _, b = mis[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mis[%d]\n", i))
+ }
+ }
+ {
+ _, b := msi[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: msi[%d]\n", i))
+ }
+ _, b = msi[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: msi[%d]\n", i))
+ }
+ }
+ {
+ _, b := mss[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mss[%d]\n", i))
+ }
+ _, b = mss[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mss[%d]\n", i))
+ }
+ }
+ {
+ _, b := mspa[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mspa[%d]\n", i))
+ }
+ _, b = mspa[s]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mspa[%d]\n", i))
+ }
+ }
+ {
+ _, b := mipT[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mipT[%d]\n", i))
+ }
+ _, b = mipT[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mipT[%d]\n", i))
+ }
+ }
+ {
+ _, b := mpTi[apT[i]]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mpTi[apT[%d]]\n", i))
+ }
+ _, b = mpTi[apT[i]]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mpTi[apT[%d]]\n", i))
+ }
+ }
+ {
+ _, b := mipM[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mipM[%d]\n", i))
+ }
+ _, b = mipM[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mipM[%d]\n", i))
+ }
+ }
+ {
+ _, b := mit[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence decl: mit[%d]\n", i))
+ }
+ _, b = mit[i]
+ if !b {
+ panic(fmt.Sprintf("tuple existence assign: mit[%d]\n", i))
+ }
+ }
+ // {
+ // _, b := mti[t]
+ // if !b {
+ // panic(fmt.Sprintf("tuple existence decl: mti[%d]\n", i))
+ // }
+ // _, b = mti[t]
+ // if !b {
+ // panic(fmt.Sprintf("tuple existence assign: mti[%d]\n", i))
+ // }
+ // }
+ }
+
+ // test nonexistence with tuple check
+ // failed lookups yield a false value for the boolean.
+ for i := count; i < 2*count; i++ {
+ s := strconv.Itoa(i)
+ f := float32(i)
+ {
+ _, b := mib[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mib[%d]", i))
+ }
+ _, b = mib[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mib[%d]", i))
+ }
+ }
+ {
+ _, b := mii[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mii[%d]", i))
+ }
+ _, b = mii[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mii[%d]", i))
+ }
+ }
+ {
+ _, b := mfi[f]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mfi[%d]", i))
+ }
+ _, b = mfi[f]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mfi[%d]", i))
+ }
+ }
+ {
+ _, b := mif[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mif[%d]", i))
+ }
+ _, b = mif[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mif[%d]", i))
+ }
+ }
+ {
+ _, b := mis[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mis[%d]", i))
+ }
+ _, b = mis[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mis[%d]", i))
+ }
+ }
+ {
+ _, b := msi[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: msi[%d]", i))
+ }
+ _, b = msi[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: msi[%d]", i))
+ }
+ }
+ {
+ _, b := mss[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mss[%d]", i))
+ }
+ _, b = mss[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mss[%d]", i))
+ }
+ }
+ {
+ _, b := mspa[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mspa[%d]", i))
+ }
+ _, b = mspa[s]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mspa[%d]", i))
+ }
+ }
+ {
+ _, b := mipT[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mipT[%d]", i))
+ }
+ _, b = mipT[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mipT[%d]", i))
+ }
+ }
+ {
+ _, b := mpTi[apT[i]]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mpTi[apt[%d]]", i))
+ }
+ _, b = mpTi[apT[i]]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mpTi[apT[%d]]", i))
+ }
+ }
+ {
+ _, b := mipM[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mipM[%d]", i))
+ }
+ _, b = mipM[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mipM[%d]", i))
+ }
+ }
+ // {
+ // _, b := mti[t]
+ // if b {
+ // panic(fmt.Sprintf("tuple nonexistence decl: mti[%d]", i))
+ // }
+ // _, b = mti[t]
+ // if b {
+ // panic(fmt.Sprintf("tuple nonexistence assign: mti[%d]", i))
+ // }
+ // }
+ {
+ _, b := mit[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence decl: mit[%d]", i))
+ }
+ _, b = mit[i]
+ if b {
+ panic(fmt.Sprintf("tuple nonexistence assign: mit[%d]", i))
+ }
+ }
+ }
+
+ // tests for structured map element updates
+ for i := 0; i < count; i++ {
+ s := strconv.Itoa(i)
+ mspa[s][i%2] = "deleted"
+ if mspa[s][i%2] != "deleted" {
+ panic(fmt.Sprintf("update mspa[%s][%d] = %s\n", s, i%2, mspa[s][i%2]))
+
+ }
+
+ mipT[i].i += 1
+ if mipT[i].i != int64(i)+1 {
+ panic(fmt.Sprintf("update mipT[%d].i = %d\n", i, mipT[i].i))
+
+ }
+ mipT[i].f = float32(i + 1)
+ if mipT[i].f != float32(i+1) {
+ panic(fmt.Sprintf("update mipT[%d].f = %g\n", i, mipT[i].f))
+
+ }
+
+ mipM[i][i]++
+ if mipM[i][i] != (i+1)+1 {
+ panic(fmt.Sprintf("update mipM[%d][%d] = %d\n", i, i, mipM[i][i]))
+
+ }
+ }
+
+ // test range on nil map
+ var mnil map[string]int
+ for _, _ = range mnil {
+ panic("range mnil")
+ }
+}
+
+func testfloat() {
+ // Test floating point numbers in maps.
+ // Two map keys refer to the same entry if the keys are ==.
+ // The special cases, then, are that +0 == -0 and that NaN != NaN.
+
+ {
+ var (
+ pz = float32(0)
+ nz = math.Float32frombits(1 << 31)
+ nana = float32(math.NaN())
+ nanb = math.Float32frombits(math.Float32bits(nana) ^ 2)
+ )
+
+ m := map[float32]string{
+ pz: "+0",
+ nana: "NaN",
+ nanb: "NaN",
+ }
+ if m[pz] != "+0" {
+ panic(fmt.Sprintln("float32 map cannot read back m[+0]:", m[pz]))
+ }
+ if m[nz] != "+0" {
+ fmt.Sprintln("float32 map does not treat", pz, "and", nz, "as equal for read")
+ panic(fmt.Sprintln("float32 map does not treat -0 and +0 as equal for read"))
+ }
+ m[nz] = "-0"
+ if m[pz] != "-0" {
+ panic(fmt.Sprintln("float32 map does not treat -0 and +0 as equal for write"))
+ }
+ if _, ok := m[nana]; ok {
+ panic(fmt.Sprintln("float32 map allows NaN lookup (a)"))
+ }
+ if _, ok := m[nanb]; ok {
+ panic(fmt.Sprintln("float32 map allows NaN lookup (b)"))
+ }
+ if len(m) != 3 {
+ panic(fmt.Sprintln("float32 map should have 3 entries:", m))
+ }
+ m[nana] = "NaN"
+ m[nanb] = "NaN"
+ if len(m) != 5 {
+ panic(fmt.Sprintln("float32 map should have 5 entries:", m))
+ }
+ }
+
+ {
+ var (
+ pz = float64(0)
+ nz = math.Float64frombits(1 << 63)
+ nana = float64(math.NaN())
+ nanb = math.Float64frombits(math.Float64bits(nana) ^ 2)
+ )
+
+ m := map[float64]string{
+ pz: "+0",
+ nana: "NaN",
+ nanb: "NaN",
+ }
+ if m[nz] != "+0" {
+ panic(fmt.Sprintln("float64 map does not treat -0 and +0 as equal for read"))
+ }
+ m[nz] = "-0"
+ if m[pz] != "-0" {
+ panic(fmt.Sprintln("float64 map does not treat -0 and +0 as equal for write"))
+ }
+ if _, ok := m[nana]; ok {
+ panic(fmt.Sprintln("float64 map allows NaN lookup (a)"))
+ }
+ if _, ok := m[nanb]; ok {
+ panic(fmt.Sprintln("float64 map allows NaN lookup (b)"))
+ }
+ if len(m) != 3 {
+ panic(fmt.Sprintln("float64 map should have 3 entries:", m))
+ }
+ m[nana] = "NaN"
+ m[nanb] = "NaN"
+ if len(m) != 5 {
+ panic(fmt.Sprintln("float64 map should have 5 entries:", m))
+ }
+ }
+
+ {
+ var (
+ pz = complex64(0)
+ nz = complex(0, math.Float32frombits(1<<31))
+ nana = complex(5, float32(math.NaN()))
+ nanb = complex(5, math.Float32frombits(math.Float32bits(float32(math.NaN()))^2))
+ )
+
+ m := map[complex64]string{
+ pz: "+0",
+ nana: "NaN",
+ nanb: "NaN",
+ }
+ if m[nz] != "+0" {
+ panic(fmt.Sprintln("complex64 map does not treat -0 and +0 as equal for read"))
+ }
+ m[nz] = "-0"
+ if m[pz] != "-0" {
+ panic(fmt.Sprintln("complex64 map does not treat -0 and +0 as equal for write"))
+ }
+ if _, ok := m[nana]; ok {
+ panic(fmt.Sprintln("complex64 map allows NaN lookup (a)"))
+ }
+ if _, ok := m[nanb]; ok {
+ panic(fmt.Sprintln("complex64 map allows NaN lookup (b)"))
+ }
+ if len(m) != 3 {
+ panic(fmt.Sprintln("complex64 map should have 3 entries:", m))
+ }
+ m[nana] = "NaN"
+ m[nanb] = "NaN"
+ if len(m) != 5 {
+ panic(fmt.Sprintln("complex64 map should have 5 entries:", m))
+ }
+ }
+
+ {
+ var (
+ pz = complex128(0)
+ nz = complex(0, math.Float64frombits(1<<63))
+ nana = complex(5, float64(math.NaN()))
+ nanb = complex(5, math.Float64frombits(math.Float64bits(float64(math.NaN()))^2))
+ )
+
+ m := map[complex128]string{
+ pz: "+0",
+ nana: "NaN",
+ nanb: "NaN",
+ }
+ if m[nz] != "+0" {
+ panic(fmt.Sprintln("complex128 map does not treat -0 and +0 as equal for read"))
+ }
+ m[nz] = "-0"
+ if m[pz] != "-0" {
+ panic(fmt.Sprintln("complex128 map does not treat -0 and +0 as equal for write"))
+ }
+ if _, ok := m[nana]; ok {
+ panic(fmt.Sprintln("complex128 map allows NaN lookup (a)"))
+ }
+ if _, ok := m[nanb]; ok {
+ panic(fmt.Sprintln("complex128 map allows NaN lookup (b)"))
+ }
+ if len(m) != 3 {
+ panic(fmt.Sprintln("complex128 map should have 3 entries:", m))
+ }
+ m[nana] = "NaN"
+ m[nanb] = "NaN"
+ if len(m) != 5 {
+ panic(fmt.Sprintln("complex128 map should have 5 entries:", m))
+ }
+ }
+}
+
+func testnan() {
+ n := 500
+ m := map[float64]int{}
+ nan := math.NaN()
+ for i := 0; i < n; i++ {
+ m[nan] = 1
+ }
+ if len(m) != n {
+ panic("wrong size map after nan insertion")
+ }
+ iters := 0
+ for k, v := range m {
+ iters++
+ if !math.IsNaN(k) {
+ panic("not NaN")
+ }
+ if v != 1 {
+ panic("wrong value")
+ }
+ }
+ if iters != n {
+ panic("wrong number of nan range iters")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/map1.go b/platform/dbops/binaries/go/go/test/map1.go
new file mode 100644
index 0000000000000000000000000000000000000000..a6b27e6ebd3a6b14502a69d889bb9fc84216bb75
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/map1.go
@@ -0,0 +1,68 @@
+// errorcheck
+
+// 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.
+
+// Test map declarations of many types, including erroneous ones.
+// Does not compile.
+
+package main
+
+type v bool
+
+var (
+ // valid
+ _ map[int8]v
+ _ map[uint8]v
+ _ map[int16]v
+ _ map[uint16]v
+ _ map[int32]v
+ _ map[uint32]v
+ _ map[int64]v
+ _ map[uint64]v
+ _ map[int]v
+ _ map[uint]v
+ _ map[uintptr]v
+ _ map[float32]v
+ _ map[float64]v
+ _ map[complex64]v
+ _ map[complex128]v
+ _ map[bool]v
+ _ map[string]v
+ _ map[chan int]v
+ _ map[*int]v
+ _ map[struct{}]v
+ _ map[[10]int]v
+
+ // invalid
+ _ map[[]int]v // ERROR "invalid map key"
+ _ map[func()]v // ERROR "invalid map key"
+ _ map[map[int]int]v // ERROR "invalid map key"
+ _ map[T1]v // ERROR "invalid map key"
+ _ map[T2]v // ERROR "invalid map key"
+ _ map[T3]v // ERROR "invalid map key"
+ _ map[T4]v // ERROR "invalid map key"
+ _ map[T5]v
+ _ map[T6]v
+ _ map[T7]v
+ _ map[T8]v
+)
+
+type T1 []int
+type T2 struct { F T1 }
+type T3 []T4
+type T4 struct { F T3 }
+
+type T5 *int
+type T6 struct { F T5 }
+type T7 *T4
+type T8 struct { F *T7 }
+
+func main() {
+ m := make(map[int]int)
+ delete() // ERROR "missing arguments|not enough arguments"
+ delete(m) // ERROR "missing second \(key\) argument|not enough arguments"
+ delete(m, 2, 3) // ERROR "too many arguments"
+ delete(1, m) // ERROR "first argument to delete must be map|argument 1 must be a map|is not a map"
+}
diff --git a/platform/dbops/binaries/go/go/test/mapclear.go b/platform/dbops/binaries/go/go/test/mapclear.go
new file mode 100644
index 0000000000000000000000000000000000000000..a29f30da743e77cb43f92f9af58eb5def6e41756
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/mapclear.go
@@ -0,0 +1,89 @@
+// run
+
+// 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.
+
+// Ensure that range loops over maps with delete statements
+// have the requisite side-effects.
+
+package main
+
+import (
+ "fmt"
+ "os"
+)
+
+func checkcleared() {
+ m := make(map[byte]int)
+ m[1] = 1
+ m[2] = 2
+ for k := range m {
+ delete(m, k)
+ }
+ l := len(m)
+ if want := 0; l != want {
+ fmt.Printf("len after map clear = %d want %d\n", l, want)
+ os.Exit(1)
+ }
+
+ m[0] = 0 // To have non empty map and avoid internal map code fast paths.
+ n := 0
+ for range m {
+ n++
+ }
+ if want := 1; n != want {
+ fmt.Printf("number of keys found = %d want %d\n", n, want)
+ os.Exit(1)
+ }
+}
+
+func checkloopvars() {
+ k := 0
+ m := make(map[int]int)
+ m[42] = 0
+ for k = range m {
+ delete(m, k)
+ }
+ if want := 42; k != want {
+ fmt.Printf("var after range with side-effect = %d want %d\n", k, want)
+ os.Exit(1)
+ }
+}
+
+func checksideeffects() {
+ var x int
+ f := func() int {
+ x++
+ return 0
+ }
+ m := make(map[int]int)
+ m[0] = 0
+ m[1] = 1
+ for k := range m {
+ delete(m, k+f())
+ }
+ if want := 2; x != want {
+ fmt.Printf("var after range with side-effect = %d want %d\n", x, want)
+ os.Exit(1)
+ }
+
+ var n int
+ m = make(map[int]int)
+ m[0] = 0
+ m[1] = 1
+ for k := range m {
+ delete(m, k)
+ n++
+ }
+ if want := 2; n != want {
+ fmt.Printf("counter for range with side-effect = %d want %d\n", n, want)
+ os.Exit(1)
+ }
+}
+
+func main() {
+ checkcleared()
+ checkloopvars()
+ checksideeffects()
+}
diff --git a/platform/dbops/binaries/go/go/test/maplinear.go b/platform/dbops/binaries/go/go/test/maplinear.go
new file mode 100644
index 0000000000000000000000000000000000000000..dbc68272bf054601d88f6057866bce874bf451f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/maplinear.go
@@ -0,0 +1,173 @@
+// run
+
+//go:build darwin || linux
+
+// 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.
+
+// Test that maps don't go quadratic for NaNs and other values.
+
+package main
+
+import (
+ "fmt"
+ "math"
+ "time"
+)
+
+// checkLinear asserts that the running time of f(n) is in O(n).
+// tries is the initial number of iterations.
+func checkLinear(typ string, tries int, f func(n int)) {
+ // Depending on the machine and OS, this test might be too fast
+ // to measure with accurate enough granularity. On failure,
+ // make it run longer, hoping that the timing granularity
+ // is eventually sufficient.
+
+ timeF := func(n int) time.Duration {
+ t1 := time.Now()
+ f(n)
+ return time.Since(t1)
+ }
+
+ t0 := time.Now()
+
+ n := tries
+ fails := 0
+ for {
+ t1 := timeF(n)
+ t2 := timeF(2 * n)
+
+ // should be 2x (linear); allow up to 3x
+ if t2 < 3*t1 {
+ if false {
+ fmt.Println(typ, "\t", time.Since(t0))
+ }
+ return
+ }
+ // If n ops run in under a second and the ratio
+ // doesn't work out, make n bigger, trying to reduce
+ // the effect that a constant amount of overhead has
+ // on the computed ratio.
+ if t1 < 1*time.Second {
+ n *= 2
+ continue
+ }
+ // Once the test runs long enough for n ops,
+ // try to get the right ratio at least once.
+ // If five in a row all fail, give up.
+ if fails++; fails >= 5 {
+ panic(fmt.Sprintf("%s: too slow: %d inserts: %v; %d inserts: %v\n",
+ typ, n, t1, 2*n, t2))
+ }
+ }
+}
+
+type I interface {
+ f()
+}
+
+type C int
+
+func (C) f() {}
+
+func main() {
+ // NaNs. ~31ms on a 1.6GHz Zeon.
+ checkLinear("NaN", 30000, func(n int) {
+ m := map[float64]int{}
+ nan := math.NaN()
+ for i := 0; i < n; i++ {
+ m[nan] = 1
+ }
+ if len(m) != n {
+ panic("wrong size map after nan insertion")
+ }
+ })
+
+ // ~6ms on a 1.6GHz Zeon.
+ checkLinear("eface", 10000, func(n int) {
+ m := map[interface{}]int{}
+ for i := 0; i < n; i++ {
+ m[i] = 1
+ }
+ })
+
+ // ~7ms on a 1.6GHz Zeon.
+ // Regression test for CL 119360043.
+ checkLinear("iface", 10000, func(n int) {
+ m := map[I]int{}
+ for i := 0; i < n; i++ {
+ m[C(i)] = 1
+ }
+ })
+
+ // ~6ms on a 1.6GHz Zeon.
+ checkLinear("int", 10000, func(n int) {
+ m := map[int]int{}
+ for i := 0; i < n; i++ {
+ m[i] = 1
+ }
+ })
+
+ // ~18ms on a 1.6GHz Zeon.
+ checkLinear("string", 10000, func(n int) {
+ m := map[string]int{}
+ for i := 0; i < n; i++ {
+ m[fmt.Sprint(i)] = 1
+ }
+ })
+
+ // ~6ms on a 1.6GHz Zeon.
+ checkLinear("float32", 10000, func(n int) {
+ m := map[float32]int{}
+ for i := 0; i < n; i++ {
+ m[float32(i)] = 1
+ }
+ })
+
+ // ~6ms on a 1.6GHz Zeon.
+ checkLinear("float64", 10000, func(n int) {
+ m := map[float64]int{}
+ for i := 0; i < n; i++ {
+ m[float64(i)] = 1
+ }
+ })
+
+ // ~22ms on a 1.6GHz Zeon.
+ checkLinear("complex64", 10000, func(n int) {
+ m := map[complex64]int{}
+ for i := 0; i < n; i++ {
+ m[complex(float32(i), float32(i))] = 1
+ }
+ })
+
+ // ~32ms on a 1.6GHz Zeon.
+ checkLinear("complex128", 10000, func(n int) {
+ m := map[complex128]int{}
+ for i := 0; i < n; i++ {
+ m[complex(float64(i), float64(i))] = 1
+ }
+ })
+
+ // ~70ms on a 1.6GHz Zeon.
+ // The iterate/delete idiom currently takes expected
+ // O(n lg n) time. Fortunately, the checkLinear test
+ // leaves enough wiggle room to include n lg n time
+ // (it actually tests for O(n^log_2(3)).
+ // To prevent false positives, average away variation
+ // by doing multiple rounds within a single run.
+ checkLinear("iterdelete", 2500, func(n int) {
+ for round := 0; round < 4; round++ {
+ m := map[int]int{}
+ for i := 0; i < n; i++ {
+ m[i] = i
+ }
+ for i := 0; i < n; i++ {
+ for k := range m {
+ delete(m, k)
+ break
+ }
+ }
+ }
+ })
+}
diff --git a/platform/dbops/binaries/go/go/test/maymorestack.go b/platform/dbops/binaries/go/go/test/maymorestack.go
new file mode 100644
index 0000000000000000000000000000000000000000..ec84ad44bc42c85604fbac35db51a0d626f971b5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/maymorestack.go
@@ -0,0 +1,47 @@
+// run -gcflags=-d=maymorestack=main.mayMoreStack
+
+// 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.
+
+// Test the maymorestack testing hook by injecting a hook that counts
+// how many times it is called and checking that count.
+
+package main
+
+import "runtime"
+
+var count uint32
+
+//go:nosplit
+func mayMoreStack() {
+ count++
+}
+
+func main() {
+ const wantCount = 128
+
+ anotherFunc(wantCount - 1) // -1 because the call to main already counted
+
+ if count == 0 {
+ panic("mayMoreStack not called")
+ } else if count != wantCount {
+ println(count, "!=", wantCount)
+ panic("wrong number of calls to mayMoreStack")
+ }
+}
+
+//go:noinline
+func anotherFunc(n int) {
+ // Trigger a stack growth on at least some calls to
+ // anotherFunc to test that mayMoreStack is called outside the
+ // morestack loop. It's also important that it is called
+ // before (not after) morestack, but that's hard to test.
+ var x [1 << 10]byte
+
+ if n > 1 {
+ anotherFunc(n - 1)
+ }
+
+ runtime.KeepAlive(x)
+}
diff --git a/platform/dbops/binaries/go/go/test/mergemul.go b/platform/dbops/binaries/go/go/test/mergemul.go
new file mode 100644
index 0000000000000000000000000000000000000000..a23115b612392acd95a38c8b390b297abac031e8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/mergemul.go
@@ -0,0 +1,117 @@
+// runoutput
+
+// 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
+
+import "fmt"
+
+// Check that expressions like (c*n + d*(n+k)) get correctly merged by
+// the compiler into (c+d)*n + d*k (with c+d and d*k computed at
+// compile time).
+//
+// The merging is performed by a combination of the multiplication
+// merge rules
+// (c*n + d*n) -> (c+d)*n
+// and the distributive multiplication rules
+// c * (d+x) -> c*d + c*x
+
+// Generate a MergeTest that looks like this:
+//
+// a8, b8 = m1*n8 + m2*(n8+k), (m1+m2)*n8 + m2*k
+// if a8 != b8 {
+// // print error msg and panic
+// }
+func makeMergeAddTest(m1, m2, k int, size string) string {
+
+ model := " a" + size + ", b" + size
+ model += fmt.Sprintf(" = %%d*n%s + %%d*(n%s+%%d), (%%d+%%d)*n%s + (%%d*%%d)", size, size, size)
+
+ test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k)
+ test += fmt.Sprintf(`
+ if a%s != b%s {
+ fmt.Printf("MergeAddTest(%d, %d, %d, %s) failed\n")
+ fmt.Printf("%%d != %%d\n", a%s, b%s)
+ panic("FAIL")
+ }
+`, size, size, m1, m2, k, size, size, size)
+ return test + "\n"
+}
+
+// Check that expressions like (c*n - d*(n+k)) get correctly merged by
+// the compiler into (c-d)*n - d*k (with c-d and d*k computed at
+// compile time).
+//
+// The merging is performed by a combination of the multiplication
+// merge rules
+// (c*n - d*n) -> (c-d)*n
+// and the distributive multiplication rules
+// c * (d-x) -> c*d - c*x
+
+// Generate a MergeTest that looks like this:
+//
+// a8, b8 = m1*n8 - m2*(n8+k), (m1-m2)*n8 - m2*k
+// if a8 != b8 {
+// // print error msg and panic
+// }
+func makeMergeSubTest(m1, m2, k int, size string) string {
+
+ model := " a" + size + ", b" + size
+ model += fmt.Sprintf(" = %%d*n%s - %%d*(n%s+%%d), (%%d-%%d)*n%s - (%%d*%%d)", size, size, size)
+
+ test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k)
+ test += fmt.Sprintf(`
+ if a%s != b%s {
+ fmt.Printf("MergeSubTest(%d, %d, %d, %s) failed\n")
+ fmt.Printf("%%d != %%d\n", a%s, b%s)
+ panic("FAIL")
+ }
+`, size, size, m1, m2, k, size, size, size)
+ return test + "\n"
+}
+
+func makeAllSizes(m1, m2, k int) string {
+ var tests string
+ tests += makeMergeAddTest(m1, m2, k, "8")
+ tests += makeMergeAddTest(m1, m2, k, "16")
+ tests += makeMergeAddTest(m1, m2, k, "32")
+ tests += makeMergeAddTest(m1, m2, k, "64")
+ tests += makeMergeSubTest(m1, m2, k, "8")
+ tests += makeMergeSubTest(m1, m2, k, "16")
+ tests += makeMergeSubTest(m1, m2, k, "32")
+ tests += makeMergeSubTest(m1, m2, k, "64")
+ tests += "\n"
+ return tests
+}
+
+func main() {
+ fmt.Println(`package main
+
+import "fmt"
+
+var n8 int8 = 42
+var n16 int16 = 42
+var n32 int32 = 42
+var n64 int64 = 42
+
+func main() {
+ var a8, b8 int8
+ var a16, b16 int16
+ var a32, b32 int32
+ var a64, b64 int64
+`)
+
+ fmt.Println(makeAllSizes(03, 05, 0)) // 3*n + 5*n
+ fmt.Println(makeAllSizes(17, 33, 0))
+ fmt.Println(makeAllSizes(80, 45, 0))
+ fmt.Println(makeAllSizes(32, 64, 0))
+
+ fmt.Println(makeAllSizes(7, 11, +1)) // 7*n + 11*(n+1)
+ fmt.Println(makeAllSizes(9, 13, +2))
+ fmt.Println(makeAllSizes(11, 16, -1))
+ fmt.Println(makeAllSizes(17, 9, -2))
+
+ fmt.Println("}")
+}
diff --git a/platform/dbops/binaries/go/go/test/method.go b/platform/dbops/binaries/go/go/test/method.go
new file mode 100644
index 0000000000000000000000000000000000000000..d97bc4a7d0907b8014fe79ab27cca0308b189cea
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method.go
@@ -0,0 +1,307 @@
+// run
+
+// 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.
+
+// Test simple methods of various types, with pointer and
+// value receivers.
+
+package main
+
+type S string
+type S1 string
+type I int
+type I1 int
+type T struct {
+ x int
+}
+type T1 T
+
+func (s S) val() int { return 1 }
+func (s *S1) val() int { return 2 }
+func (i I) val() int { return 3 }
+func (i *I1) val() int { return 4 }
+func (t T) val() int { return 7 }
+func (t *T1) val() int { return 8 }
+
+type Val interface {
+ val() int
+}
+
+func val(v Val) int { return v.val() }
+
+func main() {
+ var s S
+ var ps *S1
+ var i I
+ var pi *I1
+ var pt *T1
+ var t T
+ var v Val
+
+ if s.val() != 1 {
+ println("s.val:", s.val())
+ panic("fail")
+ }
+ if S.val(s) != 1 {
+ println("S.val(s):", S.val(s))
+ panic("fail")
+ }
+ if (*S).val(&s) != 1 {
+ println("(*S).val(s):", (*S).val(&s))
+ panic("fail")
+ }
+ if ps.val() != 2 {
+ println("ps.val:", ps.val())
+ panic("fail")
+ }
+ if (*S1).val(ps) != 2 {
+ println("(*S1).val(ps):", (*S1).val(ps))
+ panic("fail")
+ }
+ if i.val() != 3 {
+ println("i.val:", i.val())
+ panic("fail")
+ }
+ if I.val(i) != 3 {
+ println("I.val(i):", I.val(i))
+ panic("fail")
+ }
+ if (*I).val(&i) != 3 {
+ println("(*I).val(&i):", (*I).val(&i))
+ panic("fail")
+ }
+ if pi.val() != 4 {
+ println("pi.val:", pi.val())
+ panic("fail")
+ }
+ if (*I1).val(pi) != 4 {
+ println("(*I1).val(pi):", (*I1).val(pi))
+ panic("fail")
+ }
+ if t.val() != 7 {
+ println("t.val:", t.val())
+ panic("fail")
+ }
+ if pt.val() != 8 {
+ println("pt.val:", pt.val())
+ panic("fail")
+ }
+ if (*T1).val(pt) != 8 {
+ println("(*T1).val(pt):", (*T1).val(pt))
+ panic("fail")
+ }
+
+ if val(s) != 1 {
+ println("val(s):", val(s))
+ panic("fail")
+ }
+ if val(ps) != 2 {
+ println("val(ps):", val(ps))
+ panic("fail")
+ }
+ if val(i) != 3 {
+ println("val(i):", val(i))
+ panic("fail")
+ }
+ if val(pi) != 4 {
+ println("val(pi):", val(pi))
+ panic("fail")
+ }
+ if val(t) != 7 {
+ println("val(t):", val(t))
+ panic("fail")
+ }
+ if val(pt) != 8 {
+ println("val(pt):", val(pt))
+ panic("fail")
+ }
+
+ if Val.val(i) != 3 {
+ println("Val.val(i):", Val.val(i))
+ panic("fail")
+ }
+ v = i
+ if Val.val(v) != 3 {
+ println("Val.val(v):", Val.val(v))
+ panic("fail")
+ }
+
+ var zs struct{ S }
+ var zps struct{ *S1 }
+ var zi struct{ I }
+ var zpi struct{ *I1 }
+ var zpt struct{ *T1 }
+ var zt struct{ T }
+ var zv struct{ Val }
+
+ if zs.val() != 1 {
+ println("zs.val:", zs.val())
+ panic("fail")
+ }
+ if zps.val() != 2 {
+ println("zps.val:", zps.val())
+ panic("fail")
+ }
+ if zi.val() != 3 {
+ println("zi.val:", zi.val())
+ panic("fail")
+ }
+ if zpi.val() != 4 {
+ println("zpi.val:", zpi.val())
+ panic("fail")
+ }
+ if zt.val() != 7 {
+ println("zt.val:", zt.val())
+ panic("fail")
+ }
+ if zpt.val() != 8 {
+ println("zpt.val:", zpt.val())
+ panic("fail")
+ }
+
+ if val(zs) != 1 {
+ println("val(zs):", val(zs))
+ panic("fail")
+ }
+ if val(zps) != 2 {
+ println("val(zps):", val(zps))
+ panic("fail")
+ }
+ if val(zi) != 3 {
+ println("val(zi):", val(zi))
+ panic("fail")
+ }
+ if val(zpi) != 4 {
+ println("val(zpi):", val(zpi))
+ panic("fail")
+ }
+ if val(zt) != 7 {
+ println("val(zt):", val(zt))
+ panic("fail")
+ }
+ if val(zpt) != 8 {
+ println("val(zpt):", val(zpt))
+ panic("fail")
+ }
+
+ zv.Val = zi
+ if zv.val() != 3 {
+ println("zv.val():", zv.val())
+ panic("fail")
+ }
+
+ if (&zs).val() != 1 {
+ println("(&zs).val:", (&zs).val())
+ panic("fail")
+ }
+ if (&zps).val() != 2 {
+ println("(&zps).val:", (&zps).val())
+ panic("fail")
+ }
+ if (&zi).val() != 3 {
+ println("(&zi).val:", (&zi).val())
+ panic("fail")
+ }
+ if (&zpi).val() != 4 {
+ println("(&zpi).val:", (&zpi).val())
+ panic("fail")
+ }
+ if (&zt).val() != 7 {
+ println("(&zt).val:", (&zt).val())
+ panic("fail")
+ }
+ if (&zpt).val() != 8 {
+ println("(&zpt).val:", (&zpt).val())
+ panic("fail")
+ }
+
+ if val(&zs) != 1 {
+ println("val(&zs):", val(&zs))
+ panic("fail")
+ }
+ if val(&zps) != 2 {
+ println("val(&zps):", val(&zps))
+ panic("fail")
+ }
+ if val(&zi) != 3 {
+ println("val(&zi):", val(&zi))
+ panic("fail")
+ }
+ if val(&zpi) != 4 {
+ println("val(&zpi):", val(&zpi))
+ panic("fail")
+ }
+ if val(&zt) != 7 {
+ println("val(&zt):", val(&zt))
+ panic("fail")
+ }
+ if val(&zpt) != 8 {
+ println("val(&zpt):", val(&zpt))
+ panic("fail")
+ }
+
+ zv.Val = &zi
+ if zv.val() != 3 {
+ println("zv.val():", zv.val())
+ panic("fail")
+ }
+
+ promotion()
+}
+
+type A struct{ B }
+type B struct {
+ C
+ *D
+}
+type C int
+
+func (C) f() {} // value receiver, direct field of A
+func (*C) g() {} // pointer receiver
+
+type D int
+
+func (D) h() {} // value receiver, indirect field of A
+func (*D) i() {} // pointer receiver
+
+func expectPanic() {
+ if r := recover(); r == nil {
+ panic("expected nil dereference")
+ }
+}
+
+func promotion() {
+ var a A
+ // Addressable value receiver.
+ a.f()
+ a.g()
+ func() {
+ defer expectPanic()
+ a.h() // dynamic error: nil dereference in a.B.D->f()
+ }()
+ a.i()
+
+ // Non-addressable value receiver.
+ A(a).f()
+ // A(a).g() // static error: cannot call pointer method on A literal.B.C
+ func() {
+ defer expectPanic()
+ A(a).h() // dynamic error: nil dereference in A().B.D->f()
+ }()
+ A(a).i()
+
+ // Pointer receiver.
+ (&a).f()
+ (&a).g()
+ func() {
+ defer expectPanic()
+ (&a).h() // dynamic error: nil deref: nil dereference in (&a).B.D->f()
+ }()
+ (&a).i()
+
+ c := new(C)
+ c.f() // makes a copy
+ c.g()
+}
diff --git a/platform/dbops/binaries/go/go/test/method1.go b/platform/dbops/binaries/go/go/test/method1.go
new file mode 100644
index 0000000000000000000000000000000000000000..badfa55a7e203f456f83420a6bc9c23435310d8b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method1.go
@@ -0,0 +1,24 @@
+// errorcheck
+
+// 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.
+
+// Verify that method redeclarations are caught by the compiler.
+// Does not compile.
+
+package main
+
+type T struct{}
+
+func (t *T) M(int, string) // GCCGO_ERROR "previous"
+func (t *T) M(int, float64) {} // ERROR "already declared|redefinition"
+
+func (t T) H() // GCCGO_ERROR "previous"
+func (t *T) H() {} // ERROR "already declared|redefinition"
+
+func f(int, string) // GCCGO_ERROR "previous"
+func f(int, float64) {} // ERROR "redeclared|redefinition"
+
+func g(a int, b string) // GCCGO_ERROR "previous"
+func g(a int, c string) // ERROR "redeclared|redefinition"
diff --git a/platform/dbops/binaries/go/go/test/method2.go b/platform/dbops/binaries/go/go/test/method2.go
new file mode 100644
index 0000000000000000000000000000000000000000..0a497b4b84c942a3029af700f8c727907787d8ad
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method2.go
@@ -0,0 +1,41 @@
+// errorcheck
+
+// 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.
+
+// Verify that pointers and interface types cannot be method receivers.
+// Does not compile.
+
+package main
+
+type T struct {
+ a int
+}
+type P *T
+type P1 *T
+
+func (p P) val() int { return 1 } // ERROR "receiver.* pointer|invalid pointer or interface receiver|invalid receiver"
+func (p *P1) val() int { return 1 } // ERROR "receiver.* pointer|invalid pointer or interface receiver|invalid receiver"
+
+type I interface{}
+type I1 interface{}
+
+func (p I) val() int { return 1 } // ERROR "receiver.*interface|invalid pointer or interface receiver"
+func (p *I1) val() int { return 1 } // ERROR "receiver.*interface|invalid pointer or interface receiver"
+
+type Val interface {
+ val() int
+}
+
+var _ = (*Val).val // ERROR "method|type \*Val is pointer to interface, not interface"
+
+var v Val
+var pv = &v
+
+var _ = pv.val() // ERROR "undefined|pointer to interface"
+var _ = pv.val // ERROR "undefined|pointer to interface"
+
+func (t *T) g() int { return t.a }
+
+var _ = (T).g() // ERROR "needs pointer receiver|undefined|method requires pointer|cannot call pointer method"
diff --git a/platform/dbops/binaries/go/go/test/method3.go b/platform/dbops/binaries/go/go/test/method3.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd64771527ed07cefb3359189f6ba900193e6842
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method3.go
@@ -0,0 +1,35 @@
+// run
+
+// 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.
+
+// Test methods on slices.
+
+package main
+
+type T []int
+
+func (t T) Len() int { return len(t) }
+
+type I interface {
+ Len() int
+}
+
+func main() {
+ var t T = T{0, 1, 2, 3, 4}
+ var i I
+ i = t
+ if i.Len() != 5 {
+ println("i.Len", i.Len())
+ panic("fail")
+ }
+ if T.Len(t) != 5 {
+ println("T.Len", T.Len(t))
+ panic("fail")
+ }
+ if (*T).Len(&t) != 5 {
+ println("(*T).Len", (*T).Len(&t))
+ panic("fail")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/method4.go b/platform/dbops/binaries/go/go/test/method4.go
new file mode 100644
index 0000000000000000000000000000000000000000..813892bc830b05f06891ca0e87b0ec55dd889952
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method4.go
@@ -0,0 +1,8 @@
+// rundir
+
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Test method expressions with arguments.
+package ignored
diff --git a/platform/dbops/binaries/go/go/test/method5.go b/platform/dbops/binaries/go/go/test/method5.go
new file mode 100644
index 0000000000000000000000000000000000000000..d87bb6f5b27d0e586d57cff141d7bbbf852c34cb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method5.go
@@ -0,0 +1,297 @@
+// run
+
+// 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 main
+
+// Concrete types implementing M method.
+// Smaller than a word, word-sized, larger than a word.
+// Value and pointer receivers.
+
+type Tinter interface {
+ M(int, byte) (byte, int)
+}
+
+type Tsmallv byte
+
+func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x+int(v) }
+
+type Tsmallp byte
+
+func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x+int(*p) }
+
+type Twordv uintptr
+
+func (v Twordv) M(x int, b byte) (byte, int) { return b, x+int(v) }
+
+type Twordp uintptr
+
+func (p *Twordp) M(x int, b byte) (byte, int) { return b, x+int(*p) }
+
+type Tbigv [2]uintptr
+
+func (v Tbigv) M(x int, b byte) (byte, int) { return b, x+int(v[0])+int(v[1]) }
+
+type Tbigp [2]uintptr
+
+func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x+int(p[0])+int(p[1]) }
+
+// Again, with an unexported method.
+
+type tsmallv byte
+
+func (v tsmallv) m(x int, b byte) (byte, int) { return b, x+int(v) }
+
+type tsmallp byte
+
+func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x+int(*p) }
+
+type twordv uintptr
+
+func (v twordv) m(x int, b byte) (byte, int) { return b, x+int(v) }
+
+type twordp uintptr
+
+func (p *twordp) m(x int, b byte) (byte, int) { return b, x+int(*p) }
+
+type tbigv [2]uintptr
+
+func (v tbigv) m(x int, b byte) (byte, int) { return b, x+int(v[0])+int(v[1]) }
+
+type tbigp [2]uintptr
+
+func (p *tbigp) m(x int, b byte) (byte, int) { return b, x+int(p[0])+int(p[1]) }
+
+type tinter interface {
+ m(int, byte) (byte, int)
+}
+
+// Embedding via pointer.
+
+type T1 struct {
+ T2
+}
+
+type T2 struct {
+ *T3
+}
+
+type T3 struct {
+ *T4
+}
+
+type T4 struct {
+}
+
+func (t4 T4) M(x int, b byte) (byte, int) { return b, x+40 }
+
+var failed = false
+
+func CheckI(name string, i Tinter, inc int) {
+ b, x := i.M(1000, 99)
+ if b != 99 || x != 1000+inc {
+ failed = true
+ print(name, ".M(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
+ }
+
+ CheckF("(i="+name+")", i.M, inc)
+}
+
+func CheckF(name string, f func(int, byte) (byte, int), inc int) {
+ b, x := f(1000, 99)
+ if b != 99 || x != 1000+inc {
+ failed = true
+ print(name, "(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
+ }
+}
+
+func checkI(name string, i tinter, inc int) {
+ b, x := i.m(1000, 99)
+ if b != 99 || x != 1000+inc {
+ failed = true
+ print(name, ".m(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
+ }
+
+ checkF("(i="+name+")", i.m, inc)
+}
+
+func checkF(name string, f func(int, byte) (byte, int), inc int) {
+ b, x := f(1000, 99)
+ if b != 99 || x != 1000+inc {
+ failed = true
+ print(name, "(1000, 99) = ", b, ", ", x, " want 99, ", 1000+inc, "\n")
+ }
+}
+
+func shouldPanic(f func()) {
+ defer func() {
+ if recover() == nil {
+ panic("not panicking")
+ }
+ }()
+ f()
+}
+
+func shouldNotPanic(f func()) {
+ f()
+}
+
+func main() {
+ sv := Tsmallv(1)
+ CheckI("sv", sv, 1)
+ CheckF("sv.M", sv.M, 1)
+ CheckF("(&sv).M", (&sv).M, 1)
+ psv := &sv
+ CheckI("psv", psv, 1)
+ CheckF("psv.M", psv.M, 1)
+ CheckF("(*psv).M", (*psv).M, 1)
+
+ sp := Tsmallp(2)
+ CheckI("&sp", &sp, 2)
+ CheckF("sp.M", sp.M, 2)
+ CheckF("(&sp).M", (&sp).M, 2)
+ psp := &sp
+ CheckI("psp", psp, 2)
+ CheckF("psp.M", psp.M, 2)
+ CheckF("(*psp).M", (*psp).M, 2)
+
+ wv := Twordv(3)
+ CheckI("wv", wv, 3)
+ CheckF("wv.M", wv.M, 3)
+ CheckF("(&wv).M", (&wv).M, 3)
+ pwv := &wv
+ CheckI("pwv", pwv, 3)
+ CheckF("pwv.M", pwv.M, 3)
+ CheckF("(*pwv).M", (*pwv).M, 3)
+
+ wp := Twordp(4)
+ CheckI("&wp", &wp, 4)
+ CheckF("wp.M", wp.M, 4)
+ CheckF("(&wp).M", (&wp).M, 4)
+ pwp := &wp
+ CheckI("pwp", pwp, 4)
+ CheckF("pwp.M", pwp.M, 4)
+ CheckF("(*pwp).M", (*pwp).M, 4)
+
+ bv := Tbigv([2]uintptr{5, 6})
+ pbv := &bv
+ CheckI("bv", bv, 11)
+ CheckF("bv.M", bv.M, 11)
+ CheckF("(&bv).M", (&bv).M, 11)
+ CheckI("pbv", pbv, 11)
+ CheckF("pbv.M", pbv.M, 11)
+ CheckF("(*pbv).M", (*pbv).M, 11)
+
+ bp := Tbigp([2]uintptr{7,8})
+ CheckI("&bp", &bp, 15)
+ CheckF("bp.M", bp.M, 15)
+ CheckF("(&bp).M", (&bp).M, 15)
+ pbp := &bp
+ CheckI("pbp", pbp, 15)
+ CheckF("pbp.M", pbp.M, 15)
+ CheckF("(*pbp).M", (*pbp).M, 15)
+
+ _sv := tsmallv(1)
+ checkI("_sv", _sv, 1)
+ checkF("_sv.m", _sv.m, 1)
+ checkF("(&_sv).m", (&_sv).m, 1)
+ _psv := &_sv
+ checkI("_psv", _psv, 1)
+ checkF("_psv.m", _psv.m, 1)
+ checkF("(*_psv).m", (*_psv).m, 1)
+
+ _sp := tsmallp(2)
+ checkI("&_sp", &_sp, 2)
+ checkF("_sp.m", _sp.m, 2)
+ checkF("(&_sp).m", (&_sp).m, 2)
+ _psp := &_sp
+ checkI("_psp", _psp, 2)
+ checkF("_psp.m", _psp.m, 2)
+ checkF("(*_psp).m", (*_psp).m, 2)
+
+ _wv := twordv(3)
+ checkI("_wv", _wv, 3)
+ checkF("_wv.m", _wv.m, 3)
+ checkF("(&_wv).m", (&_wv).m, 3)
+ _pwv := &_wv
+ checkI("_pwv", _pwv, 3)
+ checkF("_pwv.m", _pwv.m, 3)
+ checkF("(*_pwv).m", (*_pwv).m, 3)
+
+ _wp := twordp(4)
+ checkI("&_wp", &_wp, 4)
+ checkF("_wp.m", _wp.m, 4)
+ checkF("(&_wp).m", (&_wp).m, 4)
+ _pwp := &_wp
+ checkI("_pwp", _pwp, 4)
+ checkF("_pwp.m", _pwp.m, 4)
+ checkF("(*_pwp).m", (*_pwp).m, 4)
+
+ _bv := tbigv([2]uintptr{5, 6})
+ _pbv := &_bv
+ checkI("_bv", _bv, 11)
+ checkF("_bv.m", _bv.m, 11)
+ checkF("(&_bv).m", (&_bv).m, 11)
+ checkI("_pbv", _pbv, 11)
+ checkF("_pbv.m", _pbv.m, 11)
+ checkF("(*_pbv).m", (*_pbv).m, 11)
+
+ _bp := tbigp([2]uintptr{7,8})
+ checkI("&_bp", &_bp, 15)
+ checkF("_bp.m", _bp.m, 15)
+ checkF("(&_bp).m", (&_bp).m, 15)
+ _pbp := &_bp
+ checkI("_pbp", _pbp, 15)
+ checkF("_pbp.m", _pbp.m, 15)
+ checkF("(*_pbp).m", (*_pbp).m, 15)
+
+ t4 := T4{}
+ t3 := T3{&t4}
+ t2 := T2{&t3}
+ t1 := T1{t2}
+ CheckI("t4", t4, 40)
+ CheckI("&t4", &t4, 40)
+ CheckI("t3", t3, 40)
+ CheckI("&t3", &t3, 40)
+ CheckI("t2", t2, 40)
+ CheckI("&t2", &t2, 40)
+ CheckI("t1", t1, 40)
+ CheckI("&t1", &t1, 40)
+
+ // x.M panics if x is an interface type and is nil,
+ // or if x.M expands to (*x).M where x is nil,
+ // or if x.M expands to x.y.z.w.M where something
+ // along the evaluation of x.y.z.w is nil.
+ var f func(int, byte) (byte, int)
+ shouldPanic(func() { psv = nil; f = psv.M })
+ shouldPanic(func() { pwv = nil; f = pwv.M })
+ shouldPanic(func() { pbv = nil; f = pbv.M })
+ shouldPanic(func() { var i Tinter; f = i.M })
+ shouldPanic(func() { _psv = nil; f = _psv.m })
+ shouldPanic(func() { _pwv = nil; f = _pwv.m })
+ shouldPanic(func() { _pbv = nil; f = _pbv.m })
+ shouldPanic(func() { var _i tinter; f = _i.m })
+ shouldPanic(func() { var t1 T1; f = t1.M })
+ shouldPanic(func() { var t2 T2; f = t2.M })
+ shouldPanic(func() { var t3 *T3; f = t3.M })
+ shouldPanic(func() { var t3 T3; f = t3.M })
+
+ if f != nil {
+ panic("something set f")
+ }
+
+ // x.M does not panic if x is a nil pointer and
+ // M is a method with a pointer receiver.
+ shouldNotPanic(func() { psp = nil; f = psp.M })
+ shouldNotPanic(func() { pwp = nil; f = pwp.M })
+ shouldNotPanic(func() { pbp = nil; f = pbp.M })
+ shouldNotPanic(func() { _psp = nil; f = _psp.m })
+ shouldNotPanic(func() { _pwp = nil; f = _pwp.m })
+ shouldNotPanic(func() { _pbp = nil; f = _pbp.m })
+ shouldNotPanic(func() { var t4 T4; f = t4.M })
+ if f == nil {
+ panic("nothing set f")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/method6.go b/platform/dbops/binaries/go/go/test/method6.go
new file mode 100644
index 0000000000000000000000000000000000000000..ede3467c5c26c3aa558dbe3e2a763b66f775f457
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method6.go
@@ -0,0 +1,22 @@
+// errorcheck
+
+// 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.
+
+// Verify that pointer method calls are caught during typechecking.
+// Reproducer extracted and adapted from method.go
+
+package foo
+
+type A struct {
+ B
+}
+type B int
+
+func (*B) g() {}
+
+var _ = func() {
+ var a A
+ A(a).g() // ERROR "cannot call pointer method .*on|cannot take the address of"
+}
diff --git a/platform/dbops/binaries/go/go/test/method7.go b/platform/dbops/binaries/go/go/test/method7.go
new file mode 100644
index 0000000000000000000000000000000000000000..05accb3ee04d8869dfdaf8006c057d9cd232e7be
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/method7.go
@@ -0,0 +1,67 @@
+// run
+
+// 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.
+
+// Test forms of method expressions T.m where T is
+// a literal type.
+
+package main
+
+var got, want string
+
+type I interface {
+ m()
+}
+
+type S struct {
+}
+
+func (S) m() { got += " m()" }
+func (S) m1(s string) { got += " m1(" + s + ")" }
+
+type T int
+
+func (T) m2() { got += " m2()" }
+
+type Outer struct{ *Inner }
+type Inner struct{ s string }
+
+func (i Inner) M() string { return i.s }
+
+func main() {
+ // method expressions with named receiver types
+ I.m(S{})
+ want += " m()"
+
+ S.m1(S{}, "a")
+ want += " m1(a)"
+
+ // method expressions with literal receiver types
+ f := interface{ m1(string) }.m1
+ f(S{}, "b")
+ want += " m1(b)"
+
+ interface{ m1(string) }.m1(S{}, "c")
+ want += " m1(c)"
+
+ x := S{}
+ interface{ m1(string) }.m1(x, "d")
+ want += " m1(d)"
+
+ g := struct{ T }.m2
+ g(struct{ T }{})
+ want += " m2()"
+
+ if got != want {
+ panic("got" + got + ", want" + want)
+ }
+
+ h := (*Outer).M
+ got := h(&Outer{&Inner{"hello"}})
+ want := "hello"
+ if got != want {
+ panic("got " + got + ", want " + want)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/named.go b/platform/dbops/binaries/go/go/test/named.go
new file mode 100644
index 0000000000000000000000000000000000000000..9763c76bfdf278ec98d60f2d1802ec1aee14105b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/named.go
@@ -0,0 +1,281 @@
+// run
+
+// 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.
+
+// Test that basic operations on named types are valid
+// and preserve the type.
+
+package main
+
+type Array [10]byte
+type Bool bool
+type Chan chan int
+type Float float32
+type Int int
+type Map map[int]byte
+type Slice []byte
+type String string
+
+// Calling these functions checks at compile time that the argument
+// can be converted implicitly to (used as) the given type.
+func asArray(Array) {}
+func asBool(Bool) {}
+func asChan(Chan) {}
+func asFloat(Float) {}
+func asInt(Int) {}
+func asMap(Map) {}
+func asSlice(Slice) {}
+func asString(String) {}
+
+func (Map) M() {}
+
+
+// These functions check at run time that the default type
+// (in the absence of any implicit conversion hints)
+// is the given type.
+func isArray(x interface{}) { _ = x.(Array) }
+func isBool(x interface{}) { _ = x.(Bool) }
+func isChan(x interface{}) { _ = x.(Chan) }
+func isFloat(x interface{}) { _ = x.(Float) }
+func isInt(x interface{}) { _ = x.(Int) }
+func isMap(x interface{}) { _ = x.(Map) }
+func isSlice(x interface{}) { _ = x.(Slice) }
+func isString(x interface{}) { _ = x.(String) }
+
+func main() {
+ var (
+ a Array
+ b Bool = true
+ c Chan = make(Chan)
+ f Float = 1
+ i Int = 1
+ m Map = make(Map)
+ slice Slice = make(Slice, 10)
+ str String = "hello"
+ )
+
+ asArray(a)
+ isArray(a)
+ asArray(*&a)
+ isArray(*&a)
+ asArray(Array{})
+ isArray(Array{})
+
+ asBool(b)
+ isBool(b)
+ asBool(!b)
+ isBool(!b)
+ asBool(true)
+ asBool(*&b)
+ isBool(*&b)
+ asBool(Bool(true))
+ isBool(Bool(true))
+
+ asChan(c)
+ isChan(c)
+ asChan(make(Chan))
+ isChan(make(Chan))
+ asChan(*&c)
+ isChan(*&c)
+ asChan(Chan(nil))
+ isChan(Chan(nil))
+
+ asFloat(f)
+ isFloat(f)
+ asFloat(-f)
+ isFloat(-f)
+ asFloat(+f)
+ isFloat(+f)
+ asFloat(f + 1)
+ isFloat(f + 1)
+ asFloat(1 + f)
+ isFloat(1 + f)
+ asFloat(f + f)
+ isFloat(f + f)
+ f++
+ f += 2
+ asFloat(f - 1)
+ isFloat(f - 1)
+ asFloat(1 - f)
+ isFloat(1 - f)
+ asFloat(f - f)
+ isFloat(f - f)
+ f--
+ f -= 2
+ asFloat(f * 2.5)
+ isFloat(f * 2.5)
+ asFloat(2.5 * f)
+ isFloat(2.5 * f)
+ asFloat(f * f)
+ isFloat(f * f)
+ f *= 4
+ asFloat(f / 2.5)
+ isFloat(f / 2.5)
+ asFloat(2.5 / f)
+ isFloat(2.5 / f)
+ asFloat(f / f)
+ isFloat(f / f)
+ f /= 4
+ asFloat(f)
+ isFloat(f)
+ f = 5
+ asFloat(*&f)
+ isFloat(*&f)
+ asFloat(234)
+ asFloat(Float(234))
+ isFloat(Float(234))
+ asFloat(1.2)
+ asFloat(Float(i))
+ isFloat(Float(i))
+
+ asInt(i)
+ isInt(i)
+ asInt(-i)
+ isInt(-i)
+ asInt(^i)
+ isInt(^i)
+ asInt(+i)
+ isInt(+i)
+ asInt(i + 1)
+ isInt(i + 1)
+ asInt(1 + i)
+ isInt(1 + i)
+ asInt(i + i)
+ isInt(i + i)
+ i++
+ i += 1
+ asInt(i - 1)
+ isInt(i - 1)
+ asInt(1 - i)
+ isInt(1 - i)
+ asInt(i - i)
+ isInt(i - i)
+ i--
+ i -= 1
+ asInt(i * 2)
+ isInt(i * 2)
+ asInt(2 * i)
+ isInt(2 * i)
+ asInt(i * i)
+ isInt(i * i)
+ i *= 2
+ asInt(i / 5)
+ isInt(i / 5)
+ asInt(5 / i)
+ isInt(5 / i)
+ asInt(i / i)
+ isInt(i / i)
+ i /= 2
+ asInt(i % 5)
+ isInt(i % 5)
+ asInt(5 % i)
+ isInt(5 % i)
+ asInt(i % i)
+ isInt(i % i)
+ i %= 2
+ asInt(i & 5)
+ isInt(i & 5)
+ asInt(5 & i)
+ isInt(5 & i)
+ asInt(i & i)
+ isInt(i & i)
+ i &= 2
+ asInt(i &^ 5)
+ isInt(i &^ 5)
+ asInt(5 &^ i)
+ isInt(5 &^ i)
+ asInt(i &^ i)
+ isInt(i &^ i)
+ i &^= 2
+ asInt(i | 5)
+ isInt(i | 5)
+ asInt(5 | i)
+ isInt(5 | i)
+ asInt(i | i)
+ isInt(i | i)
+ i |= 2
+ asInt(i ^ 5)
+ isInt(i ^ 5)
+ asInt(5 ^ i)
+ isInt(5 ^ i)
+ asInt(i ^ i)
+ isInt(i ^ i)
+ i ^= 2
+ asInt(i << 4)
+ isInt(i << 4)
+ i <<= 2
+ asInt(i >> 4)
+ isInt(i >> 4)
+ i >>= 2
+ asInt(i)
+ isInt(i)
+ asInt(0)
+ asInt(Int(0))
+ isInt(Int(0))
+ i = 10
+ asInt(*&i)
+ isInt(*&i)
+ asInt(23)
+ asInt(Int(f))
+ isInt(Int(f))
+
+ asMap(m)
+ isMap(m)
+ asMap(nil)
+ m = nil
+ asMap(make(Map))
+ isMap(make(Map))
+ asMap(*&m)
+ isMap(*&m)
+ asMap(Map(nil))
+ isMap(Map(nil))
+ asMap(Map{})
+ isMap(Map{})
+
+ asSlice(slice)
+ isSlice(slice)
+ asSlice(make(Slice, 5))
+ isSlice(make(Slice, 5))
+ asSlice([]byte{1, 2, 3})
+ asSlice([]byte{1, 2, 3}[0:2])
+ asSlice(slice[0:4])
+ isSlice(slice[0:4])
+ asSlice(slice[3:8])
+ isSlice(slice[3:8])
+ asSlice(nil)
+ asSlice(Slice(nil))
+ isSlice(Slice(nil))
+ slice = nil
+ asSlice(Slice{1, 2, 3})
+ isSlice(Slice{1, 2, 3})
+ asSlice(Slice{})
+ isSlice(Slice{})
+ asSlice(*&slice)
+ isSlice(*&slice)
+
+ asString(str)
+ isString(str)
+ asString(str + "a")
+ isString(str + "a")
+ asString("a" + str)
+ isString("a" + str)
+ asString(str + str)
+ isString(str + str)
+ str += "a"
+ str += str
+ asString(String('a'))
+ isString(String('a'))
+ asString(String([]byte(slice)))
+ isString(String([]byte(slice)))
+ asString(String([]byte(nil)))
+ isString(String([]byte(nil)))
+ asString("hello")
+ asString(String("hello"))
+ isString(String("hello"))
+ str = "hello"
+ isString(str)
+ asString(*&str)
+ isString(*&str)
+}
diff --git a/platform/dbops/binaries/go/go/test/named1.go b/platform/dbops/binaries/go/go/test/named1.go
new file mode 100644
index 0000000000000000000000000000000000000000..452c6da27e259c543fc9833578a0a1bc63bff7b8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/named1.go
@@ -0,0 +1,62 @@
+// errorcheck
+
+// 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.
+
+// Test that basic operations on named types are valid
+// and preserve the type.
+// Does not compile.
+
+package main
+
+type Bool bool
+
+type Map map[int]int
+
+func (Map) M() {}
+
+type Slice []byte
+
+var slice Slice
+
+func asBool(Bool) {}
+func asString(String) {}
+
+type String string
+
+func main() {
+ var (
+ b Bool = true
+ i, j int
+ c = make(chan int)
+ m = make(Map)
+ )
+
+ asBool(b)
+ asBool(!b)
+ asBool(true)
+ asBool(*&b)
+ asBool(Bool(true))
+ asBool(1 != 2) // ok now
+ asBool(i < j) // ok now
+
+ _, b = m[2] // ok now
+
+ var inter interface{}
+ _, b = inter.(Map) // ok now
+ _ = b
+
+ var minter interface {
+ M()
+ }
+ _, b = minter.(Map) // ok now
+ _ = b
+
+ _, bb := <-c
+ asBool(bb) // ERROR "cannot use.*type bool.*as type Bool|cannot use bb"
+ _, b = <-c // ok now
+ _ = b
+
+ asString(String(slice)) // ok
+}
diff --git a/platform/dbops/binaries/go/go/test/newinline.go b/platform/dbops/binaries/go/go/test/newinline.go
new file mode 100644
index 0000000000000000000000000000000000000000..69f1310ab2f3f41fedd88cdcf25a2d31ea7549ee
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/newinline.go
@@ -0,0 +1,397 @@
+// errorcheckwithauto -0 -m -d=inlfuncswithclosures=1
+
+//go:build goexperiment.newinliner
+
+// 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, using compiler diagnostic flags, that inlining is working.
+// Compiles but does not run.
+
+package foo
+
+import (
+ "errors"
+ "runtime"
+ "unsafe"
+)
+
+func add2(p *byte, n uintptr) *byte { // ERROR "can inline add2" "leaking param: p to result"
+ return (*byte)(add1(unsafe.Pointer(p), n)) // ERROR "inlining call to add1"
+}
+
+func add1(p unsafe.Pointer, x uintptr) unsafe.Pointer { // ERROR "can inline add1" "leaking param: p to result"
+ return unsafe.Pointer(uintptr(p) + x)
+}
+
+func f(x *byte) *byte { // ERROR "can inline f" "leaking param: x to result"
+ return add2(x, 1) // ERROR "inlining call to add2" "inlining call to add1"
+}
+
+//go:noinline
+func g(x int) int {
+ return x + 1
+}
+
+func h(x int) int { // ERROR "can inline h"
+ return x + 2
+}
+
+func i(x int) int { // ERROR "can inline i"
+ const y = 2
+ return x + y
+}
+
+func j(x int) int { // ERROR "can inline j"
+ switch {
+ case x > 0:
+ return x + 2
+ default:
+ return x + 1
+ }
+}
+
+func f2() int { // ERROR "can inline f2"
+ tmp1 := h
+ tmp2 := tmp1
+ return tmp2(0) // ERROR "inlining call to h"
+}
+
+var abc = errors.New("abc") // ERROR "inlining call to errors.New"
+
+var somethingWrong error
+
+// local closures can be inlined
+func l(x, y int) (int, int, error) { // ERROR "can inline l"
+ e := func(err error) (int, int, error) { // ERROR "can inline l.func1" "func literal does not escape" "leaking param: err to result"
+ return 0, 0, err
+ }
+ if x == y {
+ e(somethingWrong) // ERROR "inlining call to l.func1"
+ } else {
+ f := e
+ f(nil) // ERROR "inlining call to l.func1"
+ }
+ return y, x, nil
+}
+
+// any re-assignment prevents closure inlining
+func m() int {
+ foo := func() int { return 1 } // ERROR "can inline m.func1" "func literal does not escape"
+ x := foo()
+ foo = func() int { return 2 } // ERROR "can inline m.func2" "func literal does not escape"
+ return x + foo()
+}
+
+// address taking prevents closure inlining
+func n() int { // ERROR "can inline n"
+ foo := func() int { return 1 } // ERROR "can inline n.func1" "func literal does not escape"
+ bar := &foo
+ x := (*bar)() + foo()
+ return x
+}
+
+// make sure assignment inside closure is detected
+func o() int { // ERROR "can inline o"
+ foo := func() int { return 1 } // ERROR "can inline o.func1" "func literal does not escape"
+ func(x int) { // ERROR "can inline o.func2"
+ if x > 10 {
+ foo = func() int { return 2 } // ERROR "can inline o.func2"
+ }
+ }(11) // ERROR "func literal does not escape" "inlining call to o.func2"
+ return foo()
+}
+
+func p() int { // ERROR "can inline p"
+ return func() int { return 42 }() // ERROR "can inline p.func1" "inlining call to p.func1"
+}
+
+func q(x int) int { // ERROR "can inline q"
+ foo := func() int { return x * 2 } // ERROR "can inline q.func1" "func literal does not escape"
+ return foo() // ERROR "inlining call to q.func1"
+}
+
+func r(z int) int { // ERROR "can inline r"
+ foo := func(x int) int { // ERROR "can inline r.func1" "func literal does not escape"
+ return x + z
+ }
+ bar := func(x int) int { // ERROR "func literal does not escape" "can inline r.func2"
+ return x + func(y int) int { // ERROR "can inline r.func2.1" "can inline r.r.func2.func3"
+ return 2*y + x*z
+ }(x) // ERROR "inlining call to r.func2.1"
+ }
+ return foo(42) + bar(42) // ERROR "inlining call to r.func1" "inlining call to r.func2" "inlining call to r.r.func2.func3"
+}
+
+func s0(x int) int { // ERROR "can inline s0"
+ foo := func() { // ERROR "can inline s0.func1" "func literal does not escape"
+ x = x + 1
+ }
+ foo() // ERROR "inlining call to s0.func1"
+ return x
+}
+
+func s1(x int) int { // ERROR "can inline s1"
+ foo := func() int { // ERROR "can inline s1.func1" "func literal does not escape"
+ return x
+ }
+ x = x + 1
+ return foo() // ERROR "inlining call to s1.func1"
+}
+
+func switchBreak(x, y int) int { // ERROR "can inline switchBreak"
+ var n int
+ switch x {
+ case 0:
+ n = 1
+ Done:
+ switch y {
+ case 0:
+ n += 10
+ break Done
+ }
+ n = 2
+ }
+ return n
+}
+
+func switchType(x interface{}) int { // ERROR "can inline switchType" "x does not escape"
+ switch x.(type) {
+ case int:
+ return x.(int)
+ default:
+ return 0
+ }
+}
+
+// Test that switches on constant things, with constant cases, only cost anything for
+// the case that matches. See issue 50253.
+func switchConst1(p func(string)) { // ERROR "can inline switchConst" "p does not escape"
+ const c = 1
+ switch c {
+ case 0:
+ p("zero")
+ case 1:
+ p("one")
+ case 2:
+ p("two")
+ default:
+ p("other")
+ }
+}
+
+func switchConst2() string { // ERROR "can inline switchConst2"
+ switch runtime.GOOS {
+ case "linux":
+ return "Leenooks"
+ case "windows":
+ return "Windoze"
+ case "darwin":
+ return "MackBone"
+ case "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100":
+ return "Numbers"
+ default:
+ return "oh nose!"
+ }
+}
+func switchConst3() string { // ERROR "can inline switchConst3"
+ switch runtime.GOOS {
+ case "Linux":
+ panic("Linux")
+ case "Windows":
+ panic("Windows")
+ case "Darwin":
+ panic("Darwin")
+ case "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100":
+ panic("Numbers")
+ default:
+ return "oh nose!"
+ }
+}
+func switchConst4() { // ERROR "can inline switchConst4"
+ const intSize = 32 << (^uint(0) >> 63)
+ want := func() string { // ERROR "can inline switchConst4.func1"
+ switch intSize {
+ case 32:
+ return "32"
+ case 64:
+ return "64"
+ default:
+ panic("unreachable")
+ }
+ }() // ERROR "inlining call to switchConst4.func1"
+ _ = want
+}
+
+func inlineRangeIntoMe(data []int) { // ERROR "can inline inlineRangeIntoMe" "data does not escape"
+ rangeFunc(data, 12) // ERROR "inlining call to rangeFunc"
+}
+
+func rangeFunc(xs []int, b int) int { // ERROR "can inline rangeFunc" "xs does not escape"
+ for i, x := range xs {
+ if x == b {
+ return i
+ }
+ }
+ return -1
+}
+
+type T struct{}
+
+func (T) meth(int, int) {} // ERROR "can inline T.meth"
+
+func k() (T, int, int) { return T{}, 0, 0 } // ERROR "can inline k"
+
+func f3() { // ERROR "can inline f3"
+ T.meth(k()) // ERROR "inlining call to k" "inlining call to T.meth"
+ // ERRORAUTO "inlining call to T.meth"
+}
+
+func small1() { // ERROR "can inline small1"
+ runtime.GC()
+}
+func small2() int { // ERROR "can inline small2"
+ return runtime.GOMAXPROCS(0)
+}
+func small3(t T) { // ERROR "can inline small3"
+ t.meth2(3, 5)
+}
+func small4(t T) { // ERROR "can inline small4"
+ t.meth2(runtime.GOMAXPROCS(0), 5)
+}
+func (T) meth2(int, int) { // ERROR "can inline T.meth2"
+ runtime.GC()
+ runtime.GC()
+}
+
+// Issue #29737 - make sure we can do inlining for a chain of recursive functions
+func ee() { // ERROR "can inline ee"
+ ff(100) // ERROR "inlining call to ff" "inlining call to gg" "inlining call to hh"
+}
+
+func ff(x int) { // ERROR "can inline ff"
+ if x < 0 {
+ return
+ }
+ gg(x - 1) // ERROR "inlining call to gg" "inlining call to hh"
+}
+func gg(x int) { // ERROR "can inline gg"
+ hh(x - 1) // ERROR "inlining call to hh" "inlining call to ff"
+}
+func hh(x int) { // ERROR "can inline hh"
+ ff(x - 1) // ERROR "inlining call to ff" "inlining call to gg"
+}
+
+// Issue #14768 - make sure we can inline for loops.
+func for1(fn func() bool) { // ERROR "can inline for1" "fn does not escape"
+ for {
+ if fn() {
+ break
+ } else {
+ continue
+ }
+ }
+}
+
+func for2(fn func() bool) { // ERROR "can inline for2" "fn does not escape"
+Loop:
+ for {
+ if fn() {
+ break Loop
+ } else {
+ continue Loop
+ }
+ }
+}
+
+// Issue #18493 - make sure we can do inlining of functions with a method value
+type T1 struct{}
+
+func (a T1) meth(val int) int { // ERROR "can inline T1.meth"
+ return val + 5
+}
+
+func getMeth(t1 T1) func(int) int { // ERROR "can inline getMeth"
+ return t1.meth // ERROR "t1.meth escapes to heap"
+ // ERRORAUTO "inlining call to T1.meth"
+}
+
+func ii() { // ERROR "can inline ii"
+ var t1 T1
+ f := getMeth(t1) // ERROR "inlining call to getMeth" "t1.meth does not escape"
+ _ = f(3)
+}
+
+// Issue #42194 - make sure that functions evaluated in
+// go and defer statements can be inlined.
+func gd1(int) {
+ defer gd1(gd2()) // ERROR "inlining call to gd2" "can inline gd1.deferwrap1"
+ defer gd3()() // ERROR "inlining call to gd3"
+ go gd1(gd2()) // ERROR "inlining call to gd2" "can inline gd1.gowrap2"
+ go gd3()() // ERROR "inlining call to gd3"
+}
+
+func gd2() int { // ERROR "can inline gd2"
+ return 1
+}
+
+func gd3() func() { // ERROR "can inline gd3"
+ return ii
+}
+
+// Issue #42788 - ensure ODEREF OCONVNOP* OADDR is low cost.
+func EncodeQuad(d []uint32, x [6]float32) { // ERROR "can inline EncodeQuad" "d does not escape"
+ _ = d[:6]
+ d[0] = float32bits(x[0]) // ERROR "inlining call to float32bits"
+ d[1] = float32bits(x[1]) // ERROR "inlining call to float32bits"
+ d[2] = float32bits(x[2]) // ERROR "inlining call to float32bits"
+ d[3] = float32bits(x[3]) // ERROR "inlining call to float32bits"
+ d[4] = float32bits(x[4]) // ERROR "inlining call to float32bits"
+ d[5] = float32bits(x[5]) // ERROR "inlining call to float32bits"
+}
+
+// float32bits is a copy of math.Float32bits to ensure that
+// these tests pass with `-gcflags=-l`.
+func float32bits(f float32) uint32 { // ERROR "can inline float32bits"
+ return *(*uint32)(unsafe.Pointer(&f))
+}
+
+// Ensure OCONVNOP is zero cost.
+func Conv(v uint64) uint64 { // ERROR "can inline Conv"
+ return conv2(conv2(conv2(v))) // ERROR "inlining call to (conv1|conv2)"
+}
+func conv2(v uint64) uint64 { // ERROR "can inline conv2"
+ return conv1(conv1(conv1(conv1(v)))) // ERROR "inlining call to conv1"
+}
+func conv1(v uint64) uint64 { // ERROR "can inline conv1"
+ return uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(uint64(v)))))))))))
+}
+
+func select1(x, y chan bool) int { // ERROR "can inline select1" "x does not escape" "y does not escape"
+ select {
+ case <-x:
+ return 1
+ case <-y:
+ return 2
+ }
+}
+
+func select2(x, y chan bool) { // ERROR "can inline select2" "x does not escape" "y does not escape"
+loop: // test that labeled select can be inlined.
+ select {
+ case <-x:
+ break loop
+ case <-y:
+ }
+}
+
+func inlineSelect2(x, y chan bool) { // ERROR "can inline inlineSelect2" ERROR "x does not escape" "y does not escape"
+loop:
+ for i := 0; i < 5; i++ {
+ if i == 3 {
+ break loop
+ }
+ select2(x, y) // ERROR "inlining call to select2"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/nil.go b/platform/dbops/binaries/go/go/test/nil.go
new file mode 100644
index 0000000000000000000000000000000000000000..f8300bf56afb4f9135ef490f4a36ce0e35fb186e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nil.go
@@ -0,0 +1,180 @@
+// run
+
+// 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.
+
+// Test nil.
+
+package main
+
+import (
+ "fmt"
+ "time"
+)
+
+type T struct {
+ i int
+}
+
+type IN interface{}
+
+func main() {
+ var i *int
+ var f *float32
+ var s *string
+ var m map[float32]*int
+ var c chan int
+ var t *T
+ var in IN
+ var ta []IN
+
+ i = nil
+ f = nil
+ s = nil
+ m = nil
+ c = nil
+ t = nil
+ i = nil
+ ta = make([]IN, 1)
+ ta[0] = nil
+
+ _, _, _, _, _, _, _, _ = i, f, s, m, c, t, in, ta
+
+ arraytest()
+ chantest()
+ maptest()
+ slicetest()
+}
+
+func shouldPanic(f func()) {
+ defer func() {
+ if recover() == nil {
+ panic("not panicking")
+ }
+ }()
+ f()
+}
+
+func shouldBlock(f func()) {
+ go func() {
+ f()
+ panic("did not block")
+ }()
+ time.Sleep(1e7)
+}
+
+// nil array pointer
+
+func arraytest() {
+ var p *[10]int
+
+ // Looping over indices is fine.
+ s := 0
+ for i := range p {
+ s += i
+ }
+ if s != 45 {
+ panic(s)
+ }
+
+ s = 0
+ for i := 0; i < len(p); i++ {
+ s += i
+ }
+ if s != 45 {
+ panic(s)
+ }
+
+ // Looping over values is not.
+ shouldPanic(func() {
+ for i, v := range p {
+ s += i + v
+ }
+ })
+
+ shouldPanic(func() {
+ for i := 0; i < len(p); i++ {
+ s += p[i]
+ }
+ })
+}
+
+// nil channel
+// select tests already handle select on nil channel
+
+func chantest() {
+ var ch chan int
+
+ // nil channel is never ready
+ shouldBlock(func() {
+ ch <- 1
+ })
+ shouldBlock(func() {
+ <-ch
+ })
+ shouldBlock(func() {
+ x, ok := <-ch
+ println(x, ok) // unreachable
+ })
+
+ if len(ch) != 0 {
+ panic(len(ch))
+ }
+ if cap(ch) != 0 {
+ panic(cap(ch))
+ }
+}
+
+// nil map
+
+func maptest() {
+ var m map[int]int
+
+ // nil map appears empty
+ if len(m) != 0 {
+ panic(len(m))
+ }
+ if m[1] != 0 {
+ panic(m[1])
+ }
+ if x, ok := m[1]; x != 0 || ok {
+ panic(fmt.Sprint(x, ok))
+ }
+
+ for k, v := range m {
+ panic(k)
+ panic(v)
+ }
+
+ // can delete (non-existent) entries
+ delete(m, 2)
+
+ // but cannot be written to
+ shouldPanic(func() {
+ m[2] = 3
+ })
+}
+
+// nil slice
+
+func slicetest() {
+ var x []int
+
+ // nil slice is just a 0-element slice.
+ if len(x) != 0 {
+ panic(len(x))
+ }
+ if cap(x) != 0 {
+ panic(cap(x))
+ }
+
+ // no 0-element slices can be read from or written to
+ var s int
+ shouldPanic(func() {
+ s += x[1]
+ })
+ shouldPanic(func() {
+ x[2] = s
+ })
+}
diff --git a/platform/dbops/binaries/go/go/test/nilcheck.go b/platform/dbops/binaries/go/go/test/nilcheck.go
new file mode 100644
index 0000000000000000000000000000000000000000..e81db6dcb07eb826081342155a0c0b2cc640c4be
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilcheck.go
@@ -0,0 +1,190 @@
+// errorcheck -0 -N -d=nil
+
+// 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.
+
+// Test that nil checks are inserted.
+// Optimization is disabled, so redundant checks are not removed.
+
+package p
+
+type Struct struct {
+ X int
+ Y float64
+}
+
+type BigStruct struct {
+ X int
+ Y float64
+ A [1 << 20]int
+ Z string
+}
+
+type Empty struct {
+}
+
+type Empty1 struct {
+ Empty
+}
+
+var (
+ intp *int
+ arrayp *[10]int
+ array0p *[0]int
+ bigarrayp *[1 << 26]int
+ structp *Struct
+ bigstructp *BigStruct
+ emptyp *Empty
+ empty1p *Empty1
+)
+
+func f1() {
+ _ = *intp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+ _ = *array0p // ERROR "nil check"
+ _ = *array0p // ERROR "nil check"
+ _ = *intp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+ _ = *structp // ERROR "nil check"
+ _ = *emptyp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+}
+
+func f2() {
+ var (
+ intp *int
+ arrayp *[10]int
+ array0p *[0]int
+ bigarrayp *[1 << 20]int
+ structp *Struct
+ bigstructp *BigStruct
+ emptyp *Empty
+ empty1p *Empty1
+ )
+
+ _ = *intp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+ _ = *array0p // ERROR "nil check"
+ _ = *array0p // ERROR "nil check"
+ _ = *intp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+ _ = *structp // ERROR "nil check"
+ _ = *emptyp // ERROR "nil check"
+ _ = *arrayp // ERROR "nil check"
+ _ = *bigarrayp // ERROR "nil check"
+ _ = *bigstructp // ERROR "nil check"
+ _ = *empty1p // ERROR "nil check"
+}
+
+func fx10k() *[10000]int
+
+var b bool
+
+func f3(x *[10000]int) {
+ // Using a huge type and huge offsets so the compiler
+ // does not expect the memory hardware to fault.
+ _ = x[9999] // ERROR "nil check"
+
+ for {
+ if x[9999] != 0 { // ERROR "nil check"
+ break
+ }
+ }
+
+ x = fx10k()
+ _ = x[9999] // ERROR "nil check"
+ if b {
+ _ = x[9999] // ERROR "nil check"
+ } else {
+ _ = x[9999] // ERROR "nil check"
+ }
+ _ = x[9999] // ERROR "nil check"
+
+ x = fx10k()
+ if b {
+ _ = x[9999] // ERROR "nil check"
+ } else {
+ _ = x[9999] // ERROR "nil check"
+ }
+ _ = x[9999] // ERROR "nil check"
+
+ fx10k()
+ // This one is a bit redundant, if we figured out that
+ // x wasn't going to change across the function call.
+ // But it's a little complex to do and in practice doesn't
+ // matter enough.
+ _ = x[9999] // ERROR "nil check"
+}
+
+func f3a() {
+ x := fx10k()
+ y := fx10k()
+ z := fx10k()
+ _ = &x[9] // ERROR "nil check"
+ y = z
+ _ = &x[9] // ERROR "nil check"
+ x = y
+ _ = &x[9] // ERROR "nil check"
+}
+
+func f3b() {
+ x := fx10k()
+ y := fx10k()
+ _ = &x[9] // ERROR "nil check"
+ y = x
+ _ = &x[9] // ERROR "nil check"
+ x = y
+ _ = &x[9] // ERROR "nil check"
+}
+
+func fx10() *[10]int
+
+func f4(x *[10]int) {
+ // Most of these have no checks because a real memory reference follows,
+ // and the offset is small enough that if x is nil, the address will still be
+ // in the first unmapped page of memory.
+
+ _ = x[9] // ERROR "nil check"
+
+ for {
+ if x[9] != 0 { // ERROR "nil check"
+ break
+ }
+ }
+
+ x = fx10()
+ _ = x[9] // ERROR "nil check"
+ if b {
+ _ = x[9] // ERROR "nil check"
+ } else {
+ _ = x[9] // ERROR "nil check"
+ }
+ _ = x[9] // ERROR "nil check"
+
+ x = fx10()
+ if b {
+ _ = x[9] // ERROR "nil check"
+ } else {
+ _ = &x[9] // ERROR "nil check"
+ }
+ _ = x[9] // ERROR "nil check"
+
+ fx10()
+ _ = x[9] // ERROR "nil check"
+
+ x = fx10()
+ y := fx10()
+ _ = &x[9] // ERROR "nil check"
+ y = x
+ _ = &x[9] // ERROR "nil check"
+ x = y
+ _ = &x[9] // ERROR "nil check"
+}
+
+func f5(m map[string]struct{}) bool {
+ // Existence-only map lookups should not generate a nil check
+ tmp1, tmp2 := m[""] // ERROR "removed nil check"
+ _, ok := tmp1, tmp2
+ return ok
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr.go b/platform/dbops/binaries/go/go/test/nilptr.go
new file mode 100644
index 0000000000000000000000000000000000000000..7f42e930bdee7e95f13d28b8a3ccea4818501241
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr.go
@@ -0,0 +1,185 @@
+// run
+
+// 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.
+
+// Test that the implementation catches nil ptr indirection
+// in a large address space.
+
+// Address space starts at 1<<32 on AIX and on darwin/arm64 and on windows/arm64, so dummy is too far.
+//go:build !aix && (!darwin || !arm64) && (!windows || !arm64)
+
+package main
+
+import "unsafe"
+
+// Having a big address space means that indexing
+// at a 256 MB offset from a nil pointer might not
+// cause a memory access fault. This test checks
+// that Go is doing the correct explicit checks to catch
+// these nil pointer accesses, not just relying on the hardware.
+var dummy [256 << 20]byte // give us a big address space
+
+func main() {
+ // the test only tests what we intend to test
+ // if dummy starts in the first 256 MB of memory.
+ // otherwise there might not be anything mapped
+ // at the address that might be accidentally
+ // dereferenced below.
+ if uintptr(unsafe.Pointer(&dummy)) > 256<<20 {
+ panic("dummy too far out")
+ }
+
+ shouldPanic(p1)
+ shouldPanic(p2)
+ shouldPanic(p3)
+ shouldPanic(p4)
+ shouldPanic(p5)
+ shouldPanic(p6)
+ shouldPanic(p7)
+ shouldPanic(p8)
+ shouldPanic(p9)
+ shouldPanic(p10)
+ shouldPanic(p11)
+ shouldPanic(p12)
+ shouldPanic(p13)
+ shouldPanic(p14)
+ shouldPanic(p15)
+ shouldPanic(p16)
+}
+
+func shouldPanic(f func()) {
+ defer func() {
+ if recover() == nil {
+ panic("memory reference did not panic")
+ }
+ }()
+ f()
+}
+
+func p1() {
+ // Array index.
+ var p *[1 << 30]byte = nil
+ println(p[256<<20]) // very likely to be inside dummy, but should panic
+}
+
+var xb byte
+
+func p2() {
+ var p *[1 << 30]byte = nil
+ xb = 123
+
+ // Array index.
+ println(p[uintptr(unsafe.Pointer(&xb))]) // should panic
+}
+
+func p3() {
+ // Array to slice.
+ var p *[1 << 30]byte = nil
+ var x []byte = p[0:] // should panic
+ _ = x
+}
+
+var q *[1 << 30]byte
+
+func p4() {
+ // Array to slice.
+ var x []byte
+ var y = &x
+ *y = q[0:] // should crash (uses arraytoslice runtime routine)
+}
+
+func fb([]byte) {
+ panic("unreachable")
+}
+
+func p5() {
+ // Array to slice.
+ var p *[1 << 30]byte = nil
+ fb(p[0:]) // should crash
+}
+
+func p6() {
+ // Array to slice.
+ var p *[1 << 30]byte = nil
+ var _ []byte = p[10 : len(p)-10] // should crash
+}
+
+type T struct {
+ x [256 << 20]byte
+ i int
+}
+
+func f() *T {
+ return nil
+}
+
+var y *T
+var x = &y
+
+func p7() {
+ // Struct field access with large offset.
+ println(f().i) // should crash
+}
+
+func p8() {
+ // Struct field access with large offset.
+ println((*x).i) // should crash
+}
+
+func p9() {
+ // Struct field access with large offset.
+ var t *T
+ println(&t.i) // should crash
+}
+
+func p10() {
+ // Struct field access with large offset.
+ var t *T
+ println(t.i) // should crash
+}
+
+type T1 struct {
+ T
+}
+
+type T2 struct {
+ *T1
+}
+
+func p11() {
+ t := &T2{}
+ p := &t.i
+ println(*p)
+}
+
+// ADDR(DOT(IND(p))) needs a check also
+func p12() {
+ var p *T = nil
+ println(*(&((*p).i)))
+}
+
+// Tests suggested in golang.org/issue/6080.
+
+func p13() {
+ var x *[10]int
+ y := x[:]
+ _ = y
+}
+
+func p14() {
+ println((*[1]int)(nil)[:])
+}
+
+func p15() {
+ for i := range (*[1]int)(nil)[:] {
+ _ = i
+ }
+}
+
+func p16() {
+ for i, v := range (*[1]int)(nil)[:] {
+ _ = i + v
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr2.go b/platform/dbops/binaries/go/go/test/nilptr2.go
new file mode 100644
index 0000000000000000000000000000000000000000..8a85b6dbcb16484f3bdfe1052f20dd24a5494534
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr2.go
@@ -0,0 +1,131 @@
+// run
+
+// 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 main
+
+func main() {
+ ok := true
+ for _, tt := range tests {
+ func() {
+ defer func() {
+ if err := recover(); err == nil {
+ println(tt.name, "did not panic")
+ ok = false
+ }
+ }()
+ tt.fn()
+ }()
+ }
+ if !ok {
+ println("BUG")
+ }
+}
+
+var intp *int
+var slicep *[]byte
+var a10p *[10]int
+var a10Mp *[1<<20]int
+var structp *Struct
+var bigstructp *BigStruct
+var i int
+var m *M
+var m1 *M1
+var m2 *M2
+
+var V interface{}
+
+func use(x interface{}) {
+ V = x
+}
+
+var tests = []struct{
+ name string
+ fn func()
+}{
+ // Edit .+1,/^}/s/^[^ ].+/ {"&", func() { println(&) }},\n {"\&&", func() { println(\&&) }},/g
+ {"*intp", func() { println(*intp) }},
+ {"&*intp", func() { println(&*intp) }},
+ {"*slicep", func() { println(*slicep) }},
+ {"&*slicep", func() { println(&*slicep) }},
+ {"(*slicep)[0]", func() { println((*slicep)[0]) }},
+ {"&(*slicep)[0]", func() { println(&(*slicep)[0]) }},
+ {"(*slicep)[i]", func() { println((*slicep)[i]) }},
+ {"&(*slicep)[i]", func() { println(&(*slicep)[i]) }},
+ {"*a10p", func() { use(*a10p) }},
+ {"&*a10p", func() { println(&*a10p) }},
+ {"a10p[0]", func() { println(a10p[0]) }},
+ {"&a10p[0]", func() { println(&a10p[0]) }},
+ {"a10p[i]", func() { println(a10p[i]) }},
+ {"&a10p[i]", func() { println(&a10p[i]) }},
+ {"*structp", func() { use(*structp) }},
+ {"&*structp", func() { println(&*structp) }},
+ {"structp.i", func() { println(structp.i) }},
+ {"&structp.i", func() { println(&structp.i) }},
+ {"structp.j", func() { println(structp.j) }},
+ {"&structp.j", func() { println(&structp.j) }},
+ {"structp.k", func() { println(structp.k) }},
+ {"&structp.k", func() { println(&structp.k) }},
+ {"structp.x[0]", func() { println(structp.x[0]) }},
+ {"&structp.x[0]", func() { println(&structp.x[0]) }},
+ {"structp.x[i]", func() { println(structp.x[i]) }},
+ {"&structp.x[i]", func() { println(&structp.x[i]) }},
+ {"structp.x[9]", func() { println(structp.x[9]) }},
+ {"&structp.x[9]", func() { println(&structp.x[9]) }},
+ {"structp.l", func() { println(structp.l) }},
+ {"&structp.l", func() { println(&structp.l) }},
+ {"*bigstructp", func() { use(*bigstructp) }},
+ {"&*bigstructp", func() { println(&*bigstructp) }},
+ {"bigstructp.i", func() { println(bigstructp.i) }},
+ {"&bigstructp.i", func() { println(&bigstructp.i) }},
+ {"bigstructp.j", func() { println(bigstructp.j) }},
+ {"&bigstructp.j", func() { println(&bigstructp.j) }},
+ {"bigstructp.k", func() { println(bigstructp.k) }},
+ {"&bigstructp.k", func() { println(&bigstructp.k) }},
+ {"bigstructp.x[0]", func() { println(bigstructp.x[0]) }},
+ {"&bigstructp.x[0]", func() { println(&bigstructp.x[0]) }},
+ {"bigstructp.x[i]", func() { println(bigstructp.x[i]) }},
+ {"&bigstructp.x[i]", func() { println(&bigstructp.x[i]) }},
+ {"bigstructp.x[9]", func() { println(bigstructp.x[9]) }},
+ {"&bigstructp.x[9]", func() { println(&bigstructp.x[9]) }},
+ {"bigstructp.x[100<<20]", func() { println(bigstructp.x[100<<20]) }},
+ {"&bigstructp.x[100<<20]", func() { println(&bigstructp.x[100<<20]) }},
+ {"bigstructp.l", func() { println(bigstructp.l) }},
+ {"&bigstructp.l", func() { println(&bigstructp.l) }},
+ {"m1.F()", func() { println(m1.F()) }},
+ {"m1.M.F()", func() { println(m1.M.F()) }},
+ {"m2.F()", func() { println(m2.F()) }},
+ {"m2.M.F()", func() { println(m2.M.F()) }},
+}
+
+type Struct struct {
+ i int
+ j float64
+ k string
+ x [10]int
+ l []byte
+}
+
+type BigStruct struct {
+ i int
+ j float64
+ k string
+ x [128<<20]byte
+ l []byte
+}
+
+type M struct {
+}
+
+func (m *M) F() int {return 0}
+
+type M1 struct {
+ M
+}
+
+type M2 struct {
+ x int
+ M
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr3.go b/platform/dbops/binaries/go/go/test/nilptr3.go
new file mode 100644
index 0000000000000000000000000000000000000000..2cc510beb635df01ae75e92ee06d51212e1ef34d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr3.go
@@ -0,0 +1,256 @@
+// errorcheck -0 -d=nil
+
+//go:build !wasm && !aix
+
+// 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.
+
+// Test that nil checks are removed.
+// Optimization is enabled.
+
+package p
+
+type Struct struct {
+ X int
+ Y float64
+}
+
+type BigStruct struct {
+ X int
+ Y float64
+ A [1 << 20]int
+ Z string
+}
+
+type Empty struct {
+}
+
+type Empty1 struct {
+ Empty
+}
+
+var (
+ intp *int
+ arrayp *[10]int
+ array0p *[0]int
+ bigarrayp *[1 << 26]int
+ structp *Struct
+ bigstructp *BigStruct
+ emptyp *Empty
+ empty1p *Empty1
+)
+
+func f1() {
+ _ = *intp // ERROR "generated nil check"
+
+ // This one should be removed but the block copy needs
+ // to be turned into its own pseudo-op in order to see
+ // the indirect.
+ _ = *arrayp // ERROR "generated nil check"
+
+ // 0-byte indirect doesn't suffice.
+ // we don't registerize globals, so there are no removed.* nil checks.
+ _ = *array0p // ERROR "generated nil check"
+ _ = *array0p // ERROR "removed nil check"
+
+ _ = *intp // ERROR "removed nil check"
+ _ = *arrayp // ERROR "removed nil check"
+ _ = *structp // ERROR "generated nil check"
+ _ = *emptyp // ERROR "generated nil check"
+ _ = *arrayp // ERROR "removed nil check"
+}
+
+func f2() {
+ var (
+ intp *int
+ arrayp *[10]int
+ array0p *[0]int
+ bigarrayp *[1 << 20]int
+ structp *Struct
+ bigstructp *BigStruct
+ emptyp *Empty
+ empty1p *Empty1
+ )
+
+ _ = *intp // ERROR "generated nil check"
+ _ = *arrayp // ERROR "generated nil check"
+ _ = *array0p // ERROR "generated nil check"
+ _ = *array0p // ERROR "removed.* nil check"
+ _ = *intp // ERROR "removed.* nil check"
+ _ = *arrayp // ERROR "removed.* nil check"
+ _ = *structp // ERROR "generated nil check"
+ _ = *emptyp // ERROR "generated nil check"
+ _ = *arrayp // ERROR "removed.* nil check"
+ _ = *bigarrayp // ERROR "generated nil check" ARM removed nil check before indirect!!
+ _ = *bigstructp // ERROR "generated nil check"
+ _ = *empty1p // ERROR "generated nil check"
+}
+
+func fx10k() *[10000]int
+
+var b bool
+
+func f3(x *[10000]int) {
+ // Using a huge type and huge offsets so the compiler
+ // does not expect the memory hardware to fault.
+ _ = x[9999] // ERROR "generated nil check"
+
+ for {
+ if x[9999] != 0 { // ERROR "removed nil check"
+ break
+ }
+ }
+
+ x = fx10k()
+ _ = x[9999] // ERROR "generated nil check"
+ if b {
+ _ = x[9999] // ERROR "removed.* nil check"
+ } else {
+ _ = x[9999] // ERROR "removed.* nil check"
+ }
+ _ = x[9999] // ERROR "removed nil check"
+
+ x = fx10k()
+ if b {
+ _ = x[9999] // ERROR "generated nil check"
+ } else {
+ _ = x[9999] // ERROR "generated nil check"
+ }
+ _ = x[9999] // ERROR "generated nil check"
+
+ fx10k()
+ // This one is a bit redundant, if we figured out that
+ // x wasn't going to change across the function call.
+ // But it's a little complex to do and in practice doesn't
+ // matter enough.
+ _ = x[9999] // ERROR "removed nil check"
+}
+
+func f3a() {
+ x := fx10k()
+ y := fx10k()
+ z := fx10k()
+ _ = &x[9] // ERROR "generated nil check"
+ y = z
+ _ = &x[9] // ERROR "removed.* nil check"
+ x = y
+ _ = &x[9] // ERROR "generated nil check"
+}
+
+func f3b() {
+ x := fx10k()
+ y := fx10k()
+ _ = &x[9] // ERROR "generated nil check"
+ y = x
+ _ = &x[9] // ERROR "removed.* nil check"
+ x = y
+ _ = &x[9] // ERROR "removed.* nil check"
+}
+
+func fx10() *[10]int
+
+func f4(x *[10]int) {
+ // Most of these have no checks because a real memory reference follows,
+ // and the offset is small enough that if x is nil, the address will still be
+ // in the first unmapped page of memory.
+
+ _ = x[9] // ERROR "generated nil check" // bug: would like to remove this check (but nilcheck and load are in different blocks)
+
+ for {
+ if x[9] != 0 { // ERROR "removed nil check"
+ break
+ }
+ }
+
+ x = fx10()
+ _ = x[9] // ERROR "generated nil check" // bug would like to remove before indirect
+ if b {
+ _ = x[9] // ERROR "removed nil check"
+ } else {
+ _ = x[9] // ERROR "removed nil check"
+ }
+ _ = x[9] // ERROR "removed nil check"
+
+ x = fx10()
+ if b {
+ _ = x[9] // ERROR "generated nil check" // bug would like to remove before indirect
+ } else {
+ _ = &x[9] // ERROR "generated nil check"
+ }
+ _ = x[9] // ERROR "generated nil check" // bug would like to remove before indirect
+
+ fx10()
+ _ = x[9] // ERROR "removed nil check"
+
+ x = fx10()
+ y := fx10()
+ _ = &x[9] // ERROR "generated nil check"
+ y = x
+ _ = &x[9] // ERROR "removed[a-z ]* nil check"
+ x = y
+ _ = &x[9] // ERROR "removed[a-z ]* nil check"
+}
+
+func m1(m map[int][80]byte) byte {
+ v := m[3] // ERROR "removed nil check"
+ return v[5]
+}
+func m2(m map[int][800]byte) byte {
+ v := m[3] // ERROR "removed nil check"
+ return v[5]
+}
+func m3(m map[int][80]byte) (byte, bool) {
+ v, ok := m[3] // ERROR "removed nil check"
+ return v[5], ok
+}
+func m4(m map[int][800]byte) (byte, bool) {
+ v, ok := m[3] // ERROR "removed nil check"
+ return v[5], ok
+}
+func p1() byte {
+ p := new([100]byte)
+ return p[5] // ERROR "removed nil check"
+}
+
+type SS struct {
+ x byte
+}
+
+type TT struct {
+ SS
+}
+
+func f(t *TT) *byte {
+ // See issue 17242.
+ s := &t.SS // ERROR "generated nil check"
+ return &s.x // ERROR "removed nil check"
+}
+
+// make sure not to do nil check for newobject
+func f7() (*Struct, float64) {
+ t := new(Struct)
+ p := &t.Y // ERROR "removed nil check"
+ return t, *p // ERROR "removed nil check"
+}
+
+func f9() []int {
+ x := new([1]int)
+ x[0] = 1 // ERROR "removed nil check"
+ y := x[:] // ERROR "removed nil check"
+ return y
+}
+
+// See issue 42673.
+func f10(p **int) int {
+ return * // ERROR "removed nil check"
+ /* */
+ *p // ERROR "removed nil check"
+}
+
+func f11(x []byte) {
+ p := (*[0]byte)(x)
+ _ = *p // ERROR "generated nil check"
+ q := (*[4]byte)(x)
+ _ = *q // ERROR "removed nil check"
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr4.go b/platform/dbops/binaries/go/go/test/nilptr4.go
new file mode 100644
index 0000000000000000000000000000000000000000..c75ce10c5951f9dce03efaaeaed78f3df42f780a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr4.go
@@ -0,0 +1,24 @@
+// build
+
+// 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 the compiler does not crash during compilation.
+
+package main
+
+import "unsafe"
+
+// Issue 7413
+func f1() {
+ type t struct {
+ i int
+ }
+
+ var v *t
+ _ = int(uintptr(unsafe.Pointer(&v.i)))
+ _ = int32(uintptr(unsafe.Pointer(&v.i)))
+}
+
+func main() {}
diff --git a/platform/dbops/binaries/go/go/test/nilptr5.go b/platform/dbops/binaries/go/go/test/nilptr5.go
new file mode 100644
index 0000000000000000000000000000000000000000..51a302f25218275b0d7ee4ddde303fa2bd1fb2b4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr5.go
@@ -0,0 +1,32 @@
+// errorcheck -0 -d=nil
+
+//go:build !wasm && !aix
+
+// 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.
+
+// Test that nil checks are removed.
+// Optimization is enabled.
+
+package p
+
+func f5(p *float32, q *float64, r *float32, s *float64) float64 {
+ x := float64(*p) // ERROR "removed nil check"
+ y := *q // ERROR "removed nil check"
+ *r = 7 // ERROR "removed nil check"
+ *s = 9 // ERROR "removed nil check"
+ return x + y
+}
+
+type T struct{ b [29]byte }
+
+func f6(p, q *T) {
+ x := *p // ERROR "removed nil check"
+ *q = x // ERROR "removed nil check"
+}
+
+// make sure to remove nil check for memory move (issue #18003)
+func f8(t *struct{ b [8]int }) struct{ b [8]int } {
+ return *t // ERROR "removed nil check"
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr5_aix.go b/platform/dbops/binaries/go/go/test/nilptr5_aix.go
new file mode 100644
index 0000000000000000000000000000000000000000..3b116ca19f5e7012a07e8943a207f57489bd39b1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr5_aix.go
@@ -0,0 +1,32 @@
+// errorcheck -0 -d=nil
+
+//go:build aix
+
+// 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.
+
+// Test that nil checks are removed.
+// Optimization is enabled.
+
+package p
+
+func f5(p *float32, q *float64, r *float32, s *float64) float64 {
+ x := float64(*p) // ERROR "generated nil check"
+ y := *q // ERROR "generated nil check"
+ *r = 7 // ERROR "removed nil check"
+ *s = 9 // ERROR "removed nil check"
+ return x + y
+}
+
+type T [29]byte
+
+func f6(p, q *T) {
+ x := *p // ERROR "generated nil check"
+ *q = x // ERROR "removed nil check"
+}
+
+// make sure to remove nil check for memory move (issue #18003)
+func f8(t *[8]int) [8]int {
+ return *t // ERROR "generated nil check"
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr5_wasm.go b/platform/dbops/binaries/go/go/test/nilptr5_wasm.go
new file mode 100644
index 0000000000000000000000000000000000000000..ea380d1384f70203e40241ab4fafb65cf2b009e5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr5_wasm.go
@@ -0,0 +1,32 @@
+// errorcheck -0 -d=nil
+
+//go:build wasm
+
+// 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.
+
+// Test that nil checks are removed.
+// Optimization is enabled.
+
+package p
+
+func f5(p *float32, q *float64, r *float32, s *float64) float64 {
+ x := float64(*p) // ERROR "generated nil check"
+ y := *q // ERROR "generated nil check"
+ *r = 7 // ERROR "generated nil check"
+ *s = 9 // ERROR "generated nil check"
+ return x + y
+}
+
+type T [29]byte
+
+func f6(p, q *T) {
+ x := *p // ERROR "generated nil check"
+ *q = x // ERROR "generated nil check"
+}
+
+// make sure to remove nil check for memory move (issue #18003)
+func f8(t *[8]int) [8]int {
+ return *t // ERROR "generated nil check"
+}
diff --git a/platform/dbops/binaries/go/go/test/nilptr_aix.go b/platform/dbops/binaries/go/go/test/nilptr_aix.go
new file mode 100644
index 0000000000000000000000000000000000000000..f7a7e616d159bfc3e58c4166dedfa40dfe280547
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nilptr_aix.go
@@ -0,0 +1,185 @@
+// run
+
+// 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.
+
+// Test that the implementation catches nil ptr indirection
+// in a large address space.
+
+//go:build aix
+
+package main
+
+import "unsafe"
+
+// Having a big address space means that indexing
+// at a 1G + 256 MB offset from a nil pointer might not
+// cause a memory access fault. This test checks
+// that Go is doing the correct explicit checks to catch
+// these nil pointer accesses, not just relying on the hardware.
+// The reason of the 1G offset is because AIX addresses start after 1G.
+var dummy [256 << 20]byte // give us a big address space
+
+func main() {
+ // the test only tests what we intend to test
+ // if dummy starts in the first 256 MB of memory.
+ // otherwise there might not be anything mapped
+ // at the address that might be accidentally
+ // dereferenced below.
+ if uintptr(unsafe.Pointer(&dummy)) < 1<<32 {
+ panic("dummy not far enough")
+ }
+
+ shouldPanic(p1)
+ shouldPanic(p2)
+ shouldPanic(p3)
+ shouldPanic(p4)
+ shouldPanic(p5)
+ shouldPanic(p6)
+ shouldPanic(p7)
+ shouldPanic(p8)
+ shouldPanic(p9)
+ shouldPanic(p10)
+ shouldPanic(p11)
+ shouldPanic(p12)
+ shouldPanic(p13)
+ shouldPanic(p14)
+ shouldPanic(p15)
+ shouldPanic(p16)
+}
+
+func shouldPanic(f func()) {
+ defer func() {
+ if recover() == nil {
+ panic("memory reference did not panic")
+ }
+ }()
+ f()
+}
+
+func p1() {
+ // Array index.
+ var p *[1 << 33]byte = nil
+ println(p[1<<32+256<<20]) // very likely to be inside dummy, but should panic
+}
+
+var xb byte
+
+func p2() {
+ var p *[1 << 33]byte = nil
+ xb = 123
+
+ // Array index.
+ println(p[uintptr(unsafe.Pointer(&xb))]) // should panic
+}
+
+func p3() {
+ // Array to slice.
+ var p *[1 << 33]byte = nil
+ var x []byte = p[0:] // should panic
+ _ = x
+}
+
+var q *[1 << 33]byte
+
+func p4() {
+ // Array to slice.
+ var x []byte
+ var y = &x
+ *y = q[0:] // should crash (uses arraytoslice runtime routine)
+}
+
+func fb([]byte) {
+ panic("unreachable")
+}
+
+func p5() {
+ // Array to slice.
+ var p *[1 << 33]byte = nil
+ fb(p[0:]) // should crash
+}
+
+func p6() {
+ // Array to slice.
+ var p *[1 << 33]byte = nil
+ var _ []byte = p[10 : len(p)-10] // should crash
+}
+
+type T struct {
+ x [1<<32 + 256<<20]byte
+ i int
+}
+
+func f() *T {
+ return nil
+}
+
+var y *T
+var x = &y
+
+func p7() {
+ // Struct field access with large offset.
+ println(f().i) // should crash
+}
+
+func p8() {
+ // Struct field access with large offset.
+ println((*x).i) // should crash
+}
+
+func p9() {
+ // Struct field access with large offset.
+ var t *T
+ println(&t.i) // should crash
+}
+
+func p10() {
+ // Struct field access with large offset.
+ var t *T
+ println(t.i) // should crash
+}
+
+type T1 struct {
+ T
+}
+
+type T2 struct {
+ *T1
+}
+
+func p11() {
+ t := &T2{}
+ p := &t.i
+ println(*p)
+}
+
+// ADDR(DOT(IND(p))) needs a check also
+func p12() {
+ var p *T = nil
+ println(*(&((*p).i)))
+}
+
+// Tests suggested in golang.org/issue/6080.
+
+func p13() {
+ var x *[10]int
+ y := x[:]
+ _ = y
+}
+
+func p14() {
+ println((*[1]int)(nil)[:])
+}
+
+func p15() {
+ for i := range (*[1]int)(nil)[:] {
+ _ = i
+ }
+}
+
+func p16() {
+ for i, v := range (*[1]int)(nil)[:] {
+ _ = i + v
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/noinit.go b/platform/dbops/binaries/go/go/test/noinit.go
new file mode 100644
index 0000000000000000000000000000000000000000..84aeeafb59b629e1c79eeb20f56b324c5c44b2f7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/noinit.go
@@ -0,0 +1,343 @@
+// run
+//go:build !gcflags_noopt
+
+// 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.
+
+// Test that many initializations can be done at link time and
+// generate no executable init functions.
+// Also test that trivial func init are optimized away.
+
+package main
+
+import (
+ "errors"
+ "unsafe"
+)
+
+// All these initializations should be done at link time.
+
+type S struct{ a, b, c int }
+type SS struct{ aa, bb, cc S }
+type SA struct{ a, b, c [3]int }
+type SC struct{ a, b, c []int }
+
+var (
+ zero = 2
+ one = 1
+ pi = 3.14
+ slice = []byte{1, 2, 3}
+ sliceInt = []int{1, 2, 3}
+ hello = "hello, world"
+ bytes = []byte("hello, world")
+ four, five = 4, 5
+ x, y = 0.1, "hello"
+ nilslice []byte = nil
+ nilmap map[string]int = nil
+ nilfunc func() = nil
+ nilchan chan int = nil
+ nilptr *byte = nil
+)
+
+var a = [3]int{1001, 1002, 1003}
+var s = S{1101, 1102, 1103}
+var c = []int{1201, 1202, 1203}
+
+var aa = [3][3]int{[3]int{2001, 2002, 2003}, [3]int{2004, 2005, 2006}, [3]int{2007, 2008, 2009}}
+var as = [3]S{S{2101, 2102, 2103}, S{2104, 2105, 2106}, S{2107, 2108, 2109}}
+
+var sa = SA{[3]int{3001, 3002, 3003}, [3]int{3004, 3005, 3006}, [3]int{3007, 3008, 3009}}
+var ss = SS{S{3101, 3102, 3103}, S{3104, 3105, 3106}, S{3107, 3108, 3109}}
+
+var ca = [][3]int{[3]int{4001, 4002, 4003}, [3]int{4004, 4005, 4006}, [3]int{4007, 4008, 4009}}
+var cs = []S{S{4101, 4102, 4103}, S{4104, 4105, 4106}, S{4107, 4108, 4109}}
+
+var answers = [...]int{
+ // s
+ 1101, 1102, 1103,
+
+ // ss
+ 3101, 3102, 3103,
+ 3104, 3105, 3106,
+ 3107, 3108, 3109,
+
+ // [0]
+ 1001, 1201, 1301,
+ 2101, 2102, 2103,
+ 4101, 4102, 4103,
+ 5101, 5102, 5103,
+ 3001, 3004, 3007,
+ 3201, 3204, 3207,
+ 3301, 3304, 3307,
+
+ // [0][j]
+ 2001, 2201, 2301, 4001, 4201, 4301, 5001, 5201, 5301,
+ 2002, 2202, 2302, 4002, 4202, 4302, 5002, 5202, 5302,
+ 2003, 2203, 2303, 4003, 4203, 4303, 5003, 5203, 5303,
+
+ // [1]
+ 1002, 1202, 1302,
+ 2104, 2105, 2106,
+ 4104, 4105, 4106,
+ 5104, 5105, 5106,
+ 3002, 3005, 3008,
+ 3202, 3205, 3208,
+ 3302, 3305, 3308,
+
+ // [1][j]
+ 2004, 2204, 2304, 4004, 4204, 4304, 5004, 5204, 5304,
+ 2005, 2205, 2305, 4005, 4205, 4305, 5005, 5205, 5305,
+ 2006, 2206, 2306, 4006, 4206, 4306, 5006, 5206, 5306,
+
+ // [2]
+ 1003, 1203, 1303,
+ 2107, 2108, 2109,
+ 4107, 4108, 4109,
+ 5107, 5108, 5109,
+ 3003, 3006, 3009,
+ 3203, 3206, 3209,
+ 3303, 3306, 3309,
+
+ // [2][j]
+ 2007, 2207, 2307, 4007, 4207, 4307, 5007, 5207, 5307,
+ 2008, 2208, 2308, 4008, 4208, 4308, 5008, 5208, 5308,
+ 2009, 2209, 2309, 4009, 4209, 4309, 5009, 5209, 5309,
+}
+
+var (
+ copy_zero = zero
+ copy_one = one
+ copy_pi = pi
+ copy_slice = slice
+ copy_sliceInt = sliceInt
+ // copy_hello = hello // static init of copied strings defeats link -X; see #34675
+
+ // Could be handled without an initialization function, but
+ // requires special handling for "a = []byte("..."); b = a"
+ // which is not a likely case.
+ // copy_bytes = bytes
+ // https://codereview.appspot.com/171840043 is one approach to
+ // make this special case work.
+
+ copy_four, copy_five = four, five
+ copy_x = x
+ // copy_y = y // static init of copied strings defeats link -X; see #34675
+ copy_nilslice = nilslice
+ copy_nilmap = nilmap
+ copy_nilfunc = nilfunc
+ copy_nilchan = nilchan
+ copy_nilptr = nilptr
+)
+
+var copy_a = a
+var copy_s = s
+var copy_c = c
+
+var copy_aa = aa
+var copy_as = as
+
+var copy_sa = sa
+var copy_ss = ss
+
+var copy_ca = ca
+var copy_cs = cs
+
+var copy_answers = answers
+
+var bx bool
+var b0 = false
+var b1 = true
+
+var fx float32
+var f0 = float32(0)
+var f1 = float32(1)
+
+var gx float64
+var g0 = float64(0)
+var g1 = float64(1)
+
+var ix int
+var i0 = 0
+var i1 = 1
+
+var jx uint
+var j0 = uint(0)
+var j1 = uint(1)
+
+var cx complex64
+var c0 = complex64(0)
+var c1 = complex64(1)
+
+var dx complex128
+var d0 = complex128(0)
+var d1 = complex128(1)
+
+var sx []int
+var s0 = []int{0, 0, 0}
+var s1 = []int{1, 2, 3}
+
+func fi() int { return 1 }
+
+var ax [10]int
+var a0 = [10]int{0, 0, 0}
+var a1 = [10]int{1, 2, 3, 4}
+
+type T struct{ X, Y int }
+
+var tx T
+var t0 = T{}
+var t0a = T{0, 0}
+var t0b = T{X: 0}
+var t1 = T{X: 1, Y: 2}
+var t1a = T{3, 4}
+
+var psx *[]int
+var ps0 = &[]int{0, 0, 0}
+var ps1 = &[]int{1, 2, 3}
+
+var pax *[10]int
+var pa0 = &[10]int{0, 0, 0}
+var pa1 = &[10]int{1, 2, 3}
+
+var ptx *T
+var pt0 = &T{}
+var pt0a = &T{0, 0}
+var pt0b = &T{X: 0}
+var pt1 = &T{X: 1, Y: 2}
+var pt1a = &T{3, 4}
+
+// The checks similar to
+// var copy_bx = bx
+// are commented out. The compiler no longer statically initializes them.
+// See issue 7665 and https://codereview.appspot.com/93200044.
+// If https://codereview.appspot.com/169040043 is submitted, and this
+// test is changed to pass -complete to the compiler, then we can
+// uncomment the copy lines again.
+
+// var copy_bx = bx
+var copy_b0 = b0
+var copy_b1 = b1
+
+// var copy_fx = fx
+var copy_f0 = f0
+var copy_f1 = f1
+
+// var copy_gx = gx
+var copy_g0 = g0
+var copy_g1 = g1
+
+// var copy_ix = ix
+var copy_i0 = i0
+var copy_i1 = i1
+
+// var copy_jx = jx
+var copy_j0 = j0
+var copy_j1 = j1
+
+// var copy_cx = cx
+var copy_c0 = c0
+var copy_c1 = c1
+
+// var copy_dx = dx
+var copy_d0 = d0
+var copy_d1 = d1
+
+// var copy_sx = sx
+var copy_s0 = s0
+var copy_s1 = s1
+
+// var copy_ax = ax
+var copy_a0 = a0
+var copy_a1 = a1
+
+// var copy_tx = tx
+var copy_t0 = t0
+var copy_t0a = t0a
+var copy_t0b = t0b
+var copy_t1 = t1
+var copy_t1a = t1a
+
+// var copy_psx = psx
+var copy_ps0 = ps0
+var copy_ps1 = ps1
+
+// var copy_pax = pax
+var copy_pa0 = pa0
+var copy_pa1 = pa1
+
+// var copy_ptx = ptx
+var copy_pt0 = pt0
+var copy_pt0a = pt0a
+var copy_pt0b = pt0b
+var copy_pt1 = pt1
+var copy_pt1a = pt1a
+
+var _ interface{} = 1
+
+type T1 int
+
+func (t *T1) M() {}
+
+type Mer interface {
+ M()
+}
+
+var _ Mer = (*T1)(nil)
+
+var Byte byte
+var PtrByte unsafe.Pointer = unsafe.Pointer(&Byte)
+
+var LitSXInit = &S{1, 2, 3}
+var LitSAnyXInit any = &S{4, 5, 6}
+
+func FS(x, y, z int) *S { return &S{x, y, z} }
+func FSA(x, y, z int) any { return &S{x, y, z} }
+func F3(x int) *S { return &S{x, x, x} }
+
+var LitSCallXInit = FS(7, 8, 9)
+var LitSAnyCallXInit any = FSA(10, 11, 12)
+
+var LitSRepeat = F3(1 + 2)
+
+func F0() *S { return &S{1, 2, 3} }
+
+var LitSNoArgs = F0()
+
+var myError = errors.New("mine")
+
+func gopherize(s string) string { return "gopher gopher gopher " + s }
+
+var animals = gopherize("badger")
+
+// These init funcs should optimize away.
+
+func init() {
+}
+
+func init() {
+ if false {
+ }
+}
+
+func init() {
+ for false {
+ }
+}
+
+// Actual test: check for init funcs in runtime data structures.
+
+type initTask struct {
+ state uint32
+ nfns uint32
+}
+
+//go:linkname main_inittask main..inittask
+var main_inittask initTask
+
+func main() {
+ if nfns := main_inittask.nfns; nfns != 0 {
+ println(nfns)
+ panic("unexpected init funcs")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/nosplit.go b/platform/dbops/binaries/go/go/test/nosplit.go
new file mode 100644
index 0000000000000000000000000000000000000000..e171d1da6618ec649274f36d5fed8d76ebb4a38f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nosplit.go
@@ -0,0 +1,419 @@
+// run
+
+//go:build !nacl && !js && !aix && !wasip1 && !gcflags_noopt && gc
+
+// 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 main
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+)
+
+const debug = false
+
+var tests = `
+# These are test cases for the linker analysis that detects chains of
+# nosplit functions that would cause a stack overflow.
+#
+# Lines beginning with # are comments.
+#
+# Each test case describes a sequence of functions, one per line.
+# Each function definition is the function name, then the frame size,
+# then optionally the keyword 'nosplit', then the body of the function.
+# The body is assembly code, with some shorthands.
+# The shorthand 'call x' stands for CALL x(SB).
+# The shorthand 'callind' stands for 'CALL R0', where R0 is a register.
+# Each test case must define a function named start, and it must be first.
+# That is, a line beginning "start " indicates the start of a new test case.
+# Within a stanza, ; can be used instead of \n to separate lines.
+#
+# After the function definition, the test case ends with an optional
+# REJECT line, specifying the architectures on which the case should
+# be rejected. "REJECT" without any architectures means reject on all architectures.
+# The linker should accept the test case on systems not explicitly rejected.
+#
+# 64-bit systems do not attempt to execute test cases with frame sizes
+# that are only 32-bit aligned.
+
+# Ordinary function should work
+start 0
+
+# Large frame marked nosplit is always wrong.
+# Frame is so large it overflows cmd/link's int16.
+start 100000 nosplit
+REJECT
+
+# Calling a large frame is okay.
+start 0 call big
+big 10000
+
+# But not if the frame is nosplit.
+start 0 call big
+big 10000 nosplit
+REJECT
+
+# Recursion is okay.
+start 0 call start
+
+# Recursive nosplit runs out of space.
+start 0 nosplit call start
+REJECT
+
+# Non-trivial recursion runs out of space.
+start 0 call f1
+f1 0 nosplit call f2
+f2 0 nosplit call f1
+REJECT
+# Same but cycle starts below nosplit entry.
+start 0 call f1
+f1 0 nosplit call f2
+f2 0 nosplit call f3
+f3 0 nosplit call f2
+REJECT
+
+# Chains of ordinary functions okay.
+start 0 call f1
+f1 80 call f2
+f2 80
+
+# Chains of nosplit must fit in the stack limit, 128 bytes.
+start 0 call f1
+f1 80 nosplit call f2
+f2 80 nosplit
+REJECT
+
+# Larger chains.
+start 0 call f1
+f1 16 call f2
+f2 16 call f3
+f3 16 call f4
+f4 16 call f5
+f5 16 call f6
+f6 16 call f7
+f7 16 call f8
+f8 16 call end
+end 1000
+
+start 0 call f1
+f1 16 nosplit call f2
+f2 16 nosplit call f3
+f3 16 nosplit call f4
+f4 16 nosplit call f5
+f5 16 nosplit call f6
+f6 16 nosplit call f7
+f7 16 nosplit call f8
+f8 16 nosplit call end
+end 1000
+REJECT
+
+# Two paths both go over the stack limit.
+start 0 call f1
+f1 80 nosplit call f2 call f3
+f2 40 nosplit call f4
+f3 96 nosplit
+f4 40 nosplit
+REJECT
+
+# Test cases near the 128-byte limit.
+
+# Ordinary stack split frame is always okay.
+start 112
+start 116
+start 120
+start 124
+start 128
+start 132
+start 136
+
+# A nosplit leaf can use the whole 128-CallSize bytes available on entry.
+# (CallSize is 32 on ppc64, 8 on amd64 for frame pointer.)
+start 96 nosplit
+start 100 nosplit; REJECT ppc64 ppc64le
+start 104 nosplit; REJECT ppc64 ppc64le arm64
+start 108 nosplit; REJECT ppc64 ppc64le
+start 112 nosplit; REJECT ppc64 ppc64le arm64
+start 116 nosplit; REJECT ppc64 ppc64le
+start 120 nosplit; REJECT ppc64 ppc64le amd64 arm64
+start 124 nosplit; REJECT ppc64 ppc64le amd64
+start 128 nosplit; REJECT
+start 132 nosplit; REJECT
+start 136 nosplit; REJECT
+
+# Calling a nosplit function from a nosplit function requires
+# having room for the saved caller PC and the called frame.
+# Because ARM doesn't save LR in the leaf, it gets an extra 4 bytes.
+# Because arm64 doesn't save LR in the leaf, it gets an extra 8 bytes.
+# ppc64 doesn't save LR in the leaf, but CallSize is 32, so it gets 24 bytes.
+# Because AMD64 uses frame pointer, it has 8 fewer bytes.
+start 96 nosplit call f; f 0 nosplit
+start 100 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le
+start 104 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le arm64
+start 108 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le
+start 112 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le amd64 arm64
+start 116 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le amd64
+start 120 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le amd64 arm64
+start 124 nosplit call f; f 0 nosplit; REJECT ppc64 ppc64le amd64 386
+start 128 nosplit call f; f 0 nosplit; REJECT
+start 132 nosplit call f; f 0 nosplit; REJECT
+start 136 nosplit call f; f 0 nosplit; REJECT
+
+# Calling a splitting function from a nosplit function requires
+# having room for the saved caller PC of the call but also the
+# saved caller PC for the call to morestack.
+# Architectures differ in the same way as before.
+start 96 nosplit call f; f 0 call f
+start 100 nosplit call f; f 0 call f; REJECT ppc64 ppc64le
+start 104 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64 arm64
+start 108 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64
+start 112 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64 arm64
+start 116 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64
+start 120 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64 386 arm64
+start 124 nosplit call f; f 0 call f; REJECT ppc64 ppc64le amd64 386
+start 128 nosplit call f; f 0 call f; REJECT
+start 132 nosplit call f; f 0 call f; REJECT
+start 136 nosplit call f; f 0 call f; REJECT
+
+# Indirect calls are assumed to be splitting functions.
+start 96 nosplit callind
+start 100 nosplit callind; REJECT ppc64 ppc64le
+start 104 nosplit callind; REJECT ppc64 ppc64le amd64 arm64
+start 108 nosplit callind; REJECT ppc64 ppc64le amd64
+start 112 nosplit callind; REJECT ppc64 ppc64le amd64 arm64
+start 116 nosplit callind; REJECT ppc64 ppc64le amd64
+start 120 nosplit callind; REJECT ppc64 ppc64le amd64 386 arm64
+start 124 nosplit callind; REJECT ppc64 ppc64le amd64 386
+start 128 nosplit callind; REJECT
+start 132 nosplit callind; REJECT
+start 136 nosplit callind; REJECT
+
+# Issue 7623
+start 0 call f; f 112
+start 0 call f; f 116
+start 0 call f; f 120
+start 0 call f; f 124
+start 0 call f; f 128
+start 0 call f; f 132
+start 0 call f; f 136
+`
+
+var (
+ commentRE = regexp.MustCompile(`(?m)^#.*`)
+ rejectRE = regexp.MustCompile(`(?s)\A(.+?)((\n|; *)REJECT(.*))?\z`)
+ lineRE = regexp.MustCompile(`(\w+) (\d+)( nosplit)?(.*)`)
+ callRE = regexp.MustCompile(`\bcall (\w+)\b`)
+ callindRE = regexp.MustCompile(`\bcallind\b`)
+)
+
+func main() {
+ goarch := os.Getenv("GOARCH")
+ if goarch == "" {
+ goarch = runtime.GOARCH
+ }
+
+ dir, err := ioutil.TempDir("", "go-test-nosplit")
+ if err != nil {
+ bug()
+ fmt.Printf("creating temp dir: %v\n", err)
+ return
+ }
+ defer os.RemoveAll(dir)
+ os.Setenv("GOPATH", filepath.Join(dir, "_gopath"))
+
+ if err := ioutil.WriteFile(filepath.Join(dir, "go.mod"), []byte("module go-test-nosplit\n"), 0666); err != nil {
+ log.Panic(err)
+ }
+
+ tests = strings.Replace(tests, "\t", " ", -1)
+ tests = commentRE.ReplaceAllString(tests, "")
+
+ nok := 0
+ nfail := 0
+TestCases:
+ for len(tests) > 0 {
+ var stanza string
+ i := strings.Index(tests, "\nstart ")
+ if i < 0 {
+ stanza, tests = tests, ""
+ } else {
+ stanza, tests = tests[:i], tests[i+1:]
+ }
+
+ m := rejectRE.FindStringSubmatch(stanza)
+ if m == nil {
+ bug()
+ fmt.Printf("invalid stanza:\n\t%s\n", indent(stanza))
+ continue
+ }
+ lines := strings.TrimSpace(m[1])
+ reject := false
+ if m[2] != "" {
+ if strings.TrimSpace(m[4]) == "" {
+ reject = true
+ } else {
+ for _, rej := range strings.Fields(m[4]) {
+ if rej == goarch {
+ reject = true
+ }
+ }
+ }
+ }
+ if lines == "" && !reject {
+ continue
+ }
+
+ var gobuf bytes.Buffer
+ fmt.Fprintf(&gobuf, "package main\n")
+
+ var buf bytes.Buffer
+ ptrSize := 4
+ switch goarch {
+ case "mips", "mipsle":
+ fmt.Fprintf(&buf, "#define REGISTER (R0)\n")
+ case "mips64", "mips64le":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER (R0)\n")
+ case "loong64":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER (R0)\n")
+ case "ppc64", "ppc64le":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER (CTR)\n")
+ case "arm":
+ fmt.Fprintf(&buf, "#define REGISTER (R0)\n")
+ case "arm64":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER (R0)\n")
+ case "amd64":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER AX\n")
+ case "riscv64":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER A0\n")
+ case "s390x":
+ ptrSize = 8
+ fmt.Fprintf(&buf, "#define REGISTER R10\n")
+ default:
+ fmt.Fprintf(&buf, "#define REGISTER AX\n")
+ }
+
+ // Since all of the functions we're generating are
+ // ABI0, first enter ABI0 via a splittable function
+ // and then go to the chain we're testing. This way we
+ // don't have to account for ABI wrappers in the chain.
+ fmt.Fprintf(&gobuf, "func main0()\n")
+ fmt.Fprintf(&gobuf, "func main() { main0() }\n")
+ fmt.Fprintf(&buf, "TEXT ·main0(SB),0,$0-0\n\tCALL ·start(SB)\n")
+
+ adjusted := false
+ for _, line := range strings.Split(lines, "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ for _, subline := range strings.Split(line, ";") {
+ subline = strings.TrimSpace(subline)
+ if subline == "" {
+ continue
+ }
+ m := lineRE.FindStringSubmatch(subline)
+ if m == nil {
+ bug()
+ fmt.Printf("invalid function line: %s\n", subline)
+ continue TestCases
+ }
+ name := m[1]
+ size, _ := strconv.Atoi(m[2])
+
+ if size%ptrSize == 4 {
+ continue TestCases
+ }
+ nosplit := m[3]
+ body := m[4]
+
+ // The limit was originally 128 but is now 800.
+ // Instead of rewriting the test cases above, adjust
+ // the first nosplit frame to use up the extra bytes.
+ // This isn't exactly right because we could have
+ // nosplit -> split -> nosplit, but it's good enough.
+ if !adjusted && nosplit != "" {
+ const stackNosplitBase = 800 // internal/abi.StackNosplitBase
+ adjusted = true
+ size += stackNosplitBase - 128
+ }
+
+ if nosplit != "" {
+ nosplit = ",7"
+ } else {
+ nosplit = ",0"
+ }
+ body = callRE.ReplaceAllString(body, "CALL ·$1(SB);")
+ body = callindRE.ReplaceAllString(body, "CALL REGISTER;")
+
+ fmt.Fprintf(&gobuf, "func %s()\n", name)
+ fmt.Fprintf(&buf, "TEXT ·%s(SB)%s,$%d-0\n\t%s\n\tRET\n\n", name, nosplit, size, body)
+ }
+ }
+
+ if debug {
+ fmt.Printf("===\n%s\n", strings.TrimSpace(stanza))
+ fmt.Printf("-- main.go --\n%s", gobuf.String())
+ fmt.Printf("-- asm.s --\n%s", buf.String())
+ }
+
+ if err := ioutil.WriteFile(filepath.Join(dir, "asm.s"), buf.Bytes(), 0666); err != nil {
+ log.Fatal(err)
+ }
+ if err := ioutil.WriteFile(filepath.Join(dir, "main.go"), gobuf.Bytes(), 0666); err != nil {
+ log.Fatal(err)
+ }
+
+ cmd := exec.Command("go", "build")
+ cmd.Dir = dir
+ output, err := cmd.CombinedOutput()
+ if err == nil {
+ nok++
+ if reject {
+ bug()
+ fmt.Printf("accepted incorrectly:\n\t%s\n", indent(strings.TrimSpace(stanza)))
+ }
+ } else {
+ nfail++
+ if !reject {
+ bug()
+ fmt.Printf("rejected incorrectly:\n\t%s\n", indent(strings.TrimSpace(stanza)))
+ fmt.Printf("\n\tlinker output:\n\t%s\n", indent(string(output)))
+ }
+ }
+ }
+
+ if !bugged && (nok == 0 || nfail == 0) {
+ bug()
+ fmt.Printf("not enough test cases run\n")
+ }
+}
+
+func indent(s string) string {
+ return strings.Replace(s, "\n", "\n\t", -1)
+}
+
+var bugged = false
+
+func bug() {
+ if !bugged {
+ bugged = true
+ fmt.Printf("BUG\n")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/nowritebarrier.go b/platform/dbops/binaries/go/go/test/nowritebarrier.go
new file mode 100644
index 0000000000000000000000000000000000000000..d176e28b5ae3fd204398d703005f06f05fcbe43e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nowritebarrier.go
@@ -0,0 +1,96 @@
+// errorcheck -+ -p=runtime
+
+// 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 go:nowritebarrier and related directives.
+// This must appear to be in package runtime so the compiler
+// recognizes "systemstack".
+
+package runtime
+
+type t struct {
+ f *t
+}
+
+var x t
+var y *t
+
+//go:nowritebarrier
+func a1() {
+ x.f = y // ERROR "write barrier prohibited"
+ a2() // no error
+}
+
+//go:noinline
+func a2() {
+ x.f = y
+}
+
+//go:nowritebarrierrec
+func b1() {
+ b2()
+}
+
+//go:noinline
+func b2() {
+ x.f = y // ERROR "write barrier prohibited by caller"
+}
+
+// Test recursive cycles through nowritebarrierrec and yeswritebarrierrec.
+
+//go:nowritebarrierrec
+func c1() {
+ c2()
+}
+
+//go:yeswritebarrierrec
+func c2() {
+ c3()
+}
+
+func c3() {
+ x.f = y
+ c4()
+}
+
+//go:nowritebarrierrec
+func c4() {
+ c2()
+}
+
+//go:nowritebarrierrec
+func d1() {
+ d2()
+}
+
+func d2() {
+ d3()
+}
+
+//go:noinline
+func d3() {
+ x.f = y // ERROR "write barrier prohibited by caller"
+ d4()
+}
+
+//go:yeswritebarrierrec
+func d4() {
+ d2()
+}
+
+//go:noinline
+func systemstack(func()) {}
+
+//go:nowritebarrierrec
+func e1() {
+ systemstack(e2)
+ systemstack(func() {
+ x.f = y // ERROR "write barrier prohibited by caller"
+ })
+}
+
+func e2() {
+ x.f = y // ERROR "write barrier prohibited by caller"
+}
diff --git a/platform/dbops/binaries/go/go/test/nul1.go b/platform/dbops/binaries/go/go/test/nul1.go
new file mode 100644
index 0000000000000000000000000000000000000000..fbba19857b9cee4f01fe694b20b01e68222dfbd7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/nul1.go
@@ -0,0 +1,55 @@
+// errorcheckoutput
+
+// 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.
+
+// Test source files and strings containing NUL and invalid UTF-8.
+
+package main
+
+import (
+ "fmt"
+ "os"
+)
+
+func main() {
+ var s = "\xc2\xff"
+ var t = "\xd0\xfe"
+ var u = "\xab\x00\xfc"
+
+ if len(s) != 2 || s[0] != 0xc2 || s[1] != 0xff ||
+ len(t) != 2 || t[0] != 0xd0 || t[1] != 0xfe ||
+ len(u) != 3 || u[0] != 0xab || u[1] != 0x00 || u[2] != 0xfc {
+ println("BUG: non-UTF-8 string mangled")
+ os.Exit(2)
+ }
+
+ fmt.Print(`
+package main
+
+var x = "in string ` + "\x00" + `" // ERROR "NUL"
+
+var y = ` + "`in raw string \x00 foo`" + ` // ERROR "NUL"
+
+// in comment ` + "\x00" + ` // ERROR "NUL"
+
+/* in other comment ` + "\x00" + ` */ // ERROR "NUL"
+
+/* in source code */ ` + "\x00" + `// ERROR "NUL"
+
+var xx = "in string ` + "\xc2\xff" + `" // ERROR "UTF-8"
+
+var yy = ` + "`in raw string \xff foo`" + ` // ERROR "UTF-8"
+
+// in comment ` + "\xe2\x80\x01" + ` // ERROR "UTF-8"
+
+/* in other comment ` + "\xe0\x00\x00" + ` */ // ERROR "UTF-8|NUL"
+
+/* in variable name */
+var z` + "\xc1\x81" + ` int // ERROR "UTF-8"
+
+/* in source code */ ` + "var \xc2A int" + `// ERROR "UTF-8"
+
+`)
+}
diff --git a/platform/dbops/binaries/go/go/test/opt_branchlikely.go b/platform/dbops/binaries/go/go/test/opt_branchlikely.go
new file mode 100644
index 0000000000000000000000000000000000000000..0aee33f87a578bc8a56c6d3954baf39af81e2958
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/opt_branchlikely.go
@@ -0,0 +1,87 @@
+// errorcheck -0 -d=ssa/likelyadjust/debug=1,ssa/insert_resched_checks/off
+// rescheduling check insertion is turned off because the inserted conditional branches perturb the errorcheck
+
+//go:build amd64
+
+// 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 that branches have some prediction properties.
+package foo
+
+func f(x, y, z int) int {
+ a := 0
+ for i := 0; i < x; i++ { // ERROR "Branch prediction rule stay in loop"
+ for j := 0; j < y; j++ { // ERROR "Branch prediction rule stay in loop"
+ a += j
+ }
+ for k := 0; k < z; k++ { // ERROR "Branch prediction rule stay in loop"
+ a -= x + y + z
+ }
+ }
+ return a
+}
+
+func g(x, y, z int) int {
+ a := 0
+ if y == 0 { // ERROR "Branch prediction rule default < call"
+ y = g(y, z, x)
+ } else {
+ y++
+ }
+ if y == x { // ERROR "Branch prediction rule default < call"
+ y = g(y, z, x)
+ } else {
+ }
+ if y == 2 { // ERROR "Branch prediction rule default < call"
+ z++
+ } else {
+ y = g(z, x, y)
+ }
+ if y+z == 3 { // ERROR "Branch prediction rule call < exit"
+ println("ha ha")
+ } else {
+ panic("help help help")
+ }
+ if x != 0 { // ERROR "Branch prediction rule default < ret"
+ for i := 0; i < x; i++ { // ERROR "Branch prediction rule stay in loop"
+ if x == 4 { // ERROR "Branch prediction rule stay in loop"
+ return a
+ }
+ for j := 0; j < y; j++ { // ERROR "Branch prediction rule stay in loop"
+ for k := 0; k < z; k++ { // ERROR "Branch prediction rule stay in loop"
+ a -= j * i
+ }
+ a += j
+ }
+ }
+ }
+ return a
+}
+
+func h(x, y, z int) int {
+ a := 0
+ for i := 0; i < x; i++ { // ERROR "Branch prediction rule stay in loop"
+ for j := 0; j < y; j++ { // ERROR "Branch prediction rule stay in loop"
+ a += j
+ if i == j { // ERROR "Branch prediction rule stay in loop"
+ break
+ }
+ a *= j
+ }
+ for k := 0; k < z; k++ { // ERROR "Branch prediction rule stay in loop"
+ a -= k
+ if i == k {
+ continue
+ }
+ a *= k
+ }
+ }
+ if a > 0 { // ERROR "Branch prediction rule default < call"
+ a = g(x, y, z)
+ } else {
+ a = -a
+ }
+ return a
+}
diff --git a/platform/dbops/binaries/go/go/test/parentype.go b/platform/dbops/binaries/go/go/test/parentype.go
new file mode 100644
index 0000000000000000000000000000000000000000..eafa076481a88eebb4feb678b592b626c04f4c00
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/parentype.go
@@ -0,0 +1,19 @@
+// compile
+
+// 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.
+
+// Test that types can be parenthesized.
+
+package main
+
+func f(interface{})
+func g() {}
+func main() {
+ f(map[string]string{"a":"b","c":"d"})
+ f([...]int{1,2,3})
+ f(map[string]func(){"a":g,"c":g})
+ f(make(chan(<-chan int)))
+ f(make(chan<-(chan int)))
+}
diff --git a/platform/dbops/binaries/go/go/test/peano.go b/platform/dbops/binaries/go/go/test/peano.go
new file mode 100644
index 0000000000000000000000000000000000000000..1102a972444b8f6e1dd39795d93c35ff13a99f78
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/peano.go
@@ -0,0 +1,131 @@
+// run
+
+// 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.
+
+// Test that heavy recursion works. Simple torture test for
+// segmented stacks: do math in unary by recursion.
+
+package main
+
+import "runtime"
+
+type Number *Number
+
+// -------------------------------------
+// Peano primitives
+
+func zero() *Number {
+ return nil
+}
+
+func is_zero(x *Number) bool {
+ return x == nil
+}
+
+func add1(x *Number) *Number {
+ e := new(Number)
+ *e = x
+ return e
+}
+
+func sub1(x *Number) *Number {
+ return *x
+}
+
+func add(x, y *Number) *Number {
+ if is_zero(y) {
+ return x
+ }
+
+ return add(add1(x), sub1(y))
+}
+
+func mul(x, y *Number) *Number {
+ if is_zero(x) || is_zero(y) {
+ return zero()
+ }
+
+ return add(mul(x, sub1(y)), x)
+}
+
+func fact(n *Number) *Number {
+ if is_zero(n) {
+ return add1(zero())
+ }
+
+ return mul(fact(sub1(n)), n)
+}
+
+// -------------------------------------
+// Helpers to generate/count Peano integers
+
+func gen(n int) *Number {
+ if n > 0 {
+ return add1(gen(n - 1))
+ }
+
+ return zero()
+}
+
+func count(x *Number) int {
+ if is_zero(x) {
+ return 0
+ }
+
+ return count(sub1(x)) + 1
+}
+
+func check(x *Number, expected int) {
+ var c = count(x)
+ if c != expected {
+ print("error: found ", c, "; expected ", expected, "\n")
+ panic("fail")
+ }
+}
+
+// -------------------------------------
+// Test basic functionality
+
+func init() {
+ check(zero(), 0)
+ check(add1(zero()), 1)
+ check(gen(10), 10)
+
+ check(add(gen(3), zero()), 3)
+ check(add(zero(), gen(4)), 4)
+ check(add(gen(3), gen(4)), 7)
+
+ check(mul(zero(), zero()), 0)
+ check(mul(gen(3), zero()), 0)
+ check(mul(zero(), gen(4)), 0)
+ check(mul(gen(3), add1(zero())), 3)
+ check(mul(add1(zero()), gen(4)), 4)
+ check(mul(gen(3), gen(4)), 12)
+
+ check(fact(zero()), 1)
+ check(fact(add1(zero())), 1)
+ check(fact(gen(5)), 120)
+}
+
+// -------------------------------------
+// Factorial
+
+var results = [...]int{
+ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,
+ 39916800, 479001600,
+}
+
+func main() {
+ max := 9
+ if runtime.GOARCH == "wasm" {
+ max = 7 // stack size is limited
+ }
+ for i := 0; i <= max; i++ {
+ if f := count(fact(gen(i))); f != results[i] {
+ println("FAIL:", i, "!:", f, "!=", results[i])
+ panic(0)
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/phiopt.go b/platform/dbops/binaries/go/go/test/phiopt.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e21bfdba55aeab33ecf4d943043ff5485164861
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/phiopt.go
@@ -0,0 +1,133 @@
+// errorcheck -0 -d=ssa/phiopt/debug=3
+
+//go:build amd64 || s390x || arm64
+
+// 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 main
+
+//go:noinline
+func f0(a bool) bool {
+ x := false
+ if a {
+ x = true
+ } else {
+ x = false
+ }
+ return x // ERROR "converted OpPhi to Copy$"
+}
+
+//go:noinline
+func f1(a bool) bool {
+ x := false
+ if a {
+ x = false
+ } else {
+ x = true
+ }
+ return x // ERROR "converted OpPhi to Not$"
+}
+
+//go:noinline
+func f2(a, b int) bool {
+ x := true
+ if a == b {
+ x = false
+ }
+ return x // ERROR "converted OpPhi to Not$"
+}
+
+//go:noinline
+func f3(a, b int) bool {
+ x := false
+ if a == b {
+ x = true
+ }
+ return x // ERROR "converted OpPhi to Copy$"
+}
+
+//go:noinline
+func f4(a, b bool) bool {
+ return a || b // ERROR "converted OpPhi to OrB$"
+}
+
+//go:noinline
+func f5or(a int, b bool) bool {
+ var x bool
+ if a == 0 {
+ x = true
+ } else {
+ x = b
+ }
+ return x // ERROR "converted OpPhi to OrB$"
+}
+
+//go:noinline
+func f5and(a int, b bool) bool {
+ var x bool
+ if a == 0 {
+ x = b
+ } else {
+ x = false
+ }
+ return x // ERROR "converted OpPhi to AndB$"
+}
+
+//go:noinline
+func f6or(a int, b bool) bool {
+ x := b
+ if a == 0 {
+ // f6or has side effects so the OpPhi should not be converted.
+ x = f6or(a, b)
+ }
+ return x
+}
+
+//go:noinline
+func f6and(a int, b bool) bool {
+ x := b
+ if a == 0 {
+ // f6and has side effects so the OpPhi should not be converted.
+ x = f6and(a, b)
+ }
+ return x
+}
+
+//go:noinline
+func f7or(a bool, b bool) bool {
+ return a || b // ERROR "converted OpPhi to OrB$"
+}
+
+//go:noinline
+func f7and(a bool, b bool) bool {
+ return a && b // ERROR "converted OpPhi to AndB$"
+}
+
+//go:noinline
+func f8(s string) (string, bool) {
+ neg := false
+ if s[0] == '-' { // ERROR "converted OpPhi to Copy$"
+ neg = true
+ s = s[1:]
+ }
+ return s, neg
+}
+
+var d int
+
+//go:noinline
+func f9(a, b int) bool {
+ c := false
+ if a < 0 { // ERROR "converted OpPhi to Copy$"
+ if b < 0 {
+ d = d + 1
+ }
+ c = true
+ }
+ return c
+}
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/print.go b/platform/dbops/binaries/go/go/test/print.go
new file mode 100644
index 0000000000000000000000000000000000000000..7718c735e48d0ac5b22209aa74c4fc4254a20b9d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/print.go
@@ -0,0 +1,54 @@
+// run
+
+// 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 internal print routines that are generated
+// by the print builtin. This test is not exhaustive,
+// we're just checking that the formatting is correct.
+
+package main
+
+func main() {
+ println((interface{})(nil)) // printeface
+ println((interface { // printiface
+ f()
+ })(nil))
+ println((map[int]int)(nil)) // printpointer
+ println(([]int)(nil)) // printslice
+ println(int64(-7)) // printint
+ println(uint64(7)) // printuint
+ println(uint32(7)) // printuint
+ println(uint16(7)) // printuint
+ println(uint8(7)) // printuint
+ println(uint(7)) // printuint
+ println(uintptr(7)) // printuint
+ println(8.0) // printfloat
+ println(complex(9.0, 10.0)) // printcomplex
+ println(true) // printbool
+ println(false) // printbool
+ println("hello") // printstring
+ println("one", "two") // printsp
+
+ // test goprintf
+ defer println((interface{})(nil))
+ defer println((interface {
+ f()
+ })(nil))
+ defer println((map[int]int)(nil))
+ defer println(([]int)(nil))
+ defer println(int64(-11))
+ defer println(uint64(12))
+ defer println(uint32(12))
+ defer println(uint16(12))
+ defer println(uint8(12))
+ defer println(uint(12))
+ defer println(uintptr(12))
+ defer println(13.0)
+ defer println(complex(14.0, 15.0))
+ defer println(true)
+ defer println(false)
+ defer println("hello")
+ defer println("one", "two")
+}
diff --git a/platform/dbops/binaries/go/go/test/print.out b/platform/dbops/binaries/go/go/test/print.out
new file mode 100644
index 0000000000000000000000000000000000000000..85376af0c78eadf51ffcc0eb60b2e9fbe505c83d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/print.out
@@ -0,0 +1,34 @@
+(0x0,0x0)
+(0x0,0x0)
+0x0
+[0/0]0x0
+-7
+7
+7
+7
+7
+7
+7
++8.000000e+000
+(+9.000000e+000+1.000000e+001i)
+true
+false
+hello
+one two
+one two
+hello
+false
+true
+(+1.400000e+001+1.500000e+001i)
++1.300000e+001
+12
+12
+12
+12
+12
+12
+-11
+[0/0]0x0
+0x0
+(0x0,0x0)
+(0x0,0x0)
diff --git a/platform/dbops/binaries/go/go/test/printbig.go b/platform/dbops/binaries/go/go/test/printbig.go
new file mode 100644
index 0000000000000000000000000000000000000000..9e08c39adc232826c78e839103bfa4392c892db8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/printbig.go
@@ -0,0 +1,14 @@
+// run
+
+// 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.
+
+// Test that big numbers work as constants and print can print them.
+
+package main
+
+func main() {
+ print(-(1<<63), "\n")
+ print((1<<63)-1, "\n")
+}
diff --git a/platform/dbops/binaries/go/go/test/printbig.out b/platform/dbops/binaries/go/go/test/printbig.out
new file mode 100644
index 0000000000000000000000000000000000000000..6a16b15d987c9d87278ecb4b7943766f3aa3374c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/printbig.out
@@ -0,0 +1,2 @@
+-9223372036854775808
+9223372036854775807
diff --git a/platform/dbops/binaries/go/go/test/prove.go b/platform/dbops/binaries/go/go/test/prove.go
new file mode 100644
index 0000000000000000000000000000000000000000..1aea2822912c2726625b247d531a4dd52dd550a2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/prove.go
@@ -0,0 +1,1127 @@
+// errorcheck -0 -d=ssa/prove/debug=1
+
+//go:build amd64
+
+// 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 main
+
+import "math"
+
+func f0(a []int) int {
+ a[0] = 1
+ a[0] = 1 // ERROR "Proved IsInBounds$"
+ a[6] = 1
+ a[6] = 1 // ERROR "Proved IsInBounds$"
+ a[5] = 1 // ERROR "Proved IsInBounds$"
+ a[5] = 1 // ERROR "Proved IsInBounds$"
+ return 13
+}
+
+func f1(a []int) int {
+ if len(a) <= 5 {
+ return 18
+ }
+ a[0] = 1 // ERROR "Proved IsInBounds$"
+ a[0] = 1 // ERROR "Proved IsInBounds$"
+ a[6] = 1
+ a[6] = 1 // ERROR "Proved IsInBounds$"
+ a[5] = 1 // ERROR "Proved IsInBounds$"
+ a[5] = 1 // ERROR "Proved IsInBounds$"
+ return 26
+}
+
+func f1b(a []int, i int, j uint) int {
+ if i >= 0 && i < len(a) {
+ return a[i] // ERROR "Proved IsInBounds$"
+ }
+ if i >= 10 && i < len(a) {
+ return a[i] // ERROR "Proved IsInBounds$"
+ }
+ if i >= 10 && i < len(a) {
+ return a[i] // ERROR "Proved IsInBounds$"
+ }
+ if i >= 10 && i < len(a) {
+ return a[i-10] // ERROR "Proved IsInBounds$"
+ }
+ if j < uint(len(a)) {
+ return a[j] // ERROR "Proved IsInBounds$"
+ }
+ return 0
+}
+
+func f1c(a []int, i int64) int {
+ c := uint64(math.MaxInt64 + 10) // overflows int
+ d := int64(c)
+ if i >= d && i < int64(len(a)) {
+ // d overflows, should not be handled.
+ return a[i]
+ }
+ return 0
+}
+
+func f2(a []int) int {
+ for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ a[i+1] = i
+ a[i+1] = i // ERROR "Proved IsInBounds$"
+ }
+ return 34
+}
+
+func f3(a []uint) int {
+ for i := uint(0); i < uint(len(a)); i++ {
+ a[i] = i // ERROR "Proved IsInBounds$"
+ }
+ return 41
+}
+
+func f4a(a, b, c int) int {
+ if a < b {
+ if a == b { // ERROR "Disproved Eq64$"
+ return 47
+ }
+ if a > b { // ERROR "Disproved Less64$"
+ return 50
+ }
+ if a < b { // ERROR "Proved Less64$"
+ return 53
+ }
+ // We can't get to this point and prove knows that, so
+ // there's no message for the next (obvious) branch.
+ if a != a {
+ return 56
+ }
+ return 61
+ }
+ return 63
+}
+
+func f4b(a, b, c int) int {
+ if a <= b {
+ if a >= b {
+ if a == b { // ERROR "Proved Eq64$"
+ return 70
+ }
+ return 75
+ }
+ return 77
+ }
+ return 79
+}
+
+func f4c(a, b, c int) int {
+ if a <= b {
+ if a >= b {
+ if a != b { // ERROR "Disproved Neq64$"
+ return 73
+ }
+ return 75
+ }
+ return 77
+ }
+ return 79
+}
+
+func f4d(a, b, c int) int {
+ if a < b {
+ if a < c {
+ if a < b { // ERROR "Proved Less64$"
+ if a < c { // ERROR "Proved Less64$"
+ return 87
+ }
+ return 89
+ }
+ return 91
+ }
+ return 93
+ }
+ return 95
+}
+
+func f4e(a, b, c int) int {
+ if a < b {
+ if b > a { // ERROR "Proved Less64$"
+ return 101
+ }
+ return 103
+ }
+ return 105
+}
+
+func f4f(a, b, c int) int {
+ if a <= b {
+ if b > a {
+ if b == a { // ERROR "Disproved Eq64$"
+ return 112
+ }
+ return 114
+ }
+ if b >= a { // ERROR "Proved Leq64$"
+ if b == a { // ERROR "Proved Eq64$"
+ return 118
+ }
+ return 120
+ }
+ return 122
+ }
+ return 124
+}
+
+func f5(a, b uint) int {
+ if a == b {
+ if a <= b { // ERROR "Proved Leq64U$"
+ return 130
+ }
+ return 132
+ }
+ return 134
+}
+
+// These comparisons are compile time constants.
+func f6a(a uint8) int {
+ if a < a { // ERROR "Disproved Less8U$"
+ return 140
+ }
+ return 151
+}
+
+func f6b(a uint8) int {
+ if a < a { // ERROR "Disproved Less8U$"
+ return 140
+ }
+ return 151
+}
+
+func f6x(a uint8) int {
+ if a > a { // ERROR "Disproved Less8U$"
+ return 143
+ }
+ return 151
+}
+
+func f6d(a uint8) int {
+ if a <= a { // ERROR "Proved Leq8U$"
+ return 146
+ }
+ return 151
+}
+
+func f6e(a uint8) int {
+ if a >= a { // ERROR "Proved Leq8U$"
+ return 149
+ }
+ return 151
+}
+
+func f7(a []int, b int) int {
+ if b < len(a) {
+ a[b] = 3
+ if b < len(a) { // ERROR "Proved Less64$"
+ a[b] = 5 // ERROR "Proved IsInBounds$"
+ }
+ }
+ return 161
+}
+
+func f8(a, b uint) int {
+ if a == b {
+ return 166
+ }
+ if a > b {
+ return 169
+ }
+ if a < b { // ERROR "Proved Less64U$"
+ return 172
+ }
+ return 174
+}
+
+func f9(a, b bool) int {
+ if a {
+ return 1
+ }
+ if a || b { // ERROR "Disproved Arg$"
+ return 2
+ }
+ return 3
+}
+
+func f10(a string) int {
+ n := len(a)
+ // We optimize comparisons with small constant strings (see cmd/compile/internal/gc/walk.go),
+ // so this string literal must be long.
+ if a[:n>>1] == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" {
+ return 0
+ }
+ return 1
+}
+
+func f11a(a []int, i int) {
+ useInt(a[i])
+ useInt(a[i]) // ERROR "Proved IsInBounds$"
+}
+
+func f11b(a []int, i int) {
+ useSlice(a[i:])
+ useSlice(a[i:]) // ERROR "Proved IsSliceInBounds$"
+}
+
+func f11c(a []int, i int) {
+ useSlice(a[:i])
+ useSlice(a[:i]) // ERROR "Proved IsSliceInBounds$"
+}
+
+func f11d(a []int, i int) {
+ useInt(a[2*i+7])
+ useInt(a[2*i+7]) // ERROR "Proved IsInBounds$"
+}
+
+func f12(a []int, b int) {
+ useSlice(a[:b])
+}
+
+func f13a(a, b, c int, x bool) int {
+ if a > 12 {
+ if x {
+ if a < 12 { // ERROR "Disproved Less64$"
+ return 1
+ }
+ }
+ if x {
+ if a <= 12 { // ERROR "Disproved Leq64$"
+ return 2
+ }
+ }
+ if x {
+ if a == 12 { // ERROR "Disproved Eq64$"
+ return 3
+ }
+ }
+ if x {
+ if a >= 12 { // ERROR "Proved Leq64$"
+ return 4
+ }
+ }
+ if x {
+ if a > 12 { // ERROR "Proved Less64$"
+ return 5
+ }
+ }
+ return 6
+ }
+ return 0
+}
+
+func f13b(a int, x bool) int {
+ if a == -9 {
+ if x {
+ if a < -9 { // ERROR "Disproved Less64$"
+ return 7
+ }
+ }
+ if x {
+ if a <= -9 { // ERROR "Proved Leq64$"
+ return 8
+ }
+ }
+ if x {
+ if a == -9 { // ERROR "Proved Eq64$"
+ return 9
+ }
+ }
+ if x {
+ if a >= -9 { // ERROR "Proved Leq64$"
+ return 10
+ }
+ }
+ if x {
+ if a > -9 { // ERROR "Disproved Less64$"
+ return 11
+ }
+ }
+ return 12
+ }
+ return 0
+}
+
+func f13c(a int, x bool) int {
+ if a < 90 {
+ if x {
+ if a < 90 { // ERROR "Proved Less64$"
+ return 13
+ }
+ }
+ if x {
+ if a <= 90 { // ERROR "Proved Leq64$"
+ return 14
+ }
+ }
+ if x {
+ if a == 90 { // ERROR "Disproved Eq64$"
+ return 15
+ }
+ }
+ if x {
+ if a >= 90 { // ERROR "Disproved Leq64$"
+ return 16
+ }
+ }
+ if x {
+ if a > 90 { // ERROR "Disproved Less64$"
+ return 17
+ }
+ }
+ return 18
+ }
+ return 0
+}
+
+func f13d(a int) int {
+ if a < 5 {
+ if a < 9 { // ERROR "Proved Less64$"
+ return 1
+ }
+ }
+ return 0
+}
+
+func f13e(a int) int {
+ if a > 9 {
+ if a > 5 { // ERROR "Proved Less64$"
+ return 1
+ }
+ }
+ return 0
+}
+
+func f13f(a int64) int64 {
+ if a > math.MaxInt64 {
+ if a == 0 { // ERROR "Disproved Eq64$"
+ return 1
+ }
+ }
+ return 0
+}
+
+func f13g(a int) int {
+ if a < 3 {
+ return 5
+ }
+ if a > 3 {
+ return 6
+ }
+ if a == 3 { // ERROR "Proved Eq64$"
+ return 7
+ }
+ return 8
+}
+
+func f13h(a int) int {
+ if a < 3 {
+ if a > 1 {
+ if a == 2 { // ERROR "Proved Eq64$"
+ return 5
+ }
+ }
+ }
+ return 0
+}
+
+func f13i(a uint) int {
+ if a == 0 {
+ return 1
+ }
+ if a > 0 { // ERROR "Proved Less64U$"
+ return 2
+ }
+ return 3
+}
+
+func f14(p, q *int, a []int) {
+ // This crazy ordering usually gives i1 the lowest value ID,
+ // j the middle value ID, and i2 the highest value ID.
+ // That used to confuse CSE because it ordered the args
+ // of the two + ops below differently.
+ // That in turn foiled bounds check elimination.
+ i1 := *p
+ j := *q
+ i2 := *p
+ useInt(a[i1+j])
+ useInt(a[i2+j]) // ERROR "Proved IsInBounds$"
+}
+
+func f15(s []int, x int) {
+ useSlice(s[x:])
+ useSlice(s[:x]) // ERROR "Proved IsSliceInBounds$"
+}
+
+func f16(s []int) []int {
+ if len(s) >= 10 {
+ return s[:10] // ERROR "Proved IsSliceInBounds$"
+ }
+ return nil
+}
+
+func f17(b []int) {
+ for i := 0; i < len(b); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ // This tests for i <= cap, which we can only prove
+ // using the derived relation between len and cap.
+ // This depends on finding the contradiction, since we
+ // don't query this condition directly.
+ useSlice(b[:i]) // ERROR "Proved IsSliceInBounds$"
+ }
+}
+
+func f18(b []int, x int, y uint) {
+ _ = b[x]
+ _ = b[y]
+
+ if x > len(b) { // ERROR "Disproved Less64$"
+ return
+ }
+ if y > uint(len(b)) { // ERROR "Disproved Less64U$"
+ return
+ }
+ if int(y) > len(b) { // ERROR "Disproved Less64$"
+ return
+ }
+}
+
+func f19() (e int64, err error) {
+ // Issue 29502: slice[:0] is incorrectly disproved.
+ var stack []int64
+ stack = append(stack, 123)
+ if len(stack) > 1 {
+ panic("too many elements")
+ }
+ last := len(stack) - 1
+ e = stack[last]
+ // Buggy compiler prints "Disproved Leq64" for the next line.
+ stack = stack[:last]
+ return e, nil
+}
+
+func sm1(b []int, x int) {
+ // Test constant argument to slicemask.
+ useSlice(b[2:8]) // ERROR "Proved slicemask not needed$"
+ // Test non-constant argument with known limits.
+ if cap(b) > 10 {
+ useSlice(b[2:])
+ }
+}
+
+func lim1(x, y, z int) {
+ // Test relations between signed and unsigned limits.
+ if x > 5 {
+ if uint(x) > 5 { // ERROR "Proved Less64U$"
+ return
+ }
+ }
+ if y >= 0 && y < 4 {
+ if uint(y) > 4 { // ERROR "Disproved Less64U$"
+ return
+ }
+ if uint(y) < 5 { // ERROR "Proved Less64U$"
+ return
+ }
+ }
+ if z < 4 {
+ if uint(z) > 4 { // Not provable without disjunctions.
+ return
+ }
+ }
+}
+
+// fence1–4 correspond to the four fence-post implications.
+
+func fence1(b []int, x, y int) {
+ // Test proofs that rely on fence-post implications.
+ if x+1 > y {
+ if x < y { // ERROR "Disproved Less64$"
+ return
+ }
+ }
+ if len(b) < cap(b) {
+ // This eliminates the growslice path.
+ b = append(b, 1) // ERROR "Disproved Less64U$"
+ }
+}
+
+func fence2(x, y int) {
+ if x-1 < y {
+ if x > y { // ERROR "Disproved Less64$"
+ return
+ }
+ }
+}
+
+func fence3(b, c []int, x, y int64) {
+ if x-1 >= y {
+ if x <= y { // Can't prove because x may have wrapped.
+ return
+ }
+ }
+
+ if x != math.MinInt64 && x-1 >= y {
+ if x <= y { // ERROR "Disproved Leq64$"
+ return
+ }
+ }
+
+ c[len(c)-1] = 0 // Can't prove because len(c) might be 0
+
+ if n := len(b); n > 0 {
+ b[n-1] = 0 // ERROR "Proved IsInBounds$"
+ }
+}
+
+func fence4(x, y int64) {
+ if x >= y+1 {
+ if x <= y {
+ return
+ }
+ }
+ if y != math.MaxInt64 && x >= y+1 {
+ if x <= y { // ERROR "Disproved Leq64$"
+ return
+ }
+ }
+}
+
+// Check transitive relations
+func trans1(x, y int64) {
+ if x > 5 {
+ if y > x {
+ if y > 2 { // ERROR "Proved Less64$"
+ return
+ }
+ } else if y == x {
+ if y > 5 { // ERROR "Proved Less64$"
+ return
+ }
+ }
+ }
+ if x >= 10 {
+ if y > x {
+ if y > 10 { // ERROR "Proved Less64$"
+ return
+ }
+ }
+ }
+}
+
+func trans2(a, b []int, i int) {
+ if len(a) != len(b) {
+ return
+ }
+
+ _ = a[i]
+ _ = b[i] // ERROR "Proved IsInBounds$"
+}
+
+func trans3(a, b []int, i int) {
+ if len(a) > len(b) {
+ return
+ }
+
+ _ = a[i]
+ _ = b[i] // ERROR "Proved IsInBounds$"
+}
+
+func trans4(b []byte, x int) {
+ // Issue #42603: slice len/cap transitive relations.
+ switch x {
+ case 0:
+ if len(b) < 20 {
+ return
+ }
+ _ = b[:2] // ERROR "Proved IsSliceInBounds$"
+ case 1:
+ if len(b) < 40 {
+ return
+ }
+ _ = b[:2] // ERROR "Proved IsSliceInBounds$"
+ }
+}
+
+// Derived from nat.cmp
+func natcmp(x, y []uint) (r int) {
+ m := len(x)
+ n := len(y)
+ if m != n || m == 0 {
+ return
+ }
+
+ i := m - 1
+ for i > 0 && // ERROR "Induction variable: limits \(0,\?\], increment 1$"
+ x[i] == // ERROR "Proved IsInBounds$"
+ y[i] { // ERROR "Proved IsInBounds$"
+ i--
+ }
+
+ switch {
+ case x[i] < // todo, cannot prove this because it's dominated by i<=0 || x[i]==y[i]
+ y[i]: // ERROR "Proved IsInBounds$"
+ r = -1
+ case x[i] > // ERROR "Proved IsInBounds$"
+ y[i]: // ERROR "Proved IsInBounds$"
+ r = 1
+ }
+ return
+}
+
+func suffix(s, suffix string) bool {
+ // todo, we're still not able to drop the bound check here in the general case
+ return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
+}
+
+func constsuffix(s string) bool {
+ return suffix(s, "abc") // ERROR "Proved IsSliceInBounds$"
+}
+
+// oforuntil tests the pattern created by OFORUNTIL blocks. These are
+// handled by addLocalInductiveFacts rather than findIndVar.
+func oforuntil(b []int) {
+ i := 0
+ if len(b) > i {
+ top:
+ println(b[i]) // ERROR "Induction variable: limits \[0,\?\), increment 1$" "Proved IsInBounds$"
+ i++
+ if i < len(b) {
+ goto top
+ }
+ }
+}
+
+func atexit(foobar []func()) {
+ for i := len(foobar) - 1; i >= 0; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1"
+ f := foobar[i]
+ foobar = foobar[:i] // ERROR "IsSliceInBounds"
+ f()
+ }
+}
+
+func make1(n int) []int {
+ s := make([]int, n)
+ for i := 0; i < n; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1"
+ s[i] = 1 // ERROR "Proved IsInBounds$"
+ }
+ return s
+}
+
+func make2(n int) []int {
+ s := make([]int, n)
+ for i := range s { // ERROR "Induction variable: limits \[0,\?\), increment 1"
+ s[i] = 1 // ERROR "Proved IsInBounds$"
+ }
+ return s
+}
+
+// The range tests below test the index variable of range loops.
+
+// range1 compiles to the "efficiently indexable" form of a range loop.
+func range1(b []int) {
+ for i, v := range b { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ b[i] = v + 1 // ERROR "Proved IsInBounds$"
+ if i < len(b) { // ERROR "Proved Less64$"
+ println("x")
+ }
+ if i >= 0 { // ERROR "Proved Leq64$"
+ println("x")
+ }
+ }
+}
+
+// range2 elements are larger, so they use the general form of a range loop.
+func range2(b [][32]int) {
+ for i, v := range b { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
+ b[i][0] = v[0] + 1 // ERROR "Proved IsInBounds$"
+ if i < len(b) { // ERROR "Proved Less64$"
+ println("x")
+ }
+ if i >= 0 { // ERROR "Proved Leq64$"
+ println("x")
+ }
+ }
+}
+
+// signhint1-2 test whether the hint (int >= 0) is propagated into the loop.
+func signHint1(i int, data []byte) {
+ if i >= 0 {
+ for i < len(data) { // ERROR "Induction variable: limits \[\?,\?\), increment 1$"
+ _ = data[i] // ERROR "Proved IsInBounds$"
+ i++
+ }
+ }
+}
+
+func signHint2(b []byte, n int) {
+ if n < 0 {
+ panic("")
+ }
+ _ = b[25]
+ for i := n; i <= 25; i++ { // ERROR "Induction variable: limits \[\?,25\], increment 1$"
+ b[i] = 123 // ERROR "Proved IsInBounds$"
+ }
+}
+
+// indexGT0 tests whether prove learns int index >= 0 from bounds check.
+func indexGT0(b []byte, n int) {
+ _ = b[n]
+ _ = b[25]
+
+ for i := n; i <= 25; i++ { // ERROR "Induction variable: limits \[\?,25\], increment 1$"
+ b[i] = 123 // ERROR "Proved IsInBounds$"
+ }
+}
+
+// Induction variable in unrolled loop.
+func unrollUpExcl(a []int) int {
+ var i, x int
+ for i = 0; i < len(a)-1; i += 2 { // ERROR "Induction variable: limits \[0,\?\), increment 2$"
+ x += a[i] // ERROR "Proved IsInBounds$"
+ x += a[i+1]
+ }
+ if i == len(a)-1 {
+ x += a[i]
+ }
+ return x
+}
+
+// Induction variable in unrolled loop.
+func unrollUpIncl(a []int) int {
+ var i, x int
+ for i = 0; i <= len(a)-2; i += 2 { // ERROR "Induction variable: limits \[0,\?\], increment 2$"
+ x += a[i] // ERROR "Proved IsInBounds$"
+ x += a[i+1]
+ }
+ if i == len(a)-1 {
+ x += a[i]
+ }
+ return x
+}
+
+// Induction variable in unrolled loop.
+func unrollDownExcl0(a []int) int {
+ var i, x int
+ for i = len(a) - 1; i > 0; i -= 2 { // ERROR "Induction variable: limits \(0,\?\], increment 2$"
+ x += a[i] // ERROR "Proved IsInBounds$"
+ x += a[i-1] // ERROR "Proved IsInBounds$"
+ }
+ if i == 0 {
+ x += a[i]
+ }
+ return x
+}
+
+// Induction variable in unrolled loop.
+func unrollDownExcl1(a []int) int {
+ var i, x int
+ for i = len(a) - 1; i >= 1; i -= 2 { // ERROR "Induction variable: limits \(0,\?\], increment 2$"
+ x += a[i] // ERROR "Proved IsInBounds$"
+ x += a[i-1] // ERROR "Proved IsInBounds$"
+ }
+ if i == 0 {
+ x += a[i]
+ }
+ return x
+}
+
+// Induction variable in unrolled loop.
+func unrollDownInclStep(a []int) int {
+ var i, x int
+ for i = len(a); i >= 2; i -= 2 { // ERROR "Induction variable: limits \[2,\?\], increment 2$"
+ x += a[i-1] // ERROR "Proved IsInBounds$"
+ x += a[i-2] // ERROR "Proved IsInBounds$"
+ }
+ if i == 1 {
+ x += a[i-1]
+ }
+ return x
+}
+
+// Not an induction variable (step too large)
+func unrollExclStepTooLarge(a []int) int {
+ var i, x int
+ for i = 0; i < len(a)-1; i += 3 {
+ x += a[i]
+ x += a[i+1]
+ }
+ if i == len(a)-1 {
+ x += a[i]
+ }
+ return x
+}
+
+// Not an induction variable (step too large)
+func unrollInclStepTooLarge(a []int) int {
+ var i, x int
+ for i = 0; i <= len(a)-2; i += 3 {
+ x += a[i]
+ x += a[i+1]
+ }
+ if i == len(a)-1 {
+ x += a[i]
+ }
+ return x
+}
+
+// Not an induction variable (min too small, iterating down)
+func unrollDecMin(a []int) int {
+ var i, x int
+ for i = len(a); i >= math.MinInt64; i -= 2 {
+ x += a[i-1]
+ x += a[i-2]
+ }
+ if i == 1 { // ERROR "Disproved Eq64$"
+ x += a[i-1]
+ }
+ return x
+}
+
+// Not an induction variable (min too small, iterating up -- perhaps could allow, but why bother?)
+func unrollIncMin(a []int) int {
+ var i, x int
+ for i = len(a); i >= math.MinInt64; i += 2 {
+ x += a[i-1]
+ x += a[i-2]
+ }
+ if i == 1 { // ERROR "Disproved Eq64$"
+ x += a[i-1]
+ }
+ return x
+}
+
+// The 4 xxxxExtNto64 functions below test whether prove is looking
+// through value-preserving sign/zero extensions of index values (issue #26292).
+
+// Look through all extensions
+func signExtNto64(x []int, j8 int8, j16 int16, j32 int32) int {
+ if len(x) < 22 {
+ return 0
+ }
+ if j8 >= 0 && j8 < 22 {
+ return x[j8] // ERROR "Proved IsInBounds$"
+ }
+ if j16 >= 0 && j16 < 22 {
+ return x[j16] // ERROR "Proved IsInBounds$"
+ }
+ if j32 >= 0 && j32 < 22 {
+ return x[j32] // ERROR "Proved IsInBounds$"
+ }
+ return 0
+}
+
+func zeroExtNto64(x []int, j8 uint8, j16 uint16, j32 uint32) int {
+ if len(x) < 22 {
+ return 0
+ }
+ if j8 >= 0 && j8 < 22 {
+ return x[j8] // ERROR "Proved IsInBounds$"
+ }
+ if j16 >= 0 && j16 < 22 {
+ return x[j16] // ERROR "Proved IsInBounds$"
+ }
+ if j32 >= 0 && j32 < 22 {
+ return x[j32] // ERROR "Proved IsInBounds$"
+ }
+ return 0
+}
+
+// Process fence-post implications through 32to64 extensions (issue #29964)
+func signExt32to64Fence(x []int, j int32) int {
+ if x[j] != 0 {
+ return 1
+ }
+ if j > 0 && x[j-1] != 0 { // ERROR "Proved IsInBounds$"
+ return 1
+ }
+ return 0
+}
+
+func zeroExt32to64Fence(x []int, j uint32) int {
+ if x[j] != 0 {
+ return 1
+ }
+ if j > 0 && x[j-1] != 0 { // ERROR "Proved IsInBounds$"
+ return 1
+ }
+ return 0
+}
+
+// Ensure that bounds checks with negative indexes are not incorrectly removed.
+func negIndex() {
+ n := make([]int, 1)
+ for i := -1; i <= 0; i++ { // ERROR "Induction variable: limits \[-1,0\], increment 1$"
+ n[i] = 1
+ }
+}
+func negIndex2(n int) {
+ a := make([]int, 5)
+ b := make([]int, 5)
+ c := make([]int, 5)
+ for i := -1; i <= 0; i-- {
+ b[i] = i
+ n++
+ if n > 10 {
+ break
+ }
+ }
+ useSlice(a)
+ useSlice(c)
+}
+
+// Check that prove is zeroing these right shifts of positive ints by bit-width - 1.
+// e.g (Rsh64x64 n (Const64 [63])) && ft.isNonNegative(n) -> 0
+func sh64(n int64) int64 {
+ if n < 0 {
+ return n
+ }
+ return n >> 63 // ERROR "Proved Rsh64x64 shifts to zero"
+}
+
+func sh32(n int32) int32 {
+ if n < 0 {
+ return n
+ }
+ return n >> 31 // ERROR "Proved Rsh32x64 shifts to zero"
+}
+
+func sh32x64(n int32) int32 {
+ if n < 0 {
+ return n
+ }
+ return n >> uint64(31) // ERROR "Proved Rsh32x64 shifts to zero"
+}
+
+func sh16(n int16) int16 {
+ if n < 0 {
+ return n
+ }
+ return n >> 15 // ERROR "Proved Rsh16x64 shifts to zero"
+}
+
+func sh64noopt(n int64) int64 {
+ return n >> 63 // not optimized; n could be negative
+}
+
+// These cases are division of a positive signed integer by a power of 2.
+// The opt pass doesnt have sufficient information to see that n is positive.
+// So, instead, opt rewrites the division with a less-than-optimal replacement.
+// Prove, which can see that n is nonnegative, cannot see the division because
+// opt, an earlier pass, has already replaced it.
+// The fix for this issue allows prove to zero a right shift that was added as
+// part of the less-than-optimal reqwrite. That change by prove then allows
+// lateopt to clean up all the unnecessary parts of the original division
+// replacement. See issue #36159.
+func divShiftClean(n int) int {
+ if n < 0 {
+ return n
+ }
+ return n / int(8) // ERROR "Proved Rsh64x64 shifts to zero"
+}
+
+func divShiftClean64(n int64) int64 {
+ if n < 0 {
+ return n
+ }
+ return n / int64(16) // ERROR "Proved Rsh64x64 shifts to zero"
+}
+
+func divShiftClean32(n int32) int32 {
+ if n < 0 {
+ return n
+ }
+ return n / int32(16) // ERROR "Proved Rsh32x64 shifts to zero"
+}
+
+// Bounds check elimination
+
+func sliceBCE1(p []string, h uint) string {
+ if len(p) == 0 {
+ return ""
+ }
+
+ i := h & uint(len(p)-1)
+ return p[i] // ERROR "Proved IsInBounds$"
+}
+
+func sliceBCE2(p []string, h int) string {
+ if len(p) == 0 {
+ return ""
+ }
+ i := h & (len(p) - 1)
+ return p[i] // ERROR "Proved IsInBounds$"
+}
+
+func and(p []byte) ([]byte, []byte) { // issue #52563
+ const blocksize = 16
+ fullBlocks := len(p) &^ (blocksize - 1)
+ blk := p[:fullBlocks] // ERROR "Proved IsSliceInBounds$"
+ rem := p[fullBlocks:] // ERROR "Proved IsSliceInBounds$"
+ return blk, rem
+}
+
+func rshu(x, y uint) int {
+ z := x >> y
+ if z <= x { // ERROR "Proved Leq64U$"
+ return 1
+ }
+ return 0
+}
+
+func divu(x, y uint) int {
+ z := x / y
+ if z <= x { // ERROR "Proved Leq64U$"
+ return 1
+ }
+ return 0
+}
+
+func modu1(x, y uint) int {
+ z := x % y
+ if z < y { // ERROR "Proved Less64U$"
+ return 1
+ }
+ return 0
+}
+
+func modu2(x, y uint) int {
+ z := x % y
+ if z <= x { // ERROR "Proved Leq64U$"
+ return 1
+ }
+ return 0
+}
+
+func issue57077(s []int) (left, right []int) {
+ middle := len(s) / 2
+ left = s[:middle] // ERROR "Proved IsSliceInBounds$"
+ right = s[middle:] // ERROR "Proved IsSliceInBounds$"
+ return
+}
+
+func issue51622(b []byte) int {
+ if len(b) >= 3 && b[len(b)-3] == '#' { // ERROR "Proved IsInBounds$"
+ return len(b)
+ }
+ return 0
+}
+
+func issue45928(x int) {
+ combinedFrac := x / (x | (1 << 31)) // ERROR "Proved Neq64$"
+ useInt(combinedFrac)
+}
+
+//go:noinline
+func useInt(a int) {
+}
+
+//go:noinline
+func useSlice(a []int) {
+}
+
+func main() {
+}
diff --git a/platform/dbops/binaries/go/go/test/prove_constant_folding.go b/platform/dbops/binaries/go/go/test/prove_constant_folding.go
new file mode 100644
index 0000000000000000000000000000000000000000..ed63e6851c264bbfc71b53d3cd8746f832e89ee5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/prove_constant_folding.go
@@ -0,0 +1,33 @@
+// errorcheck -0 -d=ssa/prove/debug=2
+
+//go:build amd64
+
+// 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 main
+
+func f0i(x int) int {
+ if x == 20 {
+ return x // ERROR "Proved.+is constant 20$"
+ }
+
+ if (x + 20) == 20 {
+ return x + 5 // ERROR "Proved.+is constant 0$"
+ }
+
+ return x / 2
+}
+
+func f0u(x uint) uint {
+ if x == 20 {
+ return x // ERROR "Proved.+is constant 20$"
+ }
+
+ if (x + 20) == 20 {
+ return x + 5 // ERROR "Proved.+is constant 0$"
+ }
+
+ return x / 2
+}
diff --git a/platform/dbops/binaries/go/go/test/prove_invert_loop_with_unused_iterators.go b/platform/dbops/binaries/go/go/test/prove_invert_loop_with_unused_iterators.go
new file mode 100644
index 0000000000000000000000000000000000000000..c66f20b6e93cbd54fd4019106d1779fbc000fc5a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/prove_invert_loop_with_unused_iterators.go
@@ -0,0 +1,11 @@
+// errorcheck -0 -d=ssa/prove/debug=1
+
+//go:build amd64
+
+package main
+
+func invert(b func(), n int) {
+ for i := 0; i < n; i++ { // ERROR "(Inverted loop iteration|Induction variable: limits \[0,\?\), increment 1)"
+ b()
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/range.go b/platform/dbops/binaries/go/go/test/range.go
new file mode 100644
index 0000000000000000000000000000000000000000..3da7d170b58634ae907358f184b1ba15e689325e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/range.go
@@ -0,0 +1,494 @@
+// run
+
+// 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.
+
+// Test the 'for range' construct.
+
+package main
+
+// test range over channels
+
+func gen(c chan int, lo, hi int) {
+ for i := lo; i <= hi; i++ {
+ c <- i
+ }
+ close(c)
+}
+
+func seq(lo, hi int) chan int {
+ c := make(chan int)
+ go gen(c, lo, hi)
+ return c
+}
+
+const alphabet = "abcdefghijklmnopqrstuvwxyz"
+
+func testblankvars() {
+ n := 0
+ for range alphabet {
+ n++
+ }
+ if n != 26 {
+ println("for range: wrong count", n, "want 26")
+ panic("fail")
+ }
+ n = 0
+ for _ = range alphabet {
+ n++
+ }
+ if n != 26 {
+ println("for _ = range: wrong count", n, "want 26")
+ panic("fail")
+ }
+ n = 0
+ for _, _ = range alphabet {
+ n++
+ }
+ if n != 26 {
+ println("for _, _ = range: wrong count", n, "want 26")
+ panic("fail")
+ }
+ s := 0
+ for i, _ := range alphabet {
+ s += i
+ }
+ if s != 325 {
+ println("for i, _ := range: wrong sum", s, "want 325")
+ panic("fail")
+ }
+ r := rune(0)
+ for _, v := range alphabet {
+ r += v
+ }
+ if r != 2847 {
+ println("for _, v := range: wrong sum", r, "want 2847")
+ panic("fail")
+ }
+}
+
+func testchan() {
+ s := ""
+ for i := range seq('a', 'z') {
+ s += string(i)
+ }
+ if s != alphabet {
+ println("Wanted lowercase alphabet; got", s)
+ panic("fail")
+ }
+ n := 0
+ for range seq('a', 'z') {
+ n++
+ }
+ if n != 26 {
+ println("testchan wrong count", n, "want 26")
+ panic("fail")
+ }
+}
+
+// test that range over slice only evaluates
+// the expression after "range" once.
+
+var nmake = 0
+
+func makeslice() []int {
+ nmake++
+ return []int{1, 2, 3, 4, 5}
+}
+
+func testslice() {
+ s := 0
+ nmake = 0
+ for _, v := range makeslice() {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makeslice", nmake, "times")
+ panic("fail")
+ }
+ if s != 15 {
+ println("wrong sum ranging over makeslice", s)
+ panic("fail")
+ }
+
+ x := []int{10, 20}
+ y := []int{99}
+ i := 1
+ for i, x[i] = range y {
+ break
+ }
+ if i != 0 || x[0] != 10 || x[1] != 99 {
+ println("wrong parallel assignment", i, x[0], x[1])
+ panic("fail")
+ }
+}
+
+func testslice1() {
+ s := 0
+ nmake = 0
+ for i := range makeslice() {
+ s += i
+ }
+ if nmake != 1 {
+ println("range called makeslice", nmake, "times")
+ panic("fail")
+ }
+ if s != 10 {
+ println("wrong sum ranging over makeslice", s)
+ panic("fail")
+ }
+}
+
+func testslice2() {
+ n := 0
+ nmake = 0
+ for range makeslice() {
+ n++
+ }
+ if nmake != 1 {
+ println("range called makeslice", nmake, "times")
+ panic("fail")
+ }
+ if n != 5 {
+ println("wrong count ranging over makeslice", n)
+ panic("fail")
+ }
+}
+
+// test that range over []byte(string) only evaluates
+// the expression after "range" once.
+
+func makenumstring() string {
+ nmake++
+ return "\x01\x02\x03\x04\x05"
+}
+
+func testslice3() {
+ s := byte(0)
+ nmake = 0
+ for _, v := range []byte(makenumstring()) {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makenumstring", nmake, "times")
+ panic("fail")
+ }
+ if s != 15 {
+ println("wrong sum ranging over []byte(makenumstring)", s)
+ panic("fail")
+ }
+}
+
+// test that range over array only evaluates
+// the expression after "range" once.
+
+func makearray() [5]int {
+ nmake++
+ return [5]int{1, 2, 3, 4, 5}
+}
+
+func testarray() {
+ s := 0
+ nmake = 0
+ for _, v := range makearray() {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makearray", nmake, "times")
+ panic("fail")
+ }
+ if s != 15 {
+ println("wrong sum ranging over makearray", s)
+ panic("fail")
+ }
+}
+
+func testarray1() {
+ s := 0
+ nmake = 0
+ for i := range makearray() {
+ s += i
+ }
+ if nmake != 1 {
+ println("range called makearray", nmake, "times")
+ panic("fail")
+ }
+ if s != 10 {
+ println("wrong sum ranging over makearray", s)
+ panic("fail")
+ }
+}
+
+func testarray2() {
+ n := 0
+ nmake = 0
+ for range makearray() {
+ n++
+ }
+ if nmake != 1 {
+ println("range called makearray", nmake, "times")
+ panic("fail")
+ }
+ if n != 5 {
+ println("wrong count ranging over makearray", n)
+ panic("fail")
+ }
+}
+
+func makearrayptr() *[5]int {
+ nmake++
+ return &[5]int{1, 2, 3, 4, 5}
+}
+
+func testarrayptr() {
+ nmake = 0
+ x := len(makearrayptr())
+ if x != 5 || nmake != 1 {
+ println("len called makearrayptr", nmake, "times and got len", x)
+ panic("fail")
+ }
+ nmake = 0
+ x = cap(makearrayptr())
+ if x != 5 || nmake != 1 {
+ println("cap called makearrayptr", nmake, "times and got len", x)
+ panic("fail")
+ }
+ s := 0
+ nmake = 0
+ for _, v := range makearrayptr() {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makearrayptr", nmake, "times")
+ panic("fail")
+ }
+ if s != 15 {
+ println("wrong sum ranging over makearrayptr", s)
+ panic("fail")
+ }
+}
+
+func testarrayptr1() {
+ s := 0
+ nmake = 0
+ for i := range makearrayptr() {
+ s += i
+ }
+ if nmake != 1 {
+ println("range called makearrayptr", nmake, "times")
+ panic("fail")
+ }
+ if s != 10 {
+ println("wrong sum ranging over makearrayptr", s)
+ panic("fail")
+ }
+}
+
+func testarrayptr2() {
+ n := 0
+ nmake = 0
+ for range makearrayptr() {
+ n++
+ }
+ if nmake != 1 {
+ println("range called makearrayptr", nmake, "times")
+ panic("fail")
+ }
+ if n != 5 {
+ println("wrong count ranging over makearrayptr", n)
+ panic("fail")
+ }
+}
+
+// test that range over string only evaluates
+// the expression after "range" once.
+
+func makestring() string {
+ nmake++
+ return "abcd☺"
+}
+
+func teststring() {
+ var s rune
+ nmake = 0
+ for _, v := range makestring() {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makestring", nmake, "times")
+ panic("fail")
+ }
+ if s != 'a'+'b'+'c'+'d'+'☺' {
+ println("wrong sum ranging over makestring", s)
+ panic("fail")
+ }
+
+ x := []rune{'a', 'b'}
+ i := 1
+ for i, x[i] = range "c" {
+ break
+ }
+ if i != 0 || x[0] != 'a' || x[1] != 'c' {
+ println("wrong parallel assignment", i, x[0], x[1])
+ panic("fail")
+ }
+
+ y := []int{1, 2, 3}
+ r := rune(1)
+ for y[r], r = range "\x02" {
+ break
+ }
+ if r != 2 || y[0] != 1 || y[1] != 0 || y[2] != 3 {
+ println("wrong parallel assignment", r, y[0], y[1], y[2])
+ panic("fail")
+ }
+}
+
+func teststring1() {
+ s := 0
+ nmake = 0
+ for i := range makestring() {
+ s += i
+ }
+ if nmake != 1 {
+ println("range called makestring", nmake, "times")
+ panic("fail")
+ }
+ if s != 10 {
+ println("wrong sum ranging over makestring", s)
+ panic("fail")
+ }
+}
+
+func teststring2() {
+ n := 0
+ nmake = 0
+ for range makestring() {
+ n++
+ }
+ if nmake != 1 {
+ println("range called makestring", nmake, "times")
+ panic("fail")
+ }
+ if n != 5 {
+ println("wrong count ranging over makestring", n)
+ panic("fail")
+ }
+}
+
+// test that range over map only evaluates
+// the expression after "range" once.
+
+func makemap() map[int]int {
+ nmake++
+ return map[int]int{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: '☺'}
+}
+
+func testmap() {
+ s := 0
+ nmake = 0
+ for _, v := range makemap() {
+ s += v
+ }
+ if nmake != 1 {
+ println("range called makemap", nmake, "times")
+ panic("fail")
+ }
+ if s != 'a'+'b'+'c'+'d'+'☺' {
+ println("wrong sum ranging over makemap", s)
+ panic("fail")
+ }
+}
+
+func testmap1() {
+ s := 0
+ nmake = 0
+ for i := range makemap() {
+ s += i
+ }
+ if nmake != 1 {
+ println("range called makemap", nmake, "times")
+ panic("fail")
+ }
+ if s != 10 {
+ println("wrong sum ranging over makemap", s)
+ panic("fail")
+ }
+}
+
+func testmap2() {
+ n := 0
+ nmake = 0
+ for range makemap() {
+ n++
+ }
+ if nmake != 1 {
+ println("range called makemap", nmake, "times")
+ panic("fail")
+ }
+ if n != 5 {
+ println("wrong count ranging over makemap", n)
+ panic("fail")
+ }
+}
+
+// test that range evaluates the index and value expressions
+// exactly once per iteration.
+
+var ncalls = 0
+
+func getvar(p *int) *int {
+ ncalls++
+ return p
+}
+
+func testcalls() {
+ var i, v int
+ si := 0
+ sv := 0
+ for *getvar(&i), *getvar(&v) = range [2]int{1, 2} {
+ si += i
+ sv += v
+ }
+ if ncalls != 4 {
+ println("wrong number of calls:", ncalls, "!= 4")
+ panic("fail")
+ }
+ if si != 1 || sv != 3 {
+ println("wrong sum in testcalls", si, sv)
+ panic("fail")
+ }
+
+ ncalls = 0
+ for *getvar(&i), *getvar(&v) = range [0]int{} {
+ println("loop ran on empty array")
+ panic("fail")
+ }
+ if ncalls != 0 {
+ println("wrong number of calls:", ncalls, "!= 0")
+ panic("fail")
+ }
+}
+
+func main() {
+ testblankvars()
+ testchan()
+ testarray()
+ testarray1()
+ testarray2()
+ testarrayptr()
+ testarrayptr1()
+ testarrayptr2()
+ testslice()
+ testslice1()
+ testslice2()
+ testslice3()
+ teststring()
+ teststring1()
+ teststring2()
+ testmap()
+ testmap1()
+ testmap2()
+ testcalls()
+}
diff --git a/platform/dbops/binaries/go/go/test/range2.go b/platform/dbops/binaries/go/go/test/range2.go
new file mode 100644
index 0000000000000000000000000000000000000000..6ccf1e53d82e230df129b5ce23f7e95afb6206ea
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/range2.go
@@ -0,0 +1,24 @@
+// errorcheck -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.
+
+// See ../internal/types/testdata/spec/range.go for most tests.
+// The ones in this file cannot be expressed in that framework
+// due to conflicts between that framework's error location pickiness
+// and gofmt's comment location pickiness.
+
+package p
+
+type T struct{}
+
+func (*T) PM() {}
+func (T) M() {}
+
+func test() {
+ for range T.M { // ERROR "cannot range over T.M \(value of type func\(T\)\): func must be func\(yield func\(...\) bool\): argument is not func"
+ }
+ for range (*T).PM { // ERROR "cannot range over \(\*T\).PM \(value of type func\(\*T\)\): func must be func\(yield func\(...\) bool\): argument is not func"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/range3.go b/platform/dbops/binaries/go/go/test/range3.go
new file mode 100644
index 0000000000000000000000000000000000000000..f58a398f94c16c95623217ad3e06e8b12d4184a6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/range3.go
@@ -0,0 +1,90 @@
+// run
+
+// 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 the 'for range' construct ranging over integers.
+
+package main
+
+func testint1() {
+ bad := false
+ j := 0
+ for i := range int(4) {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ }
+ if j != 4 {
+ println("wrong count ranging over 4:", j)
+ bad = true
+ }
+ if bad {
+ panic("testint1")
+ }
+}
+
+func testint2() {
+ bad := false
+ j := 0
+ for i := range 4 {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ }
+ if j != 4 {
+ println("wrong count ranging over 4:", j)
+ bad = true
+ }
+ if bad {
+ panic("testint2")
+ }
+}
+
+func testint3() {
+ bad := false
+ type MyInt int
+ j := MyInt(0)
+ for i := range MyInt(4) {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ }
+ if j != 4 {
+ println("wrong count ranging over 4:", j)
+ bad = true
+ }
+ if bad {
+ panic("testint3")
+ }
+}
+
+// Issue #63378.
+func testint4() {
+ for i := range -1 {
+ _ = i
+ panic("must not be executed")
+ }
+}
+
+// Issue #64471.
+func testint5() {
+ for i := range 'a' {
+ var _ *rune = &i // ensure i has type rune
+ }
+}
+
+func main() {
+ testint1()
+ testint2()
+ testint3()
+ testint4()
+ testint5()
+}
diff --git a/platform/dbops/binaries/go/go/test/range4.go b/platform/dbops/binaries/go/go/test/range4.go
new file mode 100644
index 0000000000000000000000000000000000000000..0b051f6d3c0f4bf2ff7d160f71f398107fed30d1
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/range4.go
@@ -0,0 +1,351 @@
+// run -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.
+
+// Test the 'for range' construct ranging over functions.
+
+package main
+
+var gj int
+
+func yield4x(yield func() bool) {
+ _ = yield() && yield() && yield() && yield()
+}
+
+func yield4(yield func(int) bool) {
+ _ = yield(1) && yield(2) && yield(3) && yield(4)
+}
+
+func yield3(yield func(int) bool) {
+ _ = yield(1) && yield(2) && yield(3)
+}
+
+func yield2(yield func(int) bool) {
+ _ = yield(1) && yield(2)
+}
+
+func testfunc0() {
+ j := 0
+ for range yield4x {
+ j++
+ }
+ if j != 4 {
+ println("wrong count ranging over yield4x:", j)
+ panic("testfunc0")
+ }
+
+ j = 0
+ for _ = range yield4 {
+ j++
+ }
+ if j != 4 {
+ println("wrong count ranging over yield4:", j)
+ panic("testfunc0")
+ }
+}
+
+func testfunc1() {
+ bad := false
+ j := 1
+ for i := range yield4 {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ }
+ if j != 5 {
+ println("wrong count ranging over f:", j)
+ bad = true
+ }
+ if bad {
+ panic("testfunc1")
+ }
+}
+
+func testfunc2() {
+ bad := false
+ j := 1
+ var i int
+ for i = range yield4 {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ }
+ if j != 5 {
+ println("wrong count ranging over f:", j)
+ bad = true
+ }
+ if i != 4 {
+ println("wrong final i ranging over f:", i)
+ bad = true
+ }
+ if bad {
+ panic("testfunc2")
+ }
+}
+
+func testfunc3() {
+ bad := false
+ j := 1
+ var i int
+ for i = range yield4 {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ if i == 2 {
+ break
+ }
+ continue
+ }
+ if j != 3 {
+ println("wrong count ranging over f:", j)
+ bad = true
+ }
+ if i != 2 {
+ println("wrong final i ranging over f:", i)
+ bad = true
+ }
+ if bad {
+ panic("testfunc3")
+ }
+}
+
+func testfunc4() {
+ bad := false
+ j := 1
+ var i int
+ func() {
+ for i = range yield4 {
+ if i != j {
+ println("range var", i, "want", j)
+ bad = true
+ }
+ j++
+ if i == 2 {
+ return
+ }
+ }
+ }()
+ if j != 3 {
+ println("wrong count ranging over f:", j)
+ bad = true
+ }
+ if i != 2 {
+ println("wrong final i ranging over f:", i)
+ bad = true
+ }
+ if bad {
+ panic("testfunc3")
+ }
+}
+
+func func5() (int, int) {
+ for i := range yield4 {
+ return 10, i
+ }
+ panic("still here")
+}
+
+func testfunc5() {
+ x, y := func5()
+ if x != 10 || y != 1 {
+ println("wrong results", x, y, "want", 10, 1)
+ panic("testfunc5")
+ }
+}
+
+func func6() (z, w int) {
+ for i := range yield4 {
+ z = 10
+ w = i
+ return
+ }
+ panic("still here")
+}
+
+func testfunc6() {
+ x, y := func6()
+ if x != 10 || y != 1 {
+ println("wrong results", x, y, "want", 10, 1)
+ panic("testfunc6")
+ }
+}
+
+var saved []int
+
+func save(x int) {
+ saved = append(saved, x)
+}
+
+func printslice(s []int) {
+ print("[")
+ for i, x := range s {
+ if i > 0 {
+ print(", ")
+ }
+ print(x)
+ }
+ print("]")
+}
+
+func eqslice(s, t []int) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i, x := range s {
+ if x != t[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func func7() {
+ defer save(-1)
+ for i := range yield4 {
+ defer save(i)
+ }
+ defer save(5)
+}
+
+func checkslice(name string, saved, want []int) {
+ if !eqslice(saved, want) {
+ print("wrong results ")
+ printslice(saved)
+ print(" want ")
+ printslice(want)
+ print("\n")
+ panic(name)
+ }
+}
+
+func testfunc7() {
+ saved = nil
+ func7()
+ want := []int{5, 4, 3, 2, 1, -1}
+ checkslice("testfunc7", saved, want)
+}
+
+func func8() {
+ defer save(-1)
+ for i := range yield2 {
+ for j := range yield3 {
+ defer save(i*10 + j)
+ }
+ defer save(i)
+ }
+ defer save(-2)
+ for i := range yield4 {
+ defer save(i)
+ }
+ defer save(-3)
+}
+
+func testfunc8() {
+ saved = nil
+ func8()
+ want := []int{-3, 4, 3, 2, 1, -2, 2, 23, 22, 21, 1, 13, 12, 11, -1}
+ checkslice("testfunc8", saved, want)
+}
+
+func func9() {
+ n := 0
+ for _ = range yield2 {
+ for _ = range yield3 {
+ n++
+ defer save(n)
+ }
+ }
+}
+
+func testfunc9() {
+ saved = nil
+ func9()
+ want := []int{6, 5, 4, 3, 2, 1}
+ checkslice("testfunc9", saved, want)
+}
+
+// test that range evaluates the index and value expressions
+// exactly once per iteration.
+
+var ncalls = 0
+
+func getvar(p *int) *int {
+ ncalls++
+ return p
+}
+
+func iter2(list ...int) func(func(int, int) bool) {
+ return func(yield func(int, int) bool) {
+ for i, x := range list {
+ if !yield(i, x) {
+ return
+ }
+ }
+ }
+}
+
+func testcalls() {
+ var i, v int
+ ncalls = 0
+ si := 0
+ sv := 0
+ for *getvar(&i), *getvar(&v) = range iter2(1, 2) {
+ si += i
+ sv += v
+ }
+ if ncalls != 4 {
+ println("wrong number of calls:", ncalls, "!= 4")
+ panic("fail")
+ }
+ if si != 1 || sv != 3 {
+ println("wrong sum in testcalls", si, sv)
+ panic("fail")
+ }
+}
+
+type iter3YieldFunc func(int, int) bool
+
+func iter3(list ...int) func(iter3YieldFunc) {
+ return func(yield iter3YieldFunc) {
+ for k, v := range list {
+ if !yield(k, v) {
+ return
+ }
+ }
+ }
+}
+
+func testcalls1() {
+ ncalls := 0
+ for k, v := range iter3(1, 2, 3) {
+ _, _ = k, v
+ ncalls++
+ }
+ if ncalls != 3 {
+ println("wrong number of calls:", ncalls, "!= 3")
+ panic("fail")
+ }
+}
+
+func main() {
+ testfunc0()
+ testfunc1()
+ testfunc2()
+ testfunc3()
+ testfunc4()
+ testfunc5()
+ testfunc6()
+ testfunc7()
+ testfunc8()
+ testfunc9()
+ testcalls()
+ testcalls1()
+}
diff --git a/platform/dbops/binaries/go/go/test/rangegen.go b/platform/dbops/binaries/go/go/test/rangegen.go
new file mode 100644
index 0000000000000000000000000000000000000000..8231c64db758474fa3d30a9a6fcf472267b0adfb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rangegen.go
@@ -0,0 +1,350 @@
+// runoutput -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.
+
+// Torture test for range-over-func.
+//
+// cmd/internal/testdir runs this like
+//
+// go run rangegen.go >x.go
+// go run x.go
+//
+// but a longer version can be run using
+//
+// go run rangegen.go long
+//
+// In that second form, rangegen takes care of compiling
+// and running the code it generates, in batches.
+// That form takes 10-20 minutes to run.
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "math/bits"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+const verbose = false
+
+func main() {
+ long := len(os.Args) > 1 && os.Args[1] == "long"
+ log.SetFlags(0)
+ log.SetPrefix("rangegen: ")
+
+ if !long && bits.UintSize == 32 {
+ // Skip this test on 32-bit platforms, where it seems to
+ // cause timeouts and build problems.
+ skip()
+ return
+ }
+
+ b := new(bytes.Buffer)
+ tests := ""
+ flush := func(force bool) {
+ if !long || (strings.Count(tests, "\n") < 1000 && !force) {
+ return
+ }
+ p(b, mainCode, tests)
+ err := os.WriteFile("tmp.go", b.Bytes(), 0666)
+ if err != nil {
+ log.Fatal(err)
+ }
+ out, err := exec.Command("go", "run", "tmp.go").CombinedOutput()
+ if err != nil {
+ log.Fatalf("go run tmp.go: %v\n%s", err, out)
+ }
+ print(".")
+ if force {
+ print("\nPASS\n")
+ }
+ b.Reset()
+ tests = ""
+ p(b, "package main\n\n")
+ p(b, "const verbose = %v\n\n", verbose)
+ }
+
+ p(b, "package main\n\n")
+ p(b, "const verbose = %v\n\n", verbose)
+ max := 2
+ if !long {
+ max = 5
+ }
+ for i := 1; i <= max; i++ {
+ maxDouble := -1
+ if long {
+ maxDouble = i
+ }
+ for double := -1; double <= maxDouble; double++ {
+ code := gen(new(bytes.Buffer), "", "", "", i, double, func(c int) bool { return true })
+ for j := 0; j < code; j++ {
+ hi := j + 1
+ if long {
+ hi = code
+ }
+ for k := j; k < hi && k < code; k++ {
+ s := fmt.Sprintf("%d_%d_%d_%d", i, double+1, j, k)
+ code0 := gen(b, "testFunc"+s, "", "yield2", i, double, func(c int) bool { return c == j || c == k })
+ code1 := gen(b, "testSlice"+s, "_, ", "slice2", i, double, func(c int) bool { return c == j || c == k })
+ if code0 != code1 {
+ panic("bad generator")
+ }
+ tests += "test" + s + "()\n"
+ p(b, testCode, "test"+s, []int{j, k}, "testFunc"+s, "testSlice"+s)
+ flush(false)
+ }
+ }
+ }
+ }
+ for i := 1; i <= max; i++ {
+ maxDouble := -1
+ if long {
+ maxDouble = i
+ }
+ for double := -1; double <= maxDouble; double++ {
+ s := fmt.Sprintf("%d_%d", i, double+1)
+ code := gen(b, "testFunc"+s, "", "yield2", i, double, func(c int) bool { return true })
+ code1 := gen(b, "testSlice"+s, "_, ", "slice2", i, double, func(c int) bool { return true })
+ if code != code1 {
+ panic("bad generator")
+ }
+ tests += "test" + s + "()\n"
+ var all []int
+ for j := 0; j < code; j++ {
+ all = append(all, j)
+ }
+ p(b, testCode, "test"+s, all, "testFunc"+s, "testSlice"+s)
+ flush(false)
+ }
+ }
+ if long {
+ flush(true)
+ os.Remove("tmp.go")
+ return
+ }
+
+ p(b, mainCode, tests)
+
+ os.Stdout.Write(b.Bytes())
+}
+
+func p(b *bytes.Buffer, format string, args ...any) {
+ fmt.Fprintf(b, format, args...)
+}
+
+func gen(b *bytes.Buffer, name, prefix, rangeExpr string, depth, double int, allowed func(int) bool) int {
+ p(b, "func %s(o *output, code int) int {\n", name)
+ p(b, " dfr := 0; _ = dfr\n")
+ code := genLoop(b, 0, prefix, rangeExpr, depth, double, 0, "", allowed)
+ p(b, " return 0\n")
+ p(b, "}\n\n")
+ return code
+}
+
+func genLoop(b *bytes.Buffer, d int, prefix, rangeExpr string, depth, double, code int, labelSuffix string, allowed func(int) bool) int {
+ limit := 1
+ if d == double {
+ limit = 2
+ }
+ for rep := 0; rep < limit; rep++ {
+ if rep == 1 {
+ labelSuffix = "R"
+ }
+ s := fmt.Sprintf("%d%s", d, labelSuffix)
+ p(b, " o.log(`top%s`)\n", s)
+ p(b, " l%sa := 0\n", s)
+ p(b, "goto L%sa; L%sa: o.log(`L%sa`)\n", s, s, s)
+ p(b, " if l%sa++; l%sa >= 2 { o.log(`loop L%sa`); return -1 }\n", s, s, s)
+ p(b, " l%sfor := 0\n", s)
+ p(b, "goto L%sfor; L%sfor: for f := 0; f < 1; f++ { o.log(`L%sfor`)\n", s, s, s)
+ p(b, " if l%sfor++; l%sfor >= 2 { o.log(`loop L%sfor`); return -1 }\n", s, s, s)
+ p(b, " l%ssw := 0\n", s)
+ p(b, "goto L%ssw; L%ssw: switch { default: o.log(`L%ssw`)\n", s, s, s)
+ p(b, " if l%ssw++; l%ssw >= 2 { o.log(`loop L%ssw`); return -1 }\n", s, s, s)
+ p(b, " l%ssel := 0\n", s)
+ p(b, "goto L%ssel; L%ssel: select { default: o.log(`L%ssel`)\n", s, s, s)
+ p(b, " if l%ssel++; l%ssel >= 2 { o.log(`loop L%ssel`); return -1 }\n", s, s, s)
+ p(b, " l%s := 0\n", s)
+ p(b, "goto L%s; L%s: for %s i%s := range %s {\n", s, s, prefix, s, rangeExpr)
+ p(b, " o.log1(`L%s top`, i%s)\n", s, s)
+ p(b, " if l%s++; l%s >= 4 { o.log(`loop L%s`); return -1 }\n", s, s, s)
+ printTests := func() {
+ if code++; allowed(code) {
+ p(b, " if code == %v { break }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { continue }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " switch { case code == %v: continue }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { return %[1]v }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { select { default: break } }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { switch { default: break } }\n", code)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { dfr++; defer o.log1(`defer %d`, dfr) }\n", code, code)
+ }
+ for i := d; i > 0; i-- {
+ suffix := labelSuffix
+ if i < double {
+ suffix = ""
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { break L%d%s }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { select { default: break L%d%s } }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { break L%d%s }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { break L%d%ssw }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { break L%d%ssel }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { break L%d%sfor }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { continue L%d%sfor }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { goto L%d%sa }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { goto L%d%s }\n", code, i, suffix)
+ }
+ if code++; allowed(code) {
+ p(b, " if code == %v { goto L%d%sb }\n", code, i, suffix)
+ }
+ }
+ }
+ printTests()
+ if d < depth {
+ if rep == 1 {
+ double = d // signal to children to use the rep=1 labels
+ }
+ code = genLoop(b, d+1, prefix, rangeExpr, depth, double, code, labelSuffix, allowed)
+ printTests()
+ }
+ p(b, " o.log(`L%s bot`)\n", s)
+ p(b, " }\n")
+ p(b, " o.log(`L%ssel bot`)\n", s)
+ p(b, " }\n")
+ p(b, " o.log(`L%ssw bot`)\n", s)
+ p(b, " }\n")
+ p(b, " o.log(`L%sfor bot`)\n", s)
+ p(b, " }\n")
+ p(b, " o.log(`done%s`)\n", s)
+ p(b, "goto L%sb; L%sb: o.log(`L%sb`)\n", s, s, s)
+ }
+ return code
+}
+
+var testCode = `
+func %s() {
+ all := %#v
+ for i := 0; i < len(all); i++ {
+ c := all[i]
+ outFunc := run(%s, c)
+ outSlice := run(%s, c)
+ if !outFunc.eq(outSlice) {
+ println("mismatch", "%[3]s", "%[4]s", c)
+ println()
+ println("func:")
+ outFunc.print()
+ println()
+ println("slice:")
+ outSlice.print()
+ panic("mismatch")
+ }
+ }
+ if verbose {
+ println("did", "%[3]s", "%[4]s", len(all))
+ }
+}
+`
+
+var mainCode = `
+
+func main() {
+ if verbose {
+ println("main")
+ }
+ %s
+}
+
+func yield2(yield func(int)bool) { _ = yield(1) && yield(2) }
+var slice2 = []int{1,2}
+
+type output struct {
+ ret int
+ trace []any
+}
+
+func (o *output) log(x any) {
+ o.trace = append(o.trace, x)
+}
+
+func (o *output) log1(x, y any) {
+ o.trace = append(o.trace, x, y)
+}
+
+func (o *output) eq(p *output) bool{
+ if o.ret != p.ret || len(o.trace) != len(p.trace) {
+ return false
+ }
+ for i ,x := range o.trace {
+ if x != p.trace[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func (o *output) print() {
+ println("ret", o.ret, "trace-len", len(o.trace))
+ for i := 0; i < len(o.trace); i++ {
+ print("#", i, " ")
+ switch x := o.trace[i].(type) {
+ case int:
+ print(x)
+ case string:
+ print(x)
+ default:
+ print(x)
+ }
+ print("\n")
+ }
+}
+
+func run(f func(*output, int)int, i int) *output {
+ o := &output{}
+ o.ret = f(o, i)
+ return o
+}
+
+`
+
+func skip() {
+ const code = `
+package main
+func main() {
+}
+`
+ fmt.Printf("%s\n", code)
+}
diff --git a/platform/dbops/binaries/go/go/test/recover.go b/platform/dbops/binaries/go/go/test/recover.go
new file mode 100644
index 0000000000000000000000000000000000000000..e4187c018f68a7e0d6b4bc7feb17af21e2ae4c4a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover.go
@@ -0,0 +1,587 @@
+// run
+
+// 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.
+
+// Test of basic recover functionality.
+
+package main
+
+import (
+ "os"
+ "reflect"
+ "runtime"
+)
+
+func main() {
+ // go.tools/ssa/interp still has:
+ // - some lesser bugs in recover()
+ // - incomplete support for reflection
+ interp := os.Getenv("GOSSAINTERP") != ""
+
+ test1()
+ test1WithClosures()
+ test2()
+ test3()
+ if !interp {
+ test4()
+ }
+ test5()
+ test6()
+ test6WithClosures()
+ test7()
+ test8()
+ test9()
+ if !interp {
+ test9reflect1()
+ test9reflect2()
+ }
+ test10()
+ if !interp {
+ test10reflect1()
+ test10reflect2()
+ }
+ test11()
+ if !interp {
+ test11reflect1()
+ test11reflect2()
+ }
+ test111()
+ test12()
+ if !interp {
+ test12reflect1()
+ test12reflect2()
+ }
+ test13()
+ if !interp {
+ test13reflect1()
+ test13reflect2()
+ }
+ test14()
+ if !interp {
+ test14reflect1()
+ test14reflect2()
+ test15()
+ test16()
+ }
+}
+
+func die() {
+ runtime.Breakpoint() // can't depend on panic
+}
+
+func mustRecoverBody(v1, v2, v3, x interface{}) {
+ v := v1
+ if v != nil {
+ println("spurious recover", v)
+ die()
+ }
+ v = v2
+ if v == nil {
+ println("missing recover", x.(int))
+ die() // panic is useless here
+ }
+ if v != x {
+ println("wrong value", v, x)
+ die()
+ }
+
+ // the value should be gone now regardless
+ v = v3
+ if v != nil {
+ println("recover didn't recover")
+ die()
+ }
+}
+
+func doubleRecover() interface{} {
+ return recover()
+}
+
+func mustRecover(x interface{}) {
+ mustRecoverBody(doubleRecover(), recover(), recover(), x)
+}
+
+func mustNotRecover() {
+ v := recover()
+ if v != nil {
+ println("spurious recover", v)
+ die()
+ }
+}
+
+func withoutRecover() {
+ mustNotRecover() // because it's a sub-call
+}
+
+func withoutRecoverRecursive(n int) {
+ if n == 0 {
+ withoutRecoverRecursive(1)
+ } else {
+ v := recover()
+ if v != nil {
+ println("spurious recover (recursive)", v)
+ die()
+ }
+ }
+}
+
+func test1() {
+ defer mustNotRecover() // because mustRecover will squelch it
+ defer mustRecover(1) // because of panic below
+ defer withoutRecover() // should be no-op, leaving for mustRecover to find
+ defer withoutRecoverRecursive(0) // ditto
+ panic(1)
+}
+
+// Repeat test1 with closures instead of standard function.
+// Interesting because recover bases its decision
+// on the frame pointer of its caller, and a closure's
+// frame pointer is in the middle of its actual arguments
+// (after the hidden ones for the closed-over variables).
+func test1WithClosures() {
+ defer func() {
+ v := recover()
+ if v != nil {
+ println("spurious recover in closure")
+ die()
+ }
+ }()
+ defer func(x interface{}) {
+ mustNotRecover()
+ v := recover()
+ if v == nil {
+ println("missing recover", x.(int))
+ die()
+ }
+ if v != x {
+ println("wrong value", v, x)
+ die()
+ }
+ }(1)
+ defer func() {
+ mustNotRecover()
+ }()
+ panic(1)
+}
+
+func test2() {
+ // Recover only sees the panic argument
+ // if it is called from a deferred call.
+ // It does not see the panic when called from a call within a deferred call (too late)
+ // nor does it see the panic when it *is* the deferred call (too early).
+ defer mustRecover(2)
+ defer recover() // should be no-op
+ panic(2)
+}
+
+func test3() {
+ defer mustNotRecover()
+ defer func() {
+ recover() // should squelch
+ }()
+ panic(3)
+}
+
+func test4() {
+ // Equivalent to test3 but using defer to make the call.
+ defer mustNotRecover()
+ defer func() {
+ defer recover() // should squelch
+ }()
+ panic(4)
+}
+
+// Check that closures can set output arguments.
+// Run g(). If it panics, return x; else return deflt.
+func try(g func(), deflt interface{}) (x interface{}) {
+ defer func() {
+ if v := recover(); v != nil {
+ x = v
+ }
+ }()
+ defer g()
+ return deflt
+}
+
+// Check that closures can set output arguments.
+// Run g(). If it panics, return x; else return deflt.
+func try1(g func(), deflt interface{}) (x interface{}) {
+ defer func() {
+ if v := recover(); v != nil {
+ x = v
+ }
+ }()
+ defer g()
+ x = deflt
+ return
+}
+
+func test5() {
+ v := try(func() { panic(5) }, 55).(int)
+ if v != 5 {
+ println("wrong value", v, 5)
+ die()
+ }
+
+ s := try(func() {}, "hi").(string)
+ if s != "hi" {
+ println("wrong value", s, "hi")
+ die()
+ }
+
+ v = try1(func() { panic(5) }, 55).(int)
+ if v != 5 {
+ println("try1 wrong value", v, 5)
+ die()
+ }
+
+ s = try1(func() {}, "hi").(string)
+ if s != "hi" {
+ println("try1 wrong value", s, "hi")
+ die()
+ }
+}
+
+// When a deferred big call starts, it must first
+// create yet another stack segment to hold the
+// giant frame for x. Make sure that doesn't
+// confuse recover.
+func big(mustRecover bool) {
+ var x [100000]int
+ x[0] = 1
+ x[99999] = 1
+ _ = x
+
+ v := recover()
+ if mustRecover {
+ if v == nil {
+ println("missing big recover")
+ die()
+ }
+ } else {
+ if v != nil {
+ println("spurious big recover")
+ die()
+ }
+ }
+}
+
+func test6() {
+ defer big(false)
+ defer big(true)
+ panic(6)
+}
+
+func test6WithClosures() {
+ defer func() {
+ var x [100000]int
+ x[0] = 1
+ x[99999] = 1
+ _ = x
+ if recover() != nil {
+ println("spurious big closure recover")
+ die()
+ }
+ }()
+ defer func() {
+ var x [100000]int
+ x[0] = 1
+ x[99999] = 1
+ _ = x
+ if recover() == nil {
+ println("missing big closure recover")
+ die()
+ }
+ }()
+ panic("6WithClosures")
+}
+
+func test7() {
+ ok := false
+ func() {
+ // should panic, then call mustRecover 7, which stops the panic.
+ // then should keep processing ordinary defers earlier than that one
+ // before returning.
+ // this test checks that the defer func on the next line actually runs.
+ defer func() { ok = true }()
+ defer mustRecover(7)
+ panic(7)
+ }()
+ if !ok {
+ println("did not run ok func")
+ die()
+ }
+}
+
+func varargs(s *int, a ...int) {
+ *s = 0
+ for _, v := range a {
+ *s += v
+ }
+ if recover() != nil {
+ *s += 100
+ }
+}
+
+func test8a() (r int) {
+ defer varargs(&r, 1, 2, 3)
+ panic(0)
+}
+
+func test8b() (r int) {
+ defer varargs(&r, 4, 5, 6)
+ return
+}
+
+func test8() {
+ if test8a() != 106 || test8b() != 15 {
+ println("wrong value")
+ die()
+ }
+}
+
+type I interface {
+ M()
+}
+
+// pointer receiver, so no wrapper in i.M()
+type T1 struct{}
+
+func (*T1) M() {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 9)
+}
+
+func test9() {
+ var i I = &T1{}
+ defer i.M()
+ panic(9)
+}
+
+func test9reflect1() {
+ f := reflect.ValueOf(&T1{}).Method(0).Interface().(func())
+ defer f()
+ panic(9)
+}
+
+func test9reflect2() {
+ f := reflect.TypeOf(&T1{}).Method(0).Func.Interface().(func(*T1))
+ defer f(&T1{})
+ panic(9)
+}
+
+// word-sized value receiver, so no wrapper in i.M()
+type T2 uintptr
+
+func (T2) M() {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 10)
+}
+
+func test10() {
+ var i I = T2(0)
+ defer i.M()
+ panic(10)
+}
+
+func test10reflect1() {
+ f := reflect.ValueOf(T2(0)).Method(0).Interface().(func())
+ defer f()
+ panic(10)
+}
+
+func test10reflect2() {
+ f := reflect.TypeOf(T2(0)).Method(0).Func.Interface().(func(T2))
+ defer f(T2(0))
+ panic(10)
+}
+
+// tiny receiver, so basic wrapper in i.M()
+type T3 struct{}
+
+func (T3) M() {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 11)
+}
+
+func test11() {
+ var i I = T3{}
+ defer i.M()
+ panic(11)
+}
+
+func test11reflect1() {
+ f := reflect.ValueOf(T3{}).Method(0).Interface().(func())
+ defer f()
+ panic(11)
+}
+
+func test11reflect2() {
+ f := reflect.TypeOf(T3{}).Method(0).Func.Interface().(func(T3))
+ defer f(T3{})
+ panic(11)
+}
+
+// tiny receiver, so basic wrapper in i.M()
+type T3deeper struct{}
+
+func (T3deeper) M() {
+ badstate() // difference from T3
+ mustRecoverBody(doubleRecover(), recover(), recover(), 111)
+}
+
+func test111() {
+ var i I = T3deeper{}
+ defer i.M()
+ panic(111)
+}
+
+type Tiny struct{}
+
+func (Tiny) M() {
+ panic(112)
+}
+
+// i.M is a wrapper, and i.M panics.
+//
+// This is a torture test for an old implementation of recover that
+// tried to deal with wrapper functions by doing some argument
+// positioning math on both entry and exit. Doing anything on exit
+// is a problem because sometimes functions exit via panic instead
+// of an ordinary return, so panic would have to know to do the
+// same math when unwinding the stack. It gets complicated fast.
+// This particular test never worked with the old scheme, because
+// panic never did the right unwinding math.
+//
+// The new scheme adjusts Panic.argp on entry to a wrapper.
+// It has no exit work, so if a wrapper is interrupted by a panic,
+// there's no cleanup that panic itself must do.
+// This test just works now.
+func badstate() {
+ defer func() {
+ recover()
+ }()
+ var i I = Tiny{}
+ i.M()
+}
+
+// large receiver, so basic wrapper in i.M()
+type T4 [2]string
+
+func (T4) M() {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 12)
+}
+
+func test12() {
+ var i I = T4{}
+ defer i.M()
+ panic(12)
+}
+
+func test12reflect1() {
+ f := reflect.ValueOf(T4{}).Method(0).Interface().(func())
+ defer f()
+ panic(12)
+}
+
+func test12reflect2() {
+ f := reflect.TypeOf(T4{}).Method(0).Func.Interface().(func(T4))
+ defer f(T4{})
+ panic(12)
+}
+
+// enormous receiver, so wrapper splits stack to call M
+type T5 [8192]byte
+
+func (T5) M() {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 13)
+}
+
+func test13() {
+ var i I = T5{}
+ defer i.M()
+ panic(13)
+}
+
+func test13reflect1() {
+ f := reflect.ValueOf(T5{}).Method(0).Interface().(func())
+ defer f()
+ panic(13)
+}
+
+func test13reflect2() {
+ f := reflect.TypeOf(T5{}).Method(0).Func.Interface().(func(T5))
+ defer f(T5{})
+ panic(13)
+}
+
+// enormous receiver + enormous method frame, so wrapper splits stack to call M,
+// and then M splits stack to allocate its frame.
+// recover must look back two frames to find the panic.
+type T6 [8192]byte
+
+var global byte
+
+func (T6) M() {
+ var x [8192]byte
+ x[0] = 1
+ x[1] = 2
+ for i := range x {
+ global += x[i]
+ }
+ mustRecoverBody(doubleRecover(), recover(), recover(), 14)
+}
+
+func test14() {
+ var i I = T6{}
+ defer i.M()
+ panic(14)
+}
+
+func test14reflect1() {
+ f := reflect.ValueOf(T6{}).Method(0).Interface().(func())
+ defer f()
+ panic(14)
+}
+
+func test14reflect2() {
+ f := reflect.TypeOf(T6{}).Method(0).Func.Interface().(func(T6))
+ defer f(T6{})
+ panic(14)
+}
+
+// function created by reflect.MakeFunc
+
+func reflectFunc(args []reflect.Value) (results []reflect.Value) {
+ mustRecoverBody(doubleRecover(), recover(), recover(), 15)
+ return nil
+}
+
+func test15() {
+ f := reflect.MakeFunc(reflect.TypeOf((func())(nil)), reflectFunc).Interface().(func())
+ defer f()
+ panic(15)
+}
+
+func reflectFunc2(args []reflect.Value) (results []reflect.Value) {
+ // This will call reflectFunc3
+ args[0].Interface().(func())()
+ return nil
+}
+
+func reflectFunc3(args []reflect.Value) (results []reflect.Value) {
+ if v := recover(); v != nil {
+ println("spurious recover", v)
+ die()
+ }
+ return nil
+}
+
+func test16() {
+ defer mustRecover(16)
+
+ f2 := reflect.MakeFunc(reflect.TypeOf((func(func()))(nil)), reflectFunc2).Interface().(func(func()))
+ f3 := reflect.MakeFunc(reflect.TypeOf((func())(nil)), reflectFunc3).Interface().(func())
+ defer f2(f3)
+
+ panic(16)
+}
diff --git a/platform/dbops/binaries/go/go/test/recover1.go b/platform/dbops/binaries/go/go/test/recover1.go
new file mode 100644
index 0000000000000000000000000000000000000000..c14a607c6ba4a876f8deab30dc0aa4a407edd40d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover1.go
@@ -0,0 +1,141 @@
+// run
+
+// 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.
+
+// Test of recover during recursive panics.
+// Here be dragons.
+
+package main
+
+import "runtime"
+
+func main() {
+ test1()
+ test2()
+ test3()
+ test4()
+ test5()
+ test6()
+ test7()
+}
+
+func die() {
+ runtime.Breakpoint() // can't depend on panic
+}
+
+func mustRecover(x interface{}) {
+ mustNotRecover() // because it's not a defer call
+ v := recover()
+ if v == nil {
+ println("missing recover")
+ die() // panic is useless here
+ }
+ if v != x {
+ println("wrong value", v, x)
+ die()
+ }
+
+ // the value should be gone now regardless
+ v = recover()
+ if v != nil {
+ println("recover didn't recover")
+ die()
+ }
+}
+
+func mustNotRecover() {
+ v := recover()
+ if v != nil {
+ println("spurious recover")
+ die()
+ }
+}
+
+func withoutRecover() {
+ mustNotRecover() // because it's a sub-call
+}
+
+func test1() {
+ // Easy nested recursive panic.
+ defer mustRecover(1)
+ defer func() {
+ defer mustRecover(2)
+ panic(2)
+ }()
+ panic(1)
+}
+
+func test2() {
+ // Sequential panic.
+ defer mustNotRecover()
+ defer func() {
+ v := recover()
+ if v == nil || v.(int) != 2 {
+ println("wrong value", v, 2)
+ die()
+ }
+ defer mustRecover(3)
+ panic(3)
+ }()
+ panic(2)
+}
+
+func test3() {
+ // Sequential panic - like test2 but less picky.
+ defer mustNotRecover()
+ defer func() {
+ recover()
+ defer mustRecover(3)
+ panic(3)
+ }()
+ panic(2)
+}
+
+func test4() {
+ // Single panic.
+ defer mustNotRecover()
+ defer func() {
+ recover()
+ }()
+ panic(4)
+}
+
+func test5() {
+ // Single panic but recover called via defer
+ defer mustNotRecover()
+ defer func() {
+ defer recover()
+ }()
+ panic(5)
+}
+
+func test6() {
+ // Sequential panic.
+ // Like test3, but changed recover to defer (same change as test4 → test5).
+ defer mustNotRecover()
+ defer func() {
+ defer recover() // like a normal call from this func; runs because mustRecover stops the panic
+ defer mustRecover(3)
+ panic(3)
+ }()
+ panic(2)
+}
+
+func test7() {
+ // Like test6, but swapped defer order.
+ // The recover in "defer recover()" is now a no-op,
+ // because it runs called from panic, not from the func,
+ // and therefore cannot see the panic of 2.
+ // (Alternately, it cannot see the panic of 2 because
+ // there is an active panic of 3. And it cannot see the
+ // panic of 3 because it is at the wrong level (too high on the stack).)
+ defer mustRecover(2)
+ defer func() {
+ defer mustRecover(3)
+ defer recover() // now a no-op, unlike in test6.
+ panic(3)
+ }()
+ panic(2)
+}
diff --git a/platform/dbops/binaries/go/go/test/recover2.go b/platform/dbops/binaries/go/go/test/recover2.go
new file mode 100644
index 0000000000000000000000000000000000000000..31c06ba2dc1449a0dd51bef2b446461fcba93d67
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover2.go
@@ -0,0 +1,85 @@
+// run
+
+// 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.
+
+// Test of recover for run-time errors.
+
+// TODO(rsc):
+// null pointer accesses
+
+package main
+
+import "strings"
+
+var x = make([]byte, 10)
+
+func main() {
+ test1()
+ test2()
+ test3()
+ test4()
+ test5()
+ test6()
+ test7()
+}
+
+func mustRecover(s string) {
+ v := recover()
+ if v == nil {
+ panic("expected panic")
+ }
+ if e := v.(error).Error(); strings.Index(e, s) < 0 {
+ panic("want: " + s + "; have: " + e)
+ }
+}
+
+func test1() {
+ defer mustRecover("index")
+ println(x[123])
+}
+
+func test2() {
+ defer mustRecover("slice")
+ println(x[5:15])
+}
+
+func test3() {
+ defer mustRecover("slice")
+ var lo = 11
+ var hi = 9
+ println(x[lo:hi])
+}
+
+func test4() {
+ defer mustRecover("interface")
+ var x interface{} = 1
+ println(x.(float32))
+}
+
+type T struct {
+ a, b int
+ c []int
+}
+
+func test5() {
+ defer mustRecover("uncomparable")
+ var x T
+ var z interface{} = x
+ println(z != z)
+}
+
+func test6() {
+ defer mustRecover("unhashable type main.T")
+ var x T
+ var z interface{} = x
+ m := make(map[interface{}]int)
+ m[z] = 1
+}
+
+func test7() {
+ defer mustRecover("divide by zero")
+ var x, y int
+ println(x / y)
+}
diff --git a/platform/dbops/binaries/go/go/test/recover3.go b/platform/dbops/binaries/go/go/test/recover3.go
new file mode 100644
index 0000000000000000000000000000000000000000..1b26cb36367dcdd206b8b30dd5aad3e371fb9137
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover3.go
@@ -0,0 +1,83 @@
+// run
+
+// 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.
+
+// Test recovering from runtime errors.
+
+package main
+
+import (
+ "runtime"
+ "strings"
+)
+
+var didbug bool
+
+func bug() {
+ if didbug {
+ return
+ }
+ println("BUG")
+ didbug = true
+}
+
+func check(name string, f func(), err string) {
+ defer func() {
+ v := recover()
+ if v == nil {
+ bug()
+ println(name, "did not panic")
+ return
+ }
+ runt, ok := v.(runtime.Error)
+ if !ok {
+ bug()
+ println(name, "panicked but not with runtime.Error")
+ return
+ }
+ s := runt.Error()
+ if strings.Index(s, err) < 0 {
+ bug()
+ println(name, "panicked with", s, "not", err)
+ return
+ }
+ }()
+
+ f()
+}
+
+func main() {
+ var x int
+ var x64 int64
+ var p *[10]int
+ var q *[10000]int
+ var i int
+
+ check("int-div-zero", func() { println(1 / x) }, "integer divide by zero")
+ check("int64-div-zero", func() { println(1 / x64) }, "integer divide by zero")
+
+ check("nil-deref", func() { println(p[0]) }, "nil pointer dereference")
+ check("nil-deref-1", func() { println(p[1]) }, "nil pointer dereference")
+ check("nil-deref-big", func() { println(q[5000]) }, "nil pointer dereference")
+
+ i = 99999
+ var sl []int
+ p1 := new([10]int)
+ check("array-bounds", func() { println(p1[i]) }, "index out of range")
+ check("slice-bounds", func() { println(sl[i]) }, "index out of range")
+
+ var inter interface{}
+ inter = 1
+ check("type-concrete", func() { println(inter.(string)) }, "int, not string")
+ check("type-interface", func() { println(inter.(m)) }, "missing method m")
+
+ if didbug {
+ panic("recover3")
+ }
+}
+
+type m interface {
+ m()
+}
diff --git a/platform/dbops/binaries/go/go/test/recover4.go b/platform/dbops/binaries/go/go/test/recover4.go
new file mode 100644
index 0000000000000000000000000000000000000000..19b94948b8ce1499df535bbd2e59b9b1a64adb4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover4.go
@@ -0,0 +1,76 @@
+// run
+
+//go:build linux || darwin
+
+// 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.
+
+// Test that if a slice access causes a fault, a deferred func
+// sees the most recent value of the variables it accesses.
+// This is true today; the role of the test is to ensure it stays true.
+//
+// In the test, memcopy is the function that will fault, during dst[i] = src[i].
+// The deferred func recovers from the error and returns, making memcopy
+// return the current value of n. If n is not being flushed to memory
+// after each modification, the result will be a stale value of n.
+//
+// The test is set up by mmapping a 64 kB block of memory and then
+// unmapping a 16 kB hole in the middle of it. Running memcopy
+// on the resulting slice will fault when it reaches the hole.
+
+package main
+
+import (
+ "log"
+ "runtime/debug"
+ "syscall"
+)
+
+func memcopy(dst, src []byte) (n int, err error) {
+ defer func() {
+ if r, ok := recover().(error); ok {
+ err = r
+ }
+ }()
+
+ for i := 0; i < len(dst) && i < len(src); i++ {
+ dst[i] = src[i]
+ n++
+ }
+ return
+}
+
+func main() {
+ // Turn the eventual fault into a panic, not a program crash,
+ // so that memcopy can recover.
+ debug.SetPanicOnFault(true)
+
+ size := syscall.Getpagesize()
+
+ // Map 16 pages of data with a 4-page hole in the middle.
+ data, err := syscall.Mmap(-1, 0, 16*size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANON|syscall.MAP_PRIVATE)
+ if err != nil {
+ log.Fatalf("mmap: %v", err)
+ }
+
+ // Create a hole in the mapping that's PROT_NONE.
+ // Note that we can't use munmap here because the Go runtime
+ // could create a mapping that ends up in this hole otherwise,
+ // invalidating the test.
+ hole := data[len(data)/2 : 3*(len(data)/4)]
+ if err := syscall.Mprotect(hole, syscall.PROT_NONE); err != nil {
+ log.Fatalf("mprotect: %v", err)
+ }
+
+ // Check that memcopy returns the actual amount copied
+ // before the fault.
+ const offset = 5
+ n, err := memcopy(data[offset:], make([]byte, len(data)))
+ if err == nil {
+ log.Fatal("no error from memcopy across memory hole")
+ }
+ if expect := len(data)/2 - offset; n != expect {
+ log.Fatalf("memcopy returned %d, want %d", n, expect)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/recover5.go b/platform/dbops/binaries/go/go/test/recover5.go
new file mode 100644
index 0000000000000000000000000000000000000000..0e93f5ee1dca5d10e44ba0c1236654227252a9af
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/recover5.go
@@ -0,0 +1,16 @@
+// errorcheck
+
+// 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.
+
+// Verify that recover arguments requirements are enforced by the
+// compiler.
+
+package main
+
+func main() {
+ _ = recover() // OK
+ _ = recover(1) // ERROR "too many arguments"
+ _ = recover(1, 2) // ERROR "too many arguments"
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod1.go b/platform/dbops/binaries/go/go/test/reflectmethod1.go
new file mode 100644
index 0000000000000000000000000000000000000000..973bf15b8b5e0d40aa7cff4683310bfd230575cc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod1.go
@@ -0,0 +1,30 @@
+// run
+
+// 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.
+
+// The linker can prune methods that are not directly called or
+// assigned to interfaces, but only if reflect.Type.Method is
+// never used. Test it here.
+
+package main
+
+import "reflect"
+
+var called = false
+
+type M int
+
+func (m M) UniqueMethodName() {
+ called = true
+}
+
+var v M
+
+func main() {
+ reflect.TypeOf(v).Method(0).Func.Interface().(func(M))(v)
+ if !called {
+ panic("UniqueMethodName not called")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod2.go b/platform/dbops/binaries/go/go/test/reflectmethod2.go
new file mode 100644
index 0000000000000000000000000000000000000000..9ee1c245daeb62a526ed20ca37d839ce9819119a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod2.go
@@ -0,0 +1,36 @@
+// run
+
+// 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.
+
+// The linker can prune methods that are not directly called or
+// assigned to interfaces, but only if reflect.Type.MethodByName is
+// never used. Test it here.
+
+package main
+
+import reflect1 "reflect"
+
+var called = false
+
+type M int
+
+func (m M) UniqueMethodName() {
+ called = true
+}
+
+var v M
+
+type MyType interface {
+ MethodByName(string) (reflect1.Method, bool)
+}
+
+func main() {
+ var t MyType = reflect1.TypeOf(v)
+ m, _ := t.MethodByName("UniqueMethodName")
+ m.Func.Interface().(func(M))(v)
+ if !called {
+ panic("UniqueMethodName not called")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod3.go b/platform/dbops/binaries/go/go/test/reflectmethod3.go
new file mode 100644
index 0000000000000000000000000000000000000000..b423a59f77e34b54b39563292fd5bec88c6ae8c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod3.go
@@ -0,0 +1,35 @@
+// run
+
+// 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.
+
+// The linker can prune methods that are not directly called or
+// assigned to interfaces, but only if reflect.Type.Method is
+// never used. Test it here.
+
+package main
+
+import "reflect"
+
+var called = false
+
+type M int
+
+func (m M) UniqueMethodName() {
+ called = true
+}
+
+var v M
+
+type MyType interface {
+ Method(int) reflect.Method
+}
+
+func main() {
+ var t MyType = reflect.TypeOf(v)
+ t.Method(0).Func.Interface().(func(M))(v)
+ if !called {
+ panic("UniqueMethodName not called")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod4.go b/platform/dbops/binaries/go/go/test/reflectmethod4.go
new file mode 100644
index 0000000000000000000000000000000000000000..037b3dada30a69bffe9cab4928bdaaa635e8c03b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod4.go
@@ -0,0 +1,30 @@
+// run
+
+// 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.
+
+// The linker can prune methods that are not directly called or
+// assigned to interfaces, but only if reflect.Value.Method is
+// never used. Test it here.
+
+package main
+
+import "reflect"
+
+var called = false
+
+type M int
+
+func (m M) UniqueMethodName() {
+ called = true
+}
+
+var v M
+
+func main() {
+ reflect.ValueOf(v).Method(0).Interface().(func())()
+ if !called {
+ panic("UniqueMethodName not called")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod5.go b/platform/dbops/binaries/go/go/test/reflectmethod5.go
new file mode 100644
index 0000000000000000000000000000000000000000..a3fdaa2dcdfba1c19c84a0e61baa618a00f484a2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod5.go
@@ -0,0 +1,30 @@
+// run
+
+// 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.
+
+// Issue 38515: failed to mark the method wrapper
+// reflect.Type.Method itself as REFLECTMETHOD.
+
+package main
+
+import "reflect"
+
+var called bool
+
+type foo struct{}
+
+func (foo) X() { called = true }
+
+var h = reflect.Type.Method
+
+func main() {
+ v := reflect.ValueOf(foo{})
+ m := h(v.Type(), 0)
+ f := m.Func.Interface().(func(foo))
+ f(foo{})
+ if !called {
+ panic("FAIL")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod6.go b/platform/dbops/binaries/go/go/test/reflectmethod6.go
new file mode 100644
index 0000000000000000000000000000000000000000..004ea303e6916d477265ee956bd08e2a4f468e29
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod6.go
@@ -0,0 +1,32 @@
+// run
+
+// 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.
+
+// Similar to reflectmethod5.go, but for reflect.Type.MethodByName.
+
+package main
+
+import "reflect"
+
+var called bool
+
+type foo struct{}
+
+func (foo) X() { called = true }
+
+var h = reflect.Type.MethodByName
+
+func main() {
+ v := reflect.ValueOf(foo{})
+ m, ok := h(v.Type(), "X")
+ if !ok {
+ panic("FAIL")
+ }
+ f := m.Func.Interface().(func(foo))
+ f(foo{})
+ if !called {
+ panic("FAIL")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod7.go b/platform/dbops/binaries/go/go/test/reflectmethod7.go
new file mode 100644
index 0000000000000000000000000000000000000000..688238c5119fa68d97cc3d1906033ebf5c82f18d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod7.go
@@ -0,0 +1,24 @@
+// run
+
+// 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.
+
+// See issue 44207.
+
+package main
+
+import "reflect"
+
+type S int
+
+func (s S) M() {}
+
+func main() {
+ t := reflect.TypeOf(S(0))
+ fn, ok := reflect.PointerTo(t).MethodByName("M")
+ if !ok {
+ panic("FAIL")
+ }
+ fn.Func.Call([]reflect.Value{reflect.New(t)})
+}
diff --git a/platform/dbops/binaries/go/go/test/reflectmethod8.go b/platform/dbops/binaries/go/go/test/reflectmethod8.go
new file mode 100644
index 0000000000000000000000000000000000000000..482163bae6f4419811b374ec7eaea0442eef8980
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reflectmethod8.go
@@ -0,0 +1,26 @@
+// compile
+
+// 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.
+
+// Make sure that the compiler can analyze non-reflect
+// Type.{Method,MethodByName} calls.
+
+package p
+
+type I interface {
+ MethodByName(string)
+ Method(int)
+}
+
+type M struct{}
+
+func (M) MethodByName(string) {}
+func (M) Method(int) {}
+
+func f() {
+ var m M
+ I.MethodByName(m, "")
+ I.Method(m, 42)
+}
diff --git a/platform/dbops/binaries/go/go/test/rename.go b/platform/dbops/binaries/go/go/test/rename.go
new file mode 100644
index 0000000000000000000000000000000000000000..83f184b74dcbd77c84948543a6b6ab60706d7834
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rename.go
@@ -0,0 +1,103 @@
+// run
+
+// 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.
+
+// Test that predeclared names can be redeclared by the user.
+
+package main
+
+import (
+ "fmt"
+ "runtime"
+)
+
+func main() {
+ n :=
+ append +
+ bool +
+ byte +
+ complex +
+ complex64 +
+ complex128 +
+ cap +
+ close +
+ delete +
+ error +
+ false +
+ float32 +
+ float64 +
+ imag +
+ int +
+ int8 +
+ int16 +
+ int32 +
+ int64 +
+ len +
+ make +
+ new +
+ nil +
+ panic +
+ print +
+ println +
+ real +
+ recover +
+ rune +
+ string +
+ true +
+ uint +
+ uint8 +
+ uint16 +
+ uint32 +
+ uint64 +
+ uintptr +
+ iota
+ if n != NUM*(NUM-1)/2 {
+ fmt.Println("BUG: wrong n", n, NUM*(NUM-1)/2)
+ runtime.Breakpoint() // panic is inaccessible
+ }
+}
+
+const (
+ // cannot use iota here, because iota = 38 below
+ append = 1
+ bool = 2
+ byte = 3
+ complex = 4
+ complex64 = 5
+ complex128 = 6
+ cap = 7
+ close = 8
+ delete = 9
+ error = 10
+ false = 11
+ float32 = 12
+ float64 = 13
+ imag = 14
+ int = 15
+ int8 = 16
+ int16 = 17
+ int32 = 18
+ int64 = 19
+ len = 20
+ make = 21
+ new = 22
+ nil = 23
+ panic = 24
+ print = 25
+ println = 26
+ real = 27
+ recover = 28
+ rune = 29
+ string = 30
+ true = 31
+ uint = 32
+ uint8 = 33
+ uint16 = 34
+ uint32 = 35
+ uint64 = 36
+ uintptr = 37
+ iota = 38
+ NUM = 39
+)
diff --git a/platform/dbops/binaries/go/go/test/rename1.go b/platform/dbops/binaries/go/go/test/rename1.go
new file mode 100644
index 0000000000000000000000000000000000000000..56824e99eca75510a81b233d5cd4a4016fd5f02c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rename1.go
@@ -0,0 +1,60 @@
+// errorcheck
+
+// 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.
+
+// Verify that renamed identifiers no longer have their old meaning.
+// Does not compile.
+
+package main
+
+func main() {
+ var n byte // ERROR "not a type|expected type"
+ var y = float32(0) // ERROR "cannot call|expected function"
+ const (
+ a = 1 + iota // ERROR "invalid operation|incompatible types|cannot convert"
+ )
+ _, _ = n, y
+}
+
+const (
+ append = 1
+ bool = 2
+ byte = 3
+ complex = 4
+ complex64 = 5
+ complex128 = 6
+ cap = 7
+ close = 8
+ delete = 9
+ error = 10
+ false = 11
+ float32 = 12
+ float64 = 13
+ imag = 14
+ int = 15
+ int8 = 16
+ int16 = 17
+ int32 = 18
+ int64 = 19
+ len = 20
+ make = 21
+ new = 22
+ nil = 23
+ panic = 24
+ print = 25
+ println = 26
+ real = 27
+ recover = 28
+ rune = 29
+ string = 30
+ true = 31
+ uint = 32
+ uint8 = 33
+ uint16 = 34
+ uint32 = 35
+ uint64 = 36
+ uintptr = 37
+ iota = "38"
+)
diff --git a/platform/dbops/binaries/go/go/test/reorder.go b/platform/dbops/binaries/go/go/test/reorder.go
new file mode 100644
index 0000000000000000000000000000000000000000..57892f882fa5b48f0d9ed835af1ba76d5a230f0f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reorder.go
@@ -0,0 +1,167 @@
+// run
+
+// 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.
+
+// Test reordering of assignments.
+
+package main
+
+import "fmt"
+
+func main() {
+ p1()
+ p2()
+ p3()
+ p4()
+ p5()
+ p6()
+ p7()
+ p8()
+ p9()
+ p10()
+ p11()
+}
+
+var gx []int
+
+func f(i int) int {
+ return gx[i]
+}
+
+func check(x []int, x0, x1, x2 int) {
+ if x[0] != x0 || x[1] != x1 || x[2] != x2 {
+ fmt.Printf("%v, want %d,%d,%d\n", x, x0, x1, x2)
+ panic("failed")
+ }
+}
+
+func check3(x, y, z, xx, yy, zz int) {
+ if x != xx || y != yy || z != zz {
+ fmt.Printf("%d,%d,%d, want %d,%d,%d\n", x, y, z, xx, yy, zz)
+ panic("failed")
+ }
+}
+
+func p1() {
+ x := []int{1, 2, 3}
+ i := 0
+ i, x[i] = 1, 100
+ _ = i
+ check(x, 100, 2, 3)
+}
+
+func p2() {
+ x := []int{1, 2, 3}
+ i := 0
+ x[i], i = 100, 1
+ _ = i
+ check(x, 100, 2, 3)
+}
+
+func p3() {
+ x := []int{1, 2, 3}
+ y := x
+ gx = x
+ x[1], y[0] = f(0), f(1)
+ check(x, 2, 1, 3)
+}
+
+func p4() {
+ x := []int{1, 2, 3}
+ y := x
+ gx = x
+ x[1], y[0] = gx[0], gx[1]
+ check(x, 2, 1, 3)
+}
+
+func p5() {
+ x := []int{1, 2, 3}
+ y := x
+ p := &x[0]
+ q := &x[1]
+ *p, *q = x[1], y[0]
+ check(x, 2, 1, 3)
+}
+
+func p6() {
+ x := 1
+ y := 2
+ z := 3
+ px := &x
+ py := &y
+ *px, *py = y, x
+ check3(x, y, z, 2, 1, 3)
+}
+
+func f1(x, y, z int) (xx, yy, zz int) {
+ return x, y, z
+}
+
+func f2() (x, y, z int) {
+ return f1(2, 1, 3)
+}
+
+func p7() {
+ x, y, z := f2()
+ check3(x, y, z, 2, 1, 3)
+}
+
+func p8() {
+ m := make(map[int]int)
+ m[0] = len(m)
+ if m[0] != 0 {
+ panic(m[0])
+ }
+}
+
+// Issue #13433: Left-to-right assignment of OAS2XXX nodes.
+func p9() {
+ var x bool
+
+ // OAS2FUNC
+ x, x = fn()
+ checkOAS2XXX(x, "x, x = fn()")
+
+ // OAS2RECV
+ var c = make(chan bool, 10)
+ c <- false
+ x, x = <-c
+ checkOAS2XXX(x, "x, x <-c")
+
+ // OAS2MAPR
+ var m = map[int]bool{0: false}
+ x, x = m[0]
+ checkOAS2XXX(x, "x, x = m[0]")
+
+ // OAS2DOTTYPE
+ var i interface{} = false
+ x, x = i.(bool)
+ checkOAS2XXX(x, "x, x = i.(bool)")
+}
+
+//go:noinline
+func fn() (bool, bool) { return false, true }
+
+// checks the order of OAS2XXX.
+func checkOAS2XXX(x bool, s string) {
+ if !x {
+ fmt.Printf("%s; got=(false); want=(true)\n", s)
+ panic("failed")
+ }
+}
+
+//go:noinline
+func fp() (*int, int) { return nil, 42 }
+
+func p10() {
+ p := new(int)
+ p, *p = fp()
+}
+
+func p11() {
+ var i interface{}
+ p := new(bool)
+ p, *p = i.(*bool)
+}
diff --git a/platform/dbops/binaries/go/go/test/reorder2.go b/platform/dbops/binaries/go/go/test/reorder2.go
new file mode 100644
index 0000000000000000000000000000000000000000..07f1b158d0e7e962aa1c3c3fb72293d1b361807a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/reorder2.go
@@ -0,0 +1,341 @@
+// run
+
+// 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.
+
+// Test reorderings; derived from fixedbugs/bug294.go.
+
+package main
+
+var log string
+
+type TT int
+
+func (t TT) a(s string) TT {
+ log += "a(" + s + ")"
+ return t
+}
+
+func (TT) b(s string) string {
+ log += "b(" + s + ")"
+ return s
+}
+
+type F func(s string) F
+
+func a(s string) F {
+ log += "a(" + s + ")"
+ return F(a)
+}
+
+func b(s string) string {
+ log += "b(" + s + ")"
+ return s
+}
+
+type I interface {
+ a(s string) I
+ b(s string) string
+}
+
+type T1 int
+
+func (t T1) a(s string) I {
+ log += "a(" + s + ")"
+ return t
+}
+
+func (T1) b(s string) string {
+ log += "b(" + s + ")"
+ return s
+}
+
+// f(g(), h()) where g is not inlinable but h is will have the same problem.
+// As will x := g() + h() (same conditions).
+// And g() <- h().
+func f(x, y string) {
+ log += "f(" + x + ", " + y + ")"
+}
+
+//go:noinline
+func ff(x, y string) {
+ log += "ff(" + x + ", " + y + ")"
+}
+
+func h(x string) string {
+ log += "h(" + x + ")"
+ return x
+}
+
+//go:noinline
+func g(x string) string {
+ log += "g(" + x + ")"
+ return x
+}
+
+func main() {
+ err := 0
+ var t TT
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+
+ if s := t.a("1").b("3"); log != "a(1)b(3)" || s != "3" {
+ println("expecting a(1)b(3) and 3, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if s := t.a("1").a(t.b("2")).b("3") + t.a("4").b("5"); log != "a(1)b(2)a(2)b(3)a(4)b(5)" || s != "35" {
+ println("expecting a(1)b(2)a(2)b(3)a(4)b(5) and 35, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if s := t.a("4").b("5") + t.a("1").a(t.b("2")).b("3"); log != "a(4)b(5)a(1)b(2)a(2)b(3)" || s != "53" {
+ println("expecting a(4)b(5)a(1)b(2)a(2)b(3) and 35, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if ff(g("1"), g("2")); log != "g(1)g(2)ff(1, 2)" {
+ println("expecting g(1)g(2)ff..., got ", log)
+ err++
+ }
+ log = ""
+
+ if ff(g("1"), h("2")); log != "g(1)h(2)ff(1, 2)" {
+ println("expecting g(1)h(2)ff..., got ", log)
+ err++
+ }
+ log = ""
+
+ if ff(h("1"), g("2")); log != "h(1)g(2)ff(1, 2)" {
+ println("expecting h(1)g(2)ff..., got ", log)
+ err++
+ }
+ log = ""
+
+ if ff(h("1"), h("2")); log != "h(1)h(2)ff(1, 2)" {
+ println("expecting h(1)h(2)ff..., got ", log)
+ err++
+ }
+ log = ""
+
+ if s := g("1") + g("2"); log != "g(1)g(2)" || s != "12" {
+ println("expecting g1g2 and 12, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if s := g("1") + h("2"); log != "g(1)h(2)" || s != "12" {
+ println("expecting g1h2 and 12, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if s := h("1") + g("2"); log != "h(1)g(2)" || s != "12" {
+ println("expecting h1g2 and 12, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ if s := h("1") + h("2"); log != "h(1)h(2)" || s != "12" {
+ println("expecting h1h2 and 12, got ", log, " and ", s)
+ err++
+ }
+ log = ""
+
+ x := 0
+ switch x {
+ case 0:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in switch, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in switch, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in switch, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in switch, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ c := make(chan int, 1)
+ c <- 1
+ select {
+ case c <- 0:
+ case c <- 1:
+ case <-c:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in select1, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in select1, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in select1, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in select1, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ c <- 1
+ select {
+ case <-c:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in select2, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in select2, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in select2, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in select2, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ c <- 1
+ select {
+ default:
+ case c <- 1:
+ case <-c:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in select3, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in select3, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in select3, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in select3, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ c <- 1
+ select {
+ default:
+ case <-c:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in select4, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in select4, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in select4, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in select4, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ select {
+ case <-c:
+ case <-c:
+ default:
+ if a("1")("2")("3"); log != "a(1)a(2)a(3)" {
+ println("in select5, expecting a(1)a(2)a(3) , got ", log)
+ err++
+ }
+ log = ""
+
+ if t.a("1").a(t.b("2")); log != "a(1)b(2)a(2)" {
+ println("in select5, expecting a(1)b(2)a(2), got ", log)
+ err++
+ }
+ log = ""
+ if a("3")(b("4"))(b("5")); log != "a(3)b(4)a(4)b(5)a(5)" {
+ println("in select5, expecting a(3)b(4)a(4)b(5)a(5), got ", log)
+ err++
+ }
+ log = ""
+ var i I = T1(0)
+ if i.a("6").a(i.b("7")).a(i.b("8")).a(i.b("9")); log != "a(6)b(7)a(7)b(8)a(8)b(9)a(9)" {
+ println("in select5, expecting a(6)ba(7)ba(8)ba(9), got", log)
+ err++
+ }
+ log = ""
+ }
+
+ if err > 0 {
+ panic("fail")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/retjmp.go b/platform/dbops/binaries/go/go/test/retjmp.go
new file mode 100644
index 0000000000000000000000000000000000000000..778d903625469aff218ab03604845811253c6f3f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/retjmp.go
@@ -0,0 +1,9 @@
+// buildrundir
+
+// 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.
+
+// Test that return jump works correctly in assembly code.
+
+package ignored
diff --git a/platform/dbops/binaries/go/go/test/return.go b/platform/dbops/binaries/go/go/test/return.go
new file mode 100644
index 0000000000000000000000000000000000000000..95f94b9276c783367ba0949511bf48114ecd278b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/return.go
@@ -0,0 +1,2821 @@
+// errorcheck
+
+// 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.
+
+// Test compiler diagnosis of function missing return statements.
+// See issue 65 and golang.org/s/go11return.
+
+package p
+
+type T int
+
+var x interface{}
+var c chan int
+
+func external() int // ok
+
+func _() int {
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+} // ERROR "missing return"
+
+// return is okay
+func _() int {
+ print(1)
+ return 2
+}
+
+// goto is okay
+func _() int {
+L:
+ print(1)
+ goto L
+}
+
+// panic is okay
+func _() int {
+ print(1)
+ panic(2)
+}
+
+// but only builtin panic
+func _() int {
+ var panic = func(int) {}
+ print(1)
+ panic(2)
+} // ERROR "missing return"
+
+// block ending in terminating statement is okay
+func _() int {
+ {
+ print(1)
+ return 2
+ }
+}
+
+// block ending in terminating statement is okay
+func _() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+}
+
+// block ending in terminating statement is okay
+func _() int {
+ print(1)
+ {
+ panic(2)
+ }
+}
+
+// adding more code - even though it is dead - now requires a return
+
+func _() int {
+ print(1)
+ return 2
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+L:
+ print(1)
+ goto L
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ panic(2)
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ {
+ print(1)
+ return 2
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ print(1)
+ goto L
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ {
+ panic(2)
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ print(1)
+ return 2
+ }
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ {
+ panic(2)
+ }
+ print(3)
+} // ERROR "missing return"
+
+// even an empty dead block triggers the message, because it
+// becomes the final statement.
+
+func _() int {
+ print(1)
+ return 2
+ {}
+} // ERROR "missing return"
+
+func _() int {
+L:
+ print(1)
+ goto L
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ panic(2)
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ {
+ print(1)
+ return 2
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ print(1)
+ goto L
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ {
+ panic(2)
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ print(1)
+ return 2
+ }
+ {}
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ {
+ panic(2)
+ }
+ {}
+} // ERROR "missing return"
+
+// if-else chain with final else and all terminating is okay
+
+func _() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else {
+ panic(3)
+ }
+}
+
+func _() int {
+L:
+ print(1)
+ if x == nil {
+ panic(2)
+ } else {
+ goto L
+ }
+}
+
+func _() int {
+L:
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 2 {
+ panic(3)
+ } else {
+ goto L
+ }
+}
+
+// if-else chain missing final else is not okay, even if the
+// conditions cover every possible case.
+
+func _() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x != nil {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 1 {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+
+// for { loops that never break are okay.
+
+func _() int {
+ print(1)
+ for {}
+}
+
+func _() int {
+ for {
+ for {
+ break
+ }
+ }
+}
+
+func _() int {
+ for {
+ L:
+ for {
+ break L
+ }
+ }
+}
+
+// for { loops that break are not okay.
+
+func _() int {
+ print(1)
+ for { break }
+} // ERROR "missing return"
+
+func _() int {
+ for {
+ for {
+ }
+ break
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ for {
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// if there's a condition - even "true" - the loops are no longer syntactically terminating
+
+func _() int {
+ print(1)
+ for x == nil {}
+} // ERROR "missing return"
+
+func _() int {
+ for x == nil {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ for x == nil {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ for true {}
+} // ERROR "missing return"
+
+func _() int {
+ for true {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ for true {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// select in which all cases terminate and none break are okay.
+
+func _() int {
+ print(1)
+ select{}
+}
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ }
+}
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ for{}
+ }
+}
+
+func _() int {
+L:
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ goto L
+ }
+}
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ select{}
+ }
+}
+
+// if any cases don't terminate, the select isn't okay anymore
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ goto L
+ case c <- 1:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+// if any breaks refer to the select, the select isn't okay anymore, even if they're dead
+
+func _() int {
+ print(1)
+ select{ default: break }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ break
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+L:
+ select {
+ case <-c:
+ print(2)
+ for{ break L }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ break L
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ select {
+ case <-c:
+ print(1)
+ panic("abc")
+ default:
+ select{}
+ break
+ }
+} // ERROR "missing return"
+
+// switch with default in which all cases terminate is okay
+
+func _() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+func _() int {
+ print(1)
+ switch x {
+ default:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+}
+
+func _() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ default:
+ return 4
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+func _() int {
+ print(1)
+ switch {
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x {
+ case 2:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+func _() int {
+ print(1)
+L:
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x {
+ default:
+ return 4
+ break
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+L:
+ switch x {
+ case 1:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// type switch with default in which all cases terminate is okay
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ default:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+func _() int {
+ print(1)
+ switch {
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ case float64:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ case float64:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+func _() int {
+ print(1)
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+ switch x.(type) {
+ default:
+ return 4
+ break
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ print(1)
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// again, but without the leading print(1).
+// testing that everything works when the terminating statement is first.
+
+func _() int {
+} // ERROR "missing return"
+
+// return is okay
+func _() int {
+ return 2
+}
+
+// goto is okay
+func _() int {
+L:
+ goto L
+}
+
+// panic is okay
+func _() int {
+ panic(2)
+}
+
+// but only builtin panic
+func _() int {
+ var panic = func(int) {}
+ panic(2)
+} // ERROR "missing return"
+
+// block ending in terminating statement is okay
+func _() int {
+ {
+ return 2
+ }
+}
+
+// block ending in terminating statement is okay
+func _() int {
+L:
+ {
+ goto L
+ }
+}
+
+// block ending in terminating statement is okay
+func _() int {
+ {
+ panic(2)
+ }
+}
+
+// adding more code - even though it is dead - now requires a return
+
+func _() int {
+ return 2
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+L:
+ goto L
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ panic(2)
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ {
+ return 2
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ goto L
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ panic(2)
+ print(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ return 2
+ }
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ goto L
+ }
+ print(3)
+} // ERROR "missing return"
+
+func _() int {
+ {
+ panic(2)
+ }
+ print(3)
+} // ERROR "missing return"
+
+// even an empty dead block triggers the message, because it
+// becomes the final statement.
+
+func _() int {
+ return 2
+ {}
+} // ERROR "missing return"
+
+func _() int {
+L:
+ goto L
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ panic(2)
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ {
+ return 2
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ goto L
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ panic(2)
+ {}
+ }
+} // ERROR "missing return"
+
+func _() int {
+ {
+ return 2
+ }
+ {}
+} // ERROR "missing return"
+
+func _() int {
+L:
+ {
+ goto L
+ }
+ {}
+} // ERROR "missing return"
+
+func _() int {
+ {
+ panic(2)
+ }
+ {}
+} // ERROR "missing return"
+
+// if-else chain with final else and all terminating is okay
+
+func _() int {
+ if x == nil {
+ panic(2)
+ } else {
+ panic(3)
+ }
+}
+
+func _() int {
+L:
+ if x == nil {
+ panic(2)
+ } else {
+ goto L
+ }
+}
+
+func _() int {
+L:
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 2 {
+ panic(3)
+ } else {
+ goto L
+ }
+}
+
+// if-else chain missing final else is not okay, even if the
+// conditions cover every possible case.
+
+func _() int {
+ if x == nil {
+ panic(2)
+ } else if x != nil {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ if x == nil {
+ panic(2)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 1 {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+
+// for { loops that never break are okay.
+
+func _() int {
+ for {}
+}
+
+func _() int {
+ for {
+ for {
+ break
+ }
+ }
+}
+
+func _() int {
+ for {
+ L:
+ for {
+ break L
+ }
+ }
+}
+
+// for { loops that break are not okay.
+
+func _() int {
+ for { break }
+} // ERROR "missing return"
+
+func _() int {
+ for {
+ for {
+ }
+ break
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ for {
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// if there's a condition - even "true" - the loops are no longer syntactically terminating
+
+func _() int {
+ for x == nil {}
+} // ERROR "missing return"
+
+func _() int {
+ for x == nil {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ for x == nil {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ for true {}
+} // ERROR "missing return"
+
+func _() int {
+ for true {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+func _() int {
+ for true {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// select in which all cases terminate and none break are okay.
+
+func _() int {
+ select{}
+}
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ }
+}
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ for{}
+ }
+}
+
+func _() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ goto L
+ }
+}
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ select{}
+ }
+}
+
+// if any cases don't terminate, the select isn't okay anymore
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ goto L
+ case c <- 1:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+// if any breaks refer to the select, the select isn't okay anymore, even if they're dead
+
+func _() int {
+ select{ default: break }
+} // ERROR "missing return"
+
+func _() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ break
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ for{ break L }
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ break L
+ }
+} // ERROR "missing return"
+
+func _() int {
+ select {
+ case <-c:
+ panic("abc")
+ default:
+ select{}
+ break
+ }
+} // ERROR "missing return"
+
+// switch with default in which all cases terminate is okay
+
+func _() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+func _() int {
+ switch x {
+ default:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+}
+
+func _() int {
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ default:
+ return 4
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+func _() int {
+ switch {
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x {
+ case 2:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+func _() int {
+L:
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x {
+ default:
+ return 4
+ break
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ switch x {
+ case 1:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// type switch with default in which all cases terminate is okay
+
+func _() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+func _() int {
+ switch x.(type) {
+ default:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+func _() int {
+ switch {
+ }
+} // ERROR "missing return"
+
+
+func _() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ case float64:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x.(type) {
+ case float64:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+func _() int {
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x.(type) {
+ default:
+ return 4
+ break
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+func _() int {
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+func _() int {
+ switch x.(type) {
+ default:
+ return 4
+ case int, float64:
+ print(2)
+ panic(3)
+ }
+}
+
+// again, with func literals
+
+var _ = func() int {
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+} // ERROR "missing return"
+
+// return is okay
+var _ = func() int {
+ print(1)
+ return 2
+}
+
+// goto is okay
+var _ = func() int {
+L:
+ print(1)
+ goto L
+}
+
+// panic is okay
+var _ = func() int {
+ print(1)
+ panic(2)
+}
+
+// but only builtin panic
+var _ = func() int {
+ var panic = func(int) {}
+ print(1)
+ panic(2)
+} // ERROR "missing return"
+
+// block ending in terminating statement is okay
+var _ = func() int {
+ {
+ print(1)
+ return 2
+ }
+}
+
+// block ending in terminating statement is okay
+var _ = func() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+}
+
+// block ending in terminating statement is okay
+var _ = func() int {
+ print(1)
+ {
+ panic(2)
+ }
+}
+
+// adding more code - even though it is dead - now requires a return
+
+var _ = func() int {
+ print(1)
+ return 2
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ print(1)
+ goto L
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ panic(2)
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ print(1)
+ return 2
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ print(1)
+ goto L
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ {
+ panic(2)
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ print(1)
+ return 2
+ }
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ {
+ panic(2)
+ }
+ print(3)
+} // ERROR "missing return"
+
+// even an empty dead block triggers the message, because it
+// becomes the final statement.
+
+var _ = func() int {
+ print(1)
+ return 2
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ print(1)
+ goto L
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ panic(2)
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ print(1)
+ return 2
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ print(1)
+ goto L
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ {
+ panic(2)
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ print(1)
+ return 2
+ }
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ print(1)
+ goto L
+ }
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ {
+ panic(2)
+ }
+ {}
+} // ERROR "missing return"
+
+// if-else chain with final else and all terminating is okay
+
+var _ = func() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else {
+ panic(3)
+ }
+}
+
+var _ = func() int {
+L:
+ print(1)
+ if x == nil {
+ panic(2)
+ } else {
+ goto L
+ }
+}
+
+var _ = func() int {
+L:
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 2 {
+ panic(3)
+ } else {
+ goto L
+ }
+}
+
+// if-else chain missing final else is not okay, even if the
+// conditions cover every possible case.
+
+var _ = func() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x != nil {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 1 {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+
+// for { loops that never break are okay.
+
+var _ = func() int {
+ print(1)
+ for {}
+}
+
+var _ = func() int {
+ for {
+ for {
+ break
+ }
+ }
+}
+
+var _ = func() int {
+ for {
+ L:
+ for {
+ break L
+ }
+ }
+}
+
+// for { loops that break are not okay.
+
+var _ = func() int {
+ print(1)
+ for { break }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for {
+ for {
+ }
+ break
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ for {
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// if there's a condition - even "true" - the loops are no longer syntactically terminating
+
+var _ = func() int {
+ print(1)
+ for x == nil {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ for x == nil {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for x == nil {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ for true {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ for true {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for true {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// select in which all cases terminate and none break are okay.
+
+var _ = func() int {
+ print(1)
+ select{}
+}
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ }
+}
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ for{}
+ }
+}
+
+var _ = func() int {
+L:
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ goto L
+ }
+}
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ select{}
+ }
+}
+
+// if any cases don't terminate, the select isn't okay anymore
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ goto L
+ case c <- 1:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+// if any breaks refer to the select, the select isn't okay anymore, even if they're dead
+
+var _ = func() int {
+ print(1)
+ select{ default: break }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ break
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+L:
+ select {
+ case <-c:
+ print(2)
+ for{ break L }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ break L
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ select {
+ case <-c:
+ print(1)
+ panic("abc")
+ default:
+ select{}
+ break
+ }
+} // ERROR "missing return"
+
+// switch with default in which all cases terminate is okay
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+var _ = func() int {
+ print(1)
+ switch x {
+ default:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+}
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ default:
+ return 4
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+var _ = func() int {
+ print(1)
+ switch {
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 2:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+var _ = func() int {
+ print(1)
+L:
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x {
+ default:
+ return 4
+ break
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+L:
+ switch x {
+ case 1:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// type switch with default in which all cases terminate is okay
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ default:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+var _ = func() int {
+ print(1)
+ switch {
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ case float64:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ case float64:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+var _ = func() int {
+ print(1)
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+ switch x.(type) {
+ default:
+ return 4
+ break
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ print(1)
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// again, but without the leading print(1).
+// testing that everything works when the terminating statement is first.
+
+var _ = func() int {
+} // ERROR "missing return"
+
+// return is okay
+var _ = func() int {
+ return 2
+}
+
+// goto is okay
+var _ = func() int {
+L:
+ goto L
+}
+
+// panic is okay
+var _ = func() int {
+ panic(2)
+}
+
+// but only builtin panic
+var _ = func() int {
+ var panic = func(int) {}
+ panic(2)
+} // ERROR "missing return"
+
+// block ending in terminating statement is okay
+var _ = func() int {
+ {
+ return 2
+ }
+}
+
+// block ending in terminating statement is okay
+var _ = func() int {
+L:
+ {
+ goto L
+ }
+}
+
+// block ending in terminating statement is okay
+var _ = func() int {
+ {
+ panic(2)
+ }
+}
+
+// adding more code - even though it is dead - now requires a return
+
+var _ = func() int {
+ return 2
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ goto L
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ panic(2)
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ return 2
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ goto L
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ panic(2)
+ print(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ return 2
+ }
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ goto L
+ }
+ print(3)
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ panic(2)
+ }
+ print(3)
+} // ERROR "missing return"
+
+// even an empty dead block triggers the message, because it
+// becomes the final statement.
+
+var _ = func() int {
+ return 2
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ goto L
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ panic(2)
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ return 2
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ goto L
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ panic(2)
+ {}
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ return 2
+ }
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ {
+ goto L
+ }
+ {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ {
+ panic(2)
+ }
+ {}
+} // ERROR "missing return"
+
+// if-else chain with final else and all terminating is okay
+
+var _ = func() int {
+ if x == nil {
+ panic(2)
+ } else {
+ panic(3)
+ }
+}
+
+var _ = func() int {
+L:
+ if x == nil {
+ panic(2)
+ } else {
+ goto L
+ }
+}
+
+var _ = func() int {
+L:
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 2 {
+ panic(3)
+ } else {
+ goto L
+ }
+}
+
+// if-else chain missing final else is not okay, even if the
+// conditions cover every possible case.
+
+var _ = func() int {
+ if x == nil {
+ panic(2)
+ } else if x != nil {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ if x == nil {
+ panic(2)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ if x == nil {
+ panic(2)
+ } else if x == 1 {
+ return 0
+ } else if x != 1 {
+ panic(3)
+ }
+} // ERROR "missing return"
+
+
+// for { loops that never break are okay.
+
+var _ = func() int {
+ for {}
+}
+
+var _ = func() int {
+ for {
+ for {
+ break
+ }
+ }
+}
+
+var _ = func() int {
+ for {
+ L:
+ for {
+ break L
+ }
+ }
+}
+
+// for { loops that break are not okay.
+
+var _ = func() int {
+ for { break }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for {
+ for {
+ }
+ break
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ for {
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// if there's a condition - even "true" - the loops are no longer syntactically terminating
+
+var _ = func() int {
+ for x == nil {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ for x == nil {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for x == nil {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for true {}
+} // ERROR "missing return"
+
+var _ = func() int {
+ for true {
+ for {
+ break
+ }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ for true {
+ L:
+ for {
+ break L
+ }
+ }
+} // ERROR "missing return"
+
+// select in which all cases terminate and none break are okay.
+
+var _ = func() int {
+ select{}
+}
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ }
+}
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ for{}
+ }
+}
+
+var _ = func() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ goto L
+ }
+}
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ select{}
+ }
+}
+
+// if any cases don't terminate, the select isn't okay anymore
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ goto L
+ case c <- 1:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ default:
+ print(2)
+ }
+} // ERROR "missing return"
+
+
+// if any breaks refer to the select, the select isn't okay anymore, even if they're dead
+
+var _ = func() int {
+ select{ default: break }
+} // ERROR "missing return"
+
+var _ = func() int {
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ break
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ for{ break L }
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ select {
+ case <-c:
+ print(2)
+ panic("abc")
+ case c <- 1:
+ print(2)
+ break L
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ select {
+ case <-c:
+ panic("abc")
+ default:
+ select{}
+ break
+ }
+} // ERROR "missing return"
+
+// switch with default in which all cases terminate is okay
+
+var _ = func() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+var _ = func() int {
+ switch x {
+ default:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+}
+
+var _ = func() int {
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ default:
+ return 4
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+var _ = func() int {
+ switch {
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x {
+ case 2:
+ return 4
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x {
+ case 1:
+ print(2)
+ fallthrough
+ case 2:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+var _ = func() int {
+L:
+ switch x {
+ case 1:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x {
+ default:
+ return 4
+ break
+ case 1:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ switch x {
+ case 1:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+// type switch with default in which all cases terminate is okay
+
+var _ = func() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ default:
+ return 4
+ }
+}
+
+var _ = func() int {
+ switch x.(type) {
+ default:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+}
+
+// if no default or some case doesn't terminate, switch is no longer okay
+
+var _ = func() int {
+ switch {
+ }
+} // ERROR "missing return"
+
+
+var _ = func() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ case float64:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x.(type) {
+ case float64:
+ return 4
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+// if any breaks refer to the switch, switch is no longer okay
+
+var _ = func() int {
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ panic(3)
+ break L
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x.(type) {
+ default:
+ return 4
+ break
+ case int:
+ print(2)
+ panic(3)
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+L:
+ switch x.(type) {
+ case int:
+ print(2)
+ for {
+ break L
+ }
+ default:
+ return 4
+ }
+} // ERROR "missing return"
+
+var _ = func() int {
+ switch x.(type) {
+ default:
+ return 4
+ case int, float64:
+ print(2)
+ panic(3)
+ }
+}
+
+/**/
diff --git a/platform/dbops/binaries/go/go/test/rotate.go b/platform/dbops/binaries/go/go/test/rotate.go
new file mode 100644
index 0000000000000000000000000000000000000000..9dc4b1e0ff80dba2495e0aafdbdbc7217dcfab1e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rotate.go
@@ -0,0 +1,166 @@
+// skip
+
+// NOTE: the actual tests to run are rotate[0123].go
+
+// 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.
+
+// Generate test of shift and rotate by constants.
+// The output is compiled and run.
+//
+// The integer type depends on the value of mode (rotate direction,
+// signedness).
+
+package main
+
+import (
+ "bufio"
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+)
+
+func main() {
+ flag.Parse()
+
+ b := bufio.NewWriter(os.Stdout)
+ defer b.Flush()
+
+ fmt.Fprintf(b, "%s\n", prolog)
+
+ for logBits := uint(3); logBits <= 6; logBits++ {
+ typ := fmt.Sprintf("int%d", 1< 0 {
+ fmt.Printf("BUG\n")
+ }
+}
+
+`
+
+const checkFunc = `
+func check_XXX(desc string, have, want XXX) {
+ if have != want {
+ nfail++
+ fmt.Printf("%s = %T(%#x), want %T(%#x)\n", desc, have, have, want, want)
+ if nfail >= 100 {
+ fmt.Printf("BUG: stopping after 100 failures\n")
+ os.Exit(0)
+ }
+ }
+}
+`
+
+var (
+ uop = [2]func(x, y uint64) uint64{
+ func(x, y uint64) uint64 {
+ return x | y
+ },
+ func(x, y uint64) uint64 {
+ return x ^ y
+ },
+ }
+ iop = [2]func(x, y int64) int64{
+ func(x, y int64) int64 {
+ return x | y
+ },
+ func(x, y int64) int64 {
+ return x ^ y
+ },
+ }
+ cop = [2]byte{'|', '^'}
+)
+
+func gentest(b *bufio.Writer, bits uint, unsigned, inverted bool) {
+ fmt.Fprintf(b, "func init() {\n")
+ defer fmt.Fprintf(b, "}\n")
+ n := 0
+
+ // Generate tests for left/right and right/left.
+ for l := uint(0); l <= bits; l++ {
+ for r := uint(0); r <= bits; r++ {
+ for o, op := range cop {
+ typ := fmt.Sprintf("int%d", bits)
+ v := fmt.Sprintf("i%d", bits)
+ if unsigned {
+ typ = "u" + typ
+ v = "u" + v
+ }
+ v0 := int64(0x123456789abcdef0)
+ if inverted {
+ v = "n" + v
+ v0 = ^v0
+ }
+ expr1 := fmt.Sprintf("%s<<%d %c %s>>%d", v, l, op, v, r)
+ expr2 := fmt.Sprintf("%s>>%d %c %s<<%d", v, r, op, v, l)
+
+ var result string
+ if unsigned {
+ v := uint64(v0) >> (64 - bits)
+ v = uop[o](v<>r)
+ v <<= 64 - bits
+ v >>= 64 - bits
+ result = fmt.Sprintf("%#x", v)
+ } else {
+ v := int64(v0) >> (64 - bits)
+ v = iop[o](v<>r)
+ v <<= 64 - bits
+ v >>= 64 - bits
+ result = fmt.Sprintf("%#x", v)
+ }
+
+ fmt.Fprintf(b, "\tcheck_%s(%q, %s, %s(%s))\n", typ, expr1, expr1, typ, result)
+ fmt.Fprintf(b, "\tcheck_%s(%q, %s, %s(%s))\n", typ, expr2, expr2, typ, result)
+
+ // Chop test into multiple functions so that there's not one
+ // enormous function to compile/link.
+ // All the functions are named init so we don't have to do
+ // anything special to call them. ☺
+ if n++; n >= 50 {
+ fmt.Fprintf(b, "}\n")
+ fmt.Fprintf(b, "func init() {\n")
+ n = 0
+ }
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/rotate0.go b/platform/dbops/binaries/go/go/test/rotate0.go
new file mode 100644
index 0000000000000000000000000000000000000000..09dd90095297df02cdfaff043c9271f03c121399
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rotate0.go
@@ -0,0 +1,12 @@
+// runoutput ./rotate.go
+
+// 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.
+
+// Generate test of bit rotations.
+// The output is compiled and run.
+
+package main
+
+const mode = 0
diff --git a/platform/dbops/binaries/go/go/test/rotate1.go b/platform/dbops/binaries/go/go/test/rotate1.go
new file mode 100644
index 0000000000000000000000000000000000000000..19757ec2a8b6fba0b7239105bd0be9e7075b6bee
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rotate1.go
@@ -0,0 +1,12 @@
+// runoutput ./rotate.go
+
+// 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.
+
+// Generate test of bit rotations.
+// The output is compiled and run.
+
+package main
+
+const mode = 1
diff --git a/platform/dbops/binaries/go/go/test/rotate2.go b/platform/dbops/binaries/go/go/test/rotate2.go
new file mode 100644
index 0000000000000000000000000000000000000000..a55305af3455793bc3866fc82dea4e79549a9f02
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rotate2.go
@@ -0,0 +1,12 @@
+// runoutput ./rotate.go
+
+// 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.
+
+// Generate test of bit rotations.
+// The output is compiled and run.
+
+package main
+
+const mode = 2
diff --git a/platform/dbops/binaries/go/go/test/rotate3.go b/platform/dbops/binaries/go/go/test/rotate3.go
new file mode 100644
index 0000000000000000000000000000000000000000..edd5d3ac9dbba97b6a91d48b2eca53bbb7c7cf0a
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rotate3.go
@@ -0,0 +1,12 @@
+// runoutput ./rotate.go
+
+// 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.
+
+// Generate test of bit rotations.
+// The output is compiled and run.
+
+package main
+
+const mode = 3
diff --git a/platform/dbops/binaries/go/go/test/rune.go b/platform/dbops/binaries/go/go/test/rune.go
new file mode 100644
index 0000000000000000000000000000000000000000..73a5aa23f820c7748aa7972032e81a1366be3b88
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/rune.go
@@ -0,0 +1,47 @@
+// compile
+
+// 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.
+
+// Test rune constants, expressions and types.
+// Compiles but does not run.
+
+package rune
+
+var (
+ r0 = 'a'
+ r1 = 'a'+1
+ r2 = 1+'a'
+ r3 = 'a'*2
+ r4 = 'a'/2
+ r5 = 'a'<<1
+ r6 = 'b'<<2
+ r7 int32
+
+ r = []rune{r0, r1, r2, r3, r4, r5, r6, r7}
+)
+
+var (
+ f0 = 1.2
+ f1 = 1.2/'a'
+
+ f = []float64{f0, f1}
+)
+
+var (
+ i0 = 1
+ i1 = 1<<'\x01'
+
+ i = []int{i0, i1}
+)
+
+const (
+ maxRune = '\U0010FFFF'
+)
+
+var (
+ b0 = maxRune < r0
+
+ b = []bool{b0}
+)
diff --git a/platform/dbops/binaries/go/go/test/runtime.go b/platform/dbops/binaries/go/go/test/runtime.go
new file mode 100644
index 0000000000000000000000000000000000000000..58a5eee70993089ed214592343fcbc71c915a9c6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/runtime.go
@@ -0,0 +1,21 @@
+// errorcheck
+
+// 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.
+
+// Test that even if a file imports runtime,
+// it cannot get at the low-level runtime definitions
+// known to the compiler. For normal packages
+// the compiler doesn't even record the lower case
+// functions in its symbol table, but some functions
+// in runtime are hard-coded into the compiler.
+// Does not compile.
+
+package main
+
+import "runtime"
+
+func main() {
+ runtime.printbool(true) // ERROR "unexported|undefined"
+}
diff --git a/platform/dbops/binaries/go/go/test/shift1.go b/platform/dbops/binaries/go/go/test/shift1.go
new file mode 100644
index 0000000000000000000000000000000000000000..0dae49a74dc590a0a40c9007688be4d20908b2c6
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/shift1.go
@@ -0,0 +1,249 @@
+// errorcheck
+
+// 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.
+
+// Test illegal shifts.
+// Issue 1708, illegal cases.
+// Does not compile.
+
+package p
+
+func f(x int) int { return 0 }
+func g(x interface{}) int { return 0 }
+func h(x float64) int { return 0 }
+
+// from the spec
+var (
+ s uint = 33
+ u = 1.0 << s // ERROR "invalid operation|shift of non-integer operand"
+ v float32 = 1 << s // ERROR "invalid"
+)
+
+// non-constant shift expressions
+var (
+ e1 = g(2.0 << s) // ERROR "invalid|shift of non-integer operand"
+ f1 = h(2 << s) // ERROR "invalid"
+ g1 int64 = 1.1 << s // ERROR "truncated|must be integer"
+)
+
+// constant shift expressions
+const c uint = 65
+
+var (
+ a2 int = 1.0 << c // ERROR "overflow"
+ b2 = 1.0 << c // ERROR "overflow"
+ d2 = f(1.0 << c) // ERROR "overflow"
+)
+
+var (
+ // issues 4882, 4936.
+ a3 = 1.0< legal shift
+ d1 = f(2.0 << s) // typeof(2.0) is int in this context => legal shift
+)
+
+// constant shift expressions
+const c uint = 5
+
+var (
+ a2 int = 2.0 << c // a2 == 64 (type int)
+ b2 = 2.0 << c // b2 == 64 (untyped integer)
+ _ = f(b2) // verify b2 has type int
+ c2 float64 = 2 << c // c2 == 64.0 (type float64)
+ d2 = f(2.0 << c) // == f(64)
+ e2 = g(2.0 << c) // == g(int(64))
+ f2 = h(2 << c) // == h(float64(64.0))
+)
diff --git a/platform/dbops/binaries/go/go/test/shift3.go b/platform/dbops/binaries/go/go/test/shift3.go
new file mode 100644
index 0000000000000000000000000000000000000000..bed2fd66ef788c9c1b5c2a5a30fa21801f92cdf3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/shift3.go
@@ -0,0 +1,41 @@
+// run
+
+// 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 the compiler's noder uses the correct type
+// for RHS shift operands that are untyped. Must compile;
+// run for good measure.
+
+package main
+
+import (
+ "fmt"
+ "math"
+)
+
+func f(x, y int) {
+ if x != y {
+ panic(fmt.Sprintf("%d != %d", x, y))
+ }
+}
+
+func main() {
+ var x int = 1
+ f(x<<1, 2)
+ f(x<<1., 2)
+ f(x<<(1+0i), 2)
+ f(x<<0i, 1)
+
+ f(x<<(1< jv,
+ jconst && kconst && jv > kv,
+ iconst && kconst && iv > kv,
+ iconst && base == "array" && iv > Cap,
+ jconst && base == "array" && jv > Cap,
+ kconst && base == "array" && kv > Cap:
+ continue
+ }
+
+ expr := base + "[" + i + ":" + j + ":" + k + "]"
+ var xbase, xlen, xcap int
+ if iv > jv || jv > kv || kv > Cap || iv < 0 || jv < 0 || kv < 0 {
+ xbase, xlen, xcap = -1, -1, -1
+ } else {
+ xbase = iv
+ xlen = jv - iv
+ xcap = kv - iv
+ }
+ fmt.Fprintf(bout, "\tcheckSlice(%q, func() []byte { return %s }, %d, %d, %d)\n", expr, expr, xbase, xlen, xcap)
+ }
+ }
+ }
+ }
+
+ fmt.Fprintf(bout, "\tif !ok { os.Exit(1) }\n")
+ fmt.Fprintf(bout, "}\n")
+ bout.Flush()
+}
+
+var programTop = `
+package main
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+)
+
+var ok = true
+
+var (
+ array = new([10]byte)
+ slice = array[:]
+
+ vminus1 = -1
+ v0 = 0
+ v1 = 1
+ v2 = 2
+ v3 = 3
+ v4 = 4
+ v5 = 5
+ v10 = 10
+ v20 = 20
+)
+
+func notOK() {
+ if ok {
+ println("BUG:")
+ ok = false
+ }
+}
+
+func checkSlice(desc string, f func() []byte, xbase, xlen, xcap int) {
+ defer func() {
+ if err := recover(); err != nil {
+ if xbase >= 0 {
+ notOK()
+ println(desc, " unexpected panic: ", fmt.Sprint(err))
+ }
+ }
+ // "no panic" is checked below
+ }()
+
+ x := f()
+
+ arrayBase := uintptr(unsafe.Pointer(array))
+ raw := *(*[3]uintptr)(unsafe.Pointer(&x))
+ base, len, cap := raw[0] - arrayBase, raw[1], raw[2]
+ if xbase < 0 {
+ notOK()
+ println(desc, "=", base, len, cap, "want panic")
+ return
+ }
+ if cap != 0 && base != uintptr(xbase) || base >= 10 || len != uintptr(xlen) || cap != uintptr(xcap) {
+ notOK()
+ if cap == 0 {
+ println(desc, "=", base, len, cap, "want", "0-9", xlen, xcap)
+ } else {
+ println(desc, "=", base, len, cap, "want", xbase, xlen, xcap)
+ }
+ }
+}
+
+`
diff --git a/platform/dbops/binaries/go/go/test/slice3err.go b/platform/dbops/binaries/go/go/test/slice3err.go
new file mode 100644
index 0000000000000000000000000000000000000000..120ecbeccebce986363a45a194591e7d06e2b650
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/slice3err.go
@@ -0,0 +1,121 @@
+// errorcheck
+
+// 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
+
+var array *[10]int
+var slice []int
+var str string
+var i, j, k int
+
+func f() {
+ // check what missing arguments are allowed
+ _ = array[:]
+ _ = array[i:]
+ _ = array[:j]
+ _ = array[i:j]
+ _ = array[::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
+ _ = array[i::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
+ _ = array[:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
+ _ = array[i:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
+ _ = array[::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
+ _ = array[i::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
+ _ = array[:j:k]
+ _ = array[i:j:k]
+
+ _ = slice[:]
+ _ = slice[i:]
+ _ = slice[:j]
+ _ = slice[i:j]
+ _ = slice[::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
+ _ = slice[i::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
+ _ = slice[:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
+ _ = slice[i:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
+ _ = slice[::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
+ _ = slice[i::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
+ _ = slice[:j:k]
+ _ = slice[i:j:k]
+
+ _ = str[:]
+ _ = str[i:]
+ _ = str[:j]
+ _ = str[i:j]
+ _ = str[::] // ERROR "3-index slice of string" "middle index required in 3-index slice" "final index required in 3-index slice"
+ _ = str[i::] // ERROR "3-index slice of string" "middle index required in 3-index slice" "final index required in 3-index slice"
+ _ = str[:j:] // ERROR "3-index slice of string" "final index required in 3-index slice"
+ _ = str[i:j:] // ERROR "3-index slice of string" "final index required in 3-index slice"
+ _ = str[::k] // ERROR "3-index slice of string" "middle index required in 3-index slice"
+ _ = str[i::k] // ERROR "3-index slice of string" "middle index required in 3-index slice"
+ _ = str[:j:k] // ERROR "3-index slice of string"
+ _ = str[i:j:k] // ERROR "3-index slice of string"
+
+ // check invalid indices
+ _ = array[1:2]
+ _ = array[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[2:2]
+ _ = array[i:1]
+ _ = array[1:j]
+ _ = array[1:2:3]
+ _ = array[1:3:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[2:1:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[2:3:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[3:1:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[3:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[i:1:2]
+ _ = array[i:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = array[1:j:2]
+ _ = array[2:j:1] // ERROR "invalid slice index|invalid slice indices"
+ _ = array[1:2:k]
+ _ = array[2:1:k] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+
+ _ = slice[1:2]
+ _ = slice[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[2:2]
+ _ = slice[i:1]
+ _ = slice[1:j]
+ _ = slice[1:2:3]
+ _ = slice[1:3:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[2:1:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[2:3:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[3:1:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[3:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[i:1:2]
+ _ = slice[i:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[1:j:2]
+ _ = slice[2:j:1] // ERROR "invalid slice index|invalid slice indices"
+ _ = slice[1:2:k]
+ _ = slice[2:1:k] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+
+ _ = str[1:2]
+ _ = str[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = str[2:2]
+ _ = str[i:1]
+ _ = str[1:j]
+
+ // check out of bounds indices on array
+ _ = array[11:11] // ERROR "out of bounds"
+ _ = array[11:12] // ERROR "out of bounds"
+ _ = array[11:] // ERROR "out of bounds"
+ _ = array[:11] // ERROR "out of bounds"
+ _ = array[1:11] // ERROR "out of bounds"
+ _ = array[1:11:12] // ERROR "out of bounds"
+ _ = array[1:2:11] // ERROR "out of bounds"
+ _ = array[1:11:3] // ERROR "out of bounds|invalid slice index"
+ _ = array[11:2:3] // ERROR "out of bounds|inverted slice|invalid slice index"
+ _ = array[11:12:13] // ERROR "out of bounds"
+
+ // slice bounds not checked
+ _ = slice[11:11]
+ _ = slice[11:12]
+ _ = slice[11:]
+ _ = slice[:11]
+ _ = slice[1:11]
+ _ = slice[1:11:12]
+ _ = slice[1:2:11]
+ _ = slice[1:11:3] // ERROR "invalid slice index|invalid slice indices"
+ _ = slice[11:2:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
+ _ = slice[11:12:13]
+}
diff --git a/platform/dbops/binaries/go/go/test/slicecap.go b/platform/dbops/binaries/go/go/test/slicecap.go
new file mode 100644
index 0000000000000000000000000000000000000000..f71a3b07fff76e71c81dfc7c64e2e946aadab3fa
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/slicecap.go
@@ -0,0 +1,90 @@
+// run
+
+// 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 main
+
+import "unsafe"
+
+var (
+ hello = "hello"
+ bytes = []byte{1, 2, 3, 4, 5}
+ ints = []int32{1, 2, 3, 4, 5}
+
+ five = 5
+
+ ok = true
+)
+
+func notOK() {
+ if ok {
+ println("BUG:")
+ ok = false
+ }
+}
+
+func checkString(desc, s string) {
+ p1 := *(*uintptr)(unsafe.Pointer(&s))
+ p2 := *(*uintptr)(unsafe.Pointer(&hello))
+ if p1-p2 >= 5 {
+ notOK()
+ println("string", desc, "has invalid base")
+ }
+}
+
+func checkBytes(desc string, s []byte) {
+ p1 := *(*uintptr)(unsafe.Pointer(&s))
+ p2 := *(*uintptr)(unsafe.Pointer(&bytes))
+ if p1-p2 >= 5 {
+ println("byte slice", desc, "has invalid base")
+ }
+}
+
+func checkInts(desc string, s []int32) {
+ p1 := *(*uintptr)(unsafe.Pointer(&s))
+ p2 := *(*uintptr)(unsafe.Pointer(&ints))
+ if p1-p2 >= 5*4 {
+ println("int slice", desc, "has invalid base")
+ }
+}
+
+func main() {
+ {
+ x := hello
+ checkString("x", x)
+ checkString("x[5:]", x[5:])
+ checkString("x[five:]", x[five:])
+ checkString("x[5:five]", x[5:five])
+ checkString("x[five:5]", x[five:5])
+ checkString("x[five:five]", x[five:five])
+ checkString("x[1:][2:][2:]", x[1:][2:][2:])
+ y := x[4:]
+ checkString("y[1:]", y[1:])
+ }
+ {
+ x := bytes
+ checkBytes("x", x)
+ checkBytes("x[5:]", x[5:])
+ checkBytes("x[five:]", x[five:])
+ checkBytes("x[5:five]", x[5:five])
+ checkBytes("x[five:5]", x[five:5])
+ checkBytes("x[five:five]", x[five:five])
+ checkBytes("x[1:][2:][2:]", x[1:][2:][2:])
+ y := x[4:]
+ checkBytes("y[1:]", y[1:])
+ }
+ {
+ x := ints
+ checkInts("x", x)
+ checkInts("x[5:]", x[5:])
+ checkInts("x[five:]", x[five:])
+ checkInts("x[5:five]", x[5:five])
+ checkInts("x[five:5]", x[five:5])
+ checkInts("x[five:five]", x[five:five])
+ checkInts("x[1:][2:][2:]", x[1:][2:][2:])
+ y := x[4:]
+ checkInts("y[1:]", y[1:])
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/sliceopt.go b/platform/dbops/binaries/go/go/test/sliceopt.go
new file mode 100644
index 0000000000000000000000000000000000000000..b8b947229c26b1320e0cd82cea4690efba8dc714
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/sliceopt.go
@@ -0,0 +1,32 @@
+// errorcheck -0 -d=append,slice
+
+// 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.
+
+// Check optimization results for append and slicing.
+
+package main
+
+func a1(x []int, y int) []int {
+ x = append(x, y) // ERROR "append: len-only update \(in local slice\)$"
+ return x
+}
+
+func a2(x []int, y int) []int {
+ return append(x, y)
+}
+
+func a3(x *[]int, y int) {
+ *x = append(*x, y) // ERROR "append: len-only update$"
+}
+
+func s1(x **[]int, xs **string, i, j int) {
+ var z []int
+ z = (**x)[0:] // ERROR "slice: omit slice operation$"
+ println(z)
+
+ var zs string
+ zs = (**xs)[0:] // ERROR "slice: omit slice operation$"
+ println(zs)
+}
diff --git a/platform/dbops/binaries/go/go/test/solitaire.go b/platform/dbops/binaries/go/go/test/solitaire.go
new file mode 100644
index 0000000000000000000000000000000000000000..ac54cec0ac74442309535200457f5b00b0a6e71f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/solitaire.go
@@ -0,0 +1,118 @@
+// build
+
+// 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.
+
+// Test general operation by solving a peg solitaire game.
+// A version of this is in the Go playground.
+// Don't run it - produces too much output.
+
+// This program solves the (English) peg solitaire board game.
+// See also: http://en.wikipedia.org/wiki/Peg_solitaire
+
+package main
+
+const N = 11 + 1 // length of a board row (+1 for newline)
+
+// The board must be surrounded by 2 illegal fields in each direction
+// so that move() doesn't need to check the board boundaries. Periods
+// represent illegal fields, ● are pegs, and ○ are holes.
+var board = []rune(
+ `...........
+...........
+....●●●....
+....●●●....
+..●●●●●●●..
+..●●●○●●●..
+..●●●●●●●..
+....●●●....
+....●●●....
+...........
+...........
+`)
+
+// center is the position of the center hole if there is a single one;
+// otherwise it is -1.
+var center int
+
+func init() {
+ n := 0
+ for pos, field := range board {
+ if field == '○' {
+ center = pos
+ n++
+ }
+ }
+ if n != 1 {
+ center = -1 // no single hole
+ }
+}
+
+var moves int // number of times move is called
+
+// move tests if there is a peg at position pos that can jump over another peg
+// in direction dir. If the move is valid, it is executed and move returns true.
+// Otherwise, move returns false.
+func move(pos, dir int) bool {
+ moves++
+ if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {
+ board[pos] = '○'
+ board[pos+dir] = '○'
+ board[pos+2*dir] = '●'
+ return true
+ }
+ return false
+}
+
+// unmove reverts a previously executed valid move.
+func unmove(pos, dir int) {
+ board[pos] = '●'
+ board[pos+dir] = '●'
+ board[pos+2*dir] = '○'
+}
+
+// solve tries to find a sequence of moves such that there is only one peg left
+// at the end; if center is >= 0, that last peg must be in the center position.
+// If a solution is found, solve prints the board after each move in a backward
+// fashion (i.e., the last board position is printed first, all the way back to
+// the starting board position).
+func solve() bool {
+ var last, n int
+ for pos, field := range board {
+ // try each board position
+ if field == '●' {
+ // found a peg
+ for _, dir := range [...]int{-1, -N, +1, +N} {
+ // try each direction
+ if move(pos, dir) {
+ // a valid move was found and executed,
+ // see if this new board has a solution
+ if solve() {
+ unmove(pos, dir)
+ println(string(board))
+ return true
+ }
+ unmove(pos, dir)
+ }
+ }
+ last = pos
+ n++
+ }
+ }
+ // tried each possible move
+ if n == 1 && (center < 0 || last == center) {
+ // there's only one peg left
+ println(string(board))
+ return true
+ }
+ // no solution found for this board
+ return false
+}
+
+func main() {
+ if !solve() {
+ println("no solution found")
+ }
+ println(moves, "moves tried")
+}
diff --git a/platform/dbops/binaries/go/go/test/stack.go b/platform/dbops/binaries/go/go/test/stack.go
new file mode 100644
index 0000000000000000000000000000000000000000..b62febd48ddc28b77fa37f6bfb2beca2a42141bb
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/stack.go
@@ -0,0 +1,100 @@
+// run
+
+// 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.
+
+// Test stack splitting code.
+// Try to tickle stack splitting bugs by doing
+// go, defer, and closure calls at different stack depths.
+
+package main
+
+type T [20]int
+
+func g(c chan int, t T) {
+ s := 0
+ for i := 0; i < len(t); i++ {
+ s += t[i]
+ }
+ c <- s
+}
+
+func d(t T) {
+ s := 0
+ for i := 0; i < len(t); i++ {
+ s += t[i]
+ }
+ if s != len(t) {
+ println("bad defer", s)
+ panic("fail")
+ }
+}
+
+func f0() {
+ // likely to make a new stack for f0,
+ // because the call to f1 puts 3000 bytes
+ // in our frame.
+ f1()
+}
+
+func f1() [3000]byte {
+ // likely to make a new stack for f1,
+ // because 3000 bytes were used by f0
+ // and we need 3000 more for the call
+ // to f2. if the call to morestack in f1
+ // does not pass the frame size, the new
+ // stack (default size 5k) will not be big
+ // enough for the frame, and the morestack
+ // check in f2 will die, if we get that far
+ // without faulting.
+ f2()
+ return [3000]byte{}
+}
+
+func f2() [3000]byte {
+ // just take up space
+ return [3000]byte{}
+}
+
+var c = make(chan int)
+var t T
+var b = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
+
+func recur(n int) {
+ ss := string(b)
+ if len(ss) != len(b) {
+ panic("bad []byte -> string")
+ }
+ go g(c, t)
+ f0()
+ s := <-c
+ if s != len(t) {
+ println("bad go", s)
+ panic("fail")
+ }
+ f := func(t T) int {
+ s := 0
+ for i := 0; i < len(t); i++ {
+ s += t[i]
+ }
+ s += n
+ return s
+ }
+ s = f(t)
+ if s != len(t)+n {
+ println("bad func", s, "at level", n)
+ panic("fail")
+ }
+ if n > 0 {
+ recur(n - 1)
+ }
+ defer d(t)
+}
+
+func main() {
+ for i := 0; i < len(t); i++ {
+ t[i] = 1
+ }
+ recur(8000)
+}
diff --git a/platform/dbops/binaries/go/go/test/stackobj.go b/platform/dbops/binaries/go/go/test/stackobj.go
new file mode 100644
index 0000000000000000000000000000000000000000..b6af4bd8f31e1236185b9e136bbe9aee8ab14f64
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/stackobj.go
@@ -0,0 +1,57 @@
+// run
+
+// 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 (
+ "fmt"
+ "runtime"
+)
+
+type HeapObj [8]int64
+
+type StkObj struct {
+ h *HeapObj
+}
+
+var n int
+var c int = -1
+
+func gc() {
+ // encourage heap object to be collected, and have its finalizer run.
+ runtime.GC()
+ runtime.GC()
+ runtime.GC()
+ n++
+}
+
+func main() {
+ f()
+ gc() // prior to stack objects, heap object is not collected until here
+ if c < 0 {
+ panic("heap object never collected")
+ }
+ if c != 1 {
+ panic(fmt.Sprintf("expected collection at phase 1, got phase %d", c))
+ }
+}
+
+func f() {
+ var s StkObj
+ s.h = new(HeapObj)
+ runtime.SetFinalizer(s.h, func(h *HeapObj) {
+ // Remember at what phase the heap object was collected.
+ c = n
+ })
+ g(&s)
+ gc()
+}
+
+func g(s *StkObj) {
+ gc() // heap object is still live here
+ runtime.KeepAlive(s)
+ gc() // heap object should be collected here
+}
diff --git a/platform/dbops/binaries/go/go/test/stackobj2.go b/platform/dbops/binaries/go/go/test/stackobj2.go
new file mode 100644
index 0000000000000000000000000000000000000000..a1abd9b1d122010ecd3d9d5a031abc15da72c3bf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/stackobj2.go
@@ -0,0 +1,83 @@
+// run
+
+// 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 (
+ "fmt"
+ "runtime"
+)
+
+// linked list up the stack, to test lots of stack objects.
+
+type T struct {
+ // points to a heap object. Test will make sure it isn't freed.
+ data *int64
+ // next pointer for a linked list of stack objects
+ next *T
+ // duplicate of next, to stress test the pointer buffers
+ // used during stack tracing.
+ next2 *T
+}
+
+func main() {
+ makelist(nil, 10000)
+}
+
+func makelist(x *T, n int64) {
+ if n%2 != 0 {
+ panic("must be multiple of 2")
+ }
+ if n == 0 {
+ runtime.GC()
+ i := int64(1)
+ for ; x != nil; x, i = x.next, i+1 {
+ // Make sure x.data hasn't been collected.
+ if got := *x.data; got != i {
+ panic(fmt.Sprintf("bad data want %d, got %d", i, got))
+ }
+ }
+ return
+ }
+ // Put 2 objects in each frame, to test intra-frame pointers.
+ // Use both orderings to ensure the linked list isn't always in address order.
+ var a, b T
+ if n%3 == 0 {
+ a.data = newInt(n)
+ a.next = x
+ a.next2 = x
+ b.data = newInt(n - 1)
+ b.next = &a
+ b.next2 = &a
+ x = &b
+ } else {
+ b.data = newInt(n)
+ b.next = x
+ b.next2 = x
+ a.data = newInt(n - 1)
+ a.next = &b
+ a.next2 = &b
+ x = &a
+ }
+
+ makelist(x, n-2)
+}
+
+// big enough and pointer-y enough to not be tinyalloc'd
+type NotTiny struct {
+ n int64
+ p *byte
+}
+
+// newInt allocates n on the heap and returns a pointer to it.
+func newInt(n int64) *int64 {
+ h := &NotTiny{n: n}
+ p := &h.n
+ escape = p
+ return p
+}
+
+var escape *int64
diff --git a/platform/dbops/binaries/go/go/test/stackobj3.go b/platform/dbops/binaries/go/go/test/stackobj3.go
new file mode 100644
index 0000000000000000000000000000000000000000..8bb8fb3270581438908873f5e35e6b84ae0f4d5d
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/stackobj3.go
@@ -0,0 +1,93 @@
+// run
+
+// 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 test makes sure that ambiguously live arguments work correctly.
+
+package main
+
+import (
+ "runtime"
+)
+
+type HeapObj [8]int64
+
+type StkObj struct {
+ h *HeapObj
+}
+
+var n int
+var c int = -1
+
+func gc() {
+ // encourage heap object to be collected, and have its finalizer run.
+ runtime.GC()
+ runtime.GC()
+ runtime.GC()
+ n++
+}
+
+var null StkObj
+
+var sink *HeapObj
+
+//go:noinline
+func use(p *StkObj) {
+}
+
+//go:noinline
+func f(s StkObj, b bool) {
+ var p *StkObj
+ if b {
+ p = &s
+ } else {
+ p = &null
+ }
+ // use is required here to prevent the conditional
+ // code above from being executed after the first gc() call.
+ use(p)
+ // If b==false, h should be collected here.
+ gc() // 0
+ sink = p.h
+ gc() // 1
+ sink = nil
+ // If b==true, h should be collected here.
+ gc() // 2
+}
+
+func fTrue() {
+ var s StkObj
+ s.h = new(HeapObj)
+ c = -1
+ n = 0
+ runtime.SetFinalizer(s.h, func(h *HeapObj) {
+ // Remember at what phase the heap object was collected.
+ c = n
+ })
+ f(s, true)
+ if c != 2 {
+ panic("bad liveness")
+ }
+}
+
+func fFalse() {
+ var s StkObj
+ s.h = new(HeapObj)
+ c = -1
+ n = 0
+ runtime.SetFinalizer(s.h, func(h *HeapObj) {
+ // Remember at what phase the heap object was collected.
+ c = n
+ })
+ f(s, false)
+ if c != 0 {
+ panic("bad liveness")
+ }
+}
+
+func main() {
+ fTrue()
+ fFalse()
+}
diff --git a/platform/dbops/binaries/go/go/test/strcopy.go b/platform/dbops/binaries/go/go/test/strcopy.go
new file mode 100644
index 0000000000000000000000000000000000000000..6d32baeec501331d50ff03933b9e12c152e38e04
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/strcopy.go
@@ -0,0 +1,29 @@
+// run
+
+// 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.
+
+// Test that string([]byte(string)) makes a copy and doesn't reduce to
+// nothing. (Issue 25834)
+
+package main
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+func main() {
+ var (
+ buf = make([]byte, 2<<10)
+ large = string(buf)
+ sub = large[10:12]
+ subcopy = string([]byte(sub))
+ subh = *(*reflect.StringHeader)(unsafe.Pointer(&sub))
+ subcopyh = *(*reflect.StringHeader)(unsafe.Pointer(&subcopy))
+ )
+ if subh.Data == subcopyh.Data {
+ panic("sub and subcopy have the same underlying array")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/strength.go b/platform/dbops/binaries/go/go/test/strength.go
new file mode 100644
index 0000000000000000000000000000000000000000..823d05af085b504b4f1a3246c8b96bedf647a4c8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/strength.go
@@ -0,0 +1,45 @@
+// runoutput
+
+// 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.
+
+// Generate test of strength reduction for multiplications
+// with constants. Especially useful for amd64/386.
+
+package main
+
+import "fmt"
+
+func testMul(fact, bits int) string {
+ n := fmt.Sprintf("testMul_%d_%d", fact, bits)
+ fmt.Printf("func %s(s int%d) {\n", n, bits)
+
+ want := 0
+ for i := 0; i < 200; i++ {
+ fmt.Printf(` if want, got := int%d(%d), s*%d; want != got {
+ failed = true
+ fmt.Printf("got %d * %%d == %%d, wanted %d\n", s, got)
+ }
+`, bits, want, i, i, want)
+ want += fact
+ }
+
+ fmt.Printf("}\n")
+ return fmt.Sprintf("%s(%d)", n, fact)
+}
+
+func main() {
+ fmt.Printf("package main\n")
+ fmt.Printf("import \"fmt\"\n")
+ fmt.Printf("var failed = false\n")
+
+ f1 := testMul(17, 32)
+ f2 := testMul(131, 64)
+
+ fmt.Printf("func main() {\n")
+ fmt.Println(f1)
+ fmt.Println(f2)
+ fmt.Printf("if failed {\n panic(\"multiplication failed\")\n}\n")
+ fmt.Printf("}\n")
+}
diff --git a/platform/dbops/binaries/go/go/test/string_lit.go b/platform/dbops/binaries/go/go/test/string_lit.go
new file mode 100644
index 0000000000000000000000000000000000000000..4751b82ccf49836ab17a2dfb345623f8afa6ec4f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/string_lit.go
@@ -0,0 +1,150 @@
+// run
+
+// 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.
+
+// Test string literal syntax.
+
+package main
+
+import "os"
+
+var ecode int
+
+func assert(a, b, c string) {
+ if a != b {
+ ecode = 1
+ print("FAIL: ", c, ": ", a, "!=", b, "\n")
+ var max int = len(a)
+ if len(b) > max {
+ max = len(b)
+ }
+ for i := 0; i < max; i++ {
+ ac := 0
+ bc := 0
+ if i < len(a) {
+ ac = int(a[i])
+ }
+ if i < len(b) {
+ bc = int(b[i])
+ }
+ if ac != bc {
+ print("\ta[", i, "] = ", ac, "; b[", i, "] =", bc, "\n")
+ }
+ }
+ panic("string_lit")
+ }
+}
+
+const (
+ gx1 = "aä本☺"
+ gx2 = "aä\xFF\xFF本☺"
+ gx2fix = "aä\uFFFD\uFFFD本☺"
+)
+
+var (
+ gr1 = []rune(gx1)
+ gr2 = []rune(gx2)
+ gb1 = []byte(gx1)
+ gb2 = []byte(gx2)
+)
+
+func main() {
+ ecode = 0
+ s :=
+ "" +
+ " " +
+ "'`" +
+ "a" +
+ "ä" +
+ "本" +
+ "\a\b\f\n\r\t\v\\\"" +
+ "\000\123\x00\xca\xFE\u0123\ubabe\U0000babe" +
+
+ `` +
+ ` ` +
+ `'"` +
+ `a` +
+ `ä` +
+ `本` +
+ `\a\b\f\n\r\t\v\\\'` +
+ `\000\123\x00\xca\xFE\u0123\ubabe\U0000babe` +
+ `\x\u\U\`
+
+ assert("", ``, "empty")
+ assert(" ", " ", "blank")
+ assert("\x61", "a", "lowercase a")
+ assert("\x61", `a`, "lowercase a (backquote)")
+ assert("\u00e4", "ä", "a umlaut")
+ assert("\u00e4", `ä`, "a umlaut (backquote)")
+ assert("\u672c", "本", "nihon")
+ assert("\u672c", `本`, "nihon (backquote)")
+ assert("\x07\x08\x0c\x0a\x0d\x09\x0b\x5c\x22",
+ "\a\b\f\n\r\t\v\\\"",
+ "backslashes")
+ assert("\\a\\b\\f\\n\\r\\t\\v\\\\\\\"",
+ `\a\b\f\n\r\t\v\\\"`,
+ "backslashes (backquote)")
+ assert("\x00\x53\000\xca\376S몾몾",
+ "\000\123\x00\312\xFE\u0053\ubabe\U0000babe",
+ "backslashes 2")
+ assert("\\000\\123\\x00\\312\\xFE\\u0123\\ubabe\\U0000babe",
+ `\000\123\x00\312\xFE\u0123\ubabe\U0000babe`,
+ "backslashes 2 (backquote)")
+ assert("\\x\\u\\U\\", `\x\u\U\`, "backslash 3 (backquote)")
+
+ // test large and surrogate-half runes. perhaps not the most logical place for these tests.
+ var r int32
+ r = 0x10ffff // largest rune value
+ s = string(r)
+ assert(s, "\xf4\x8f\xbf\xbf", "largest rune")
+ r = 0x10ffff + 1
+ s = string(r)
+ assert(s, "\xef\xbf\xbd", "too-large rune")
+ r = 0xD800
+ s = string(r)
+ assert(s, "\xef\xbf\xbd", "surrogate rune min")
+ r = 0xDFFF
+ s = string(r)
+ assert(s, "\xef\xbf\xbd", "surrogate rune max")
+ r = -1
+ s = string(r)
+ assert(s, "\xef\xbf\xbd", "negative rune")
+
+ // the large rune tests again, this time using constants instead of a variable.
+ // these conversions will be done at compile time.
+ s = string(0x10ffff) // largest rune value
+ assert(s, "\xf4\x8f\xbf\xbf", "largest rune constant")
+ s = string(0x10ffff + 1)
+ assert(s, "\xef\xbf\xbd", "too-large rune constant")
+ s = string(0xD800)
+ assert(s, "\xef\xbf\xbd", "surrogate rune min constant")
+ s = string(0xDFFF)
+ assert(s, "\xef\xbf\xbd", "surrogate rune max constant")
+ s = string(-1)
+ assert(s, "\xef\xbf\xbd", "negative rune")
+
+ // the large rune tests yet again, with a slice.
+ rs := []rune{0x10ffff, 0x10ffff + 1, 0xD800, 0xDFFF, -1}
+ s = string(rs)
+ assert(s, "\xf4\x8f\xbf\xbf\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd", "large rune slice")
+
+ assert(string(gr1), gx1, "global ->[]rune")
+ assert(string(gr2), gx2fix, "global invalid ->[]rune")
+ assert(string(gb1), gx1, "->[]byte")
+ assert(string(gb2), gx2, "global invalid ->[]byte")
+
+ var (
+ r1 = []rune(gx1)
+ r2 = []rune(gx2)
+ b1 = []byte(gx1)
+ b2 = []byte(gx2)
+ )
+ assert(string(r1), gx1, "->[]rune")
+ assert(string(r2), gx2fix, "invalid ->[]rune")
+ assert(string(b1), gx1, "->[]byte")
+ assert(string(b2), gx2, "invalid ->[]byte")
+
+ os.Exit(ecode)
+}
diff --git a/platform/dbops/binaries/go/go/test/stringrange.go b/platform/dbops/binaries/go/go/test/stringrange.go
new file mode 100644
index 0000000000000000000000000000000000000000..99e5edb5a429d1ce4dc0ca30e4bc77385018c8ef
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/stringrange.go
@@ -0,0 +1,71 @@
+// run
+
+// 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.
+
+// Test range over strings.
+
+package main
+
+import (
+ "fmt"
+ "os"
+ "unicode/utf8"
+)
+
+func main() {
+ s := "\000\123\x00\xca\xFE\u0123\ubabe\U0000babe\U0010FFFFx"
+ expect := []rune{0, 0123, 0, 0xFFFD, 0xFFFD, 0x123, 0xbabe, 0xbabe, 0x10FFFF, 'x'}
+ offset := 0
+ var i int
+ var c rune
+ ok := true
+ cnum := 0
+ for i, c = range s {
+ r, size := utf8.DecodeRuneInString(s[i:len(s)]) // check it another way
+ if i != offset {
+ fmt.Printf("unexpected offset %d not %d\n", i, offset)
+ ok = false
+ }
+ if r != expect[cnum] {
+ fmt.Printf("unexpected rune %d from DecodeRuneInString: %x not %x\n", i, r, expect[cnum])
+ ok = false
+ }
+ if c != expect[cnum] {
+ fmt.Printf("unexpected rune %d from range: %x not %x\n", i, r, expect[cnum])
+ ok = false
+ }
+ offset += size
+ cnum++
+ }
+ if i != len(s)-1 {
+ fmt.Println("after loop i is", i, "not", len(s)-1)
+ ok = false
+ }
+
+ i = 12345
+ c = 23456
+ for i, c = range "" {
+ }
+ if i != 12345 {
+ fmt.Println("range empty string assigned to index:", i)
+ ok = false
+ }
+ if c != 23456 {
+ fmt.Println("range empty string assigned to value:", c)
+ ok = false
+ }
+
+ for _, c := range "a\xed\xa0\x80a" {
+ if c != 'a' && c != utf8.RuneError {
+ fmt.Printf("surrogate UTF-8 does not error: %U\n", c)
+ ok = false
+ }
+ }
+
+ if !ok {
+ fmt.Println("BUG: stringrange")
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/struct0.go b/platform/dbops/binaries/go/go/test/struct0.go
new file mode 100644
index 0000000000000000000000000000000000000000..403e977ac91141a3d0aaa7258dcb43d70c207eb8
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/struct0.go
@@ -0,0 +1,34 @@
+// run
+
+// 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.
+
+// Test zero length structs.
+// Used to not be evaluated.
+// Issue 2232.
+
+package main
+
+func recv(c chan interface{}) struct{} {
+ return (<-c).(struct{})
+}
+
+var m = make(map[interface{}]int)
+
+func recv1(c chan interface{}) {
+ defer rec()
+ m[(<-c).(struct{})] = 0
+}
+
+func rec() {
+ recover()
+}
+
+func main() {
+ c := make(chan interface{})
+ go recv(c)
+ c <- struct{}{}
+ go recv1(c)
+ c <- struct{}{}
+}
diff --git a/platform/dbops/binaries/go/go/test/switch.go b/platform/dbops/binaries/go/go/test/switch.go
new file mode 100644
index 0000000000000000000000000000000000000000..1806fa7f9be422e646bb6b8b9bc292422dcbbabd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch.go
@@ -0,0 +1,417 @@
+// run
+
+// 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.
+
+// Test switch statements.
+
+package main
+
+import "os"
+
+func assert(cond bool, msg string) {
+ if !cond {
+ print("assertion fail: ", msg, "\n")
+ panic(1)
+ }
+}
+
+func main() {
+ i5 := 5
+ i7 := 7
+ hello := "hello"
+
+ switch true {
+ case i5 < 5:
+ assert(false, "<")
+ case i5 == 5:
+ assert(true, "!")
+ case i5 > 5:
+ assert(false, ">")
+ }
+
+ switch {
+ case i5 < 5:
+ assert(false, "<")
+ case i5 == 5:
+ assert(true, "!")
+ case i5 > 5:
+ assert(false, ">")
+ }
+
+ switch x := 5; true {
+ case i5 < x:
+ assert(false, "<")
+ case i5 == x:
+ assert(true, "!")
+ case i5 > x:
+ assert(false, ">")
+ }
+
+ switch x := 5; true {
+ case i5 < x:
+ assert(false, "<")
+ case i5 == x:
+ assert(true, "!")
+ case i5 > x:
+ assert(false, ">")
+ }
+
+ switch i5 {
+ case 0:
+ assert(false, "0")
+ case 1:
+ assert(false, "1")
+ case 2:
+ assert(false, "2")
+ case 3:
+ assert(false, "3")
+ case 4:
+ assert(false, "4")
+ case 5:
+ assert(true, "5")
+ case 6:
+ assert(false, "6")
+ case 7:
+ assert(false, "7")
+ case 8:
+ assert(false, "8")
+ case 9:
+ assert(false, "9")
+ default:
+ assert(false, "default")
+ }
+
+ switch i5 {
+ case 0, 1, 2, 3, 4:
+ assert(false, "4")
+ case 5:
+ assert(true, "5")
+ case 6, 7, 8, 9:
+ assert(false, "9")
+ default:
+ assert(false, "default")
+ }
+
+ switch i5 {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ assert(false, "4")
+ case 5:
+ assert(true, "5")
+ case 6:
+ case 7:
+ case 8:
+ case 9:
+ default:
+ assert(i5 == 5, "good")
+ }
+
+ switch i5 {
+ case 0:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 1:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 2:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 3:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 4:
+ dummy := 0
+ _ = dummy
+ assert(false, "4")
+ case 5:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 6:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 7:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 8:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 9:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ default:
+ dummy := 0
+ _ = dummy
+ assert(i5 == 5, "good")
+ }
+
+ fired := false
+ switch i5 {
+ case 0:
+ dummy := 0
+ _ = dummy
+ fallthrough // tests scoping of cases
+ case 1:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 2:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 3:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 4:
+ dummy := 0
+ _ = dummy
+ assert(false, "4")
+ case 5:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 6:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 7:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 8:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ case 9:
+ dummy := 0
+ _ = dummy
+ fallthrough
+ default:
+ dummy := 0
+ _ = dummy
+ fired = !fired
+ assert(i5 == 5, "good")
+ }
+ assert(fired, "fired")
+
+ count := 0
+ switch i5 {
+ case 0:
+ count = count + 1
+ fallthrough
+ case 1:
+ count = count + 1
+ fallthrough
+ case 2:
+ count = count + 1
+ fallthrough
+ case 3:
+ count = count + 1
+ fallthrough
+ case 4:
+ count = count + 1
+ assert(false, "4")
+ case 5:
+ count = count + 1
+ fallthrough
+ case 6:
+ count = count + 1
+ fallthrough
+ case 7:
+ count = count + 1
+ fallthrough
+ case 8:
+ count = count + 1
+ fallthrough
+ case 9:
+ count = count + 1
+ fallthrough
+ default:
+ assert(i5 == count, "good")
+ }
+ assert(fired, "fired")
+
+ switch hello {
+ case "wowie":
+ assert(false, "wowie")
+ case "hello":
+ assert(true, "hello")
+ case "jumpn":
+ assert(false, "jumpn")
+ default:
+ assert(false, "default")
+ }
+
+ fired = false
+ switch i := i5 + 2; i {
+ case i7:
+ fired = true
+ default:
+ assert(false, "fail")
+ }
+ assert(fired, "var")
+
+ // switch on nil-only comparison types
+ switch f := func() {}; f {
+ case nil:
+ assert(false, "f should not be nil")
+ default:
+ }
+
+ switch m := make(map[int]int); m {
+ case nil:
+ assert(false, "m should not be nil")
+ default:
+ }
+
+ switch a := make([]int, 1); a {
+ case nil:
+ assert(false, "m should not be nil")
+ default:
+ }
+
+ // switch on interface.
+ switch i := interface{}("hello"); i {
+ case 42:
+ assert(false, `i should be "hello"`)
+ case "hello":
+ assert(true, "hello")
+ default:
+ assert(false, `i should be "hello"`)
+ }
+
+ // switch on implicit bool converted to interface
+ // was broken: see issue 3980
+ switch i := interface{}(true); {
+ case i:
+ assert(true, "true")
+ case false:
+ assert(false, "i should be true")
+ default:
+ assert(false, "i should be true")
+ }
+
+ // switch on interface with constant cases differing by type.
+ // was rejected by compiler: see issue 4781
+ type T int
+ type B bool
+ type F float64
+ type S string
+ switch i := interface{}(float64(1.0)); i {
+ case nil:
+ assert(false, "i should be float64(1.0)")
+ case (*int)(nil):
+ assert(false, "i should be float64(1.0)")
+ case 1:
+ assert(false, "i should be float64(1.0)")
+ case T(1):
+ assert(false, "i should be float64(1.0)")
+ case F(1.0):
+ assert(false, "i should be float64(1.0)")
+ case 1.0:
+ assert(true, "true")
+ case "hello":
+ assert(false, "i should be float64(1.0)")
+ case S("hello"):
+ assert(false, "i should be float64(1.0)")
+ case true, B(false):
+ assert(false, "i should be float64(1.0)")
+ case false, B(true):
+ assert(false, "i should be float64(1.0)")
+ }
+
+ // switch on array.
+ switch ar := [3]int{1, 2, 3}; ar {
+ case [3]int{1, 2, 3}:
+ assert(true, "[1 2 3]")
+ case [3]int{4, 5, 6}:
+ assert(false, "ar should be [1 2 3]")
+ default:
+ assert(false, "ar should be [1 2 3]")
+ }
+
+ // switch on channel
+ switch c1, c2 := make(chan int), make(chan int); c1 {
+ case nil:
+ assert(false, "c1 did not match itself")
+ case c2:
+ assert(false, "c1 did not match itself")
+ case c1:
+ assert(true, "chan")
+ default:
+ assert(false, "c1 did not match itself")
+ }
+
+ // empty switch
+ switch {
+ }
+
+ // empty switch with default case.
+ fired = false
+ switch {
+ default:
+ fired = true
+ }
+ assert(fired, "fail")
+
+ // Default and fallthrough.
+ count = 0
+ switch {
+ default:
+ count++
+ fallthrough
+ case false:
+ count++
+ }
+ assert(count == 2, "fail")
+
+ // fallthrough to default, which is not at end.
+ count = 0
+ switch i5 {
+ case 5:
+ count++
+ fallthrough
+ default:
+ count++
+ case 6:
+ count++
+ }
+ assert(count == 2, "fail")
+
+ i := 0
+ switch x := 5; {
+ case i < x:
+ os.Exit(0)
+ case i == x:
+ case i > x:
+ os.Exit(1)
+ }
+
+ // Unified IR converts the tag and all case values to empty
+ // interface, when any of the case values aren't assignable to the
+ // tag value's type. Make sure that `case nil:` compares against the
+ // tag type's nil value (i.e., `(*int)(nil)`), not nil interface
+ // (i.e., `any(nil)`).
+ switch (*int)(nil) {
+ case nil:
+ // ok
+ case any(nil):
+ assert(false, "case any(nil) matched")
+ default:
+ assert(false, "default matched")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch2.go b/platform/dbops/binaries/go/go/test/switch2.go
new file mode 100644
index 0000000000000000000000000000000000000000..66e89fda19e2c3079b5b453d1ed5d2df7a25bca5
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch2.go
@@ -0,0 +1,39 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous switch statements are detected by the compiler.
+// Does not compile.
+
+package main
+
+func f() {
+ switch {
+ case 0; // ERROR "expecting := or = or : or comma|expected :"
+ }
+
+ switch {
+ case 0; // ERROR "expecting := or = or : or comma|expected :"
+ default:
+ }
+
+ switch {
+ case 0: case 0: default:
+ }
+
+ switch {
+ case 0: f(); case 0:
+ case 0: f() case 0: // ERROR "unexpected case at end of statement"
+ }
+
+ switch {
+ case 0: f(); default:
+ case 0: f() default: // ERROR "unexpected default at end of statement"
+ }
+
+ switch {
+ if x: // ERROR "expected case or default or }"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch3.go b/platform/dbops/binaries/go/go/test/switch3.go
new file mode 100644
index 0000000000000000000000000000000000000000..403563223c7d11d7bbd82ace8e84e5d76538465f
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch3.go
@@ -0,0 +1,72 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous switch statements are detected by the compiler.
+// Does not compile.
+
+package main
+
+type I interface {
+ M()
+}
+
+func bad() {
+ var i I
+ var s string
+
+ switch i {
+ case s: // ERROR "mismatched types string and I|incompatible types"
+ }
+
+ switch s {
+ case i: // ERROR "mismatched types I and string|incompatible types"
+ }
+
+ var m, m1 map[int]int
+ switch m {
+ case nil:
+ case m1: // ERROR "can only compare map m to nil|map can only be compared to nil|cannot compare"
+ default:
+ }
+
+ var a, a1 []int
+ switch a {
+ case nil:
+ case a1: // ERROR "can only compare slice a to nil|slice can only be compared to nil|cannot compare"
+ default:
+ }
+
+ var f, f1 func()
+ switch f {
+ case nil:
+ case f1: // ERROR "can only compare func f to nil|func can only be compared to nil|cannot compare"
+ default:
+ }
+
+ var ar, ar1 [4]func()
+ switch ar { // ERROR "cannot switch on"
+ case ar1:
+ default:
+ }
+
+ var st, st1 struct{ f func() }
+ switch st { // ERROR "cannot switch on"
+ case st1:
+ }
+}
+
+func good() {
+ var i interface{}
+ var s string
+
+ switch i {
+ case s:
+ }
+
+ switch s {
+ case i:
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch4.go b/platform/dbops/binaries/go/go/test/switch4.go
new file mode 100644
index 0000000000000000000000000000000000000000..f38efe68c6e62d3c4b945d2b6252afbbf5954788
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch4.go
@@ -0,0 +1,36 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous switch statements are detected by the compiler.
+// Does not compile.
+
+package main
+
+type I interface {
+ M()
+}
+
+func bad() {
+
+ i5 := 5
+ switch i5 {
+ case 5:
+ fallthrough // ERROR "cannot fallthrough final case in switch"
+ }
+}
+
+func good() {
+ var i interface{}
+ var s string
+
+ switch i {
+ case s:
+ }
+
+ switch s {
+ case i:
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch5.go b/platform/dbops/binaries/go/go/test/switch5.go
new file mode 100644
index 0000000000000000000000000000000000000000..dcf7ba0cf45f6b41b4136666fa5cb22e6ca0b4b7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch5.go
@@ -0,0 +1,94 @@
+// errorcheck
+
+// 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.
+
+// Verify that switch statements with duplicate cases are detected by the compiler.
+// Does not compile.
+
+package main
+
+func f0(x int) {
+ switch x {
+ case 0:
+ case 0: // ERROR "duplicate case (0 in switch)?"
+ }
+
+ switch x {
+ case 0:
+ case int(0): // ERROR "duplicate case (int.0. .value 0. in switch)?"
+ }
+}
+
+func f1(x float32) {
+ switch x {
+ case 5:
+ case 5: // ERROR "duplicate case (5 in switch)?"
+ case 5.0: // ERROR "duplicate case (5 in switch)?"
+ }
+}
+
+func f2(s string) {
+ switch s {
+ case "":
+ case "": // ERROR "duplicate case (.. in switch)?"
+ case "abc":
+ case "abc": // ERROR "duplicate case (.abc. in switch)?"
+ }
+}
+
+func f3(e interface{}) {
+ switch e {
+ case 0:
+ case 0: // ERROR "duplicate case (0 in switch)?"
+ case int64(0):
+ case float32(10):
+ case float32(10): // ERROR "duplicate case (float32\(10\) .value 10. in switch)?"
+ case float64(10):
+ case float64(10): // ERROR "duplicate case (float64\(10\) .value 10. in switch)?"
+ }
+}
+
+func f5(a [1]int) {
+ switch a {
+ case [1]int{0}:
+ case [1]int{0}: // OK -- see issue 15896
+ }
+}
+
+// Ensure duplicate const bool clauses are accepted.
+func f6() int {
+ switch {
+ case 0 == 0:
+ return 0
+ case 1 == 1: // Intentionally OK, even though a duplicate of the above const true
+ return 1
+ }
+ return 2
+}
+
+// Ensure duplicates in ranges are detected (issue #17517).
+func f7(a int) {
+ switch a {
+ case 0:
+ case 0, 1: // ERROR "duplicate case 0"
+ case 1, 2, 3, 4: // ERROR "duplicate case 1"
+ }
+}
+
+// Ensure duplicates with simple literals are printed as they were
+// written, not just their values. Particularly useful for runes.
+func f8(r rune) {
+ const x = 10
+ switch r {
+ case 33, 33: // ERROR "duplicate case (33 in switch)?"
+ case 34, '"': // ERROR "duplicate case '"' .value 34. in switch"
+ case 35, rune('#'): // ERROR "duplicate case (rune.'#'. .value 35. in switch)?"
+ case 36, rune(36): // ERROR "duplicate case (rune.36. .value 36. in switch)?"
+ case 37, '$'+1: // ERROR "duplicate case ('\$' \+ 1 .value 37. in switch)?"
+ case 'b':
+ case 'a', 'b', 'c', 'd': // ERROR "duplicate case ('b' .value 98.)?"
+ case x, x: // ERROR "duplicate case (x .value 10.)?"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch6.go b/platform/dbops/binaries/go/go/test/switch6.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd66df5a5888dac4bcaaf96527501138296ebecd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch6.go
@@ -0,0 +1,46 @@
+// errorcheck
+
+// 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.
+
+// Check the compiler's switch handling that happens
+// at typechecking time.
+// This must be separate from other checks,
+// because errors during typechecking
+// prevent other errors from being discovered.
+
+package main
+
+// Verify that type switch statements with impossible cases are detected by the compiler.
+func f0(e error) {
+ switch e.(type) {
+ case int: // ERROR "impossible type switch case: (int\n\t)?e \(.*type error\) cannot have dynamic type int \(missing method Error\)"
+ }
+}
+
+// Verify that the compiler rejects multiple default cases.
+func f1(e interface{}) {
+ switch e {
+ default:
+ default: // ERROR "multiple defaults( in switch)?"
+ }
+ switch e.(type) {
+ default:
+ default: // ERROR "multiple defaults( in switch)?"
+ }
+}
+
+type I interface {
+ Foo()
+}
+
+type X int
+
+func (*X) Foo() {}
+func f2() {
+ var i I
+ switch i.(type) {
+ case X: // ERROR "impossible type switch case: (X\n\t)?i \(.*type I\) cannot have dynamic type X \(method Foo has pointer receiver\)"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/switch7.go b/platform/dbops/binaries/go/go/test/switch7.go
new file mode 100644
index 0000000000000000000000000000000000000000..3fb0129b15e2d35c0d0ad766d792d5562cc612d2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/switch7.go
@@ -0,0 +1,35 @@
+// errorcheck
+
+// 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.
+
+// Verify that type switch statements with duplicate cases are detected
+// by the compiler.
+// Does not compile.
+
+package main
+
+import "fmt"
+
+func f4(e interface{}) {
+ switch e.(type) {
+ case int:
+ case int: // ERROR "duplicate case int in type switch"
+ case int64:
+ case error:
+ case error: // ERROR "duplicate case error in type switch"
+ case fmt.Stringer:
+ case fmt.Stringer: // ERROR "duplicate case fmt.Stringer in type switch"
+ case struct {
+ i int "tag1"
+ }:
+ case struct {
+ i int "tag2"
+ }:
+ case struct { // ERROR "duplicate case struct { i int .tag1. } in type switch|duplicate case"
+ i int "tag1"
+ }:
+ }
+}
+
diff --git a/platform/dbops/binaries/go/go/test/tighten.go b/platform/dbops/binaries/go/go/test/tighten.go
new file mode 100644
index 0000000000000000000000000000000000000000..92ed2492b26e74f7581ec6af2542a9fe2981c86c
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/tighten.go
@@ -0,0 +1,22 @@
+// errorcheck -0 -d=ssa/tighten/debug=1
+
+//go:build arm64
+
+// 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
+
+var (
+ e any
+ ts uint16
+)
+
+func moveValuesWithMemoryArg(len int) {
+ for n := 0; n < len; n++ {
+ // Load of e.data is lowed as a MOVDload op, which has a memory
+ // argument. It's moved near where it's used.
+ _ = e != ts // ERROR "MOVDload is moved$" "MOVDaddr is moved$"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/tinyfin.go b/platform/dbops/binaries/go/go/test/tinyfin.go
new file mode 100644
index 0000000000000000000000000000000000000000..5171dfc72e22af8f3e1c5d3c46f7a5bd0c6309b9
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/tinyfin.go
@@ -0,0 +1,64 @@
+// run
+
+// 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 finalizers work for tiny (combined) allocations.
+
+package main
+
+import (
+ "runtime"
+ "time"
+)
+
+func main() {
+ // Does not work on gccgo due to partially conservative GC.
+ // Try to enable when we have fully precise GC.
+ if runtime.Compiler == "gccgo" {
+ return
+ }
+ const N = 100
+ finalized := make(chan int32, N)
+ for i := 0; i < N; i++ {
+ x := new(int32) // subject to tiny alloc
+ *x = int32(i)
+ // the closure must be big enough to be combined
+ runtime.SetFinalizer(x, func(p *int32) {
+ finalized <- *p
+ })
+ }
+ runtime.GC()
+ count := 0
+ done := make([]bool, N)
+ timeout := time.After(5*time.Second)
+ for {
+ select {
+ case <-timeout:
+ println("timeout,", count, "finalized so far")
+ panic("not all finalizers are called")
+ case x := <-finalized:
+ // Check that p points to the correct subobject of the tiny allocation.
+ // It's a bit tricky, because we can't capture another variable
+ // with the expected value (it would be combined as well).
+ if x < 0 || x >= N {
+ println("got", x)
+ panic("corrupted")
+ }
+ if done[x] {
+ println("got", x)
+ panic("already finalized")
+ }
+ done[x] = true
+ count++
+ if count > N/10*9 {
+ // Some of the finalizers may not be executed,
+ // if the outermost allocations are combined with something persistent.
+ // Currently 4 int32's are combined into a 16-byte block,
+ // ensure that most of them are finalized.
+ return
+ }
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/torture.go b/platform/dbops/binaries/go/go/test/torture.go
new file mode 100644
index 0000000000000000000000000000000000000000..197b481e66de03f015fe82b949a77bbf20c6756e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/torture.go
@@ -0,0 +1,346 @@
+// compile
+
+// 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.
+
+// Various tests for expressions with high complexity.
+
+package main
+
+// Concatenate 16 4-bit integers into a 64-bit number.
+func concat(s *[16]byte) uint64 {
+ r := (((((((((((((((uint64(s[0])<<4|
+ uint64(s[1]))<<4|
+ uint64(s[2]))<<4|
+ uint64(s[3]))<<4|
+ uint64(s[4]))<<4|
+ uint64(s[5]))<<4|
+ uint64(s[6]))<<4|
+ uint64(s[7]))<<4|
+ uint64(s[8]))<<4|
+ uint64(s[9]))<<4|
+ uint64(s[10]))<<4|
+ uint64(s[11]))<<4|
+ uint64(s[12]))<<4|
+ uint64(s[13]))<<4|
+ uint64(s[14]))<<4 |
+ uint64(s[15]))
+ return r
+}
+
+// Compute the determinant of a 4x4-matrix by the sum
+// over all index permutations.
+func determinant(m [4][4]float64) float64 {
+ return m[0][0]*m[1][1]*m[2][2]*m[3][3] -
+ m[0][0]*m[1][1]*m[2][3]*m[3][2] -
+ m[0][0]*m[1][2]*m[2][1]*m[3][3] +
+ m[0][0]*m[1][2]*m[2][3]*m[3][1] +
+ m[0][0]*m[1][3]*m[2][1]*m[3][2] -
+ m[0][0]*m[1][3]*m[2][2]*m[3][1] -
+ m[0][1]*m[1][0]*m[2][2]*m[3][3] +
+ m[0][1]*m[1][0]*m[2][3]*m[3][2] +
+ m[0][1]*m[1][2]*m[2][0]*m[3][3] -
+ m[0][1]*m[1][2]*m[2][3]*m[3][0] -
+ m[0][1]*m[1][3]*m[2][0]*m[3][2] +
+ m[0][1]*m[1][3]*m[2][2]*m[3][0] +
+ m[0][2]*m[1][0]*m[2][1]*m[3][3] -
+ m[0][2]*m[1][0]*m[2][3]*m[3][1] -
+ m[0][2]*m[1][1]*m[2][0]*m[3][3] +
+ m[0][2]*m[1][1]*m[2][3]*m[3][0] +
+ m[0][2]*m[1][3]*m[2][0]*m[3][1] -
+ m[0][2]*m[1][3]*m[2][1]*m[3][0] -
+ m[0][3]*m[1][0]*m[2][1]*m[3][2] +
+ m[0][3]*m[1][0]*m[2][2]*m[3][1] +
+ m[0][3]*m[1][1]*m[2][0]*m[3][2] -
+ m[0][3]*m[1][1]*m[2][2]*m[3][0] -
+ m[0][3]*m[1][2]*m[2][0]*m[3][1] +
+ m[0][3]*m[1][2]*m[2][1]*m[3][0]
+}
+
+// Compute the determinant of a 4x4-matrix by the sum
+// over all index permutations.
+func determinantInt(m [4][4]int) int {
+ return m[0][0]*m[1][1]*m[2][2]*m[3][3] -
+ m[0][0]*m[1][1]*m[2][3]*m[3][2] -
+ m[0][0]*m[1][2]*m[2][1]*m[3][3] +
+ m[0][0]*m[1][2]*m[2][3]*m[3][1] +
+ m[0][0]*m[1][3]*m[2][1]*m[3][2] -
+ m[0][0]*m[1][3]*m[2][2]*m[3][1] -
+ m[0][1]*m[1][0]*m[2][2]*m[3][3] +
+ m[0][1]*m[1][0]*m[2][3]*m[3][2] +
+ m[0][1]*m[1][2]*m[2][0]*m[3][3] -
+ m[0][1]*m[1][2]*m[2][3]*m[3][0] -
+ m[0][1]*m[1][3]*m[2][0]*m[3][2] +
+ m[0][1]*m[1][3]*m[2][2]*m[3][0] +
+ m[0][2]*m[1][0]*m[2][1]*m[3][3] -
+ m[0][2]*m[1][0]*m[2][3]*m[3][1] -
+ m[0][2]*m[1][1]*m[2][0]*m[3][3] +
+ m[0][2]*m[1][1]*m[2][3]*m[3][0] +
+ m[0][2]*m[1][3]*m[2][0]*m[3][1] -
+ m[0][2]*m[1][3]*m[2][1]*m[3][0] -
+ m[0][3]*m[1][0]*m[2][1]*m[3][2] +
+ m[0][3]*m[1][0]*m[2][2]*m[3][1] +
+ m[0][3]*m[1][1]*m[2][0]*m[3][2] -
+ m[0][3]*m[1][1]*m[2][2]*m[3][0] -
+ m[0][3]*m[1][2]*m[2][0]*m[3][1] +
+ m[0][3]*m[1][2]*m[2][1]*m[3][0]
+}
+
+// Compute the determinant of a 4x4-matrix by the sum
+// over all index permutations.
+func determinantByte(m [4][4]byte) byte {
+ return m[0][0]*m[1][1]*m[2][2]*m[3][3] -
+ m[0][0]*m[1][1]*m[2][3]*m[3][2] -
+ m[0][0]*m[1][2]*m[2][1]*m[3][3] +
+ m[0][0]*m[1][2]*m[2][3]*m[3][1] +
+ m[0][0]*m[1][3]*m[2][1]*m[3][2] -
+ m[0][0]*m[1][3]*m[2][2]*m[3][1] -
+ m[0][1]*m[1][0]*m[2][2]*m[3][3] +
+ m[0][1]*m[1][0]*m[2][3]*m[3][2] +
+ m[0][1]*m[1][2]*m[2][0]*m[3][3] -
+ m[0][1]*m[1][2]*m[2][3]*m[3][0] -
+ m[0][1]*m[1][3]*m[2][0]*m[3][2] +
+ m[0][1]*m[1][3]*m[2][2]*m[3][0] +
+ m[0][2]*m[1][0]*m[2][1]*m[3][3] -
+ m[0][2]*m[1][0]*m[2][3]*m[3][1] -
+ m[0][2]*m[1][1]*m[2][0]*m[3][3] +
+ m[0][2]*m[1][1]*m[2][3]*m[3][0] +
+ m[0][2]*m[1][3]*m[2][0]*m[3][1] -
+ m[0][2]*m[1][3]*m[2][1]*m[3][0] -
+ m[0][3]*m[1][0]*m[2][1]*m[3][2] +
+ m[0][3]*m[1][0]*m[2][2]*m[3][1] +
+ m[0][3]*m[1][1]*m[2][0]*m[3][2] -
+ m[0][3]*m[1][1]*m[2][2]*m[3][0] -
+ m[0][3]*m[1][2]*m[2][0]*m[3][1] +
+ m[0][3]*m[1][2]*m[2][1]*m[3][0]
+}
+
+type A []A
+
+// A sequence of constant indexings.
+func IndexChain1(s A) A {
+ return s[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]
+}
+
+// A sequence of non-constant indexings.
+func IndexChain2(s A, i int) A {
+ return s[i][i][i][i][i][i][i][i][i][i][i][i][i][i][i][i]
+}
+
+// Another sequence of indexings.
+func IndexChain3(s []int) int {
+ return s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[0]]]]]]]]]]]]]]]]]]]]]
+}
+
+// A right-leaning tree of byte multiplications.
+func righttree(a, b, c, d uint8) uint8 {
+ return a * (b * (c * (d *
+ (a * (b * (c * (d *
+ (a * (b * (c * (d *
+ (a * (b * (c * (d *
+ (a * (b * (c * (d *
+ a * (b * (c * d)))))))))))))))))))))
+
+}
+
+// A left-leaning tree of byte multiplications.
+func lefttree(a, b, c, d uint8) uint8 {
+ return ((((((((((((((((((a * b) * c) * d *
+ a) * b) * c) * d *
+ a) * b) * c) * d *
+ a) * b) * c) * d *
+ a) * b) * c) * d *
+ a) * b) * c) * d)
+}
+
+type T struct {
+ Next I
+}
+
+type I interface{}
+
+// A chains of type assertions.
+func ChainT(t *T) *T {
+ return t.
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T).
+ Next.(*T)
+}
+
+type U struct {
+ Children []J
+}
+
+func (u *U) Child(n int) J { return u.Children[n] }
+
+type J interface {
+ Child(n int) J
+}
+
+func ChainUAssert(u *U) *U {
+ return u.Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U).
+ Child(0).(*U)
+}
+
+func ChainUNoAssert(u *U) *U {
+ return u.Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).
+ Child(0).(*U)
+}
+
+// Type assertions and slice indexing. See issue 4207.
+func ChainAssertIndex(u *U) J {
+ return u.
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0].(*U).
+ Children[0]
+}
+
+type UArr struct {
+ Children [2]J
+}
+
+func (u *UArr) Child(n int) J { return u.Children[n] }
+
+func ChainAssertArrayIndex(u *UArr) J {
+ return u.
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0].(*UArr).
+ Children[0]
+}
+
+type UArrPtr struct {
+ Children *[2]J
+}
+
+func (u *UArrPtr) Child(n int) J { return u.Children[n] }
+
+func ChainAssertArrayptrIndex(u *UArrPtr) J {
+ return u.
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0].(*UArrPtr).
+ Children[0]
+}
+
+// Chains of divisions. See issue 4201.
+
+func ChainDiv(a, b int) int {
+ return a / b / a / b / a / b / a / b /
+ a / b / a / b / a / b / a / b /
+ a / b / a / b / a / b / a / b
+}
+
+func ChainDivRight(a, b int) int {
+ return a / (b / (a / (b /
+ (a / (b / (a / (b /
+ (a / (b / (a / (b /
+ (a / (b / (a / (b /
+ (a / (b / (a / b))))))))))))))))))
+}
+
+func ChainDivConst(a int) int {
+ return a / 17 / 17 / 17 /
+ 17 / 17 / 17 / 17 /
+ 17 / 17 / 17 / 17
+}
+
+func ChainMulBytes(a, b, c byte) byte {
+ return a*(a*(a*(a*(a*(a*(a*(a*(a*b+c)+c)+c)+c)+c)+c)+c)+c) + c
+}
+
+func ChainCap() {
+ select {
+ case <-make(chan int, cap(make(chan int, cap(make(chan int, cap(make(chan int, cap(make(chan int))))))))):
+ default:
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/turing.go b/platform/dbops/binaries/go/go/test/turing.go
new file mode 100644
index 0000000000000000000000000000000000000000..acbe85b646ce7671dafc290afe39afb5aa5fe9e7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/turing.go
@@ -0,0 +1,59 @@
+// run
+
+// 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.
+
+// Test simulating a Turing machine, sort of.
+
+package main
+
+// brainfuck
+
+var p, pc int
+var a [30000]byte
+
+const prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.!"
+
+func scan(dir int) {
+ for nest := dir; dir*nest > 0; pc += dir {
+ switch prog[pc+dir] {
+ case ']':
+ nest--
+ case '[':
+ nest++
+ }
+ }
+}
+
+func main() {
+ r := ""
+ for {
+ switch prog[pc] {
+ case '>':
+ p++
+ case '<':
+ p--
+ case '+':
+ a[p]++
+ case '-':
+ a[p]--
+ case '.':
+ r += string(a[p])
+ case '[':
+ if a[p] == 0 {
+ scan(1)
+ }
+ case ']':
+ if a[p] != 0 {
+ scan(-1)
+ }
+ default:
+ if r != "Hello World!\n" {
+ panic(r)
+ }
+ return
+ }
+ pc++
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/typecheck.go b/platform/dbops/binaries/go/go/test/typecheck.go
new file mode 100644
index 0000000000000000000000000000000000000000..f822ae98ef3237db32e232af8e4c2b20ea6690bd
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typecheck.go
@@ -0,0 +1,22 @@
+// errorcheck
+
+// 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.
+
+// Verify that the Go compiler will not
+// die after running into an undefined
+// type in the argument list for a
+// function.
+// Does not compile.
+
+package main
+
+func mine(int b) int { // ERROR "undefined.*b"
+ return b + 2 // ERROR "undefined.*b"
+}
+
+func main() {
+ mine() // ERROR "not enough arguments"
+ c = mine() // ERROR "undefined.*c|not enough arguments"
+}
diff --git a/platform/dbops/binaries/go/go/test/typecheckloop.go b/platform/dbops/binaries/go/go/test/typecheckloop.go
new file mode 100644
index 0000000000000000000000000000000000000000..a143e0984ce79a7ba437a1b113364aa99e7e83a2
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typecheckloop.go
@@ -0,0 +1,14 @@
+// errorcheck
+
+// 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.
+
+// Verify that constant definition loops are caught during
+// typechecking and that the errors print correctly.
+
+package main
+
+const A = 1 + B // ERROR "constant definition loop\n.*A uses B\n.*B uses C\n.*C uses A|initialization cycle"
+const B = C - 1 // ERROR "constant definition loop\n.*B uses C\n.*C uses B|initialization cycle"
+const C = A + B + 1
diff --git a/platform/dbops/binaries/go/go/test/typeswitch.go b/platform/dbops/binaries/go/go/test/typeswitch.go
new file mode 100644
index 0000000000000000000000000000000000000000..30a4b4975fbb3afeb7a54e19bcf7b57df4d130ff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typeswitch.go
@@ -0,0 +1,116 @@
+// run
+
+// 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.
+
+// Test simple type switches, including chans, maps etc.
+
+package main
+
+import "os"
+
+const (
+ Bool = iota
+ Int
+ Float
+ String
+ Struct
+ Chan
+ Array
+ Map
+ Func
+ Last
+)
+
+type S struct {
+ a int
+}
+
+var s S = S{1234}
+
+var c = make(chan int)
+
+var a = []int{0, 1, 2, 3}
+
+var m = make(map[string]int)
+
+func assert(b bool, s string) {
+ if !b {
+ println(s)
+ os.Exit(1)
+ }
+}
+
+func f(i int) interface{} {
+ switch i {
+ case Bool:
+ return true
+ case Int:
+ return 7
+ case Float:
+ return 7.4
+ case String:
+ return "hello"
+ case Struct:
+ return s
+ case Chan:
+ return c
+ case Array:
+ return a
+ case Map:
+ return m
+ case Func:
+ return f
+ }
+ panic("bad type number")
+}
+
+func main() {
+ for i := Bool; i < Last; i++ {
+ switch x := f(i).(type) {
+ case bool:
+ assert(x == true && i == Bool, "bool")
+ case int:
+ assert(x == 7 && i == Int, "int")
+ case float64:
+ assert(x == 7.4 && i == Float, "float64")
+ case string:
+ assert(x == "hello" && i == String, "string")
+ case S:
+ assert(x.a == 1234 && i == Struct, "struct")
+ case chan int:
+ assert(x == c && i == Chan, "chan")
+ case []int:
+ assert(x[3] == 3 && i == Array, "array")
+ case map[string]int:
+ assert(x != nil && i == Map, "map")
+ case func(i int) interface{}:
+ assert(x != nil && i == Func, "fun")
+ default:
+ assert(false, "unknown")
+ }
+ }
+
+ // boolean switch (has had bugs in past; worth writing down)
+ switch {
+ case true:
+ assert(true, "switch 2 bool")
+ default:
+ assert(false, "switch 2 unknown")
+ }
+
+ switch true {
+ case true:
+ assert(true, "switch 3 bool")
+ default:
+ assert(false, "switch 3 unknown")
+ }
+
+ switch false {
+ case false:
+ assert(true, "switch 4 bool")
+ default:
+ assert(false, "switch 4 unknown")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/typeswitch1.go b/platform/dbops/binaries/go/go/test/typeswitch1.go
new file mode 100644
index 0000000000000000000000000000000000000000..a980ce4c070d4f2c08d698bb846406d39f4d18c7
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typeswitch1.go
@@ -0,0 +1,85 @@
+// run
+
+// 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.
+
+// Test simple type switches on basic types.
+
+package main
+
+import "fmt"
+
+const (
+ a = iota
+ b
+ c
+ d
+ e
+)
+
+var x = []int{1, 2, 3}
+
+func f(x int, len *byte) {
+ *len = byte(x)
+}
+
+func whatis(x interface{}) string {
+ switch xx := x.(type) {
+ default:
+ return fmt.Sprint("default ", xx)
+ case int, int8, int16, int32:
+ return fmt.Sprint("signed ", xx)
+ case int64:
+ return fmt.Sprint("signed64 ", int64(xx))
+ case uint, uint8, uint16, uint32:
+ return fmt.Sprint("unsigned ", xx)
+ case uint64:
+ return fmt.Sprint("unsigned64 ", uint64(xx))
+ case nil:
+ return fmt.Sprint("nil ", xx)
+ }
+ panic("not reached")
+}
+
+func whatis1(x interface{}) string {
+ xx := x
+ switch xx.(type) {
+ default:
+ return fmt.Sprint("default ", xx)
+ case int, int8, int16, int32:
+ return fmt.Sprint("signed ", xx)
+ case int64:
+ return fmt.Sprint("signed64 ", xx.(int64))
+ case uint, uint8, uint16, uint32:
+ return fmt.Sprint("unsigned ", xx)
+ case uint64:
+ return fmt.Sprint("unsigned64 ", xx.(uint64))
+ case nil:
+ return fmt.Sprint("nil ", xx)
+ }
+ panic("not reached")
+}
+
+func check(x interface{}, s string) {
+ w := whatis(x)
+ if w != s {
+ fmt.Println("whatis", x, "=>", w, "!=", s)
+ panic("fail")
+ }
+
+ w = whatis1(x)
+ if w != s {
+ fmt.Println("whatis1", x, "=>", w, "!=", s)
+ panic("fail")
+ }
+}
+
+func main() {
+ check(1, "signed 1")
+ check(uint(1), "unsigned 1")
+ check(int64(1), "signed64 1")
+ check(uint64(1), "unsigned64 1")
+ check(1.5, "default 1.5")
+ check(nil, "nil ")
+}
diff --git a/platform/dbops/binaries/go/go/test/typeswitch2.go b/platform/dbops/binaries/go/go/test/typeswitch2.go
new file mode 100644
index 0000000000000000000000000000000000000000..62c96c8330f6010333dce002269511ba3ee49fff
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typeswitch2.go
@@ -0,0 +1,37 @@
+// errorcheck
+
+// 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.
+
+// Verify that various erroneous type switches are caught by the compiler.
+// Does not compile.
+
+package main
+
+import "io"
+
+func whatis(x interface{}) string {
+ switch x.(type) {
+ case int:
+ return "int"
+ case int: // ERROR "duplicate"
+ return "int8"
+ case io.Reader:
+ return "Reader1"
+ case io.Reader: // ERROR "duplicate"
+ return "Reader2"
+ case interface {
+ r()
+ w()
+ }:
+ return "rw"
+ case interface { // ERROR "duplicate"
+ w()
+ r()
+ }:
+ return "wr"
+
+ }
+ return ""
+}
diff --git a/platform/dbops/binaries/go/go/test/typeswitch2b.go b/platform/dbops/binaries/go/go/test/typeswitch2b.go
new file mode 100644
index 0000000000000000000000000000000000000000..135ae86cff1b88aacfefd4e2c86c4a1497ea701e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typeswitch2b.go
@@ -0,0 +1,20 @@
+// errorcheck
+
+// 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.
+
+// Verify that various erroneous type switches are caught by the compiler.
+// Does not compile.
+
+package main
+
+func notused(x interface{}) {
+ // The first t is in a different scope than the 2nd t; it cannot
+ // be accessed (=> declared and not used error); but it is legal
+ // to declare it.
+ switch t := 0; t := x.(type) { // ERROR "declared and not used"
+ case int:
+ _ = t // this is using the t of "t := x.(type)"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/typeswitch3.go b/platform/dbops/binaries/go/go/test/typeswitch3.go
new file mode 100644
index 0000000000000000000000000000000000000000..2e144d81c00cef738b5ff3acadd19d1aedfa6ba3
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/typeswitch3.go
@@ -0,0 +1,56 @@
+// errorcheck
+
+// 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.
+
+// Verify that erroneous type switches are caught by the compiler.
+// Issue 2700, among other things.
+// Does not compile.
+
+package main
+
+import (
+ "io"
+)
+
+type I interface {
+ M()
+}
+
+func main() {
+ var x I
+ switch x.(type) {
+ case string: // ERROR "impossible"
+ println("FAIL")
+ }
+
+ // Issue 2700: if the case type is an interface, nothing is impossible
+
+ var r io.Reader
+
+ _, _ = r.(io.Writer)
+
+ switch r.(type) {
+ case io.Writer:
+ }
+
+ // Issue 2827.
+ switch _ := r.(type) { // ERROR "invalid variable name _|no new variables?"
+ }
+}
+
+func noninterface() {
+ var i int
+ switch i.(type) { // ERROR "cannot type switch on non-interface value|not an interface"
+ case string:
+ case int:
+ }
+
+ type S struct {
+ name string
+ }
+ var s S
+ switch s.(type) { // ERROR "cannot type switch on non-interface value|not an interface"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/uintptrescapes.go b/platform/dbops/binaries/go/go/test/uintptrescapes.go
new file mode 100644
index 0000000000000000000000000000000000000000..554bb76422cff04ce65efdafa29f5252657b9ec4
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/uintptrescapes.go
@@ -0,0 +1,9 @@
+// rundir
+
+// 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 that the go:uintptrescapes comment works as expected.
+
+package ignored
diff --git a/platform/dbops/binaries/go/go/test/uintptrescapes2.go b/platform/dbops/binaries/go/go/test/uintptrescapes2.go
new file mode 100644
index 0000000000000000000000000000000000000000..656286c0ff2bd72e7580bd7592a533d4a346d1df
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/uintptrescapes2.go
@@ -0,0 +1,65 @@
+// errorcheck -0 -l -m -live
+
+// 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 escape analysis and liveness inferred for uintptrescapes functions.
+
+package p
+
+import (
+ "unsafe"
+)
+
+//go:uintptrescapes
+func F1(a uintptr) {} // ERROR "escaping uintptr"
+
+//go:uintptrescapes
+func F2(a ...uintptr) {} // ERROR "escaping ...uintptr"
+
+//go:uintptrescapes
+func F3(uintptr) {} // ERROR "escaping uintptr"
+
+//go:uintptrescapes
+func F4(...uintptr) {} // ERROR "escaping ...uintptr"
+
+type T struct{}
+
+//go:uintptrescapes
+func (T) M1(a uintptr) {} // ERROR "escaping uintptr"
+
+//go:uintptrescapes
+func (T) M2(a ...uintptr) {} // ERROR "escaping ...uintptr"
+
+func TestF1() {
+ var t int // ERROR "moved to heap"
+ F1(uintptr(unsafe.Pointer(&t))) // ERROR "live at call to F1: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func TestF3() {
+ var t2 int // ERROR "moved to heap"
+ F3(uintptr(unsafe.Pointer(&t2))) // ERROR "live at call to F3: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func TestM1() {
+ var t T
+ var v int // ERROR "moved to heap"
+ t.M1(uintptr(unsafe.Pointer(&v))) // ERROR "live at call to T.M1: .?autotmp" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func TestF2() {
+ var v int // ERROR "moved to heap"
+ F2(0, 1, uintptr(unsafe.Pointer(&v)), 2) // ERROR "live at call to newobject: .?autotmp" "live at call to F2: .?autotmp" "escapes to heap" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func TestF4() {
+ var v2 int // ERROR "moved to heap"
+ F4(0, 1, uintptr(unsafe.Pointer(&v2)), 2) // ERROR "live at call to newobject: .?autotmp" "live at call to F4: .?autotmp" "escapes to heap" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
+
+func TestM2() {
+ var t T
+ var v int // ERROR "moved to heap"
+ t.M2(0, 1, uintptr(unsafe.Pointer(&v)), 2) // ERROR "live at call to newobject: .?autotmp" "live at call to T.M2: .?autotmp" "escapes to heap" "stack object .autotmp_[0-9]+ unsafe.Pointer$"
+}
diff --git a/platform/dbops/binaries/go/go/test/uintptrescapes3.go b/platform/dbops/binaries/go/go/test/uintptrescapes3.go
new file mode 100644
index 0000000000000000000000000000000000000000..92be5d1eef4239d63b4830ec711100b9907fb3da
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/uintptrescapes3.go
@@ -0,0 +1,63 @@
+// run
+
+// 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.
+
+// Test that //go:uintptrescapes works for methods.
+
+package main
+
+import (
+ "fmt"
+ "runtime"
+ "unsafe"
+)
+
+var callback func()
+
+//go:noinline
+//go:uintptrescapes
+func F(ptr uintptr) { callback() }
+
+//go:noinline
+//go:uintptrescapes
+func Fv(ptrs ...uintptr) { callback() }
+
+type T struct{}
+
+//go:noinline
+//go:uintptrescapes
+func (T) M(ptr uintptr) { callback() }
+
+//go:noinline
+//go:uintptrescapes
+func (T) Mv(ptrs ...uintptr) { callback() }
+
+// Each test should pass uintptr(ptr) as an argument to a function call,
+// which in turn should call callback. The callback checks that ptr is kept alive.
+var tests = []func(ptr unsafe.Pointer){
+ func(ptr unsafe.Pointer) { F(uintptr(ptr)) },
+ func(ptr unsafe.Pointer) { Fv(uintptr(ptr)) },
+ func(ptr unsafe.Pointer) { T{}.M(uintptr(ptr)) },
+ func(ptr unsafe.Pointer) { T{}.Mv(uintptr(ptr)) },
+}
+
+func main() {
+ for i, test := range tests {
+ finalized := false
+
+ ptr := new([64]byte)
+ runtime.SetFinalizer(ptr, func(*[64]byte) {
+ finalized = true
+ })
+
+ callback = func() {
+ runtime.GC()
+ if finalized {
+ fmt.Printf("test #%d failed\n", i)
+ }
+ }
+ test(unsafe.Pointer(ptr))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/uintptrkeepalive.go b/platform/dbops/binaries/go/go/test/uintptrkeepalive.go
new file mode 100644
index 0000000000000000000000000000000000000000..97834dcd1af5478e62e4ab34c04e23da9366973b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/uintptrkeepalive.go
@@ -0,0 +1,11 @@
+// errorcheck -std
+
+// 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
+
+//go:uintptrkeepalive
+func missingNosplit(uintptr) { // ERROR "go:uintptrkeepalive requires go:nosplit"
+}
diff --git a/platform/dbops/binaries/go/go/test/undef.go b/platform/dbops/binaries/go/go/test/undef.go
new file mode 100644
index 0000000000000000000000000000000000000000..61524f3d4c364433c5692948655ffde3c586dddc
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/undef.go
@@ -0,0 +1,45 @@
+// errorcheck
+
+// 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.
+
+// Test line numbers in error messages.
+// Does not compile.
+
+package main
+
+var (
+ _ = x // ERROR "undefined.*x"
+ _ = x // ERROR "undefined.*x"
+ _ = x // ERROR "undefined.*x"
+)
+
+type T struct {
+ y int
+}
+
+func foo() *T { return &T{y: 99} }
+func bar() int { return y } // ERROR "undefined.*y"
+
+type T1 struct {
+ y1 int
+}
+
+func foo1() *T1 { return &T1{y1: 99} }
+var y1 = 2
+func bar1() int { return y1 }
+
+func f1(val interface{}) {
+ switch v := val.(type) {
+ default:
+ println(v)
+ }
+}
+
+func f2(val interface{}) {
+ switch val.(type) {
+ default:
+ println(v) // ERROR "undefined.*v"
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/unsafe_slice_data.go b/platform/dbops/binaries/go/go/test/unsafe_slice_data.go
new file mode 100644
index 0000000000000000000000000000000000000000..e8b8207547fabd92cbe5a3066d2acc27105c2510
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/unsafe_slice_data.go
@@ -0,0 +1,22 @@
+// run
+
+// 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 main
+
+import (
+ "fmt"
+ "reflect"
+ "unsafe"
+)
+
+func main() {
+ var s = []byte("abc")
+ sh1 := *(*reflect.SliceHeader)(unsafe.Pointer(&s))
+ ptr2 := unsafe.Pointer(unsafe.SliceData(s))
+ if ptr2 != unsafe.Pointer(sh1.Data) {
+ panic(fmt.Errorf("unsafe.SliceData %p != %p", ptr2, unsafe.Pointer(sh1.Data)))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/unsafe_string.go b/platform/dbops/binaries/go/go/test/unsafe_string.go
new file mode 100644
index 0000000000000000000000000000000000000000..ceecc6ff2f2efccd5c6c433af86cdf95782cd83b
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/unsafe_string.go
@@ -0,0 +1,18 @@
+// run
+
+// 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 main
+
+import (
+ "unsafe"
+)
+
+func main() {
+ hello := [5]byte{'m', 'o', 's', 'h', 'i'}
+ if unsafe.String(&hello[0], uint64(len(hello))) != "moshi" {
+ panic("unsafe.String convert error")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/unsafe_string_data.go b/platform/dbops/binaries/go/go/test/unsafe_string_data.go
new file mode 100644
index 0000000000000000000000000000000000000000..a3a69af5180a791983f103a5e3844ccc5da91241
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/unsafe_string_data.go
@@ -0,0 +1,22 @@
+// run
+
+// 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 main
+
+import (
+ "fmt"
+ "reflect"
+ "unsafe"
+)
+
+func main() {
+ var s = "abc"
+ sh1 := (*reflect.StringHeader)(unsafe.Pointer(&s))
+ ptr2 := unsafe.Pointer(unsafe.StringData(s))
+ if ptr2 != unsafe.Pointer(sh1.Data) {
+ panic(fmt.Errorf("unsafe.StringData ret %p != %p", ptr2, unsafe.Pointer(sh1.Data)))
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/unsafebuiltins.go b/platform/dbops/binaries/go/go/test/unsafebuiltins.go
new file mode 100644
index 0000000000000000000000000000000000000000..8ee72ec2e8abdfab43dd489a4c41582cb71149ca
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/unsafebuiltins.go
@@ -0,0 +1,107 @@
+// run
+
+// 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 (
+ "math"
+ "unsafe"
+)
+
+const maxUintptr = 1 << (8 * unsafe.Sizeof(uintptr(0)))
+
+func main() {
+ var p [10]byte
+
+ // unsafe.Add
+ {
+ p1 := unsafe.Pointer(&p[1])
+ assert(unsafe.Add(p1, 1) == unsafe.Pointer(&p[2]))
+ assert(unsafe.Add(p1, -1) == unsafe.Pointer(&p[0]))
+ }
+
+ // unsafe.Slice
+ {
+ s := unsafe.Slice(&p[0], len(p))
+ assert(&s[0] == &p[0])
+ assert(len(s) == len(p))
+ assert(cap(s) == len(p))
+
+ // nil pointer with zero length returns nil
+ assert(unsafe.Slice((*int)(nil), 0) == nil)
+
+ // nil pointer with positive length panics
+ mustPanic(func() { _ = unsafe.Slice((*int)(nil), 1) })
+
+ // negative length
+ var neg int = -1
+ mustPanic(func() { _ = unsafe.Slice(new(byte), neg) })
+
+ // length too large
+ var tooBig uint64 = math.MaxUint64
+ mustPanic(func() { _ = unsafe.Slice(new(byte), tooBig) })
+
+ // size overflows address space
+ mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8) })
+ mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8+1) })
+
+ // sliced memory overflows address space
+ last := (*byte)(unsafe.Pointer(^uintptr(0)))
+ _ = unsafe.Slice(last, 1)
+ mustPanic(func() { _ = unsafe.Slice(last, 2) })
+ }
+
+ // unsafe.String
+ {
+ s := unsafe.String(&p[0], len(p))
+ assert(s == string(p[:]))
+ assert(len(s) == len(p))
+
+ // the empty string
+ assert(unsafe.String(nil, 0) == "")
+
+ // nil pointer with positive length panics
+ mustPanic(func() { _ = unsafe.String(nil, 1) })
+
+ // negative length
+ var neg int = -1
+ mustPanic(func() { _ = unsafe.String(new(byte), neg) })
+
+ // length too large
+ var tooBig uint64 = math.MaxUint64
+ mustPanic(func() { _ = unsafe.String(new(byte), tooBig) })
+
+ // string memory overflows address space
+ last := (*byte)(unsafe.Pointer(^uintptr(0)))
+ _ = unsafe.String(last, 1)
+ mustPanic(func() { _ = unsafe.String(last, 2) })
+ }
+
+ // unsafe.StringData
+ {
+ var s = "string"
+ assert(string(unsafe.Slice(unsafe.StringData(s), len(s))) == s)
+ }
+
+ //unsafe.SliceData
+ {
+ var s = []byte("slice")
+ assert(unsafe.String(unsafe.SliceData(s), len(s)) == string(s))
+ }
+}
+
+func assert(ok bool) {
+ if !ok {
+ panic("FAIL")
+ }
+}
+
+func mustPanic(f func()) {
+ defer func() {
+ assert(recover() != nil)
+ }()
+ f()
+}
diff --git a/platform/dbops/binaries/go/go/test/used.go b/platform/dbops/binaries/go/go/test/used.go
new file mode 100644
index 0000000000000000000000000000000000000000..5bdc5a731886913c393b42177ffc17964fbc4579
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/used.go
@@ -0,0 +1,145 @@
+// errorcheck
+
+// 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"
+
+const C = 1
+
+var x, x1, x2 int
+var b bool
+var s string
+var c chan int
+var cp complex128
+var slice []int
+var array [2]int
+var bytes []byte
+var runes []rune
+var r rune
+
+func f0() {}
+func f1() int { return 1 }
+func f2() (int, int) { return 1, 1 }
+
+type T struct{ X int }
+
+func (T) M1() int { return 1 }
+func (T) M0() {}
+func (T) M() {}
+
+var t T
+var tp *T
+
+type I interface{ M() }
+
+var i I
+
+var m map[int]int
+
+func _() {
+ // Note: if the next line changes to x, the error silences the x+x etc below!
+ x1 // ERROR "x1 .* not used"
+
+ nil // ERROR "nil .* not used"
+ C // ERROR "C .* not used"
+ 1 // ERROR "1 .* not used"
+ x + x // ERROR "x \+ x .* not used"
+ x - x // ERROR "x - x .* not used"
+ x | x // ERROR "x \| x .* not used"
+ "a" + s // ERROR ".a. \+ s .* not used"
+ &x // ERROR "&x .* not used"
+ b && b // ERROR "b && b .* not used"
+ append(slice, 1) // ERROR "append\(slice, 1\) .* not used"
+ string(bytes) // ERROR "string\(bytes\) .* not used"
+ string(runes) // ERROR "string\(runes\) .* not used"
+ f0() // ok
+ f1() // ok
+ f2() // ok
+ _ = f0() // ERROR "f0\(\) .*used as value"
+ _ = f1() // ok
+ _, _ = f2() // ok
+ _ = f2() // ERROR "assignment mismatch: 1 variable but f2 returns 2 values|cannot assign"
+ _ = f1(), 0 // ERROR "assignment mismatch: 1 variable but 2 values|cannot assign"
+ T.M0 // ERROR "T.M0 .* not used"
+ t.M0 // ERROR "t.M0 .* not used"
+ cap // ERROR "use of builtin cap not in function call|must be called"
+ cap(slice) // ERROR "cap\(slice\) .* not used"
+ close(c) // ok
+ _ = close(c) // ERROR "close\(c\) .*used as value"
+ func() {} // ERROR "func literal .* not used|is not used"
+ X{} // ERROR "undefined: X"
+ map[string]int{} // ERROR "map\[string\]int{} .* not used"
+ struct{}{} // ERROR "struct ?{}{} .* not used"
+ [1]int{} // ERROR "\[1\]int{} .* not used"
+ []int{} // ERROR "\[\]int{} .* not used"
+ &struct{}{} // ERROR "&struct ?{}{} .* not used"
+ float32(x) // ERROR "float32\(x\) .* not used"
+ I(t) // ERROR "I\(t\) .* not used"
+ int(x) // ERROR "int\(x\) .* not used"
+ copy(slice, slice) // ok
+ _ = copy(slice, slice) // ok
+ delete(m, 1) // ok
+ _ = delete(m, 1) // ERROR "delete\(m, 1\) .*used as value"
+ t.X // ERROR "t.X .* not used"
+ tp.X // ERROR "tp.X .* not used"
+ t.M // ERROR "t.M .* not used"
+ I.M // ERROR "I.M .* not used"
+ i.(T) // ERROR "i.\(T\) .* not used"
+ x == x // ERROR "x == x .* not used"
+ x != x // ERROR "x != x .* not used"
+ x != x // ERROR "x != x .* not used"
+ x < x // ERROR "x < x .* not used"
+ x >= x // ERROR "x >= x .* not used"
+ x > x // ERROR "x > x .* not used"
+ *tp // ERROR "\*tp .* not used"
+ slice[0] // ERROR "slice\[0\] .* not used"
+ m[1] // ERROR "m\[1\] .* not used"
+ len(slice) // ERROR "len\(slice\) .* not used"
+ make(chan int) // ERROR "make\(chan int\) .* not used"
+ make(map[int]int) // ERROR "make\(map\[int\]int\) .* not used"
+ make([]int, 1) // ERROR "make\(\[\]int, 1\) .* not used"
+ x * x // ERROR "x \* x .* not used"
+ x / x // ERROR "x / x .* not used"
+ x % x // ERROR "x % x .* not used"
+ x << x // ERROR "x << x .* not used"
+ x >> x // ERROR "x >> x .* not used"
+ x & x // ERROR "x & x .* not used"
+ x &^ x // ERROR "x &\^ x .* not used"
+ new(int) // ERROR "new\(int\) .* not used"
+ !b // ERROR "!b .* not used"
+ ^x // ERROR "\^x .* not used"
+ +x // ERROR "\+x .* not used"
+ -x // ERROR "-x .* not used"
+ b || b // ERROR "b \|\| b .* not used"
+ panic(1) // ok
+ _ = panic(1) // ERROR "panic\(1\) .*used as value"
+ print(1) // ok
+ _ = print(1) // ERROR "print\(1\) .*used as value"
+ println(1) // ok
+ _ = println(1) // ERROR "println\(1\) .*used as value"
+ c <- 1 // ok
+ slice[1:1] // ERROR "slice\[1:1\] .* not used"
+ array[1:1] // ERROR "array\[1:1\] .* not used"
+ s[1:1] // ERROR "s\[1:1\] .* not used"
+ slice[1:1:1] // ERROR "slice\[1:1:1\] .* not used"
+ array[1:1:1] // ERROR "array\[1:1:1\] .* not used"
+ recover() // ok
+ <-c // ok
+ string(r) // ERROR "string\(r\) .* not used"
+ iota // ERROR "undefined: iota|cannot use iota"
+ real(cp) // ERROR "real\(cp\) .* not used"
+ imag(cp) // ERROR "imag\(cp\) .* not used"
+ complex(1, 2) // ERROR "complex\(1, 2\) .* not used"
+ unsafe.Alignof(t.X) // ERROR "unsafe.Alignof\(t.X\) .* not used"
+ unsafe.Offsetof(t.X) // ERROR "unsafe.Offsetof\(t.X\) .* not used"
+ unsafe.Sizeof(t) // ERROR "unsafe.Sizeof\(t\) .* not used"
+ _ = int // ERROR "type int is not an expression|not an expression"
+ (x) // ERROR "x .* not used|not used"
+ _ = new(x2) // ERROR "x2 is not a type|not a type"
+ // Disabled due to issue #43125.
+ // _ = new(1 + 1) // DISABLED "1 \+ 1 is not a type"
+}
diff --git a/platform/dbops/binaries/go/go/test/utf.go b/platform/dbops/binaries/go/go/test/utf.go
new file mode 100644
index 0000000000000000000000000000000000000000..3ac79447e635fcfcb43f819508b0f6bbf2558685
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/utf.go
@@ -0,0 +1,66 @@
+// run
+
+// 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.
+
+// Test UTF-8 in strings and character constants.
+
+package main
+
+import "unicode/utf8"
+
+func main() {
+ var chars [6]rune
+ chars[0] = 'a'
+ chars[1] = 'b'
+ chars[2] = 'c'
+ chars[3] = '\u65e5'
+ chars[4] = '\u672c'
+ chars[5] = '\u8a9e'
+ s := ""
+ for i := 0; i < 6; i++ {
+ s += string(chars[i])
+ }
+ var l = len(s)
+ for w, i, j := 0, 0, 0; i < l; i += w {
+ var r rune
+ r, w = utf8.DecodeRuneInString(s[i:len(s)])
+ if w == 0 {
+ panic("zero width in string")
+ }
+ if r != chars[j] {
+ panic("wrong value from string")
+ }
+ j++
+ }
+ // encoded as bytes: 'a' 'b' 'c' e6 97 a5 e6 9c ac e8 aa 9e
+ const L = 12
+ if L != l {
+ panic("wrong length constructing array")
+ }
+ a := make([]byte, L)
+ a[0] = 'a'
+ a[1] = 'b'
+ a[2] = 'c'
+ a[3] = 0xe6
+ a[4] = 0x97
+ a[5] = 0xa5
+ a[6] = 0xe6
+ a[7] = 0x9c
+ a[8] = 0xac
+ a[9] = 0xe8
+ a[10] = 0xaa
+ a[11] = 0x9e
+ for w, i, j := 0, 0, 0; i < L; i += w {
+ var r rune
+ r, w = utf8.DecodeRune(a[i:L])
+ if w == 0 {
+ panic("zero width in bytes")
+ }
+ if r != chars[j] {
+ panic("wrong value from bytes")
+ }
+ j++
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/varerr.go b/platform/dbops/binaries/go/go/test/varerr.go
new file mode 100644
index 0000000000000000000000000000000000000000..349cc8b4e3b546ba971a42116ae2d2262c2ac932
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/varerr.go
@@ -0,0 +1,17 @@
+// errorcheck
+
+// 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.
+
+// Verify that a couple of illegal variable declarations are caught by the compiler.
+// Does not compile.
+
+package main
+
+func main() {
+ _ = asdf // ERROR "undefined.*asdf"
+
+ new = 1 // ERROR "use of builtin new not in function call|invalid left hand side|must be called"
+}
+
diff --git a/platform/dbops/binaries/go/go/test/varinit.go b/platform/dbops/binaries/go/go/test/varinit.go
new file mode 100644
index 0000000000000000000000000000000000000000..84a4a1aa55cd58cf2169b1c2b83ec517d67f6a26
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/varinit.go
@@ -0,0 +1,31 @@
+// run
+
+// 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.
+
+// Test var x = x + 1 works.
+
+package main
+
+func main() {
+ var x int = 1
+ if x != 1 {
+ print("found ", x, ", expected 1\n")
+ panic("fail")
+ }
+ {
+ var x int = x + 1
+ if x != 2 {
+ print("found ", x, ", expected 2\n")
+ panic("fail")
+ }
+ }
+ {
+ x := x + 1
+ if x != 2 {
+ print("found ", x, ", expected 2\n")
+ panic("fail")
+ }
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/winbatch.go b/platform/dbops/binaries/go/go/test/winbatch.go
new file mode 100644
index 0000000000000000000000000000000000000000..54c2fff13463bdf3a51bbb1ea3a321d37bc26f1e
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/winbatch.go
@@ -0,0 +1,68 @@
+// run
+
+// 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.
+
+// Check that batch files are maintained as CRLF files (consistent
+// behavior on all operating systems). See golang.org/issue/37791.
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+func main() {
+ // Ensure that the GOROOT/src/all.bat file exists and has strict CRLF line endings.
+ enforceBatchStrictCRLF(filepath.Join(runtime.GOROOT(), "src", "all.bat"))
+
+ // Walk the entire Go repository source tree (without GOROOT/pkg),
+ // skipping directories that start with "." and named "testdata",
+ // and ensure all .bat files found have exact CRLF line endings.
+ err := filepath.WalkDir(runtime.GOROOT(), func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() && (strings.HasPrefix(d.Name(), ".") || d.Name() == "testdata") {
+ return filepath.SkipDir
+ }
+ if path == filepath.Join(runtime.GOROOT(), "pkg") {
+ // GOROOT/pkg is known to contain generated artifacts, not source code.
+ // Skip it to avoid false positives. (Also see golang.org/issue/37929.)
+ return filepath.SkipDir
+ }
+ if filepath.Ext(d.Name()) == ".bat" {
+ enforceBatchStrictCRLF(path)
+ }
+ return nil
+ })
+ if err != nil {
+ log.Fatalln(err)
+ }
+}
+
+func enforceBatchStrictCRLF(path string) {
+ b, err := ioutil.ReadFile(path)
+ if err != nil {
+ log.Fatalln(err)
+ }
+ cr, lf := bytes.Count(b, []byte{13}), bytes.Count(b, []byte{10})
+ crlf := bytes.Count(b, []byte{13, 10})
+ if cr != crlf || lf != crlf {
+ if rel, err := filepath.Rel(runtime.GOROOT(), path); err == nil {
+ // Make the test failure more readable by showing a path relative to GOROOT.
+ path = rel
+ }
+ fmt.Printf("Windows batch file %s does not use strict CRLF line termination.\n", path)
+ fmt.Printf("Please convert it to CRLF before checking it in due to golang.org/issue/37791.\n")
+ os.Exit(1)
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/writebarrier.go b/platform/dbops/binaries/go/go/test/writebarrier.go
new file mode 100644
index 0000000000000000000000000000000000000000..1b30fa509e5503275904c53fb7d559296ab85259
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/writebarrier.go
@@ -0,0 +1,305 @@
+// errorcheck -0 -l -d=wb
+
+// 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.
+
+// Test where write barriers are and are not emitted.
+
+package p
+
+import "unsafe"
+
+func f(x **byte, y *byte) {
+ *x = y // no barrier (dead store)
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f1(x *[]byte, y []byte) {
+ *x = y // no barrier (dead store)
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f1a(x *[]byte, y *[]byte) {
+ *x = *y // ERROR "write barrier"
+
+ z := *y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f2(x *interface{}, y interface{}) {
+ *x = y // no barrier (dead store)
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f2a(x *interface{}, y *interface{}) {
+ *x = *y // no barrier (dead store)
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f3(x *string, y string) {
+ *x = y // no barrier (dead store)
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f3a(x *string, y *string) {
+ *x = *y // ERROR "write barrier"
+
+ z := *y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f4(x *[2]string, y [2]string) {
+ *x = y // ERROR "write barrier"
+
+ z := y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+func f4a(x *[2]string, y *[2]string) {
+ *x = *y // ERROR "write barrier"
+
+ z := *y // no barrier
+ *x = z // ERROR "write barrier"
+}
+
+type T struct {
+ X *int
+ Y int
+ M map[int]int
+}
+
+func f5(t, u *T) {
+ t.X = &u.Y // ERROR "write barrier"
+}
+
+func f6(t *T) {
+ t.M = map[int]int{1: 2} // ERROR "write barrier"
+}
+
+func f7(x, y *int) []*int {
+ var z [3]*int
+ i := 0
+ z[i] = x // ERROR "write barrier"
+ i++
+ z[i] = y // ERROR "write barrier"
+ i++
+ return z[:i]
+}
+
+func f9(x *interface{}, v *byte) {
+ *x = v // ERROR "write barrier"
+}
+
+func f10(x *byte, f func(interface{})) {
+ f(x)
+}
+
+func f11(x *unsafe.Pointer, y unsafe.Pointer) {
+ *x = unsafe.Pointer(uintptr(y) + 1) // ERROR "write barrier"
+}
+
+func f12(x []*int, y *int) []*int {
+ // write barrier for storing y in x's underlying array
+ x = append(x, y) // ERROR "write barrier"
+ return x
+}
+
+func f12a(x []int, y int) []int {
+ // y not a pointer, so no write barriers in this function
+ x = append(x, y)
+ return x
+}
+
+func f13(x []int, y *[]int) {
+ *y = append(x, 1) // ERROR "write barrier"
+}
+
+func f14(y *[]int) {
+ *y = append(*y, 1) // ERROR "write barrier"
+}
+
+type T1 struct {
+ X *int
+}
+
+func f15(x []T1, y T1) []T1 {
+ return append(x, y) // ERROR "write barrier"
+}
+
+type T8 struct {
+ X [8]*int
+}
+
+func f16(x []T8, y T8) []T8 {
+ return append(x, y) // ERROR "write barrier"
+}
+
+func t1(i interface{}) **int {
+ // From issue 14306, make sure we have write barriers in a type switch
+ // where the assigned variable escapes.
+ switch x := i.(type) {
+ case *int: // ERROR "write barrier"
+ return &x
+ }
+ switch y := i.(type) {
+ case **int: // no write barrier here
+ return y
+ }
+ return nil
+}
+
+type T17 struct {
+ f func(*T17)
+}
+
+func f17(x *T17) {
+ // Originally from golang.org/issue/13901, but the hybrid
+ // barrier requires both to have barriers.
+ x.f = f17 // ERROR "write barrier"
+ x.f = func(y *T17) { *y = *x } // ERROR "write barrier"
+}
+
+type T18 struct {
+ a []int
+ s string
+}
+
+func f18(p *T18, x *[]int) {
+ p.a = p.a[:5] // no barrier
+ *x = (*x)[0:5] // no barrier
+ p.a = p.a[3:5] // ERROR "write barrier"
+ p.a = p.a[1:2:3] // ERROR "write barrier"
+ p.s = p.s[8:9] // ERROR "write barrier"
+ *x = (*x)[3:5] // ERROR "write barrier"
+}
+
+func f19(x, y *int, i int) int {
+ // Constructing a temporary slice on the stack should not
+ // require any write barriers. See issue 14263.
+ a := []*int{x, y} // no barrier
+ return *a[i]
+}
+
+func f20(x, y *int, i int) []*int {
+ // ... but if that temporary slice escapes, then the
+ // write barriers are necessary.
+ a := []*int{x, y} // ERROR "write barrier"
+ return a
+}
+
+var x21 *int
+var y21 struct {
+ x *int
+}
+var z21 int
+
+// f21x: Global -> heap pointer updates must have write barriers.
+func f21a(x *int) {
+ x21 = x // ERROR "write barrier"
+ y21.x = x // ERROR "write barrier"
+}
+
+func f21b(x *int) {
+ x21 = &z21 // ERROR "write barrier"
+ y21.x = &z21 // ERROR "write barrier"
+}
+
+func f21c(x *int) {
+ y21 = struct{ x *int }{x} // ERROR "write barrier"
+}
+
+func f22(x *int) (y *int) {
+ // pointer write on stack should have no write barrier.
+ // this is a case that the frontend failed to eliminate.
+ p := &y
+ *p = x // no barrier
+ return
+}
+
+type T23 struct {
+ p *int
+ a int
+}
+
+var t23 T23
+var i23 int
+
+// f23x: zeroing global needs write barrier for the hybrid barrier.
+func f23a() {
+ t23 = T23{} // ERROR "write barrier"
+}
+
+func f23b() {
+ // also test partial assignments
+ t23 = T23{a: 1} // ERROR "write barrier"
+}
+
+func f23c() {
+ t23 = T23{} // no barrier (dead store)
+ // also test partial assignments
+ t23 = T23{p: &i23} // ERROR "write barrier"
+}
+
+var g int
+
+func f24() **int {
+ p := new(*int)
+ *p = &g // no write barrier here
+ return p
+}
+func f25() []string {
+ return []string{"abc", "def", "ghi"} // no write barrier here
+}
+
+type T26 struct {
+ a, b, c int
+ d, e, f *int
+}
+
+var g26 int
+
+func f26(p *int) *T26 { // see issue 29573
+ return &T26{
+ a: 5,
+ b: 6,
+ c: 7,
+ d: &g26, // no write barrier: global ptr
+ e: nil, // no write barrier: nil ptr
+ f: p, // ERROR "write barrier"
+ }
+}
+
+func f27(p *int) []interface{} {
+ return []interface{}{
+ nil, // no write barrier: zeroed memory, nil ptr
+ (*T26)(nil), // no write barrier: zeroed memory, type ptr & nil ptr
+ &g26, // no write barrier: zeroed memory, type ptr & global ptr
+ 7, // no write barrier: zeroed memory, type ptr & global ptr
+ p, // ERROR "write barrier"
+ }
+}
+
+var g28 [256]uint64
+
+func f28() []interface{} {
+ return []interface{}{
+ false, // no write barrier
+ true, // no write barrier
+ 0, // no write barrier
+ 1, // no write barrier
+ uint8(127), // no write barrier
+ int8(-4), // no write barrier
+ &g28[5], // no write barrier
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/zerodivide.go b/platform/dbops/binaries/go/go/test/zerodivide.go
new file mode 100644
index 0000000000000000000000000000000000000000..fd36d67d1ad6dc8b189473a7e45206edea866428
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/zerodivide.go
@@ -0,0 +1,246 @@
+// run
+
+// 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.
+
+// Test that zero division causes a panic.
+
+package main
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "strings"
+)
+
+type ErrorTest struct {
+ name string
+ fn func()
+ err string
+}
+
+var (
+ i, j, k int = 0, 0, 1
+ i8, j8, k8 int8 = 0, 0, 1
+ i16, j16, k16 int16 = 0, 0, 1
+ i32, j32, k32 int32 = 0, 0, 1
+ i64, j64, k64 int64 = 0, 0, 1
+
+ bb = []int16{2, 0}
+
+ u, v, w uint = 0, 0, 1
+ u8, v8, w8 uint8 = 0, 0, 1
+ u16, v16, w16 uint16 = 0, 0, 1
+ u32, v32, w32 uint32 = 0, 0, 1
+ u64, v64, w64 uint64 = 0, 0, 1
+ up, vp, wp uintptr = 0, 0, 1
+
+ f, g, h float64 = 0, 0, 1
+ f32, g32, h32 float32 = 0, 0, 1
+ f64, g64, h64, inf, negInf, nan float64 = 0, 0, 1, math.Inf(1), math.Inf(-1), math.NaN()
+
+ c, d, e complex128 = 0 + 0i, 0 + 0i, 1 + 1i
+ c64, d64, e64 complex64 = 0 + 0i, 0 + 0i, 1 + 1i
+ c128, d128, e128 complex128 = 0 + 0i, 0 + 0i, 1 + 1i
+)
+
+// Fool gccgo into thinking that these variables can change.
+func NotCalled() {
+ i++
+ j++
+ k++
+ i8++
+ j8++
+ k8++
+ i16++
+ j16++
+ k16++
+ i32++
+ j32++
+ k32++
+ i64++
+ j64++
+ k64++
+
+ u++
+ v++
+ w++
+ u8++
+ v8++
+ w8++
+ u16++
+ v16++
+ w16++
+ u32++
+ v32++
+ w32++
+ u64++
+ v64++
+ w64++
+ up++
+ vp++
+ wp++
+
+ f += 1
+ g += 1
+ h += 1
+ f32 += 1
+ g32 += 1
+ h32 += 1
+ f64 += 1
+ g64 += 1
+ h64 += 1
+
+ c += 1 + 1i
+ d += 1 + 1i
+ e += 1 + 1i
+ c64 += 1 + 1i
+ d64 += 1 + 1i
+ e64 += 1 + 1i
+ c128 += 1 + 1i
+ d128 += 1 + 1i
+ e128 += 1 + 1i
+}
+
+var tmp interface{}
+
+// We could assign to _ but the compiler optimizes it too easily.
+func use(v interface{}) {
+ tmp = v
+}
+
+// Verify error/no error for all types.
+var errorTests = []ErrorTest{
+ // All integer divide by zero should error.
+ ErrorTest{"int 0/0", func() { use(i / j) }, "divide"},
+ ErrorTest{"int8 0/0", func() { use(i8 / j8) }, "divide"},
+ ErrorTest{"int16 0/0", func() { use(i16 / j16) }, "divide"},
+ ErrorTest{"int32 0/0", func() { use(i32 / j32) }, "divide"},
+ ErrorTest{"int64 0/0", func() { use(i64 / j64) }, "divide"},
+
+ ErrorTest{"int 1/0", func() { use(k / j) }, "divide"},
+ ErrorTest{"int8 1/0", func() { use(k8 / j8) }, "divide"},
+ ErrorTest{"int16 1/0", func() { use(k16 / j16) }, "divide"},
+ ErrorTest{"int32 1/0", func() { use(k32 / j32) }, "divide"},
+ ErrorTest{"int64 1/0", func() { use(k64 / j64) }, "divide"},
+
+ // From issue 5790, we should ensure that _ assignments
+ // still evaluate and generate zerodivide panics.
+ ErrorTest{"int16 _ = bb[0]/bb[1]", func() { _ = bb[0] / bb[1] }, "divide"},
+
+ ErrorTest{"uint 0/0", func() { use(u / v) }, "divide"},
+ ErrorTest{"uint8 0/0", func() { use(u8 / v8) }, "divide"},
+ ErrorTest{"uint16 0/0", func() { use(u16 / v16) }, "divide"},
+ ErrorTest{"uint32 0/0", func() { use(u32 / v32) }, "divide"},
+ ErrorTest{"uint64 0/0", func() { use(u64 / v64) }, "divide"},
+ ErrorTest{"uintptr 0/0", func() { use(up / vp) }, "divide"},
+
+ ErrorTest{"uint 1/0", func() { use(w / v) }, "divide"},
+ ErrorTest{"uint8 1/0", func() { use(w8 / v8) }, "divide"},
+ ErrorTest{"uint16 1/0", func() { use(w16 / v16) }, "divide"},
+ ErrorTest{"uint32 1/0", func() { use(w32 / v32) }, "divide"},
+ ErrorTest{"uint64 1/0", func() { use(w64 / v64) }, "divide"},
+ ErrorTest{"uintptr 1/0", func() { use(wp / vp) }, "divide"},
+
+ // All float64ing divide by zero should not error.
+ ErrorTest{"float64 0/0", func() { use(f / g) }, ""},
+ ErrorTest{"float32 0/0", func() { use(f32 / g32) }, ""},
+ ErrorTest{"float64 0/0", func() { use(f64 / g64) }, ""},
+
+ ErrorTest{"float64 1/0", func() { use(h / g) }, ""},
+ ErrorTest{"float32 1/0", func() { use(h32 / g32) }, ""},
+ ErrorTest{"float64 1/0", func() { use(h64 / g64) }, ""},
+ ErrorTest{"float64 inf/0", func() { use(inf / g64) }, ""},
+ ErrorTest{"float64 -inf/0", func() { use(negInf / g64) }, ""},
+ ErrorTest{"float64 nan/0", func() { use(nan / g64) }, ""},
+
+ // All complex divide by zero should not error.
+ ErrorTest{"complex 0/0", func() { use(c / d) }, ""},
+ ErrorTest{"complex64 0/0", func() { use(c64 / d64) }, ""},
+ ErrorTest{"complex128 0/0", func() { use(c128 / d128) }, ""},
+
+ ErrorTest{"complex 1/0", func() { use(e / d) }, ""},
+ ErrorTest{"complex64 1/0", func() { use(e64 / d64) }, ""},
+ ErrorTest{"complex128 1/0", func() { use(e128 / d128) }, ""},
+}
+
+func error_(fn func()) (error string) {
+ defer func() {
+ if e := recover(); e != nil {
+ error = e.(runtime.Error).Error()
+ }
+ }()
+ fn()
+ return ""
+}
+
+type FloatTest struct {
+ f, g float64
+ out float64
+}
+
+var float64Tests = []FloatTest{
+ FloatTest{0, 0, nan},
+ FloatTest{nan, 0, nan},
+ FloatTest{inf, 0, inf},
+ FloatTest{negInf, 0, negInf},
+}
+
+func alike(a, b float64) bool {
+ switch {
+ case math.IsNaN(a) && math.IsNaN(b):
+ return true
+ case a == b:
+ return math.Signbit(a) == math.Signbit(b)
+ }
+ return false
+}
+
+func main() {
+ bad := false
+ for _, t := range errorTests {
+ err := error_(t.fn)
+ switch {
+ case t.err == "" && err == "":
+ // fine
+ case t.err != "" && err == "":
+ if !bad {
+ bad = true
+ fmt.Printf("BUG\n")
+ }
+ fmt.Printf("%s: expected %q; got no error\n", t.name, t.err)
+ case t.err == "" && err != "":
+ if !bad {
+ bad = true
+ fmt.Printf("BUG\n")
+ }
+ fmt.Printf("%s: expected no error; got %q\n", t.name, err)
+ case t.err != "" && err != "":
+ if !strings.Contains(err, t.err) {
+ if !bad {
+ bad = true
+ fmt.Printf("BUG\n")
+ }
+ fmt.Printf("%s: expected %q; got %q\n", t.name, t.err, err)
+ continue
+ }
+ }
+ }
+
+ // At this point we know we don't error on the values we're testing
+ for _, t := range float64Tests {
+ x := t.f / t.g
+ if !alike(x, t.out) {
+ if !bad {
+ bad = true
+ fmt.Printf("BUG\n")
+ }
+ fmt.Printf("%v/%v: expected %g error; got %g\n", t.f, t.g, t.out, x)
+ }
+ }
+ if bad {
+ panic("zerodivide")
+ }
+}
diff --git a/platform/dbops/binaries/go/go/test/zerosize.go b/platform/dbops/binaries/go/go/test/zerosize.go
new file mode 100644
index 0000000000000000000000000000000000000000..53a29f792713602cc1f3dcab9f17b0a1fbaf4aaf
--- /dev/null
+++ b/platform/dbops/binaries/go/go/test/zerosize.go
@@ -0,0 +1,33 @@
+// run
+
+// 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 zero-sized variables get same address as
+// runtime.zerobase.
+
+package main
+
+var x, y [0]int
+var p, q = new([0]int), new([0]int) // should get &runtime.zerobase
+
+func main() {
+ if &x != &y {
+ // Failing for now. x and y are at same address, but compiler optimizes &x==&y to false. Skip.
+ // print("&x=", &x, " &y=", &y, " &x==&y = ", &x==&y, "\n")
+ // panic("FAIL")
+ }
+ if p != q {
+ print("p=", p, " q=", q, " p==q = ", p==q, "\n")
+ panic("FAIL")
+ }
+ if &x != p {
+ print("&x=", &x, " p=", p, " &x==p = ", &x==p, "\n")
+ panic("FAIL")
+ }
+ if &y != p {
+ print("&y=", &y, " p=", p, " &y==p = ", &y==p, "\n")
+ panic("FAIL")
+ }
+}